diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 2a239e563..737852fb6 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,34 +6,34 @@ # Connectors -/Connectors/ArcGIS/* @KatKatKateryna -/Connectors/Autocad/* @clairekuang @oguzhankoral @didimitrie -/Connectors/Civil3d/* @clairekuang @oguzhankoral @didimitrie +/Connectors/Autocad/* @oguzhankoral @JR-Morgan @dogukankaratas +/Connectors/Civil3d/* @oguzhankoral @JR-Morgan @dogukankaratas /Connectors/CSi/* @bjoernsteinhagen @dogukankaratas /Connectors/Navisworks/* @jsdbroughton -/Connectors/Revit/* @clairekuang @oguzhankoral @didimitrie -/Connectors/Rhino/* @clairekuang @oguzhankoral @didimitrie +/Connectors/Revit/* @oguzhankoral +/Connectors/Rhino/* @oguzhankoral @JR-Morgan /Connectors/Tekla/* @bjoernsteinhagen @dogukankaratas # Converters -/Convertors/ArcGIS/* @KatKatKateryna -/Convertors/Autocad/* @clairekuang @oguzhankoral @didimitrie -/Convertors/Civil3d/* @clairekuang @oguzhankoral @didimitrie +/Convertors/Autocad/* @oguzhankoral @JR-Morgan @dogukankaratas +/Convertors/Civil3d/* @oguzhankoral @JR-Morgan @dogukankaratas /Convertors/CSi/* @bjoernsteinhagen @dogukankaratas /Convertors/Navisworks/* @jsdbroughton -/Convertors/Revit/* @clairekuang @oguzhankoral @didimitrie -/Convertors/Rhino/* @clairekuang @oguzhankoral @didimitrie +/Convertors/Revit/* @oguzhankoral +/Convertors/Rhino/* @oguzhankoral @JR-Morgan /Convertors/Tekla/* @bjoernsteinhagen @dogukankaratas # DUI -/DUI3/* @clairekuang @oguzhankoral @didimitrie +/DUI3/* @oguzhankoral # Importers -/Importers/* @JR-Morgan @didimitrie @oguzhankoral @adamhathcock +/Importers/* @JR-Morgan @oguzhankoral # SDK -/SDK/* @JR-Morgan @clairekuang @didimitrie @oguzhankoral @adamhathcock +/SDK/* @JR-Morgan @oguzhankoral # Build -/Build/* @JR-Morgan @oguzhankoral @adamhathcock +/Build/* @JR-Morgan @oguzhankoral +/.github/* @JR-Morgan @oguzhankoral +/.config/* @JR-Morgan @oguzhankoral diff --git a/Connectors/Autocad/Directory.Build.targets b/Connectors/Autocad/Directory.Build.targets index 5afa22167..5d93d9f50 100644 --- a/Connectors/Autocad/Directory.Build.targets +++ b/Connectors/Autocad/Directory.Build.targets @@ -1,7 +1,7 @@ - + @@ -9,11 +9,12 @@ - + + - + @@ -21,7 +22,8 @@ - + + diff --git a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Bindings/AutocadSendBaseBinding.cs b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Bindings/AutocadSendBaseBinding.cs index f30544012..9c23996ed 100644 --- a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Bindings/AutocadSendBaseBinding.cs +++ b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Bindings/AutocadSendBaseBinding.cs @@ -1,6 +1,7 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using Autodesk.AutoCAD.DatabaseServices; +using Autodesk.AutoCAD.Geometry; using Speckle.Connectors.Autocad.HostApp.Extensions; using Speckle.Connectors.Common.Caching; using Speckle.Connectors.Common.Cancellation; @@ -40,6 +41,9 @@ public abstract class AutocadSendBaseBinding : ISendBinding /// private ConcurrentBag ChangedObjectIds { get; set; } = new(); + private readonly List _docSubsTracker = new(); + private readonly Dictionary _docUcsTracker = new(); + protected AutocadSendBaseBinding( DocumentModelStore store, IBrowserBridge parent, @@ -71,6 +75,10 @@ public abstract class AutocadSendBaseBinding : ISendBinding // catches the case when autocad just opens up with a blank new doc SubscribeToObjectChanges(Application.DocumentManager.CurrentDocument); } + + Application.SystemVariableChanged += (_, e) => + _topLevelExceptionHandler.CatchUnhandled(() => OnSystemVariableChanged(e)); + // Since ids of the objects generates from same seed, we should clear the cache always whenever doc swapped. _store.DocumentChanged += (_, _) => { @@ -78,8 +86,6 @@ public abstract class AutocadSendBaseBinding : ISendBinding }; } - private readonly List _docSubsTracker = new(); - private void SubscribeToObjectChanges(Document doc) { if (doc == null || doc.Database == null || _docSubsTracker.Contains(doc.Name)) @@ -88,11 +94,58 @@ public abstract class AutocadSendBaseBinding : ISendBinding } _docSubsTracker.Add(doc.Name); + _docUcsTracker[doc.Name] = doc.Editor.CurrentUserCoordinateSystem; + doc.Database.ObjectAppended += (_, e) => OnObjectChanged(e.DBObject); doc.Database.ObjectErased += (_, e) => OnObjectChanged(e.DBObject); doc.Database.ObjectModified += (_, e) => OnObjectChanged(e.DBObject); } + /// + /// Handles system variable changes to detect UCS modifications. + /// When UCS changes, clears the conversion cache and expires all sender model cards. + /// + private void OnSystemVariableChanged(Autodesk.AutoCAD.ApplicationServices.SystemVariableChangedEventArgs e) + { + // check if this is a UCS-defining system variable + string varName = e.Name.ToUpperInvariant(); + bool isUcsChange = varName == "UCSNAME" || varName == "UCSORG" || varName == "UCSXDIR" || varName == "UCSYDIR"; + + if (!isUcsChange) + { + return; + } + + // get the currently active document + Document doc = Application.DocumentManager.MdiActiveDocument; + if (doc == null) + { + return; + } + + var currentUcs = doc.Editor.CurrentUserCoordinateSystem; + + // first time tracking this document's UCS + if (!_docUcsTracker.TryGetValue(doc.Name, out Matrix3d storedUcs)) + { + _docUcsTracker[doc.Name] = currentUcs; + return; + } + + // ucs hasn't actually changed (multiple variables fire for single UCS change) + if (currentUcs.IsEqualTo(storedUcs)) + { + return; + } + + // ucs has changed - all cached conversions invalid + _sendConversionCache.ClearCache(); + _docUcsTracker[doc.Name] = currentUcs; + + // expire all sender model cards + _idleManager.SubscribeToIdle(nameof(ExpireAllSenders), async () => await ExpireAllSenders()); + } + private void OnObjectChanged(DBObject dbObject) => _topLevelExceptionHandler.CatchUnhandled(() => OnChangeChangedObjectIds(dbObject)); @@ -123,6 +176,19 @@ public abstract class AutocadSendBaseBinding : ISendBinding ChangedObjectIds = new(); } + /// + /// Expires all sender model cards when a global change occurs (like UCS change). + /// + private async Task ExpireAllSenders() + { + var senders = _store.GetSenders(); + var expiredSenderIds = senders.Select(s => s.ModelCardId.NotNull()).ToList(); + if (expiredSenderIds.Count > 0) + { + await Commands.SetModelsExpired(expiredSenderIds); + } + } + public List GetSendFilters() => _sendFilters; public List GetSendSettings() => []; diff --git a/Connectors/Autocad/Speckle.Connectors.AutocadShared/HostApp/AutocadInstanceUnpacker.cs b/Connectors/Autocad/Speckle.Connectors.AutocadShared/HostApp/AutocadInstanceUnpacker.cs index d38ebca41..3b9611c84 100644 --- a/Connectors/Autocad/Speckle.Connectors.AutocadShared/HostApp/AutocadInstanceUnpacker.cs +++ b/Connectors/Autocad/Speckle.Connectors.AutocadShared/HostApp/AutocadInstanceUnpacker.cs @@ -3,9 +3,9 @@ using Microsoft.Extensions.Logging; using Speckle.Connectors.Autocad.HostApp.Extensions; using Speckle.Connectors.Autocad.Operations.Send; using Speckle.Connectors.Common.Instances; +using Speckle.Converters.Autocad.Helpers; using Speckle.Converters.AutocadShared.ToSpeckle; using Speckle.Converters.Common; -using Speckle.DoubleNumerics; using Speckle.Sdk; using Speckle.Sdk.Models.Instances; @@ -46,6 +46,7 @@ public class AutocadInstanceUnpacker : IInstanceUnpacker { UnpackInstance(blockReference, 0, transaction); } + _instanceObjectsManager.AddAtomicObject(obj.ApplicationId, obj); } return _instanceObjectsManager.GetUnpackResult(); @@ -66,13 +67,14 @@ public class AutocadInstanceUnpacker : IInstanceUnpacker ? instance.AnonymousBlockTableRecord : instance.BlockTableRecord; + // transforms on instances are always stored in WCS InstanceProxy instanceProxy = new() { applicationId = instanceId, definitionId = definitionId.ToString(), maxDepth = depth, - transform = GetMatrix(instance.BlockTransform.ToArray()), + transform = TransformHelper.ConvertToInstanceMatrix4x4(instance.BlockTransform), units = _unitsConverter.ConvertOrThrow(Application.DocumentManager.CurrentDocument.Database.Insunits) }; @@ -173,6 +175,7 @@ public class AutocadInstanceUnpacker : IInstanceUnpacker UnpackInstance(blockReference, depth + 1, transaction); } + _instanceObjectsManager.AddAtomicDefinitionObjectId(appId); _instanceObjectsManager.AddAtomicObject(appId, new(obj, appId)); } @@ -183,7 +186,4 @@ public class AutocadInstanceUnpacker : IInstanceUnpacker _logger.LogError(ex, "Failed unpacking Autocad instance"); } } - - private Matrix4x4 GetMatrix(double[] t) => - new(t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9], t[10], t[11], t[12], t[13], t[14], t[15]); } diff --git a/Connectors/Autocad/Speckle.Connectors.AutocadShared/HostApp/AutocadMaterialUnpacker.cs b/Connectors/Autocad/Speckle.Connectors.AutocadShared/HostApp/AutocadMaterialUnpacker.cs index 9b1f843b3..0f87df9a5 100644 --- a/Connectors/Autocad/Speckle.Connectors.AutocadShared/HostApp/AutocadMaterialUnpacker.cs +++ b/Connectors/Autocad/Speckle.Connectors.AutocadShared/HostApp/AutocadMaterialUnpacker.cs @@ -51,6 +51,12 @@ public class AutocadMaterialUnpacker if (transaction.GetObject(entity.MaterialId, OpenMode.ForRead) is Material material) { + // skip default material + if (material.Name == "Global") + { + continue; + } + string materialId = material.GetSpeckleApplicationId(); if (materialProxies.TryGetValue(materialId, out RenderMaterialProxy? value)) { @@ -77,6 +83,12 @@ public class AutocadMaterialUnpacker { if (transaction.GetObject(layer.MaterialId, OpenMode.ForRead) is Material material) { + // skip default material + if (material.Name == "Global") + { + continue; + } + string materialId = material.GetSpeckleApplicationId(); string layerId = layer.GetSpeckleApplicationId(); // Do not use handle directly, see note in the 'GetSpeckleApplicationId' method if (materialProxies.TryGetValue(materialId, out RenderMaterialProxy? value)) diff --git a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Operations/Send/AutocadRootObjectBaseBuilder.cs b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Operations/Send/AutocadRootObjectBaseBuilder.cs index 0434dcc35..20b5660d2 100644 --- a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Operations/Send/AutocadRootObjectBaseBuilder.cs +++ b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Operations/Send/AutocadRootObjectBaseBuilder.cs @@ -1,5 +1,6 @@ using System.Diagnostics.CodeAnalysis; using Autodesk.AutoCAD.DatabaseServices; +using Autodesk.AutoCAD.Geometry; using Microsoft.Extensions.Logging; using Speckle.Connectors.Autocad.HostApp; using Speckle.Connectors.Common.Builders; @@ -7,6 +8,8 @@ using Speckle.Connectors.Common.Caching; using Speckle.Connectors.Common.Conversion; using Speckle.Connectors.Common.Extensions; using Speckle.Connectors.Common.Operations; +using Speckle.Converters.Autocad; +using Speckle.Converters.Autocad.Helpers; using Speckle.Converters.Common; using Speckle.Sdk; using Speckle.Sdk.Logging; @@ -19,6 +22,7 @@ namespace Speckle.Connectors.Autocad.Operations.Send; public abstract class AutocadRootObjectBaseBuilder : IRootObjectBuilder { private readonly IRootToSpeckleConverter _converter; + private readonly IConverterSettingsStore _converterSettings; private readonly string[] _documentPathSeparator = ["\\"]; private readonly ISendConversionCache _sendConversionCache; private readonly AutocadInstanceUnpacker _instanceUnpacker; @@ -30,6 +34,7 @@ public abstract class AutocadRootObjectBaseBuilder : IRootObjectBuilder converterSettings, ISendConversionCache sendConversionCache, AutocadInstanceUnpacker instanceObjectManager, AutocadMaterialUnpacker materialUnpacker, @@ -40,6 +45,7 @@ public abstract class AutocadRootObjectBaseBuilder : IRootObjectBuilder usedAcadLayers = new(); // Keeps track of autocad layers used, so we can pass them on later to the material and color unpacker. List results = new(); int count = 0; + + // 4 - Convert atomic objects foreach (var (entity, applicationId) in atomicObjects) { cancellationToken.ThrowIfCancellationRequested(); @@ -104,9 +128,28 @@ public abstract class AutocadRootObjectBaseBuilder : IRootObjectBuilder currentSettings with { ReferencePointTransform = null })) + { + result = ConvertAutocadEntity(entity, applicationId, objectCollection, instanceProxies, projectId); + } + } + else // this is a selected atomic object (not part of definition) + { + result = ConvertAutocadEntity( + entity, + applicationId, + objectCollection, + instanceProxies, + projectId, + referenceTransform // set this for top level instance proxies to use if needed + ); + } + results.Add(result); onOperationProgressed.Report(new("Converting", (double)++count / atomicObjects.Count)); } @@ -115,10 +158,10 @@ public abstract class AutocadRootObjectBaseBuilder : IRootObjectBuilder instanceProxies, - string projectId + string projectId, + Matrix3d? transform = null ) { string sourceType = entity.GetType().ToString(); try { Base converted; - if (entity is BlockReference && instanceProxies.TryGetValue(applicationId, out InstanceProxy? instanceProxy)) + if (entity is BlockReference br && instanceProxies.TryGetValue(applicationId, out InstanceProxy? instanceProxy)) { + // modify transform by reference point this if it is top level + if (instanceProxy.maxDepth == 0 && transform is Matrix3d validTransform) + { + instanceProxy.transform = TransformHelper.ConvertToInstanceMatrix4x4( + br.BlockTransform.PreMultiplyBy(validTransform) + ); + } + converted = instanceProxy; } else if (_sendConversionCache.TryGetValue(projectId, applicationId, out ObjectReference? value)) diff --git a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Operations/Send/AutocadRootObjectBuilder.cs b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Operations/Send/AutocadRootObjectBuilder.cs index 7278ecae6..a356d6960 100644 --- a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Operations/Send/AutocadRootObjectBuilder.cs +++ b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Operations/Send/AutocadRootObjectBuilder.cs @@ -2,6 +2,7 @@ using Autodesk.AutoCAD.DatabaseServices; using Microsoft.Extensions.Logging; using Speckle.Connectors.Autocad.HostApp; using Speckle.Connectors.Common.Caching; +using Speckle.Converters.Autocad; using Speckle.Converters.Common; using Speckle.Sdk.Logging; using Speckle.Sdk.Models.Collections; @@ -15,6 +16,7 @@ public sealed class AutocadRootObjectBuilder : AutocadRootObjectBaseBuilder public AutocadRootObjectBuilder( AutocadLayerUnpacker layerUnpacker, IRootToSpeckleConverter converter, + IConverterSettingsStore converterSettings, ISendConversionCache sendConversionCache, AutocadInstanceUnpacker instanceObjectManager, AutocadMaterialUnpacker materialUnpacker, @@ -25,6 +27,7 @@ public sealed class AutocadRootObjectBuilder : AutocadRootObjectBaseBuilder ) : base( converter, + converterSettings, sendConversionCache, instanceObjectManager, materialUnpacker, diff --git a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Plugin/BundleAutoCAD/PackageContents.xml b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Plugin/BundleAutoCAD/PackageContents.xml new file mode 100644 index 000000000..5285a6d3f --- /dev/null +++ b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Plugin/BundleAutoCAD/PackageContents.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Plugin/BundleCivil3D/PackageContents.xml b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Plugin/BundleCivil3D/PackageContents.xml new file mode 100644 index 000000000..c193b44b6 --- /dev/null +++ b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Plugin/BundleCivil3D/PackageContents.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Speckle.Connectors.AutocadShared.projitems b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Speckle.Connectors.AutocadShared.projitems index 04d739257..1c3a680cd 100644 --- a/Connectors/Autocad/Speckle.Connectors.AutocadShared/Speckle.Connectors.AutocadShared.projitems +++ b/Connectors/Autocad/Speckle.Connectors.AutocadShared/Speckle.Connectors.AutocadShared.projitems @@ -53,4 +53,12 @@ + + + Always + + + Always + + \ No newline at end of file diff --git a/Connectors/Autocad/Speckle.Connectors.Civil3dShared/Operations/Send/Civil3dRootObjectBuilder.cs b/Connectors/Autocad/Speckle.Connectors.Civil3dShared/Operations/Send/Civil3dRootObjectBuilder.cs index 9f17bd7e0..c1a629415 100644 --- a/Connectors/Autocad/Speckle.Connectors.Civil3dShared/Operations/Send/Civil3dRootObjectBuilder.cs +++ b/Connectors/Autocad/Speckle.Connectors.Civil3dShared/Operations/Send/Civil3dRootObjectBuilder.cs @@ -4,6 +4,7 @@ using Speckle.Connectors.Autocad.HostApp; using Speckle.Connectors.Autocad.Operations.Send; using Speckle.Connectors.Common.Caching; using Speckle.Connectors.Common.Operations; +using Speckle.Converters.Autocad; using Speckle.Converters.Civil3dShared.ToSpeckle; using Speckle.Converters.Common; using Speckle.Sdk.Logging; @@ -20,6 +21,7 @@ public sealed class Civil3dRootObjectBuilder : AutocadRootObjectBaseBuilder AutocadLayerUnpacker layerUnpacker, PropertySetDefinitionHandler propertySetDefinitionHandler, IRootToSpeckleConverter converter, + IConverterSettingsStore converterSettings, ISendConversionCache sendConversionCache, AutocadInstanceUnpacker instanceObjectManager, AutocadMaterialUnpacker materialUnpacker, @@ -30,6 +32,7 @@ public sealed class Civil3dRootObjectBuilder : AutocadRootObjectBaseBuilder ) : base( converter, + converterSettings, sendConversionCache, instanceObjectManager, materialUnpacker, diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/BasicConnectorBindingRevit.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/BasicConnectorBindingRevit.cs index 034eff0b9..9013f4080 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/BasicConnectorBindingRevit.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/BasicConnectorBindingRevit.cs @@ -73,7 +73,12 @@ internal sealed class BasicConnectorBindingRevit : IBasicConnectorBinding } //should this use the Hashcode of the document instead of something like CreationGUID? - var info = new DocumentInfo(doc.PathName, doc.Title, doc.GetHashCode().ToString()); + var info = new DocumentInfo( + doc.PathName, + doc.Title, + doc.GetHashCode().ToString(), + doc.IsModelInCloud ? doc.GetCloudModelUrn() : null + ); return info; } diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/RevitReceiveBinding.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/RevitReceiveBinding.cs index f841b3fe6..f2f09ee5d 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/RevitReceiveBinding.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/RevitReceiveBinding.cs @@ -4,6 +4,7 @@ using Speckle.Connectors.Common.Cancellation; using Speckle.Connectors.DUI.Bindings; using Speckle.Connectors.DUI.Bridge; using Speckle.Connectors.DUI.Settings; +using Speckle.Connectors.Revit.Operations.Receive; using Speckle.Connectors.Revit.Plugin; using Speckle.Converters.Common; using Speckle.Converters.RevitShared.Settings; @@ -24,7 +25,8 @@ public sealed class RevitReceiveBinding( private IReceiveBindingUICommands Commands { get; } = new ReceiveBindingUICommands(parent); #pragma warning disable CA1024 - public List GetReceiveSettings() => [new Operations.Receive.Settings.ReceiveReferencePointSetting()]; + public List GetReceiveSettings() => + [new Operations.Receive.Settings.ReceiveReferencePointSetting(), new ReceiveInstancesAsFamiliesSetting()]; #pragma warning restore CA1024 public void CancelReceive(string modelCardId) => cancellationManager.CancelOperation(modelCardId); @@ -45,7 +47,8 @@ public sealed class RevitReceiveBinding( false, true, false, - false + false, + toHostSettingsManager.GetReceiveInstancesAsFamiliesSetting(card) ) ); }, diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/RevitSendBinding.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/RevitSendBinding.cs index 2e66d3803..c7a107cfd 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/RevitSendBinding.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Bindings/RevitSendBinding.cs @@ -187,7 +187,8 @@ internal sealed class RevitSendBinding : RevitBaseBinding, ISendBinding _toSpeckleSettingsManager.GetSendParameterNullOrEmptyStringsSetting(document, card), _toSpeckleSettingsManager.GetLinkedModelsSetting(document, card), _toSpeckleSettingsManager.GetSendRebarsAsVolumetric(document, card), - _toSpeckleSettingsManager.GetSendAreasAsMesh(document, card) + _toSpeckleSettingsManager.GetSendAreasAsMesh(document, card), + _toSpeckleSettingsManager.GetSendRebarsAsVolumetric(document, card) ) ); }, diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/DependencyInjection/RevitConnectorModule.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/DependencyInjection/RevitConnectorModule.cs index 3311dc5be..3e0199724 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/DependencyInjection/RevitConnectorModule.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/DependencyInjection/RevitConnectorModule.cs @@ -70,11 +70,18 @@ public static class ServiceRegistration // receive operation and dependencies serviceCollection.AddScoped(); serviceCollection.AddScoped(); + serviceCollection.AddScoped(); + serviceCollection.AddScoped(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); + serviceCollection.AddScoped(); + serviceCollection.AddScoped(); + serviceCollection.AddScoped(); serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); serviceCollection.AddSingleton(); serviceCollection.AddSingleton(DefaultTraversal.CreateTraversalFunc()); serviceCollection.AddScoped(); diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/ElementUnpacker.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/ElementUnpacker.cs index f78622879..fd7e2eb73 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/ElementUnpacker.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/ElementUnpacker.cs @@ -9,8 +9,19 @@ namespace Speckle.Connectors.Revit.HostApp; /// public class ElementUnpacker { + private static readonly List s_skippedCategories = + [ + BuiltInCategory.OST_SketchLines, + BuiltInCategory.OST_MassForm, + BuiltInCategory.OST_StairsSketchBoundaryLines, + BuiltInCategory.OST_StairsSketchLandingCenterLines, + BuiltInCategory.OST_StairsSketchRiserLines, + BuiltInCategory.OST_RebarSketchLines, + BuiltInCategory.OST_StairsSketchRunLines + ]; + /// - /// Unpacks a random set of revit objects into atomic objects. It currently unpacks groups recurisvely, nested families into atomic family instances. + /// Unpacks a random set of revit objects into atomic objects. It currently unpacks groups recursively, nested families into atomic family instances. /// This method will also "pack" curtain walls if necessary (ie, if mullions or panels are selected without their parent curtain wall, they are sent independently; if the parent curtain wall is selected, they will be removed out as the curtain wall will include all its children). /// /// @@ -32,7 +43,7 @@ public class ElementUnpacker } /// - /// Unpacks input element ids into their subelements, eg groups and nested family instances + /// Unpacks input element ids into their sub-elements, eg groups and nested family instances /// /// /// @@ -57,11 +68,21 @@ public class ElementUnpacker // UNPACK: Groups if (element is Group g) { - // When a group is from a linked model, GetMemberIds may behave differently - // We add null checks to handle cases where elements can't be properly resolved - // POC: this might screw up generating hosting rel generation here, because nested families in groups get flattened out by GetMemberIds(). - var groupElements = g.GetMemberIds().Select(doc.GetElement).Where(el => el != null); - unpackedElements.AddRange(UnpackElements(groupElements, doc)); + var memberIds = g.GetMemberIds(); + + if (memberIds.Count <= 0) + { + continue; + } + + // using a collector more efficient + using var collector = new FilteredElementCollector(doc, memberIds); + collector.WhereElementIsNotElementType(); // exclude "Type" elements (FamilySymbols) + var filter = new ElementMulticategoryFilter(s_skippedCategories, inverted: true); // exclude "Sketch/Form" categories + collector.WherePasses(filter); + + // recursively unpack the valid results + unpackedElements.AddRange(UnpackElements(collector, doc)); } else if (element is BaseArray baseArray) { diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyCategoryUtils.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyCategoryUtils.cs new file mode 100644 index 000000000..ff062bae3 --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyCategoryUtils.cs @@ -0,0 +1,77 @@ +using Autodesk.Revit.DB; +using Microsoft.Extensions.Logging; +using Speckle.Converters.RevitShared.Helpers; +using Speckle.Objects.Data; +using Speckle.Sdk.Models.Collections; +using Speckle.Sdk.Models.GraphTraversal; +using Speckle.Sdk.Models.Instances; + +namespace Speckle.Connectors.Revit.HostApp; + +public class FamilyCategoryUtils +{ + private readonly CategoryExtractor _categoryExtractor; + private readonly ILogger _logger; + + public FamilyCategoryUtils(CategoryExtractor categoryExtractor, ILogger logger) + { + _categoryExtractor = categoryExtractor; + _logger = logger; + } + + public string? ExtractCategoryForDefinition( + InstanceDefinitionProxy definition, + ICollection<(Collection[] collectionPath, IInstanceComponent component)> instanceComponents, + IReadOnlyDictionary speckleObjectLookup + ) + { + var definitionId = definition.applicationId ?? definition.id; + + var firstInstance = instanceComponents + .Select(x => x.component) + .OfType() + .FirstOrDefault(i => i.definitionId == definitionId); + + if (firstInstance == null) + { + return null; + } + + var instanceObjectId = firstInstance.applicationId ?? firstInstance.id; + if (instanceObjectId != null && speckleObjectLookup.TryGetValue(instanceObjectId, out var tc)) + { + var parentDataObject = tc.Parent?.Current as DataObject; + return _categoryExtractor.ExtractBuiltInCategory(parentDataObject, tc.Current); + } + + return null; + } + + public void SetFamilyCategory(Document familyDoc, string? builtInCategoryString) + { + if (!familyDoc.IsFamilyDocument || string.IsNullOrEmpty(builtInCategoryString)) + { + return; + } + + if (Enum.TryParse(builtInCategoryString, out BuiltInCategory bic)) + { + try + { + Category targetCategory = familyDoc.Settings.Categories.get_Item(bic); + if (targetCategory != null) + { + familyDoc.OwnerFamily.FamilyCategory = targetCategory; + } + } + catch (Autodesk.Revit.Exceptions.ArgumentException) + { + _logger.LogInformation("Category {Category} cannot be assigned to a Family. Falling back to default.", bic); + } + catch (Autodesk.Revit.Exceptions.InvalidOperationException ex) + { + _logger.LogWarning(ex, "Invalid operation when setting category {Category}. Falling back to default.", bic); + } + } + } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyGeometryBaker.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyGeometryBaker.cs new file mode 100644 index 000000000..03c28f7d1 --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyGeometryBaker.cs @@ -0,0 +1,336 @@ +using Autodesk.Revit.DB; +using Microsoft.Extensions.Logging; +using Speckle.Converters.Common.Objects; +using Speckle.Objects.Other; +using Speckle.Sdk; +using Speckle.Sdk.Common; +using Speckle.Sdk.Models; +using Speckle.Sdk.Models.Collections; +using Speckle.Sdk.Models.Extensions; +using Speckle.Sdk.Models.GraphTraversal; +using Speckle.Sdk.Models.Instances; +using SMesh = Speckle.Objects.Geometry.Mesh; + +namespace Speckle.Connectors.Revit.HostApp; + +/// +/// Handles the low-level conversion and baking of Speckle geometries into a Revit Family Document. +/// Extracted from RevitFamilyBaker to separate geometry generation from high-level orchestration, reducing class coupling. +/// +public class FamilyGeometryBaker +{ + private readonly ILogger _logger; + private readonly ITypedConverter> _geometryConverter; + private readonly ITypedConverter _freeformMeshConverter; + + public FamilyGeometryBaker( + ILogger logger, + ITypedConverter> geometryConverter, + ITypedConverter freeformMeshConverter + ) + { + _logger = logger; + _geometryConverter = geometryConverter; + _freeformMeshConverter = freeformMeshConverter; + } + + public void BakeFamilyGeometry( + Document famDoc, + InstanceDefinitionProxy definition, + IReadOnlyDictionary objectLookup, + IReadOnlyDictionary materialMap, + FamilyMaterialManager materialManager, + Action placeNestedInstanceAction + ) + { + if (definition.objects.Count == 0) + { + return; + } + + foreach (var id in definition.objects) + { + if (!objectLookup.TryGetValue(id, out var tc)) + { + continue; + } + + string? extractedSubcategoryName = null; + var parentTc = tc.Parent; + while (parentTc != null) + { + if (parentTc.Current is Collection col && !string.IsNullOrWhiteSpace(col.name)) + { + extractedSubcategoryName = col.name; + break; + } + parentTc = parentTc.Parent; + } + + ProcessObjectForFamily( + famDoc, + tc.Current, + null, + definition.name, + extractedSubcategoryName, + materialManager, + materialMap, + placeNestedInstanceAction + ); + } + } + + private void ProcessObjectForFamily( + Document famDoc, + Base obj, + Category? currentSubcategory, + string familyName, + string? extractedSubcategoryName, + FamilyMaterialManager? materialManager, + IReadOnlyDictionary? materialMap, + Action placeNestedInstanceAction + ) + { + try + { + Category? newSubcategory = currentSubcategory; + string? subcategoryName = extractedSubcategoryName ?? (obj as Collection)?.name; + + if (!string.IsNullOrWhiteSpace(subcategoryName)) + { + var familyCategory = famDoc.OwnerFamily.FamilyCategory; + if (familyCategory != null) + { + if (familyCategory.SubCategories.Contains(subcategoryName)) + { + newSubcategory = familyCategory.SubCategories.get_Item(subcategoryName); + } + else + { + try + { + newSubcategory = famDoc.Settings.Categories.NewSubcategory(familyCategory, subcategoryName); + } + catch (Autodesk.Revit.Exceptions.ArgumentException) + { + _logger.LogWarning("Failed to create Revit subcategory with name: {SubcategoryName}", subcategoryName); + newSubcategory = currentSubcategory; + } + } + } + } + + if (obj is Collection col) + { + foreach (var element in col.elements) + { + ProcessObjectForFamily( + famDoc, + element, + newSubcategory, + familyName, + null, + materialManager, + materialMap, + placeNestedInstanceAction + ); + } + } + else if (obj is InstanceProxy instanceProxy) + { + placeNestedInstanceAction(famDoc, instanceProxy, materialManager); + } + else + { + BakeGeometry(famDoc, obj, newSubcategory, materialManager, materialMap, placeNestedInstanceAction); + } + } + catch (Autodesk.Revit.Exceptions.ApplicationException ex) + { + _logger.LogWarning(ex, "Revit API error baking object {ObjectId} into family {Family}", obj.id, familyName); + } + catch (SpeckleException ex) + { + _logger.LogWarning(ex, "Speckle error baking object {ObjectId} into family {Family}", obj.id, familyName); + } + } + + private void BakeGeometry( + Document famDoc, + Base obj, + Category? subcategory, + FamilyMaterialManager? materialManager, + IReadOnlyDictionary? materialMap, + Action placeNestedInstanceAction + ) + { + string objectId = obj.applicationId ?? obj.id.NotNull(); + string? speckleMatId = null; + + if (materialMap != null && materialMap.TryGetValue(objectId, out var mat)) + { + speckleMatId = mat.id; + } + + if (obj is SMesh mesh) + { + BakeMesh(famDoc, mesh, subcategory, speckleMatId, materialManager); + return; + } + + try + { + var geometries = _geometryConverter.Convert(obj); + + if (geometries.Count > 0) + { + var solids = new List(geometries.Count); + var nonSolids = new List(geometries.Count); + + foreach (var geom in geometries) + { + if (geom is Solid s && !s.Faces.IsEmpty) + { + solids.Add(s); + } + else + { + nonSolids.Add(geom); + } + } + + foreach (var solid in solids) + { + using var freeFormElement = FreeFormElement.Create(famDoc, solid); + if (subcategory != null) + { + freeFormElement.Subcategory = subcategory; + } + + if ( + materialManager != null + && speckleMatId != null + && materialManager.FamilyParameters.TryGetValue(speckleMatId, out var famParam) + ) + { + Parameter ffeMatParam = freeFormElement.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM); + if (ffeMatParam != null && famDoc.FamilyManager.CanElementParameterBeAssociated(ffeMatParam)) + { + famDoc.FamilyManager.AssociateElementParameterToFamilyParameter(ffeMatParam, famParam); + } + } + } + + if (nonSolids.Count > 0) + { + // try to use the Family's actual Category, otherwise default to Generic Model + ElementId categoryId = + famDoc.OwnerFamily.FamilyCategory?.Id ?? new ElementId(BuiltInCategory.OST_GenericModel); + + if (!DirectShape.IsValidCategoryId(categoryId, famDoc)) + { + categoryId = new ElementId(BuiltInCategory.OST_GenericModel); + } + + try + { + using var ds = DirectShape.CreateElement(famDoc, categoryId); + ds.SetShape(nonSolids); + } + catch (Autodesk.Revit.Exceptions.ArgumentException ex) + { + _logger.LogWarning( + ex, + "DirectShape rejected Category ID {CategoryId}, falling back to Generic Model", + categoryId + ); + + using var fallbackDs = DirectShape.CreateElement(famDoc, new ElementId(BuiltInCategory.OST_GenericModel)); + fallbackDs.SetShape(nonSolids); + } + } + + return; + } + } + catch (SpeckleException) { } + + var displayValues = obj.TryGetDisplayValue(); + if (displayValues != null) + { + foreach (var item in displayValues) + { + BakeGeometry(famDoc, item, subcategory, materialManager, materialMap, placeNestedInstanceAction); + } + } + } + + private void BakeMesh( + Document famDoc, + SMesh mesh, + Category? subcategory, + string? speckleMatId, + FamilyMaterialManager? materialManager + ) + { + GeometryObject geomObject; + try + { + geomObject = _freeformMeshConverter.Convert(mesh); + } + catch (SpeckleException ex) + { + _logger.LogWarning(ex, "Failed to convert Speckle Mesh into Revit freeform geometry."); + return; + } + + if (geomObject is Solid solid) + { + using var freeFormElement = FreeFormElement.Create(famDoc, solid); + if (subcategory != null) + { + freeFormElement.Subcategory = subcategory; + } + + if ( + materialManager != null + && speckleMatId != null + && materialManager.FamilyParameters.TryGetValue(speckleMatId, out var famParam) + ) + { + Parameter ffeMatParam = freeFormElement.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM); + if (ffeMatParam != null && famDoc.FamilyManager.CanElementParameterBeAssociated(ffeMatParam)) + { + famDoc.FamilyManager.AssociateElementParameterToFamilyParameter(ffeMatParam, famParam); + } + } + } + else if (geomObject is Mesh revitMesh) + { + // try to use the Family's actual Category, otherwise default to Generic Model + ElementId categoryId = famDoc.OwnerFamily.FamilyCategory?.Id ?? new ElementId(BuiltInCategory.OST_GenericModel); + + if (!DirectShape.IsValidCategoryId(categoryId, famDoc)) + { + categoryId = new ElementId(BuiltInCategory.OST_GenericModel); + } + + try + { + using var ds = DirectShape.CreateElement(famDoc, categoryId); + ds.SetShape([revitMesh]); + } + catch (Autodesk.Revit.Exceptions.ArgumentException ex) + { + _logger.LogWarning( + ex, + "DirectShape rejected Category ID {CategoryId}, falling back to Generic Model", + categoryId + ); + + using var fallbackDs = DirectShape.CreateElement(famDoc, new ElementId(BuiltInCategory.OST_GenericModel)); + fallbackDs.SetShape([revitMesh]); + } + } + } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyMaterialManager.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyMaterialManager.cs new file mode 100644 index 000000000..2acf9e3bf --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyMaterialManager.cs @@ -0,0 +1,199 @@ +using Autodesk.Revit.DB; +using Microsoft.Extensions.Logging; +using Speckle.Objects.Other; +using Speckle.Sdk; +using Speckle.Sdk.Common; +using Speckle.Sdk.Models.GraphTraversal; +using Speckle.Sdk.Models.Instances; + +namespace Speckle.Connectors.Revit.HostApp; + +/// +/// Manages the resolution and assignment of materials, subcategories, and parameters +/// strictly within the context of a temporary Family Document. +/// +public class FamilyMaterialManager +{ + private readonly RevitMaterialBaker _materialBaker; + private readonly ILogger _logger; + private static readonly char[] s_invalidRevitChars = + [ + '\\', + ':', + '{', + '}', + '[', + ']', + '|', + ';', + '<', + '>', + '?', + '`', + '~' + ]; + + public Dictionary FamilyParameters { get; } = []; + public Dictionary SubCategories { get; } = []; + private Dictionary BakedMaterials { get; } = []; + + public FamilyMaterialManager(RevitMaterialBaker materialBaker, ILogger logger) + { + _materialBaker = materialBaker; + _logger = logger; + } + + /// + /// Sanitizes string to ensure it is valid for Revit Parameters and SubCategories. + /// + public static string GetSafeName(string rawName) + { + if (string.IsNullOrWhiteSpace(rawName)) + { + return "Unnamed"; + } + + char[] buffer = rawName.ToCharArray(); + bool changed = false; + + for (int i = 0; i < buffer.Length; i++) + { + if (Array.IndexOf(s_invalidRevitChars, buffer[i]) >= 0) + { + buffer[i] = '_'; + changed = true; + } + } + + return changed ? new string(buffer) : rawName; + } + + public void SetupFamilyMaterials( + Document famDoc, + InstanceDefinitionProxy definition, + IReadOnlyDictionary objectLookup, + IReadOnlyDictionary materialMap + ) + { + Category baseCategory = famDoc.OwnerFamily.FamilyCategory; + + foreach (var id in definition.objects) + { + if (!objectLookup.TryGetValue(id, out var tc)) + { + continue; + } + + var obj = tc.Current; + string objectId = obj.applicationId ?? obj.id.NotNull(); + + if (materialMap.TryGetValue(objectId, out var renderMat)) + { + if (BakedMaterials.ContainsKey(renderMat.id.NotNullOrWhiteSpace())) + { + continue; + } + + try + { + // 1. Bake the material locally + ElementId famMatId = _materialBaker.BakeMaterial(renderMat, famDoc); + BakedMaterials[renderMat.id] = famMatId; + + // 2. Setup Subcategory (for DirectShapes) + string rawName = string.IsNullOrWhiteSpace(renderMat.name) ? renderMat.id : renderMat.name; + string safeName = GetSafeName(rawName); + + string subCatName = $"Mat_{safeName}"; + subCatName = subCatName.Length > 50 ? subCatName[..50] : subCatName; + + if (baseCategory != null) + { + if (!baseCategory.SubCategories.Contains(subCatName)) + { + Category subCat = famDoc.Settings.Categories.NewSubcategory(baseCategory, subCatName); + subCat.Material = famDoc.GetElement(famMatId) as Material; + SubCategories[renderMat.id] = subCat.Id; + } + else + { + SubCategories[renderMat.id] = baseCategory.SubCategories.get_Item(subCatName).Id; + } + } + + // 3. Setup Family Parameter (for FreeFormElements) + string paramName = $"Material_{safeName}"; + FamilyParameter? existingParam = famDoc.FamilyManager.get_Parameter(paramName); + if (existingParam == null) + { + FamilyParameter famParam = famDoc.FamilyManager.AddParameter( + paramName, + GroupTypeId.Materials, + SpecTypeId.Reference.Material, + false + ); + FamilyParameters[renderMat.id] = famParam; + } + else + { + FamilyParameters[renderMat.id] = existingParam; + } + } + catch (Exception ex) when (!ex.IsFatal()) + { + _logger.LogWarning(ex, "Failed to setup family material {MatName}", renderMat.name); + } + } + } + } + + public static void AssignProjectMaterialsToFamily( + Document document, + FamilySymbol symbol, + IReadOnlyDictionary originalNameToProjectMatId + ) + { + Category? baseCategory = document.Settings.Categories.get_Item(BuiltInCategory.OST_GenericModel); + + // Create a local map with sanitized keys so it perfectly matches the safeNames applied in the Family + var sanitizedMatMap = new Dictionary(); + foreach (var kvp in originalNameToProjectMatId) + { + sanitizedMatMap[GetSafeName(kvp.Key)] = kvp.Value; + } + + foreach (Parameter p in symbol.Parameters) + { + if (p.Definition.Name.StartsWith("Material_") && p.StorageType == StorageType.ElementId) + { + string safeName = p.Definition.Name["Material_".Length..]; + + if (sanitizedMatMap.TryGetValue(safeName, out var projMatId) && !p.IsReadOnly) + { + p.Set(projMatId); + } + } + } + + if (baseCategory != null) + { + foreach (var kvp in sanitizedMatMap) + { + string safeName = kvp.Key; + ElementId projMatId = kvp.Value; + + string subCatName = $"Mat_{safeName}"; + subCatName = subCatName.Length > 50 ? subCatName[..50] : subCatName; + + if (baseCategory.SubCategories.Contains(subCatName)) + { + Category projSubCat = baseCategory.SubCategories.get_Item(subCatName); + if (projSubCat != null && document.GetElement(projMatId) is Material projMat) + { + projSubCat.Material = projMat; + } + } + } + } + } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyTransformUtils.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyTransformUtils.cs new file mode 100644 index 000000000..d2e1b9173 --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/FamilyTransformUtils.cs @@ -0,0 +1,184 @@ +using Autodesk.Revit.DB; +using Microsoft.Extensions.Logging; +using Speckle.DoubleNumerics; + +namespace Speckle.Connectors.Revit.HostApp; + +/// +/// Pure math and transform utilities for Revit Family Instance placement. +/// +/// +/// Architecturally, these methods live in the Connector rather than the Converters project +/// because stripping scale/skew and applying API mirroring are Host App-specific workarounds +/// for Revit's shitty Family Instance rules, not general stateless conversion logic. +/// +public class FamilyTransformUtils +{ + private readonly ILogger _logger; + + public FamilyTransformUtils(ILogger logger) + { + _logger = logger; + } + + /// + /// Checks if a transform matrix contains non-uniform scaling or shear/skew. + /// + /// + /// Revit family instances natively reject matrices with scale or skew. + /// We flag these matrices so we can sanitize them before placement. + /// + public bool HasScaleOrSkew(Matrix4x4 matrix) + { + // Extract lengths of basis vectors + var lenX = Math.Sqrt(matrix.M11 * matrix.M11 + matrix.M21 * matrix.M21 + matrix.M31 * matrix.M31); + var lenY = Math.Sqrt(matrix.M12 * matrix.M12 + matrix.M22 * matrix.M22 + matrix.M32 * matrix.M32); + var lenZ = Math.Sqrt(matrix.M13 * matrix.M13 + matrix.M23 * matrix.M23 + matrix.M33 * matrix.M33); + + // Calculate dot products to check for orthogonality + var dotXy = matrix.M11 * matrix.M12 + matrix.M21 * matrix.M22 + matrix.M31 * matrix.M32; + var dotXz = matrix.M11 * matrix.M13 + matrix.M21 * matrix.M23 + matrix.M31 * matrix.M33; + var dotYz = matrix.M12 * matrix.M13 + matrix.M22 * matrix.M23 + matrix.M32 * matrix.M33; + + double tol = 1e-4; + + bool isOrthogonal = Math.Abs(dotXy) < tol && Math.Abs(dotXz) < tol && Math.Abs(dotYz) < tol; + bool isUnitScale = Math.Abs(lenX - 1.0) < tol && Math.Abs(lenY - 1.0) < tol && Math.Abs(lenZ - 1.0) < tol; + + return !isOrthogonal || !isUnitScale; + } + + /// + /// Sanitizes a transform matrix by stripping out any scale or skew, returning a rigid transform. + /// + public Matrix4x4 RemoveScaleAndSkew(Matrix4x4 matrix) + { + // 1. Extract Z column and normalize + double zX = matrix.M13, + zY = matrix.M23, + zZ = matrix.M33; + double lenZ = Math.Sqrt(zX * zX + zY * zY + zZ * zZ); + if (lenZ > 1e-6) + { + zX /= lenZ; + zY /= lenZ; + zZ /= lenZ; + } + else + { + zX = 0; + zY = 0; + zZ = 1; + } + + // 2. Extract Y column + double yX = matrix.M12, + yY = matrix.M22, + yZ = matrix.M32; + + // 3. Cross product Y and Z to get orthogonal X + double xX = yY * zZ - yZ * zY; + double xY = yZ * zX - yX * zZ; + double xZ = yX * zY - yY * zX; + double lenX = Math.Sqrt(xX * xX + xY * xY + xZ * xZ); + if (lenX > 1e-6) + { + xX /= lenX; + xY /= lenX; + xZ /= lenX; + } + else + { + xX = 1; + xY = 0; + xZ = 0; + } + + // 4. Cross product Z and X to get orthogonal unit Y + yX = zY * xZ - zZ * xY; + yY = zZ * xX - zX * xZ; + yZ = zX * xY - zY * xX; + double lenY = Math.Sqrt(yX * yX + yY * yY + yZ * yZ); + if (lenY > 1e-6) + { + yX /= lenY; + yY /= lenY; + yZ /= lenY; + } + + return new Matrix4x4( + xX, + yX, + zX, + matrix.M14, + xY, + yY, + zY, + matrix.M24, + xZ, + yZ, + zZ, + matrix.M34, + matrix.M41, + matrix.M42, + matrix.M43, + matrix.M44 + ); + } + + /// + /// Evaluates the determinant of a matrix to check if it encodes a mirrored state. + /// + /// + /// A negative determinant implies a left-handed coordinate system (mirroring). + /// We extract this so we can apply the mirror via Revit's native API instead. + /// + public (bool X, bool Y, bool Z) GetMirrorState(Matrix4x4 matrix) + { + var det = + matrix.M11 * (matrix.M22 * matrix.M33 - matrix.M23 * matrix.M32) + - matrix.M12 * (matrix.M21 * matrix.M33 - matrix.M23 * matrix.M31) + + matrix.M13 * (matrix.M21 * matrix.M32 - matrix.M22 * matrix.M31); + + return det < 0 ? (true, false, false) : (false, false, false); + } + + /// + /// Applies native Revit mirror operations to an element based on the evaluated mirror state. + /// + /// + /// Because we strip the mirrored (left-handed) state from the initial transform to keep Revit happy, + /// we must restore the mirrored geometry as a post-placement operation. + /// + public void ApplyMirroring( + Document document, + ElementId elementId, + Autodesk.Revit.DB.Plane plane, + (bool X, bool Y, bool Z) mirrorState + ) + { + var mirrorOperations = new List<(string name, bool shouldMirror, Autodesk.Revit.DB.Plane mirrorPlane)> + { + ("YZ", mirrorState.X, Autodesk.Revit.DB.Plane.CreateByOriginAndBasis(plane.Origin, plane.YVec, plane.Normal)), + ("XZ", mirrorState.Y, Autodesk.Revit.DB.Plane.CreateByOriginAndBasis(plane.Origin, plane.XVec, plane.Normal)), + ("XY", mirrorState.Z, Autodesk.Revit.DB.Plane.CreateByOriginAndBasis(plane.Origin, plane.XVec, plane.YVec)) + }; + + foreach (var (name, _, mirrorPlane) in mirrorOperations.Where(op => op.shouldMirror)) + { + try + { + document.Regenerate(); + ElementTransformUtils.MirrorElements(document, [elementId], mirrorPlane, false); + } + catch (Autodesk.Revit.Exceptions.ApplicationException e) + { + _logger.LogWarning(e, "Failed to mirror element on {PlaneName} plane", name); + } + finally + { + mirrorPlane.Dispose(); + } + } + } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/RevitFamilyBaker.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/RevitFamilyBaker.cs new file mode 100644 index 000000000..b8c3d71da --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/RevitFamilyBaker.cs @@ -0,0 +1,621 @@ +using System.IO; +using Autodesk.Revit.Creation; +using Autodesk.Revit.DB; +using Autodesk.Revit.DB.Structure; +using Microsoft.Extensions.Logging; +using Speckle.Connectors.Common.Conversion; +using Speckle.Connectors.Common.Operations; +using Speckle.Converters.Common; +using Speckle.Converters.Common.Objects; +using Speckle.Converters.RevitShared.Helpers; +using Speckle.Converters.RevitShared.Settings; +using Speckle.DoubleNumerics; +using Speckle.Objects.Other; +using Speckle.Sdk; +using Speckle.Sdk.Common; +using Speckle.Sdk.Common.Exceptions; +using Speckle.Sdk.Models; +using Speckle.Sdk.Models.Collections; +using Speckle.Sdk.Models.GraphTraversal; +using Speckle.Sdk.Models.Instances; +using DB = Autodesk.Revit.DB; +using Document = Autodesk.Revit.DB.Document; + +namespace Speckle.Connectors.Revit.HostApp; + +public sealed class RevitFamilyBaker : IDisposable +{ + private readonly IConverterSettingsStore _converterSettings; + private readonly RevitToHostCacheSingleton _cache; + private readonly ILogger _logger; + private readonly ITypedConverter<(Matrix4x4 matrix, string units), DB.Transform> _transformConverter; + private readonly RevitMaterialBaker _materialBaker; + private readonly FamilyGeometryBaker _familyGeometryBaker; + private readonly FamilyCategoryUtils _familyCategoryUtils; + private readonly FamilyTransformUtils _familyTransformUtils; + + private string? _cachedTemplatePath; + private readonly Dictionary _bakedFamilyPaths = []; + + private readonly string _tempDirectory; + private static readonly char[] s_invalidChars = Path.GetInvalidFileNameChars(); + + public RevitFamilyBaker( + IConverterSettingsStore converterSettings, + RevitToHostCacheSingleton cache, + ILogger logger, + ITypedConverter<(Matrix4x4 matrix, string units), DB.Transform> transformConverter, + RevitMaterialBaker materialBaker, + FamilyGeometryBaker familyGeometryBaker, + FamilyCategoryUtils familyCategoryUtils, + FamilyTransformUtils familyTransformUtils + ) + { + _converterSettings = converterSettings; + _cache = cache; + _logger = logger; + _transformConverter = transformConverter; + _materialBaker = materialBaker; + _familyGeometryBaker = familyGeometryBaker; + _familyCategoryUtils = familyCategoryUtils; + _familyTransformUtils = familyTransformUtils; + _tempDirectory = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid().ToString("N")[..8]}"); + Directory.CreateDirectory(_tempDirectory); + } + + public (List results, List createdElementIds) BakeInstances( + ICollection<(Collection[] collectionPath, IInstanceComponent component)> instanceComponents, + IReadOnlyDictionary speckleObjectLookup, + IReadOnlyCollection materialProxies, + IProgress onOperationProgressed + ) + { + var document = _converterSettings.Current.Document; + var results = new List(); + var createdElementIds = new List(); + + var (objectToMaterialMap, safeNameToProjectMatId) = BuildMaterialMaps(materialProxies); + var consumedIds = BuildConsumedIdsSet(instanceComponents, speckleObjectLookup); + var sortedComponents = SortComponentsForBaking(instanceComponents); + + var count = 0; + foreach (var (_, component) in sortedComponents) + { + onOperationProgressed.Report(new("Creating families", (double)++count / sortedComponents.Count)); + + try + { + if (component is InstanceDefinitionProxy definitionProxy) + { + var categoryString = _familyCategoryUtils.ExtractCategoryForDefinition( + definitionProxy, + instanceComponents, + speckleObjectLookup + ); + var result = CreateFamilyFromDefinition( + document, + definitionProxy, + speckleObjectLookup, + objectToMaterialMap, + safeNameToProjectMatId, + categoryString + ); + + if (result.HasValue) + { + results.Add( + new ReceiveConversionResult(Status.SUCCESS, definitionProxy, result.Value.family.Id.ToString(), "Family") + ); + } + } + else if (component is InstanceProxy instanceProxy) + { + bool isConsumed = + (instanceProxy.id != null && consumedIds.Contains(instanceProxy.id)) + || (instanceProxy.applicationId != null && consumedIds.Contains(instanceProxy.applicationId)); + + if (isConsumed) + { + continue; + } + + var instance = PlaceFamilyInstance(document, instanceProxy); + + if (instance != null) + { + createdElementIds.Add(instance.UniqueId); + + if (_familyTransformUtils.HasScaleOrSkew(instanceProxy.transform)) + { + var warningEx = new SpeckleException( + "Block instance placed with its original position and rotation, but the unsupported scale/skew was dropped" + ); + results.Add( + new ReceiveConversionResult( + Status.WARNING, + instanceProxy, + instance.UniqueId, + "FamilyInstance", + warningEx + ) + ); + } + else + { + results.Add( + new ReceiveConversionResult(Status.SUCCESS, instanceProxy, instance.UniqueId, "FamilyInstance") + ); + } + } + } + } + catch (Exception ex) when (!ex.IsFatal()) + { + string componentId = component switch + { + InstanceDefinitionProxy d => d.applicationId ?? d.id.NotNull(), + InstanceProxy i => i.applicationId ?? i.id.NotNull(), + _ => "unknown" + }; + _logger.LogError(ex, "Failed to process instance component {ComponentId}", componentId); + + if (component is Base b) + { + results.Add(new ReceiveConversionResult(Status.ERROR, b, null, null, ex)); + } + } + } + + return (results, createdElementIds); + } + + private ( + Dictionary objectToMaterialMap, + Dictionary safeNameToProjectMatId + ) BuildMaterialMaps(IReadOnlyCollection materialProxies) + { + Dictionary objectToMaterialMap = new(); + Dictionary safeNameToProjectMatId = new(); + + foreach (var proxy in materialProxies) + { + string matId = proxy.value.id.NotNullOrWhiteSpace(); + string safeName = string.IsNullOrWhiteSpace(proxy.value.name) ? matId : proxy.value.name; + + foreach (var objId in proxy.objects) + { + objectToMaterialMap[objId] = proxy.value; + } + + if (proxy.objects.Count > 0) + { + foreach (var objId in proxy.objects) + { + if (_cache.MaterialsByObjectId.TryGetValue(objId, out var projMatId)) + { + safeNameToProjectMatId[safeName] = projMatId; + break; + } + } + } + } + + return (objectToMaterialMap, safeNameToProjectMatId); + } + + private static HashSet BuildConsumedIdsSet( + ICollection<(Collection[] collectionPath, IInstanceComponent component)> instanceComponents, + IReadOnlyDictionary speckleObjectLookup + ) + { + var consumedIds = new HashSet(); + + foreach (var (_, component) in instanceComponents) + { + if (component is InstanceDefinitionProxy definition) + { + foreach (var childId in definition.objects ?? Enumerable.Empty()) + { + consumedIds.Add(childId); + if (speckleObjectLookup.TryGetValue(childId, out var childTc)) + { + var childObj = childTc.Current; + if (childObj.id != null) + { + consumedIds.Add(childObj.id); + } + + if (childObj.applicationId != null) + { + consumedIds.Add(childObj.applicationId); + } + } + } + } + } + + return consumedIds; + } + + private static List<(Collection[] collectionPath, IInstanceComponent component)> SortComponentsForBaking( + ICollection<(Collection[] collectionPath, IInstanceComponent component)> instanceComponents + ) => + instanceComponents + .OrderByDescending(x => x.component.maxDepth) + .ThenBy(x => x.component is InstanceDefinitionProxy ? 0 : 1) + .ToList(); + + private (Family family, FamilySymbol symbol)? CreateFamilyFromDefinition( + Document document, + InstanceDefinitionProxy definitionProxy, + IReadOnlyDictionary objectLookup, + IReadOnlyDictionary materialMap, + IReadOnlyDictionary safeNameToProjectMatId, + string? categoryString + ) + { + var definitionId = definitionProxy.applicationId ?? definitionProxy.id.NotNull(); + + if (_cache.FamiliesByDefinitionId.TryGetValue(definitionId, out var existingFamily)) + { + var existingSymbol = _cache.SymbolsByDefinitionId[definitionId]; + return (existingFamily, existingSymbol); + } + + var familyName = GetFamilyName(definitionProxy); + + bool isNewFamily = false; + var family = FindFamilyByName(document, familyName); + + if (family == null) + { + family = CreateFamily(document, familyName, definitionProxy, objectLookup, materialMap, categoryString); + isNewFamily = true; + } + + if (family == null) + { + _logger.LogWarning("Failed to create family for definition {DefinitionId}", definitionId); + return null; + } + + var symbolId = family.GetFamilySymbolIds().FirstOrDefault(); + if (symbolId == null || symbolId == ElementId.InvalidElementId) + { + return null; + } + + if (document.GetElement(symbolId) is not FamilySymbol symbol) + { + return null; + } + + if (!symbol.IsActive) + { + symbol.Activate(); + document.Regenerate(); + } + + if (isNewFamily) + { + FamilyMaterialManager.AssignProjectMaterialsToFamily(document, symbol, safeNameToProjectMatId); + } + + _cache.FamiliesByDefinitionId[definitionId] = family; + _cache.SymbolsByDefinitionId[definitionId] = symbol; + + return (family, symbol); + } + + private Family? CreateFamily( + Document document, + string familyName, + InstanceDefinitionProxy definition, + IReadOnlyDictionary objectLookup, + IReadOnlyDictionary materialMap, + string? categoryString + ) + { + var templatePath = GetFamilyTemplatePath(document); + var famDoc = document.Application.NewFamilyDocument(templatePath); + var tempPath = Path.Combine(_tempDirectory, $"{familyName}.rfa"); + + try + { + using (var t = new Transaction(famDoc, "Populate Family")) + { + t.Start(); + + var materialManager = new FamilyMaterialManager(_materialBaker, _logger); + materialManager.SetupFamilyMaterials(famDoc, definition, objectLookup, materialMap); + + _familyGeometryBaker.BakeFamilyGeometry( + famDoc, + definition, + objectLookup, + materialMap, + materialManager, + PlaceNestedInstance + ); + + SetFamilyWorkPlaneBased(famDoc, true); + _familyCategoryUtils.SetFamilyCategory(famDoc, categoryString); + t.Commit(); + } + + var saveOptions = new SaveAsOptions { OverwriteExistingFile = true }; + famDoc.SaveAs(tempPath, saveOptions); + famDoc.Close(false); + + var definitionId = definition.applicationId ?? definition.id.NotNull(); + _bakedFamilyPaths[definitionId] = tempPath; + + document.LoadFamily(tempPath, new FamilyLoadOptions(), out var loadedFamily); + return loadedFamily; + } + catch (Autodesk.Revit.Exceptions.ApplicationException ex) + { + _logger.LogError(ex, "Revit API error creating family {FamilyName}", familyName); + famDoc.Close(false); + SafeDelete(tempPath); + throw; + } + catch (IOException ex) + { + _logger.LogError(ex, "IO error creating family {FamilyName}", familyName); + famDoc.Close(false); + SafeDelete(tempPath); + throw; + } + } + + private void PlaceNestedInstance(Document famDoc, InstanceProxy instanceProxy, FamilyMaterialManager? materialManager) + { + var childDefinitionId = instanceProxy.definitionId; + + if (!_bakedFamilyPaths.TryGetValue(childDefinitionId, out var rfaPath) || !File.Exists(rfaPath)) + { + return; + } + + var familyName = Path.GetFileNameWithoutExtension(rfaPath); + Family? childFamily = FindFamilyByName(famDoc, familyName) ?? LoadFamilyWrapper(famDoc, rfaPath); + + using var _ = childFamily; + if (childFamily == null) + { + return; + } + + var symbolId = childFamily.GetFamilySymbolIds().FirstOrDefault(); + if (symbolId == null || famDoc.GetElement(symbolId) is not FamilySymbol symbol) + { + return; + } + + if (!symbol.IsActive) + { + symbol.Activate(); + } + + var instance = CreateAndPlaceFamilyInstance(famDoc, instanceProxy, symbol); + + if (instance != null && materialManager != null) + { + foreach (Parameter childParam in symbol.Parameters) + { + if (childParam.Definition.Name.StartsWith("Material_") && childParam.StorageType == StorageType.ElementId) + { + string paramName = childParam.Definition.Name; + + FamilyParameter? parentFamParam = + famDoc.FamilyManager.get_Parameter(paramName) + ?? famDoc.FamilyManager.AddParameter( + paramName, + GroupTypeId.Materials, + SpecTypeId.Reference.Material, + false + ); + + if (famDoc.FamilyManager.CanElementParameterBeAssociated(childParam)) + { + try + { + famDoc.FamilyManager.AssociateElementParameterToFamilyParameter(childParam, parentFamParam); + } + catch (Autodesk.Revit.Exceptions.ArgumentException ex) + { + _logger.LogWarning(ex, "Failed to associate material parameter {ParamName}", paramName); + } + } + } + } + } + } + + private static Family? LoadFamilyWrapper(Document doc, string path) + { + doc.LoadFamily(path, new FamilyLoadOptions(), out var family); + return family; + } + + private FamilyInstance? CreateAndPlaceFamilyInstance(Document doc, InstanceProxy instanceProxy, FamilySymbol symbol) + { + var isMirrored = _familyTransformUtils.GetMirrorState(instanceProxy.transform).X; + var hasScaleOrSkew = _familyTransformUtils.HasScaleOrSkew(instanceProxy.transform); + + var cleanMatrix = + (hasScaleOrSkew || isMirrored) + ? _familyTransformUtils.RemoveScaleAndSkew(instanceProxy.transform) + : instanceProxy.transform; + + var revitTransform = _transformConverter.Convert((cleanMatrix, instanceProxy.units)); + + XYZ origin = revitTransform.Origin; + XYZ basisX = revitTransform.BasisX.Normalize(); + XYZ basisY = revitTransform.BasisY.Normalize(); + + var plane = DB.Plane.CreateByOriginAndBasis(origin, basisX, basisY); + using var sketchPlane = SketchPlane.Create(doc, plane); + + var creationData = new FamilyInstanceCreationData( + location: origin, + symbol: symbol, + host: sketchPlane, + level: null, + structuralType: StructuralType.NonStructural + ); + + ICollection ids = doc.IsFamilyDocument + ? doc.FamilyCreate.NewFamilyInstances2([creationData]) + : doc.Create.NewFamilyInstances2([creationData]); + + if (ids.Count == 0 || doc.GetElement(ids.First()) is not FamilyInstance instance) + { + return null; + } + + doc.Regenerate(); + var mirrorState = _familyTransformUtils.GetMirrorState(instanceProxy.transform); + _familyTransformUtils.ApplyMirroring(doc, instance.Id, plane, mirrorState); + + return instance; + } + + private FamilyInstance? PlaceFamilyInstance(Document document, InstanceProxy instanceProxy) + { + var definitionId = instanceProxy.definitionId; + + if (_cache.SymbolsByDefinitionId.TryGetValue(definitionId, out var symbol)) + { + return CreateAndPlaceFamilyInstance(document, instanceProxy, symbol); + } + + _logger.LogWarning("No family symbol found for definition {DefinitionId}", definitionId); + return null; + } + + private static void SetFamilyWorkPlaneBased(Document famDoc, bool enabled) + { + var workPlaneBasedParam = famDoc.OwnerFamily.get_Parameter(BuiltInParameter.FAMILY_WORK_PLANE_BASED); + if (workPlaneBasedParam != null && !workPlaneBasedParam.IsReadOnly) + { + workPlaneBasedParam.Set(enabled ? 1 : 0); + } + } + + private string GetFamilyTemplatePath(Document document) + { + if (_cachedTemplatePath != null) + { + return _cachedTemplatePath; + } + + var version = document.Application.VersionNumber; + var isMetric = document.DisplayUnitSystem == DisplayUnit.METRIC; + var templateName = isMetric ? "Metric Generic Model.rft" : "Generic Model.rft"; + var assemblyLocation = typeof(RevitFamilyBaker).Assembly.Location; + var assemblyDir = + Path.GetDirectoryName(assemblyLocation) ?? throw new ConversionException("Could not resolve assembly directory"); + + var templatePath = Path.Combine(assemblyDir, "Resources", "Templates", version, templateName); + + if (!File.Exists(templatePath)) + { + _logger.LogError("Revit Family Template missing. Searched path: {templatePath}", templatePath); + throw new ConversionException($"Could not find required family template: {templateName}"); + } + + _cachedTemplatePath = templatePath; + return templatePath; + } + + private static string GetFamilyName(InstanceDefinitionProxy definitionProxy) + { + var baseName = definitionProxy.name; + if (string.IsNullOrWhiteSpace(baseName)) + { + return "Unnamed_Block"; + } + + char[] buffer = baseName.ToCharArray(); + bool changed = false; + + for (int i = 0; i < buffer.Length; i++) + { + if (Array.IndexOf(s_invalidChars, buffer[i]) >= 0) + { + buffer[i] = '_'; + changed = true; + } + } + + var safeName = changed ? new string(buffer) : baseName; + + // truncate to avoid MAX_PATH exceptions. 100 chars should be very safe. + if (safeName.Length > 100) + { + // Append a short hash of the definition ID to guarantee uniqueness after truncation + var shortId = definitionProxy.id?[..8] ?? Guid.NewGuid().ToString("N")[..8]; + return $"{safeName[..90]}_{shortId}"; + } + + return safeName; + } + + private static Family? FindFamilyByName(Document document, string familyName) + { + using var collector = new FilteredElementCollector(document); + return collector.OfClass(typeof(Family)).OfType().FirstOrDefault(f => f.Name == familyName); + } + + private static void SafeDelete(string path) + { + try + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } + + public void Dispose() + { + _bakedFamilyPaths.Clear(); + + try + { + if (Directory.Exists(_tempDirectory)) + { + Directory.Delete(_tempDirectory, true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.LogWarning(ex, "Failed to clean up temporary family directory at {TempDir}", _tempDirectory); + } + } + + private sealed class FamilyLoadOptions : IFamilyLoadOptions + { + public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues) + { + overwriteParameterValues = true; + return true; + } + + public bool OnSharedFamilyFound( + Family sharedFamily, + bool familyInUse, + out FamilySource source, + out bool overwriteParameterValues + ) + { + source = FamilySource.Family; + overwriteParameterValues = true; + return true; + } + } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/RevitMaterialBaker.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/RevitMaterialBaker.cs index baa698407..97e595eb0 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/RevitMaterialBaker.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/HostApp/RevitMaterialBaker.cs @@ -31,7 +31,7 @@ public class RevitMaterialBaker _converterSettings = converterSettings; } - private ElementId? FindExistingMaterialByName(string? materialName) + private ElementId? FindExistingMaterialByName(string? materialName, Document document) { if (string.IsNullOrWhiteSpace(materialName)) { @@ -40,7 +40,7 @@ public class RevitMaterialBaker string sanitizedName = _revitUtils.RemoveInvalidChars(materialName!); - using var collector = new FilteredElementCollector(_converterSettings.Current.Document); + using var collector = new FilteredElementCollector(document); var existingMaterial = collector .OfClass(typeof(Material)) .Cast() @@ -120,53 +120,54 @@ public class RevitMaterialBaker } /// - /// Will bake render materials in the revit document. + /// Bakes a single Speckle RenderMaterial into the provided document. + /// Used both for project-level baking and isolated family-level baking. + /// + public ElementId BakeMaterial(RenderMaterial speckleRenderMaterial, Document document) + { + ElementId? existingMaterialId = FindExistingMaterialByName(speckleRenderMaterial.name, document); + + if (existingMaterialId != null) + { + return existingMaterialId; + } + + // create new material + // all values assumed to be on the 0 - 1 scale need to pass through this validation and logging (if assumption wrong) + double roughness = ClampToUnitRange(speckleRenderMaterial.roughness, "roughness", speckleRenderMaterial.name); + double opacity = ClampToUnitRange(speckleRenderMaterial.opacity, "opacity", speckleRenderMaterial.name); + double metalness = ClampToUnitRange(speckleRenderMaterial.metalness, "metalness", speckleRenderMaterial.name); + + var diffuse = System.Drawing.Color.FromArgb(speckleRenderMaterial.diffuse); + double transparency = 1 - opacity; + double smoothness = 1 - roughness; + string matName = _revitUtils.RemoveInvalidChars($"{speckleRenderMaterial.name}"); + + var newMaterialId = Material.Create(document, matName); + var revitMaterial = (Material)document.GetElement(newMaterialId); + revitMaterial.Color = new Color(diffuse.R, diffuse.G, diffuse.B); + revitMaterial.Transparency = (int)(transparency * 100); + revitMaterial.Shininess = (int)(metalness * 128); + revitMaterial.Smoothness = (int)(smoothness * 100); + + return revitMaterial.Id; + } + + /// + /// Will bake render materials in the project document. /// - /// - /// public Dictionary BakeMaterials( IReadOnlyCollection speckleRenderMaterialProxies ) { Dictionary objectIdAndMaterialIndexMap = new(); + var document = _converterSettings.Current.Document; + foreach (var proxy in speckleRenderMaterialProxies) { - var speckleRenderMaterial = proxy.value; - try { - // first try to match existing material by name - ElementId? existingMaterialId = FindExistingMaterialByName(speckleRenderMaterial.name); - - ElementId materialIdToUse; - - if (existingMaterialId != null) - { - // Use existing material - materialIdToUse = existingMaterialId; - } - else - { - // create new material - // all values assumed to be on the 0 - 1 scale need to pass through this validation and logging (if assumption wrong) - double roughness = ClampToUnitRange(speckleRenderMaterial.roughness, "roughness", speckleRenderMaterial.name); - double opacity = ClampToUnitRange(speckleRenderMaterial.opacity, "opacity", speckleRenderMaterial.name); - double metalness = ClampToUnitRange(speckleRenderMaterial.metalness, "metalness", speckleRenderMaterial.name); - - var diffuse = System.Drawing.Color.FromArgb(speckleRenderMaterial.diffuse); - double transparency = 1 - opacity; - double smoothness = 1 - roughness; - string matName = _revitUtils.RemoveInvalidChars($"{speckleRenderMaterial.name}"); - - var newMaterialId = Material.Create(_converterSettings.Current.Document, matName); - var revitMaterial = (Material)_converterSettings.Current.Document.GetElement(newMaterialId); - revitMaterial.Color = new Color(diffuse.R, diffuse.G, diffuse.B); - revitMaterial.Transparency = (int)(transparency * 100); - revitMaterial.Shininess = (int)(metalness * 128); - revitMaterial.Smoothness = (int)(smoothness * 100); - - materialIdToUse = revitMaterial.Id; - } + ElementId materialIdToUse = BakeMaterial(proxy.value, document); foreach (var objectId in proxy.objects) { @@ -187,27 +188,20 @@ public class RevitMaterialBaker var validBaseGroupName = _revitUtils.RemoveInvalidChars(baseGroupName); var document = _converterSettings.Current.Document; - using (var collector = new FilteredElementCollector(document)) - { - var materialIds = collector - .OfClass(typeof(Material)) - .Where(m => m.Name.Contains(validBaseGroupName)) - .Select(m => m.Id) - .ToList(); + using var collector = new FilteredElementCollector(document); + var materialIds = collector + .OfClass(typeof(Material)) + .Where(m => m.Name.Contains(validBaseGroupName)) + .Select(m => m.Id) + .ToList(); - document.Delete(materialIds); - } + document.Delete(materialIds); } /// /// After CNX-2661, we've seen some edge cases contradicting the expected 0 - 1 range for PRB properties. /// Defensively, we'd rather clamp these values than throw. /// - /// - /// Created a method so that we can extend the checks to any numerical value potentially leading to a negative value, - /// which would throw an exception. Generalised method since Math.Clamp() only available since C# 8.0 and this method - /// handles logging (in the hope that we can get a better feel for these "weird" models, e.g. 0 - 100 scale??) - /// private double ClampToUnitRange(double value, string propertyName, string materialName) { if (value is < 0 or > 1) diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/DirectShapeUnpackStrategy.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/DirectShapeUnpackStrategy.cs new file mode 100644 index 000000000..de692216a --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/DirectShapeUnpackStrategy.cs @@ -0,0 +1,30 @@ +using Speckle.Connectors.Common.Instances; +using Speckle.Connectors.Common.Operations.Receive; +using Speckle.Objects.Data; + +namespace Speckle.Connectors.Revit.Operations.Receive; + +public class DirectShapeUnpackStrategy : RevitUnpackStrategyBase +{ + private readonly ILocalToGlobalUnpacker _localToGlobalUnpacker; + + public DirectShapeUnpackStrategy(ILocalToGlobalUnpacker localToGlobalUnpacker) + { + _localToGlobalUnpacker = localToGlobalUnpacker; + } + + public override UnpackStrategyResult Unpack(RootObjectUnpackerResult unpackedRoot) + { + // 1. Build the parent map so we don't lose metadata + var parentDataObjectMap = new Dictionary(); + PopulateParentDataObjectMap(unpackedRoot, parentDataObjectMap); + + // 2. Flatten everything, including instances + var maps = _localToGlobalUnpacker.Unpack(unpackedRoot.DefinitionProxies, unpackedRoot.ObjectsToConvert.ToList()); + + // 3. Filter out DataObjects to avoid converter crashes + var cleanedMaps = FilterUnpackedDataObjects(maps); + + return new UnpackStrategyResult(cleanedMaps, null, parentDataObjectMap); + } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/FamilyUnpackStrategy.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/FamilyUnpackStrategy.cs new file mode 100644 index 000000000..0146e4a19 --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/FamilyUnpackStrategy.cs @@ -0,0 +1,92 @@ +using Speckle.Connectors.Common.Instances; +using Speckle.Connectors.Common.Operations.Receive; +using Speckle.Objects.Data; +using Speckle.Sdk.Common; +using Speckle.Sdk.Models.Collections; +using Speckle.Sdk.Models.Instances; + +namespace Speckle.Connectors.Revit.Operations.Receive; + +public class FamilyUnpackStrategy : RevitUnpackStrategyBase +{ + private readonly ILocalToGlobalUnpacker _localToGlobalUnpacker; + private readonly RootObjectUnpacker _rootObjectUnpacker; + + public FamilyUnpackStrategy(ILocalToGlobalUnpacker localToGlobalUnpacker, RootObjectUnpacker rootObjectUnpacker) + { + _localToGlobalUnpacker = localToGlobalUnpacker; + _rootObjectUnpacker = rootObjectUnpacker; + } + + public override UnpackStrategyResult Unpack(RootObjectUnpackerResult unpackedRoot) + { + var parentDataObjectMap = new Dictionary(); + var displayValueDefinitionIds = new HashSet(); + + // 1. Build parent maps and identify definitions used purely for DataObject display values + PopulateParentDataObjectMap(unpackedRoot, parentDataObjectMap, displayValueDefinitionIds); + + // 2. Split out standard atomic objects from instance components + var (atomicObjects, instanceComponents) = _rootObjectUnpacker.SplitAtomicObjectsAndInstances( + unpackedRoot.ObjectsToConvert + ); + + // 3. Collect true definition geometries to filter out + var consumedObjectIds = new HashSet(); + if (unpackedRoot.DefinitionProxies != null) + { + foreach (var dp in unpackedRoot.DefinitionProxies) + { + var defId = dp.applicationId ?? dp.id.NotNull(); + if (!displayValueDefinitionIds.Contains(defId) && (dp.id == null || !displayValueDefinitionIds.Contains(dp.id))) + { + foreach (var objId in dp.objects) + { + consumedObjectIds.Add(objId); + } + } + } + } + + // 4. Filter out consumed objects + var filteredAtomicObjects = atomicObjects + .Where(tc => + { + var appId = tc.Current.applicationId; + var id = tc.Current.id; + return (appId == null || !consumedObjectIds.Contains(appId)) && (id == null || !consumedObjectIds.Contains(id)); + }) + .ToList(); + + // 5. Prepare true Family instances (ignore the display value proxies) + var instanceComponentsWithPath = instanceComponents + .Where(tc => tc.Current is not InstanceProxy proxy || !displayValueDefinitionIds.Contains(proxy.definitionId)) + .Select(tc => (Array.Empty(), tc.Current as IInstanceComponent)) + .Where(x => x.Item2 != null) + .Select(x => (x.Item1, x.Item2!)) + .ToList(); + + // 6. Add true definition proxies + if (unpackedRoot.DefinitionProxies != null) + { + var definitions = unpackedRoot + .DefinitionProxies.Where(proxy => + { + var defId = proxy.applicationId ?? proxy.id.NotNull(); + return !displayValueDefinitionIds.Contains(defId) + && (proxy.id == null || !displayValueDefinitionIds.Contains(proxy.id)); + }) + .Select(proxy => (Array.Empty(), proxy as IInstanceComponent)); + + instanceComponentsWithPath.AddRange(definitions); + } + + // 7. Flatten surviving atomic objects + var localToGlobalMaps = _localToGlobalUnpacker.Unpack(unpackedRoot.DefinitionProxies, filteredAtomicObjects); + + // 8. Clean out DataObjects using the shared base logic! + var cleanedMaps = FilterUnpackedDataObjects(localToGlobalMaps); + + return new UnpackStrategyResult(cleanedMaps, instanceComponentsWithPath, parentDataObjectMap); + } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/IRevitUnpackingStrategy.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/IRevitUnpackingStrategy.cs new file mode 100644 index 000000000..65f481cba --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/IRevitUnpackingStrategy.cs @@ -0,0 +1,25 @@ +using Speckle.Connectors.Common.Instances; +using Speckle.Connectors.Common.Operations.Receive; +using Speckle.Objects.Data; +using Speckle.Sdk.Models.Collections; +using Speckle.Sdk.Models.Instances; + +namespace Speckle.Connectors.Revit.Operations.Receive; + +public record UnpackStrategyResult( + IReadOnlyCollection LocalToGlobalMaps, + List<(Collection[] path, IInstanceComponent component)>? InstanceComponents, + Dictionary ParentDataObjectMap +); + +/// +/// Defines the strategy for unpacking a commit into bakeable Revit objects. +/// +/// +/// Depending on the setting, we either blindly flatten everything into DirectShapes, or we carefully +/// split out instance components to bake as native Revit Families. +/// +public interface IRevitUnpackStrategy +{ + UnpackStrategyResult Unpack(RootObjectUnpackerResult unpackedRoot); +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/ReceiveInstancesAsFamiliesSetting.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/ReceiveInstancesAsFamiliesSetting.cs new file mode 100644 index 000000000..39494c761 --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/ReceiveInstancesAsFamiliesSetting.cs @@ -0,0 +1,16 @@ +using Speckle.Connectors.DUI.Settings; + +namespace Speckle.Connectors.Revit.Operations.Receive; + +public class ReceiveInstancesAsFamiliesSetting(bool value = ReceiveInstancesAsFamiliesSetting.DEFAULT_VALUE) + : ICardSetting +{ + public const string SETTING_ID = "receiveInstancesAsFamiliesSetting"; + public const bool DEFAULT_VALUE = false; + + public string? Id { get; set; } = SETTING_ID; + public string? Title { get; set; } = "Receive Blocks as Families"; + public string? Type { get; set; } = "boolean"; + public object? Value { get; set; } = value; + public List? Enum { get; set; } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitHostObjectBuilder.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitHostObjectBuilder.cs index 30043d222..dc598a92e 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitHostObjectBuilder.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitHostObjectBuilder.cs @@ -13,16 +13,17 @@ using Speckle.Converters.RevitShared; using Speckle.Converters.RevitShared.Helpers; using Speckle.Converters.RevitShared.Settings; using Speckle.DoubleNumerics; -using Speckle.Objects; using Speckle.Objects.Data; using Speckle.Objects.Geometry; +using Speckle.Objects.Other; using Speckle.Sdk; using Speckle.Sdk.Common; using Speckle.Sdk.Common.Exceptions; using Speckle.Sdk.Logging; using Speckle.Sdk.Models; +using Speckle.Sdk.Models.Collections; +using Speckle.Sdk.Models.GraphTraversal; using Speckle.Sdk.Models.Instances; -using Transform = Speckle.Objects.Other.Transform; namespace Speckle.Connectors.Revit.Operations.Receive; @@ -31,10 +32,8 @@ public sealed class RevitHostObjectBuilder( IConverterSettingsStore converterSettings, ITransactionManager transactionManager, ISdkActivityFactory activityFactory, - ILocalToGlobalUnpacker localToGlobalUnpacker, RevitGroupBaker groupManager, RevitMaterialBaker materialBaker, - RevitViewBaker viewBaker, RootObjectUnpacker rootObjectUnpacker, ILogger logger, IThreadContext threadContext, @@ -43,12 +42,13 @@ public sealed class RevitHostObjectBuilder( (Base atomicObject, IReadOnlyCollection matrix, DataObject? parentDataObject), DirectShape > localToGlobalDirectShapeConverter, - IReceiveConversionHandler conversionHandler + IReceiveConversionHandler conversionHandler, + RevitFamilyBaker familyBaker, + DirectShapeUnpackStrategy directShapeUnpackStrategy, + FamilyUnpackStrategy familyUnpackStrategy, + RevitPreBakeSetupService preBakeSetupService ) : IHostObjectBuilder, IDisposable { - // Maps atomic object applicationId -> parent DataObject - private readonly Dictionary _atomicObjectToParentDataObject = new(); - public Task Build( Base rootObject, string projectName, @@ -102,113 +102,18 @@ public sealed class RevitHostObjectBuilder( // 1 - Unpack objects and proxies from root commit object var unpackedRoot = rootObjectUnpacker.Unpack(rootObject); - var localToGlobalMaps = localToGlobalUnpacker.Unpack( - unpackedRoot.DefinitionProxies, - unpackedRoot.ObjectsToConvert.ToList() - ); - // Register DataObjects with InstanceProxy displayValues - RegisterDataObjectsWithInstanceProxies(unpackedRoot); + // 2 - Determine conversion path based on setting + var receiveInstancesAsFamilies = converterSettings.Current.ReceiveInstancesAsFamilies; + IRevitUnpackStrategy unpackStrategy = receiveInstancesAsFamilies ? familyUnpackStrategy : directShapeUnpackStrategy; - // NOTE: below is 💩... https://github.com/specklesystems/speckle-sharp-connectors/pull/813 broke sketchup to revit workflow - // ids were modified to fix receiving instances [CNX-1707](https://linear.app/speckle/issue/CNX-1707/revit-curves-and-meshes-in-blocks-come-as-duplicated) - // but we then broke sketchup to revit because applicationIds in proxies didn't match modified application ids which cam from #813 hack - // given urgency to get sketchup to revit workflow back up and running, temp fix involves setting modified ids before material baking, mapping original app ids to modified ids and using those - // this way, CNX-1707 fix stays in tact and we fix sketchup to revit - // TODO: TransformTo and material baking needs to be fixed in Revit!! + // 3 - Split objects/Flatten objects based on strategy + var unpackResult = unpackStrategy.Unpack(unpackedRoot); - // create a mapping from original to modified IDs <- so that we can actually map ids in the proxies to the objects - // as part of CNX-2677, we have a one-to-many problem. many instances share the same reference, so we use a list - Dictionary> originalToModifiedIds = new(); + // 4 - Apply ID modifications and bake materials + preBakeSetupService.ApplyIdModificationsAndBakeMaterials(unpackResult, unpackedRoot); - // modify application IDs BEFORE material baking - foreach (LocalToGlobalMap localToGlobalMap in localToGlobalMaps) - { - if ( - localToGlobalMap.AtomicObject is ITransformable transformable - && localToGlobalMap.Matrix.Count > 0 - && localToGlobalMap.AtomicObject["units"] is string units - ) - { - var id = localToGlobalMap.AtomicObject.id; - var originalAppId = localToGlobalMap.AtomicObject.applicationId ?? id; - - // Apply transformations... - ITransformable? newTransformable = null; - foreach (var mat in localToGlobalMap.Matrix) - { - transformable.TransformTo(new Transform() { matrix = mat, units = units }, out newTransformable); - transformable = newTransformable; - } - - localToGlobalMap.AtomicObject = (newTransformable as Base)!; - localToGlobalMap.AtomicObject.id = id; - - // create modified ID and store mapping <- fixes CNX-1707 but causes us material mapping headache!!! - string modifiedAppId = $"{originalAppId}_{Guid.NewGuid().ToString("N")[..8]}"; - if (originalAppId != null) - { - if (!originalToModifiedIds.TryGetValue(originalAppId, out List? modifiedIds)) - { - modifiedIds = new List(); - originalToModifiedIds[originalAppId] = modifiedIds; - } - - modifiedIds.Add(modifiedAppId); - } - - localToGlobalMap.AtomicObject.applicationId = modifiedAppId; - localToGlobalMap.Matrix = new HashSet(); - } - } - - // Update the RenderMaterialProxies with the "new" (aka hacked) application IDs - if (unpackedRoot.RenderMaterialProxies != null) - { - foreach (var proxy in unpackedRoot.RenderMaterialProxies) - { - var objectIdsToUse = new List(); - foreach (var objectId in proxy.objects) - { - // Use the modified ID if it exists, otherwise keep the original <- this SUCKS and we need to change - if (originalToModifiedIds.TryGetValue(objectId, out var modifiedIds)) - { - objectIdsToUse.AddRange(modifiedIds); - } - else - { - objectIdsToUse.Add(objectId); - } - } - proxy.objects = objectIdsToUse; - } - } - - // Update DataObject lookup IDs - UpdateAtomicObjectLookupWithModifiedIds(originalToModifiedIds); - - // 2 - Bake materials (now with the updated IDs) - if (unpackedRoot.RenderMaterialProxies != null) - { - transactionManager.StartTransaction(true, "Baking materials"); - materialBaker.MapLayersRenderMaterials(unpackedRoot); - var map = materialBaker.BakeMaterials(unpackedRoot.RenderMaterialProxies); - foreach (var kvp in map) - { - revitToHostCacheSingleton.MaterialsByObjectId.Add(kvp.Key, kvp.Value); - } - transactionManager.CommitTransaction(); - } - - // 2.1 - Bake views - if (unpackedRoot.Cameras is not null) - { - transactionManager.StartTransaction(true, "Baking views"); - viewBaker.BakeViews(unpackedRoot.Cameras); - transactionManager.CommitTransaction(); - } - - // 3 - Bake objects + // 5 - Bake objects ( HostObjectBuilderResult builderResult, List<(DirectShape res, string applicationId)> postBakePaintTargets @@ -229,12 +134,52 @@ public sealed class RevitHostObjectBuilder( ) ) { - conversionResults = BakeObjects(localToGlobalMaps, onOperationProgressed, cancellationToken); + conversionResults = BakeObjects( + unpackResult.LocalToGlobalMaps, + unpackResult.ParentDataObjectMap, + onOperationProgressed, + cancellationToken + ); } + transactionManager.CommitTransaction(); } - // 4 - Paint solids + // Bakes instances as families (if setting is enabled Count > 0) + if (receiveInstancesAsFamilies && unpackResult.InstanceComponents is { Count: > 0 }) + { + var speckleObjectLookup = new Dictionary(); + foreach (var tc in unpackedRoot.ObjectsToConvert) + { + var obj = tc.Current; + + // 1. Primary Index: our Hash + // TODO: investigate. this should never be null? but i (Björn) had some weird edge-cases + if (!string.IsNullOrEmpty(obj.id)) + { + speckleObjectLookup[obj.id.NotNullOrWhiteSpace()] = tc; + } + + // 2. Secondary Index: Application ID (kinda fallback) + if (!string.IsNullOrEmpty(obj.applicationId)) + { + speckleObjectLookup[obj.applicationId.NotNullOrWhiteSpace()] = tc; + } + } + + // Pass the unpacked material proxies down to the family baker, defaulting to empty if null + var materialProxies = unpackedRoot.RenderMaterialProxies ?? []; + + conversionResults = BakeInstancesAsFamilies( + unpackResult.InstanceComponents, + conversionResults, + speckleObjectLookup, + materialProxies, + onOperationProgressed + ); + } + + // 6 - Paint solids { using var _ = activityFactory.Start("Painting solids"); transactionManager.StartTransaction(true, "Painting solids"); @@ -242,7 +187,7 @@ public sealed class RevitHostObjectBuilder( transactionManager.CommitTransaction(); } - // 5 - Create group + // 7 - Create group { using var _ = activityFactory.Start("Grouping"); transactionManager.StartTransaction(true, "Grouping"); @@ -253,85 +198,53 @@ public sealed class RevitHostObjectBuilder( return conversionResults.builderResult; } - /// - /// Registers DataObjects that have InstanceProxy displayValues and builds the lookup. - /// - private void RegisterDataObjectsWithInstanceProxies(RootObjectUnpackerResult unpackedRoot) + private ( + HostObjectBuilderResult builderResult, + List<(DirectShape res, string applicationId)> postBakePaintTargets + ) BakeInstancesAsFamilies( + List<(Collection[] path, IInstanceComponent component)> instanceComponents, + ( + HostObjectBuilderResult builderResult, + List<(DirectShape res, string applicationId)> postBakePaintTargets + ) currentResults, + Dictionary speckleObjectLookup, + IReadOnlyCollection materialProxies, + IProgress onOperationProgressed + ) { - var definitionToDataObject = new Dictionary(); + using var _ = activityFactory.Start("Creating families"); + transactionManager.StartTransaction(true, "Creating families"); - foreach (var tc in unpackedRoot.ObjectsToConvert) + (List familyResults, List familyElementIds) = familyBaker.BakeInstances( + instanceComponents, + speckleObjectLookup, + materialProxies, + onOperationProgressed + ); + + // Merge results + var mergedConversionResults = currentResults.builderResult.ConversionResults.ToList(); + mergedConversionResults.AddRange(familyResults); + + var mergedBakedObjectIds = currentResults.builderResult.BakedObjectIds.ToList(); + mergedBakedObjectIds.AddRange(familyElementIds); + + // Add created elements to group + foreach (var elementId in familyElementIds) { - if (tc.Current is DataObject dataObject) + var element = converterSettings.Current.Document.GetElement(elementId); + if (element != null) { - var instanceProxies = dataObject.displayValue.OfType().ToList(); - if (instanceProxies.Count > 0) - { - foreach (var ip in instanceProxies) - { - definitionToDataObject[ip.definitionId] = dataObject; - } - } + groupManager.AddToTopLevelGroup(element); } } - // Build lookup: definition object applicationId -> parent DataObject - _atomicObjectToParentDataObject.Clear(); - if (unpackedRoot.DefinitionProxies is not null) - { - foreach (var defProxy in unpackedRoot.DefinitionProxies) - { - if ( - defProxy.applicationId is not null - && definitionToDataObject.TryGetValue(defProxy.applicationId, out var parentDataObject) - ) - { - foreach (var objectId in defProxy.objects) - { - _atomicObjectToParentDataObject[objectId] = parentDataObject; - } - } - else - { - logger.LogError( - "Could not find parent DataObject for DefinitionProxy {ApplicationId}", - defProxy.applicationId - ); - } - } - } - } + transactionManager.CommitTransaction(); - /// - /// Updates the atomic object lookup with modified IDs - /// - private void UpdateAtomicObjectLookupWithModifiedIds(Dictionary> originalToModifiedIds) - { - // Build updated entries first to avoid modifying collection during iteration - var entriesToAdd = new List>(); - var keysToRemove = new List(); - - foreach (var kvp in _atomicObjectToParentDataObject) - { - if (originalToModifiedIds.TryGetValue(kvp.Key, out var modifiedIds)) - { - keysToRemove.Add(kvp.Key); - foreach (var modifiedId in modifiedIds) - { - entriesToAdd.Add(new(modifiedId, kvp.Value)); - } - } - } - - foreach (var key in keysToRemove) - { - _atomicObjectToParentDataObject.Remove(key); - } - - foreach (var entry in entriesToAdd) - { - _atomicObjectToParentDataObject[entry.Key] = entry.Value; - } + return ( + new HostObjectBuilderResult(mergedBakedObjectIds, mergedConversionResults), + currentResults.postBakePaintTargets + ); } private Autodesk.Revit.DB.Transform? CalculateNewTransform( @@ -357,6 +270,7 @@ public sealed class RevitHostObjectBuilder( List<(DirectShape res, string applicationId)> postBakePaintTargets ) BakeObjects( IReadOnlyCollection localToGlobalMaps, + Dictionary parentDataObjectMap, IProgress onOperationProgressed, CancellationToken cancellationToken ) @@ -383,7 +297,7 @@ public sealed class RevitHostObjectBuilder( DataObject? parentDataObject = null; if (atomicId is not null) { - _atomicObjectToParentDataObject.TryGetValue(atomicId, out parentDataObject); + parentDataObjectMap.TryGetValue(atomicId, out parentDataObject); } // direct shape creation happens here @@ -417,6 +331,7 @@ public sealed class RevitHostObjectBuilder( conversionResults.Add(new(Status.ERROR, localToGlobalMap.AtomicObject, null, null, ex)); } } + return (new(bakedObjectIds, conversionResults), postBakePaintTargets); } @@ -458,13 +373,12 @@ public sealed class RevitHostObjectBuilder( { DirectShapeLibrary.GetDirectShapeLibrary(converterSettings.Current.Document).Reset(); // Note: this needs to be cleared, as it is being used in the converter - revitToHostCacheSingleton.MaterialsByObjectId.Clear(); // Massive hack! - _atomicObjectToParentDataObject.Clear(); + revitToHostCacheSingleton.Clear(); // "Massive hack!" - Anonymous. Ogu and Björn: it looks legit groupManager.PurgeGroups(baseGroupName); materialBaker.PurgeMaterials(baseGroupName); } - public void Dispose() => transactionManager?.Dispose(); + public void Dispose() => transactionManager.Dispose(); // NOTE: temp poc HACK! // this hack only works if we are only assuming one material applied to the solids inside DataObject displayValue. as soon as we have multiple solids with multiple materials it will break again. @@ -482,6 +396,7 @@ public sealed class RevitHostObjectBuilder( { SetSolidPostBakePaintTargets(item, directShapes, targets); } + break; } } diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitPreBakeSetupService.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitPreBakeSetupService.cs new file mode 100644 index 000000000..1aa27af9c --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitPreBakeSetupService.cs @@ -0,0 +1,149 @@ +using Speckle.Connectors.Common.Instances; +using Speckle.Connectors.Common.Operations.Receive; +using Speckle.Connectors.Revit.HostApp; +using Speckle.Converters.RevitShared.Helpers; +using Speckle.DoubleNumerics; +using Speckle.Objects; +using Speckle.Objects.Data; +using Speckle.Sdk.Models; +using Transform = Speckle.Objects.Other.Transform; + +namespace Speckle.Connectors.Revit.Operations.Receive; + +public class RevitPreBakeSetupService +{ + private readonly ITransactionManager _transactionManager; + private readonly RevitMaterialBaker _materialBaker; + private readonly RevitViewBaker _viewBaker; + private readonly RevitToHostCacheSingleton _revitToHostCacheSingleton; + + public RevitPreBakeSetupService( + ITransactionManager transactionManager, + RevitMaterialBaker materialBaker, + RevitViewBaker viewBaker, + RevitToHostCacheSingleton revitToHostCacheSingleton + ) + { + _transactionManager = transactionManager; + _materialBaker = materialBaker; + _viewBaker = viewBaker; + _revitToHostCacheSingleton = revitToHostCacheSingleton; + } + + public void ApplyIdModificationsAndBakeMaterials( + UnpackStrategyResult unpackResult, + RootObjectUnpackerResult unpackedRoot + ) + { + Dictionary> originalToModifiedIds = new(); + + foreach (LocalToGlobalMap localToGlobalMap in unpackResult.LocalToGlobalMaps) + { + if ( + localToGlobalMap.AtomicObject is ITransformable transformable + && localToGlobalMap.Matrix.Count > 0 + && localToGlobalMap.AtomicObject["units"] is string units + ) + { + var id = localToGlobalMap.AtomicObject.id; + var originalAppId = localToGlobalMap.AtomicObject.applicationId ?? id; + + ITransformable? newTransformable = null; + foreach (var mat in localToGlobalMap.Matrix) + { + transformable.TransformTo(new Transform() { matrix = mat, units = units }, out newTransformable); + transformable = newTransformable; + } + + localToGlobalMap.AtomicObject = (newTransformable as Base)!; + localToGlobalMap.AtomicObject.id = id; + + string modifiedAppId = $"{originalAppId}_{Guid.NewGuid().ToString("N")[..8]}"; + if (originalAppId != null) + { + if (!originalToModifiedIds.TryGetValue(originalAppId, out List? modifiedIds)) + { + modifiedIds = new List(); + originalToModifiedIds[originalAppId] = modifiedIds; + } + modifiedIds.Add(modifiedAppId); + } + + localToGlobalMap.AtomicObject.applicationId = modifiedAppId; + localToGlobalMap.Matrix = new HashSet(); + } + } + + if (unpackedRoot.RenderMaterialProxies != null) + { + foreach (var proxy in unpackedRoot.RenderMaterialProxies) + { + var objectIdsToUse = new List(); + foreach (var objectId in proxy.objects) + { + if (originalToModifiedIds.TryGetValue(objectId, out var modifiedIds)) + { + objectIdsToUse.AddRange(modifiedIds); + } + else + { + objectIdsToUse.Add(objectId); + } + } + proxy.objects = objectIdsToUse; + } + } + + UpdateAtomicObjectLookupWithModifiedIds(unpackResult.ParentDataObjectMap, originalToModifiedIds); + + if (unpackedRoot.RenderMaterialProxies != null) + { + _transactionManager.StartTransaction(true, "Baking materials"); + _materialBaker.MapLayersRenderMaterials(unpackedRoot); + var map = _materialBaker.BakeMaterials(unpackedRoot.RenderMaterialProxies); + foreach (var kvp in map) + { + _revitToHostCacheSingleton.MaterialsByObjectId.Add(kvp.Key, kvp.Value); + } + _transactionManager.CommitTransaction(); + } + + if (unpackedRoot.Cameras is not null) + { + _transactionManager.StartTransaction(true, "Baking views"); + _viewBaker.BakeViews(unpackedRoot.Cameras); + _transactionManager.CommitTransaction(); + } + } + + private void UpdateAtomicObjectLookupWithModifiedIds( + Dictionary map, + Dictionary> originalToModifiedIds + ) + { + var entriesToAdd = new List>(); + var keysToRemove = new List(); + + foreach (var kvp in map) + { + if (originalToModifiedIds.TryGetValue(kvp.Key, out var modifiedIds)) + { + keysToRemove.Add(kvp.Key); + foreach (var modifiedId in modifiedIds) + { + entriesToAdd.Add(new KeyValuePair(modifiedId, kvp.Value)); + } + } + } + + foreach (var key in keysToRemove) + { + map.Remove(key); + } + + foreach (var entry in entriesToAdd) + { + map[entry.Key] = entry.Value; + } + } +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitUnpackStrategyBase.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitUnpackStrategyBase.cs new file mode 100644 index 000000000..622e36482 --- /dev/null +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/RevitUnpackStrategyBase.cs @@ -0,0 +1,75 @@ +using Speckle.Connectors.Common.Instances; +using Speckle.Connectors.Common.Operations.Receive; +using Speckle.Objects.Data; +using Speckle.Sdk.Common; +using Speckle.Sdk.Models.Instances; + +namespace Speckle.Connectors.Revit.Operations.Receive; + +public abstract class RevitUnpackStrategyBase : IRevitUnpackStrategy +{ + public abstract UnpackStrategyResult Unpack(RootObjectUnpackerResult unpackedRoot); + + /// + /// Builds a map of definition IDs and geometry IDs to their parent DataObject to preserve metadata. + /// + protected void PopulateParentDataObjectMap( + RootObjectUnpackerResult unpackedRoot, + Dictionary map, + HashSet? displayValueDefinitionIds = null + ) + { + var definitionToDataObject = new Dictionary(); + + foreach (var tc in unpackedRoot.ObjectsToConvert) + { + if (tc.Current is DataObject dataObject) + { + var instanceProxies = dataObject.displayValue.OfType().ToList(); + if (instanceProxies.Count > 0) + { + foreach (var ip in instanceProxies) + { + definitionToDataObject[ip.definitionId] = dataObject; + displayValueDefinitionIds?.Add(ip.definitionId); + } + } + } + } + + if (unpackedRoot.DefinitionProxies is not null) + { + foreach (var defProxy in unpackedRoot.DefinitionProxies) + { + var defId = defProxy.applicationId ?? defProxy.id.NotNull(); + if ( + definitionToDataObject.TryGetValue(defId, out var parentDataObject) + || (defProxy.id != null && definitionToDataObject.TryGetValue(defProxy.id, out parentDataObject)) + ) + { + foreach (var objectId in defProxy.objects) + { + map[objectId] = parentDataObject; + } + } + } + } + } + + /// + /// Removes DataObjects that use InstanceProxies as display values from the map list. + /// Their geometries are already flattened, and this prevents the geometry converter from crashing. + /// + protected IReadOnlyCollection FilterUnpackedDataObjects( + IReadOnlyCollection maps + ) => + maps.Where(map => + { + if (map.AtomicObject is DataObject dataObject && dataObject.displayValue.Any(dv => dv is InstanceProxy)) + { + return false; + } + return true; + }) + .ToList(); +} diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/ToHostSettingsManager.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/ToHostSettingsManager.cs index 0a11d5d1f..2f4907a48 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/ToHostSettingsManager.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Receive/ToHostSettingsManager.cs @@ -50,6 +50,25 @@ public class ToHostSettingsManager : IToHostSettingsManager return null; } + public bool GetReceiveInstancesAsFamiliesSetting(ModelCard modelCard) + { + var settingValue = + modelCard.Settings?.FirstOrDefault(s => s.Id == ReceiveInstancesAsFamiliesSetting.SETTING_ID)?.Value as bool?; + + if (settingValue is not null) + { + return settingValue.Value; + } + + _logger.LogWarning( + "Receive instances as families setting was null for model {ModelCardId}, using default: {DefaultValue}", + modelCard.ModelCardId, + ReceiveInstancesAsFamiliesSetting.DEFAULT_VALUE + ); + + return ReceiveInstancesAsFamiliesSetting.DEFAULT_VALUE; + } + private Transform? GetTransform(ReceiveReferencePointType referencePointType) { Transform? referencePointTransform = null; diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Send/Filters/RevitViewsFilter.cs b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Send/Filters/RevitViewsFilter.cs index 882cceb37..a49c36a6a 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Send/Filters/RevitViewsFilter.cs +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Operations/Send/Filters/RevitViewsFilter.cs @@ -82,11 +82,10 @@ public class RevitViewsFilter : DiscriminatedObject, ISendFilter, IRevitSendFilt IEnumerable elementsInView = GetFilteredElementsForView(document, view); - // NOTE: FilteredElementCollector() includes sweeps and reveals from a wall family's definition and includes them as additional objects - // on this return. displayValue for Wall already includes these, therefore we end up with duplicate elements on wall sweeps - // related to [CNX-1482](https://linear.app/speckle/issue/CNX-1482/wall-sweeps-published-duplicated) - // i (björn) noticed that all these elements have an empty string as Name parameter, hence below exclusion. tested as much as possible, seems like legit fix - var objectIds = elementsInView.Where(e => !string.IsNullOrEmpty(e.Name)).Select(e => e.UniqueId).ToList(); + // Filter out wall sweep/reveal sub-elements with empty names to avoid duplicates (CNX-1482). + // Only these specific categories are excluded — other unnamed elements like steel connections + // must be kept (CNX-3130). + var objectIds = elementsInView.Where(e => !IsEmptyNameWallSubElement(e)).Select(e => e.UniqueId).ToList(); // we need the view uniqueId among the objectIds // to expire the modelCards with viewFilters when the user changes category visibility // a change in category visibility will trigger DocChangeHandler in RevitSendBinding @@ -176,4 +175,21 @@ public class RevitViewsFilter : DiscriminatedObject, ISendFilter, IRevitSendFilt return allElements; } + + /// + /// Detects wall sweep/reveal sub-elements that have empty names when returned by the + /// view-scoped FilteredElementCollector. These are duplicates of geometry already included + /// in the parent wall's displayValue. + /// See CNX-1482. + /// + private static bool IsEmptyNameWallSubElement(Element e) + { + if (!string.IsNullOrEmpty(e.Name)) + { + return false; + } + + var bic = e.Category?.GetBuiltInCategory(); + return bic is BuiltInCategory.OST_Cornices or BuiltInCategory.OST_Reveals; + } } diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2022/Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2022/Generic Model.rft new file mode 100644 index 000000000..b8f04fb4e Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2022/Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2022/Metric Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2022/Metric Generic Model.rft new file mode 100644 index 000000000..b68c3da6c Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2022/Metric Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2023/Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2023/Generic Model.rft new file mode 100644 index 000000000..dc58ad088 Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2023/Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2023/Metric Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2023/Metric Generic Model.rft new file mode 100644 index 000000000..4ec7c3a6e Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2023/Metric Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2024/Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2024/Generic Model.rft new file mode 100644 index 000000000..12651aadb Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2024/Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2024/Metric Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2024/Metric Generic Model.rft new file mode 100644 index 000000000..c1e96b345 Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2024/Metric Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2025/Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2025/Generic Model.rft new file mode 100644 index 000000000..33988076d Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2025/Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2025/Metric Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2025/Metric Generic Model.rft new file mode 100644 index 000000000..95b5c2bc9 Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2025/Metric Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2026/Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2026/Generic Model.rft new file mode 100644 index 000000000..df44c8ec8 Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2026/Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2026/Metric Generic Model.rft b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2026/Metric Generic Model.rft new file mode 100644 index 000000000..7ea41a4f1 Binary files /dev/null and b/Connectors/Revit/Speckle.Connectors.RevitShared/Resources/Templates/2026/Metric Generic Model.rft differ diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Speckle.Connectors.RevitShared.projitems b/Connectors/Revit/Speckle.Connectors.RevitShared/Speckle.Connectors.RevitShared.projitems index f0d300bfd..c40a5ebdf 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/Speckle.Connectors.RevitShared.projitems +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Speckle.Connectors.RevitShared.projitems @@ -21,13 +21,20 @@ + + + + + + + @@ -37,9 +44,13 @@ + + + + @@ -63,4 +74,10 @@ + + + PreserveNewest + Resources\Templates\$(RevitVersion)\%(RecursiveDir)%(FileName)%(Extension) + + \ No newline at end of file diff --git a/Connectors/Revit/Speckle.Connectors.RevitShared/Speckle.Connectors.RevitShared.shproj b/Connectors/Revit/Speckle.Connectors.RevitShared/Speckle.Connectors.RevitShared.shproj index e6073eb4d..a1ef2e09e 100644 --- a/Connectors/Revit/Speckle.Connectors.RevitShared/Speckle.Connectors.RevitShared.shproj +++ b/Connectors/Revit/Speckle.Connectors.RevitShared/Speckle.Connectors.RevitShared.shproj @@ -10,4 +10,4 @@ - \ No newline at end of file + diff --git a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Objects/SpeckleDataObjectPassthrough.cs b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Objects/SpeckleDataObjectPassthrough.cs index 983c88d8b..f70583ae5 100644 --- a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Objects/SpeckleDataObjectPassthrough.cs +++ b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Objects/SpeckleDataObjectPassthrough.cs @@ -104,9 +104,19 @@ public class SpeckleDataObjectPassthrough() } List inputGeometry = new(); - if (!da.GetDataList(1, inputGeometry) && result == null) + bool hasGeometries = da.GetDataList(1, inputGeometry); + + string? inputName = null; + da.GetData(2, ref inputName); + + SpecklePropertyGroupGoo? inputProperties = null; + da.GetData(3, ref inputProperties); + + bool hasAppId = TryGetApplicationIdInput(da, out string? inputAppId); + + if (result == null && !hasGeometries && inputName == null && inputProperties == null && !hasAppId) { - AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Pass in a Speckle DataObject or Geometries"); + AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Pass in a DataObject or at least one input."); return; } @@ -119,19 +129,25 @@ public class SpeckleDataObjectPassthrough() } } - string? inputName = null; - da.GetData(2, ref inputName); - - SpecklePropertyGroupGoo? inputProperties = null; - da.GetData(3, ref inputProperties); - // process geometry if (result == null) { result = new SpeckleDataObjectWrapperGoo().Value; } - if (inputGeometry.Count > 0) + // process name first (geometry loop must use the final name) + if (inputName != null) + { + result.Name = inputName; + } + + // process properties first (geometry loop must use the final properties) + if (inputProperties != null) + { + result.Properties = inputProperties; + } + + if (hasGeometries) { result.Geometries.Clear(); foreach (var inputGeo in inputGeometry) @@ -148,21 +164,18 @@ public class SpeckleDataObjectPassthrough() result.Geometries.Add(mutatingGeo); } } - - // process name - if (inputName != null) + else if (inputName != null || inputProperties != null) { - result.Name = inputName; - } - - // process properties - if (inputProperties != null) - { - result.Properties = inputProperties; + // keep existing geometries in sync when only name/properties are overridden + foreach (var geo in result.Geometries) + { + geo.Base[Constants.NAME_PROP] = result.Name; + geo.Properties = result.Properties; + } } // process application id (only if user provided one) - if (TryGetApplicationIdInput(da, out string? inputAppId)) + if (hasAppId) { result.ApplicationId = inputAppId; } diff --git a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/AccountManagerComponent.cs b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/AccountManagerComponent.cs index 1319837f6..5f35ae81b 100644 --- a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/AccountManagerComponent.cs +++ b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/AccountManagerComponent.cs @@ -36,13 +36,14 @@ public class AccountManagerComponent : GH_Component, IDisposable ComponentCategories.OPERATIONS ) { - Attributes = new AccountManagerComponentAttributes(this); _accountManager = PriorityLoader.Container.GetRequiredService(); Accounts = _accountManager.GetAccounts().ToList(); SignInButton = new GhContextMenuButton("Sign In", "Sign In", "Click to sign into Speckle account.", AuthFlow); } + public override void CreateAttributes() => m_attributes = new AccountManagerComponentAttributes(this); + private bool AuthFlow(ToolStripDropDown menu) { _isAddingAccount = true; diff --git a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/Receive/ReceiveAsyncComponent.cs b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/Receive/ReceiveAsyncComponent.cs index 8cf6318d6..2aa2573f9 100644 --- a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/Receive/ReceiveAsyncComponent.cs +++ b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/Receive/ReceiveAsyncComponent.cs @@ -32,9 +32,10 @@ public class ReceiveAsyncComponent : GH_AsyncComponent : base("Load", "L", "Load a model from Speckle", ComponentCategories.PRIMARY_RIBBON, ComponentCategories.OPERATIONS) { BaseWorker = new ReceiveComponentWorker(this); - Attributes = new ReceiveAsyncComponentAttributes(this); } + public override void CreateAttributes() => m_attributes = new ReceiveAsyncComponentAttributes(this); + public override Guid ComponentGuid => GetType().GUID; protected override Bitmap Icon => Resources.speckle_operations_load; @@ -535,19 +536,11 @@ public sealed class ReceiveComponentWorker : WorkerInstance _selected; - set => _selected = value; - } - protected override void Layout() { base.Layout(); diff --git a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/Send/SendAsyncComponent.cs b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/Send/SendAsyncComponent.cs index 0427a66e4..3a4c24984 100644 --- a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/Send/SendAsyncComponent.cs +++ b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/Send/SendAsyncComponent.cs @@ -35,9 +35,10 @@ public class SendAsyncComponent : GH_AsyncComponent ) { BaseWorker = new SendComponentWorker(this); - Attributes = new SendAsyncComponentAttributes(this); } + public override void CreateAttributes() => m_attributes = new SendAsyncComponentAttributes(this); + public override Guid ComponentGuid => GetType().GUID; protected override Bitmap Icon => Resources.speckle_operations_publish; @@ -477,19 +478,11 @@ public class SendComponentWorker : WorkerInstance public class SendAsyncComponentAttributes : GH_ComponentAttributes { - private bool _selected; - public SendAsyncComponentAttributes(GH_Component owner) : base(owner) { } private Rectangle ButtonBounds { get; set; } - public override bool Selected - { - get => _selected; - set => _selected = value; - } - protected override void Layout() { base.Layout(); diff --git a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/SpeckleSelectModelComponent.cs b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/SpeckleSelectModelComponent.cs index 60faeaa1c..b45156ffa 100644 --- a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/SpeckleSelectModelComponent.cs +++ b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Components/Operations/SpeckleSelectModelComponent.cs @@ -43,7 +43,6 @@ public class SpeckleSelectModelComponent : GH_Component ComponentCategories.OPERATIONS ) { - Attributes = new SpeckleSelectModelComponentAttributes(this); SpeckleOperationWizard = new SpeckleOperationWizard(RefreshComponent, UpdateComponentMessage, false); WorkspaceContextMenuButton = SpeckleOperationWizard.WorkspaceMenuHandler.WorkspaceContextMenuButton; @@ -52,6 +51,8 @@ public class SpeckleSelectModelComponent : GH_Component VersionContextMenuButton = SpeckleOperationWizard!.VersionMenuHandler!.VersionContextMenuButton; // TODO: fix this shit later when we split } + public override void CreateAttributes() => m_attributes = new SpeckleSelectModelComponentAttributes(this); + private Task RefreshComponent() { ExpireSolution(true); diff --git a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Operations/Receive/LocalToGlobalMapHandler.cs b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Operations/Receive/LocalToGlobalMapHandler.cs index 3f7ac4f2b..86ea65235 100644 --- a/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Operations/Receive/LocalToGlobalMapHandler.cs +++ b/Connectors/Rhino/Speckle.Connectors.GrasshopperShared/Operations/Receive/LocalToGlobalMapHandler.cs @@ -140,13 +140,7 @@ internal sealed class LocalToGlobalMapHandler _materialUnpacker ); - // nothing converted - nothing to do - if (converted.Count == 0) - { - return; - } - - // handle normal DataObject (has converted geometry) + // handle all DataObjects if (obj is DataObject normalDataObject) { var geometries = ConvertToGeometryWrappers(converted); @@ -156,6 +150,12 @@ internal sealed class LocalToGlobalMapHandler return; } + // nothing converted - nothing to do (for non-DataObjects) + if (converted.Count == 0) + { + return; + } + // handle normal geometry (not DataObject) SpecklePropertyGroupGoo propertyGroup = new(); if (obj[Constants.PROPERTIES_PROP] is Dictionary props) diff --git a/Connectors/Rhino/Speckle.Connectors.RhinoShared/Bindings/RhinoMapperBinding.cs b/Connectors/Rhino/Speckle.Connectors.RhinoShared/Bindings/RhinoMapperBinding.cs index be63a6f1f..912de10a0 100644 --- a/Connectors/Rhino/Speckle.Connectors.RhinoShared/Bindings/RhinoMapperBinding.cs +++ b/Connectors/Rhino/Speckle.Connectors.RhinoShared/Bindings/RhinoMapperBinding.cs @@ -92,36 +92,105 @@ public class RhinoMapperBinding : IBinding /// /// Assigns selected objects to a specific Revit category. /// + /// + /// If block instance is selected, mapping is applied uniformly to all instances of that block definition in the doc. + /// public void AssignObjectsToCategory(string[] objectIds, string categoryValue) { + var objectsToModify = new HashSet(); + var processedDefinitions = new HashSet(); // Tracks unique block definitions + foreach (var objectIdString in objectIds) { - // NOTE: should we be checking if key already exists? - // For POC, straightforward set on object var rhinoObject = _rhinoObjectHelper.GetRhinoObject(objectIdString); - var attrs = rhinoObject?.Attributes.Duplicate(); - attrs?.SetUserString(RevitMappingConstants.CATEGORY_USER_STRING_KEY, categoryValue); - RhinoDoc.ActiveDoc.Objects.ModifyAttributes(rhinoObject, attrs, true); + switch (rhinoObject) + { + case null: + continue; + case InstanceObject instanceObj: + { + var defIndex = instanceObj.InstanceDefinition.Index; + + // HashSet.Add returns true only if the index wasn't already in the set. + // we only want to fetch and loop through siblings once per definition. + if (processedDefinitions.Add(defIndex)) + { + var siblingInstances = instanceObj.InstanceDefinition.GetReferences(0); + foreach (var sibling in siblingInstances) + { + objectsToModify.Add(sibling); + } + } + + break; + } + default: + objectsToModify.Add(rhinoObject); + break; + } } - // Trigger single update after all changes + // Apply the mapping uniformly to all collected objects + foreach (var obj in objectsToModify) + { + var attrs = obj.Attributes.Duplicate(); + attrs.SetUserString(RevitMappingConstants.CATEGORY_USER_STRING_KEY, categoryValue); + RhinoDoc.ActiveDoc.Objects.ModifyAttributes(obj, attrs, true); + } + + // Trigger single UI update _idleManager.SubscribeToIdle(nameof(NotifyMappingsChanged), NotifyMappingsChanged); } /// /// Removes category assignments from specific objects. /// + /// + /// If block instance is selected, assignment is cleared uniformly from all instances of that block definition in the doc. + /// public void ClearObjectsCategoryAssignment(string[] objectIds) { + var objectsToModify = new HashSet(); + var processedDefinitions = new HashSet(); // Tracks unique block definitions + foreach (var objectIdString in objectIds) { var rhinoObject = _rhinoObjectHelper.GetRhinoObject(objectIdString); - var attrs = rhinoObject?.Attributes.Duplicate(); - attrs?.DeleteUserString(RevitMappingConstants.CATEGORY_USER_STRING_KEY); - RhinoDoc.ActiveDoc.Objects.ModifyAttributes(rhinoObject, attrs, true); + switch (rhinoObject) + { + case null: + continue; + case InstanceObject instanceObj: + { + var defIndex = instanceObj.InstanceDefinition.Index; + + // Deduplicate definition processing + if (processedDefinitions.Add(defIndex)) + { + var siblingInstances = instanceObj.InstanceDefinition.GetReferences(0); + foreach (var sibling in siblingInstances) + { + objectsToModify.Add(sibling); + } + } + + break; + } + default: + objectsToModify.Add(rhinoObject); + break; + } } - // Trigger single update after all changes + // Clear the mapping from all collected objects + foreach (var obj in objectsToModify) + { + var attrs = obj.Attributes.Duplicate(); + attrs.DeleteUserString(RevitMappingConstants.CATEGORY_USER_STRING_KEY); + RhinoDoc.ActiveDoc.Objects.ModifyAttributes(obj, attrs, true); + } + + // Trigger single UI update _idleManager.SubscribeToIdle(nameof(NotifyMappingsChanged), NotifyMappingsChanged); } diff --git a/Connectors/Rhino/Speckle.Connectors.RhinoShared/Operations/Send/RhinoRootObjectBuilder.cs b/Connectors/Rhino/Speckle.Connectors.RhinoShared/Operations/Send/RhinoRootObjectBuilder.cs index 491c06c12..8394ec6c5 100644 --- a/Connectors/Rhino/Speckle.Connectors.RhinoShared/Operations/Send/RhinoRootObjectBuilder.cs +++ b/Connectors/Rhino/Speckle.Connectors.RhinoShared/Operations/Send/RhinoRootObjectBuilder.cs @@ -86,7 +86,7 @@ public class RhinoRootObjectBuilder : IRootObjectBuilder unpackResults = _instanceUnpacker.UnpackSelection(rhinoObjects); } - var (atomicObjects, instanceProxies, instanceDefinitionProxies) = unpackResults; + var (atomicObjects, atomicDefinitionObjectIds, instanceProxies, instanceDefinitionProxies) = unpackResults; // POC: we should formalise this, sooner or later - or somehow fix it a bit more rootObjectCollection[ProxyKeys.INSTANCE_DEFINITION] = instanceDefinitionProxies; // this won't work re traversal on receive diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/AutocadConversionSettings.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/AutocadConversionSettings.cs index 093f92e9b..7add8edff 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/AutocadConversionSettings.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/AutocadConversionSettings.cs @@ -1,3 +1,3 @@ -namespace Speckle.Converters.Autocad; +namespace Speckle.Converters.Autocad; -public record AutocadConversionSettings(Document Document, string SpeckleUnits); +public record AutocadConversionSettings(Document Document, AG.Matrix3d? ReferencePointTransform, string SpeckleUnits); diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/AutocadConversionSettingsFactory.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/AutocadConversionSettingsFactory.cs index 08b4d4a68..433139174 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/AutocadConversionSettingsFactory.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/AutocadConversionSettingsFactory.cs @@ -1,4 +1,4 @@ -using Speckle.Converters.Common; +using Speckle.Converters.Common; using Speckle.InterfaceGenerator; namespace Speckle.Converters.Autocad; @@ -7,6 +7,12 @@ namespace Speckle.Converters.Autocad; public class AutocadConversionSettingsFactory(IHostToSpeckleUnitConverter unitsConverter) : IAutocadConversionSettingsFactory { - public AutocadConversionSettings Create(Document document) => - new(document, unitsConverter.ConvertOrThrow(document.Database.Insunits)); + public AutocadConversionSettings Create(Document document) + { + AG.Matrix3d? m = + document.Editor.CurrentUserCoordinateSystem == AG.Matrix3d.Identity + ? null + : document.Editor.CurrentUserCoordinateSystem; + return new(document, m, unitsConverter.ConvertOrThrow(document.Database.Insunits)); + } } diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/Extensions/ListExtensions.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/Extensions/ListExtensions.cs index 99595f357..add433011 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/Extensions/ListExtensions.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/Extensions/ListExtensions.cs @@ -2,34 +2,6 @@ namespace Speckle.Converters.Autocad.Extensions; public static class ListExtensions { - public static SOG.Polyline ConvertToSpecklePolyline(this List pointList, string speckleUnits) - { - // throw if list is malformed - if (pointList.Count % 3 != 0) - { - throw new ArgumentException("Point list of xyz values is malformed", nameof(pointList)); - } - - return new() { value = pointList, units = speckleUnits }; - } - - public static List ConvertToPoint2d(this List pointList, double conversionFactor = 1) - { - // throw if list is malformed - if (pointList.Count % 2 != 0) - { - throw new ArgumentException("Point list of xy values is malformed", nameof(pointList)); - } - - List points2d = new(pointList.Count / 2); - for (int i = 1; i < pointList.Count; i += 2) - { - points2d.Add(new AG.Point2d(pointList[i - 1] * conversionFactor, pointList[i] * conversionFactor)); - } - - return points2d; - } - public static List ConvertToPoint3d(this List pointList, double conversionFactor = 1) { // throw if list is malformed @@ -52,4 +24,18 @@ public static class ListExtensions return points3d; } + + /// + /// Converts a list of doubles to Point3d objects and transforms them to OCS (Object Coordinate System) + /// based on the provided normal vector + /// + public static List ConvertToPoint3dInOcs( + this List pointList, + AG.Vector3d normal, + double conversionFactor = 1 + ) + { + AG.Matrix3d matrixOcs = AG.Matrix3d.WorldToPlane(normal); + return pointList.ConvertToPoint3d(conversionFactor).Select(p => p.TransformBy(matrixOcs)).ToList(); + } } diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/Helpers/ReferencePointHelper.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/Helpers/ReferencePointHelper.cs new file mode 100644 index 000000000..c0b34a98b --- /dev/null +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/Helpers/ReferencePointHelper.cs @@ -0,0 +1,42 @@ +namespace Speckle.Converters.Autocad.Helpers; + +/// +/// Helper class for working with reference points +/// +public static class ReferencePointHelper +{ + public const string REFERENCE_POINT_TRANSFORM_KEY = "referencePointTransform"; + + /// + /// Changes Autocad Matrix3d Transform to a double array. + /// Uses a 16-element column-major matrix representation. See https://speckle.guide/dev/objects.html + /// + public static Dictionary CreateTransformDataForRootObject(AG.Matrix3d transform) + { + return new Dictionary + { + { + "transform", // TODO: it would also be nice to include the key-value pair for reference point type as a string + new[] + { + transform.CoordinateSystem3d.Xaxis.X, + transform.CoordinateSystem3d.Xaxis.Y, + transform.CoordinateSystem3d.Xaxis.Z, + 0, + transform.CoordinateSystem3d.Yaxis.X, + transform.CoordinateSystem3d.Yaxis.Y, + transform.CoordinateSystem3d.Yaxis.Z, + 0, + transform.CoordinateSystem3d.Zaxis.X, + transform.CoordinateSystem3d.Zaxis.Y, + transform.CoordinateSystem3d.Zaxis.Z, + 0, + transform.CoordinateSystem3d.Origin.X, + transform.CoordinateSystem3d.Origin.Y, + transform.CoordinateSystem3d.Origin.Z, + 1 + } + } + }; + } +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/Helpers/TransformHelper.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/Helpers/TransformHelper.cs new file mode 100644 index 000000000..9a2d48237 --- /dev/null +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/Helpers/TransformHelper.cs @@ -0,0 +1,73 @@ +using Speckle.DoubleNumerics; + +namespace Speckle.Converters.Autocad.Helpers; + +/// +/// Helper class for working with transforms +/// +public static class TransformHelper +{ + /// + /// Converts an AutoCAD matrix3d to a row-dominant Speckle Matrix4x4 + /// + /// + /// + /// + /// Use for System Numerics operations, eg matrix and vector multiplication + /// + public static Matrix4x4 ConvertToMatrix4x4(AG.Matrix3d m) => + new( + m[0, 0], + m[1, 0], + m[2, 0], + m[3, 0], + m[0, 1], + m[1, 1], + m[2, 1], + m[3, 1], + m[0, 2], + m[1, 2], + m[2, 2], + m[3, 2], + m[0, 3], + m[1, 3], + m[2, 3], + m[3, 3] + ); + + /// + /// Speckle Instances use a transform that is column-dominant, not row dominant. + /// + /// + /// + /// Use only for Speckle Instance object transforms. + public static Matrix4x4 ConvertToInstanceMatrix4x4(AG.Matrix3d m) => + new( + m[0, 0], + m[0, 1], + m[0, 2], + m[0, 3], + m[1, 0], + m[1, 1], + m[1, 2], + m[1, 3], + m[2, 0], + m[2, 1], + m[2, 2], + m[2, 3], + m[3, 0], + m[3, 1], + m[3, 2], + m[3, 3] + ); + + /// + /// Get the transform matrix from an entity's OCS to the WCS + /// + /// + /// + /// + /// Use this method for certain properties or methods on entities that return values in OCS + /// + public static AG.Matrix3d GetTransformFromOCSToWCS(AG.Vector3d normal) => AG.Matrix3d.WorldToPlane(normal); +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/IReferencePointConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/IReferencePointConverter.cs new file mode 100644 index 000000000..d114b5ced --- /dev/null +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/IReferencePointConverter.cs @@ -0,0 +1,33 @@ +namespace Speckle.Converters.Autocad; + +public interface IReferencePointConverter +{ + /// + /// Converts a list of doubles representing point3ds in WCS coordinates to the current active coordinate system + /// + /// + /// + List ConvertWCSDoublesToExternalCoordinates(List d); + + /// + /// Converts a Point in WCS coordinates to the current active coordinate system + /// + /// + /// + AG.Point3d ConvertWCSPointToExternalCoordinates(AG.Point3d p); + + /// + /// Converts a Vector in WCS coordinates to the current active coordinate system + /// + /// + /// + AG.Vector3d ConvertWCSVectorToExternalCoordinates(AG.Vector3d v); + + /// + /// Converts an elevation in OCS coordinates to the current active coordinate system + /// + /// elevation in OCS + /// OCS plane normal in WCS + /// + double ConvertOCSElevationDoubleToExternalCoordinates(double e, AG.Vector3d normal); +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ReferencePointConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ReferencePointConverter.cs new file mode 100644 index 000000000..33fef2814 --- /dev/null +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ReferencePointConverter.cs @@ -0,0 +1,74 @@ +using Speckle.Converters.Autocad.Helpers; +using Speckle.Converters.Common; +using Speckle.DoubleNumerics; + +namespace Speckle.Converters.Autocad; + +/// +/// POC: reference point functionality needs to be revisited (we are currently baking in these transforms into all geometry using the point and vector converters, and losing the transform). +/// This converter uses the transform from the converter settings (from the current doc) +/// +public class ReferencePointConverter(IConverterSettingsStore converterSettings) + : IReferencePointConverter +{ + public List ConvertWCSDoublesToExternalCoordinates(List d) + { + if (d.Count % 3 != 0) + { + throw new ArgumentException("Point list of xyz values is malformed", nameof(d)); + } + + if (converterSettings.Current.ReferencePointTransform is AG.Matrix3d m) + { + Matrix4x4 transform = TransformHelper.ConvertToMatrix4x4(m.Inverse()); + + var transformed = new List(d.Count); + + for (int i = 0; i < d.Count; i += 3) + { + Vector3 p = Vector3.Transform(new(d[i], d[i + 1], d[i + 2]), transform); + + transformed.Add(p.X); + transformed.Add(p.Y); + transformed.Add(p.Z); + } + + return transformed; + } + + return d; + } + + public AG.Point3d ConvertWCSPointToExternalCoordinates(AG.Point3d p) + { + if (converterSettings.Current.ReferencePointTransform is AG.Matrix3d transform) + { + return p.TransformBy(transform.Inverse()); + } + + return p; + } + + public AG.Vector3d ConvertWCSVectorToExternalCoordinates(AG.Vector3d v) + { + if (converterSettings.Current.ReferencePointTransform is AG.Matrix3d transform) + { + return v.TransformBy(transform.Inverse()); + } + + return v; + } + + public double ConvertOCSElevationDoubleToExternalCoordinates(double elevation, AG.Vector3d normal) + { + // get a point on the plane in WCS + AG.Point3d wcsPoint = AG.Point3d.Origin + normal * elevation; + + // transform to external coords + AG.Point3d extPoint = ConvertWCSPointToExternalCoordinates(wcsPoint); + AG.Vector3d extNormal = ConvertWCSVectorToExternalCoordinates(normal); + + // calculate elevation as perpendicular distance in external coords + return extPoint.GetAsVector().DotProduct(extNormal); + } +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ServiceRegistration.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ServiceRegistration.cs index e748b49a4..adc447336 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ServiceRegistration.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ServiceRegistration.cs @@ -26,6 +26,8 @@ public static class ServiceRegistration >(); serviceCollection.AddMatchingInterfacesAsTransient(Assembly.GetExecutingAssembly()); + serviceCollection.AddScoped(); + // add other classes serviceCollection.AddScoped(); serviceCollection.AddScoped(); diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/Speckle.Converters.AutocadShared.projitems b/Converters/Autocad/Speckle.Converters.AutocadShared/Speckle.Converters.AutocadShared.projitems index cfe3ceade..2808e48d3 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/Speckle.Converters.AutocadShared.projitems +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/Speckle.Converters.AutocadShared.projitems @@ -1,4 +1,4 @@ - + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) @@ -16,6 +16,10 @@ + + + + @@ -54,6 +58,7 @@ + @@ -62,6 +67,7 @@ + @@ -80,7 +86,6 @@ - @@ -88,9 +93,11 @@ - + + + - + diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Geometry/AutocadPolycurveToHostConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Geometry/AutocadPolycurveToHostConverter.cs index 65a3028b5..96df3782b 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Geometry/AutocadPolycurveToHostConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Geometry/AutocadPolycurveToHostConverter.cs @@ -11,16 +11,19 @@ public class AutocadPolycurveToHostConverter : IToHostTopLevelConverter private readonly ITypedConverter _polylineConverter; private readonly ITypedConverter _polyline2dConverter; private readonly ITypedConverter _polyline3dConverter; + private readonly ITypedConverter> _polycurveConverter; public AutocadPolycurveToHostConverter( ITypedConverter polylineConverter, ITypedConverter polyline2dConverter, - ITypedConverter polyline3dConverter + ITypedConverter polyline3dConverter, + ITypedConverter> polycurveConverter ) { _polylineConverter = polylineConverter; _polyline2dConverter = polyline2dConverter; _polyline3dConverter = polyline3dConverter; + _polycurveConverter = polycurveConverter; } public object Convert(Base target) @@ -30,7 +33,7 @@ public class AutocadPolycurveToHostConverter : IToHostTopLevelConverter switch (polycurve.polyType) { case SOG.Autocad.AutocadPolyType.Light: - return _polylineConverter.Convert(polycurve); + return Has2DValue(polycurve) ? _polycurveConverter.Convert(polycurve) : _polylineConverter.Convert(polycurve); case SOG.Autocad.AutocadPolyType.Simple2d: case SOG.Autocad.AutocadPolyType.FitCurve2d: @@ -47,4 +50,29 @@ public class AutocadPolycurveToHostConverter : IToHostTopLevelConverter throw new ValidationException("Unknown poly type for AutocadPolycurve"); } } + + // Method for backwards compatibility: polylines from 3.10 and before had point2d values in OCS instead of point3d values in WCS/UCS + private bool Has2DValue(SOG.Autocad.AutocadPolycurve polycurve) + { + int pointListCount = polycurve.value.Count; + if (pointListCount % 3 == 0 && pointListCount % 2 != 0) + { + return false; + } + + if (pointListCount % 2 != 0) + { + throw new ValidationException( + "Polycurve value list was deformed, could not translate into 2d or 3d coordinates." + ); + } + + int segmentVertexCount = polycurve.closed ? polycurve.segments.Count : polycurve.segments.Count + 1; + if (pointListCount / 2 == segmentVertexCount) + { + return true; + } + + return false; + } } diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Raw/AutocadPolycurveToHostPolyline2dRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Raw/AutocadPolycurveToHostPolyline2dRawConverter.cs index b3ad64154..6c986d336 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Raw/AutocadPolycurveToHostPolyline2dRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Raw/AutocadPolycurveToHostPolyline2dRawConverter.cs @@ -26,33 +26,33 @@ public class AutocadPolycurveToHostPolyline2dRawConverter // check for normal if (target.normal is not SOG.Vector normal) { - throw new System.ArgumentException($"Autocad polycurve of type {target.polyType} did not have a normal"); + throw new ArgumentException($"Autocad polycurve of type {target.polyType} did not have a normal"); } // check for elevation if (target.elevation is not double elevation) { - throw new System.ArgumentException($"Autocad polycurve of type {target.polyType} did not have an elevation"); + throw new ArgumentException($"Autocad polycurve of type {target.polyType} did not have an elevation"); } - // get vertices + // convert the normal, get vertices and transform them to ocs + var convertedNormal = _vectorConverter.Convert(normal); double f = Units.GetConversionFactor(target.units, _settingsStore.Current.SpeckleUnits); - List points = target.value.ConvertToPoint3d(f); + List points = target.value.ConvertToPoint3dInOcs(convertedNormal, f); // check for invalid bulges if (target.bulges is null || target.bulges.Count < points.Count) { - throw new System.ArgumentException($"Autocad polycurve of type {target.polyType} had null or malformed bulges"); + throw new ArgumentException($"Autocad polycurve of type {target.polyType} had null or malformed bulges"); } // check for invalid tangents if (target.tangents is null || target.tangents.Count < points.Count) { - throw new System.ArgumentException($"Autocad polycurve of type {target.polyType} had null or malformed tangents"); + throw new ArgumentException($"Autocad polycurve of type {target.polyType} had null or malformed tangents"); } // create the polyline2d using the empty constructor - AG.Vector3d convertedNormal = _vectorConverter.Convert(normal); double convertedElevation = elevation * f; ADB.Polyline2d polyline = new() diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Raw/AutocadPolycurveToHostPolylineRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Raw/AutocadPolycurveToHostPolylineRawConverter.cs index dff137087..e05430e6f 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Raw/AutocadPolycurveToHostPolylineRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToHost/Raw/AutocadPolycurveToHostPolylineRawConverter.cs @@ -24,26 +24,26 @@ public class AutocadPolycurveToHostPolylineRawConverter : ITypedConverter points2d = target.value.ConvertToPoint2d(f); + List points3d = target.value.ConvertToPoint3dInOcs(normal, f); ADB.Polyline polyline = new() { - Normal = _vectorConverter.Convert(target.normal), + Normal = normal, Elevation = (double)target.elevation * f, Closed = target.closed }; - for (int i = 0; i < points2d.Count; i++) + for (int i = 0; i < points3d.Count; i++) { var bulge = target.bulges is null ? 0 : target.bulges[i]; - polyline.AddVertexAt(i, points2d[i], bulge, 0, 0); + polyline.AddVertexAt(i, new(points3d[i].X, points3d[i].Y), bulge, 0, 0); } return polyline; diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/PolyfaceMeshToSpeckleConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/PolyfaceMeshToSpeckleConverter.cs index a8d23bbef..679498076 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/PolyfaceMeshToSpeckleConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/PolyfaceMeshToSpeckleConverter.cs @@ -1,4 +1,3 @@ -using Autodesk.AutoCAD.Geometry; using Speckle.Converters.Common; using Speckle.Converters.Common.Objects; using Speckle.Sdk.Models; @@ -14,18 +13,15 @@ namespace Speckle.Converters.Autocad.Geometry; [NameAndRankValue(typeof(ADB.PolyFaceMesh), NameAndRankValueAttribute.SPECKLE_DEFAULT_RANK)] public class DBPolyfaceMeshToSpeckleConverter : IToSpeckleTopLevelConverter { - private readonly ITypedConverter _pointConverter; - private readonly ITypedConverter _boxConverter; + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; public DBPolyfaceMeshToSpeckleConverter( - ITypedConverter pointConverter, - ITypedConverter boxConverter, + IReferencePointConverter referencePointConverter, IConverterSettingsStore settingsStore ) { - _pointConverter = pointConverter; - _boxConverter = boxConverter; + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -33,7 +29,7 @@ public class DBPolyfaceMeshToSpeckleConverter : IToSpeckleTopLevelConverter public SOG.Mesh RawConvert(ADB.PolyFaceMesh target) { - List dbVertices = new(); + List vertices = new(); List faces = new(); List faceVisibility = new(); List colors = new(); @@ -45,7 +41,9 @@ public class DBPolyfaceMeshToSpeckleConverter : IToSpeckleTopLevelConverter switch (obj) { case ADB.PolyFaceMeshVertex o: - dbVertices.Add(o.Position); + vertices.Add(o.Position.X); + vertices.Add(o.Position.Y); + vertices.Add(o.Position.Z); colors.Add(o.Color.ColorValue.ToArgb()); break; case ADB.FaceRecord o: @@ -84,22 +82,13 @@ public class DBPolyfaceMeshToSpeckleConverter : IToSpeckleTopLevelConverter tr.Commit(); } - List vertices = new(dbVertices.Count * 3); - foreach (Point3d vert in dbVertices) - { - vertices.AddRange(_pointConverter.Convert(vert).ToList()); - } - - SOG.Box bbox = _boxConverter.Convert(target.GeometricExtents); - SOG.Mesh speckleMesh = new() { - vertices = vertices, + vertices = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(vertices), // transform by reference point faces = faces, colors = colors, units = _settingsStore.Current.SpeckleUnits, - bbox = bbox, ["faceVisibility"] = faceVisibility }; diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/Polyline2dToSpeckleConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/Polyline2dToSpeckleConverter.cs index e6cdfe890..1b73a5a50 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/Polyline2dToSpeckleConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/Polyline2dToSpeckleConverter.cs @@ -19,30 +19,30 @@ public class Polyline2dToSpeckleConverter : IToSpeckleTopLevelConverter, ITypedConverter { + private readonly ITypedConverter, SOG.Polyline> _doublesConverter; private readonly ITypedConverter _arcConverter; private readonly ITypedConverter _lineConverter; - private readonly ITypedConverter _polylineConverter; private readonly ITypedConverter _splineConverter; private readonly ITypedConverter _vectorConverter; - private readonly ITypedConverter _boxConverter; + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; public Polyline2dToSpeckleConverter( + ITypedConverter, SOG.Polyline> doublesConverter, ITypedConverter arcConverter, ITypedConverter lineConverter, - ITypedConverter polylineConverter, ITypedConverter splineConverter, ITypedConverter vectorConverter, - ITypedConverter boxConverter, + IReferencePointConverter referencePointConverter, IConverterSettingsStore settingsStore ) { + _doublesConverter = doublesConverter; _arcConverter = arcConverter; _lineConverter = lineConverter; - _polylineConverter = polylineConverter; _splineConverter = splineConverter; _vectorConverter = vectorConverter; - _boxConverter = boxConverter; + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -85,11 +85,13 @@ public class Polyline2dToSpeckleConverter for (int i = 0; i < vertices.Count; i++) { - ADB.Vertex2d vertex = vertices[i]; + ADB.Vertex2d vertex = vertices[i]; // this is in OCS // get vertex value in the Global Coordinate System (GCS). - // NOTE: for some reason, the z value of the position for rotated polyline2ds doesn't seem to match the exploded segment endpoint values - value.AddRange(vertex.Position.ToArray()); + AG.Point3d vertexGCS = target.VertexPosition(vertex); + value.Add(vertexGCS.X); + value.Add(vertexGCS.Y); + value.Add(vertexGCS.Z); // get the bulge and tangent bulges.Add(vertex.Bulge); @@ -160,31 +162,31 @@ public class Polyline2dToSpeckleConverter if (isSpline) { SOG.Curve spline = _splineConverter.Convert(target.Spline); - SOG.Polyline displayValue = segmentValues.ConvertToSpecklePolyline(_settingsStore.Current.SpeckleUnits); - if (displayValue != null) - { - spline.displayValue = displayValue; - } - + spline.displayValue = _doublesConverter.Convert(segmentValues); segments.Add(spline); } - SOG.Vector normal = _vectorConverter.Convert(target.Normal); - SOG.Box bbox = _boxConverter.Convert(target.GeometricExtents); + SOG.Vector normal = _vectorConverter.Convert(target.Normal); // wcs + + // get the elevation transformed by ucs + double elevation = _referencePointConverter.ConvertOCSElevationDoubleToExternalCoordinates( + target.Elevation, + target.Normal + ); + SOG.Autocad.AutocadPolycurve polycurve = new() { segments = segments, - value = value, + value = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(value), // convert with reference point bulges = bulges, tangents = tangents, normal = normal, - elevation = target.Elevation, + elevation = elevation, polyType = polyType, closed = target.Closed, length = target.Length, area = target.Area, - bbox = bbox, units = _settingsStore.Current.SpeckleUnits }; diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/Polyline3dToSpeckleConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/Polyline3dToSpeckleConverter.cs index 76218142d..43a8e00ab 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/Polyline3dToSpeckleConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/Polyline3dToSpeckleConverter.cs @@ -18,21 +18,21 @@ public class Polyline3dToSpeckleConverter : IToSpeckleTopLevelConverter, ITypedConverter { - private readonly ITypedConverter _pointConverter; + private readonly ITypedConverter, SOG.Polyline> _doublesConverter; private readonly ITypedConverter _splineConverter; - private readonly ITypedConverter _boxConverter; + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; public Polyline3dToSpeckleConverter( - ITypedConverter pointConverter, + ITypedConverter, SOG.Polyline> doublesConverter, ITypedConverter splineConverter, - ITypedConverter boxConverter, + IReferencePointConverter referencePointConverter, IConverterSettingsStore settingsStore ) { - _pointConverter = pointConverter; + _doublesConverter = doublesConverter; _splineConverter = splineConverter; - _boxConverter = boxConverter; + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -56,7 +56,6 @@ public class Polyline3dToSpeckleConverter } // get all vertex data except control vertices - List value = new(); List vertices = target .GetSubEntities( ADB.OpenMode.ForRead, @@ -64,10 +63,13 @@ public class Polyline3dToSpeckleConverter ) .Where(e => e.VertexType != ADB.Vertex3dType.FitVertex) // Do not collect fit vertex points, they are not used for creation .ToList(); + List value = new(vertices.Count * 3); for (int i = 0; i < vertices.Count; i++) { // vertex value is in the Global Coordinate System (GCS). - value.AddRange(vertices[i].Position.ToArray()); + value.Add(vertices[i].Position.X); + value.Add(vertices[i].Position.Y); + value.Add(vertices[i].Position.Z); } List segments = new(); @@ -94,18 +96,15 @@ public class Polyline3dToSpeckleConverter } } - SOG.Polyline displayValue = segmentValues.ConvertToSpecklePolyline(_settingsStore.Current.SpeckleUnits); - if (displayValue != null) - { - spline.displayValue = displayValue; - } + // set displayValue of spline + spline.displayValue = _doublesConverter.Convert(segmentValues); segments.Add(spline); } // for simple polyline3ds just get the polyline segment from the value else { - SOG.Polyline polyline = value.ConvertToSpecklePolyline(_settingsStore.Current.SpeckleUnits); + SOG.Polyline polyline = _doublesConverter.Convert(value); if (target.Closed) { polyline.closed = true; @@ -114,8 +113,6 @@ public class Polyline3dToSpeckleConverter segments.Add(polyline); } - SOG.Box bbox = _boxConverter.Convert(target.GeometricExtents); - SOG.Autocad.AutocadPolycurve polycurve = new() { @@ -123,11 +120,10 @@ public class Polyline3dToSpeckleConverter bulges = null, tangents = null, normal = null, - value = value, + value = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(value), // convert with reference point polyType = polyType, closed = target.Closed, length = target.Length, - bbox = bbox, units = _settingsStore.Current.SpeckleUnits }; diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/PolylineToSpeckleConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/PolylineToSpeckleConverter.cs index da89a945b..6ad5630bd 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/PolylineToSpeckleConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/PolylineToSpeckleConverter.cs @@ -17,22 +17,23 @@ public class PolylineToSpeckleConverter { private readonly ITypedConverter _lineConverter; private readonly ITypedConverter _arcConverter; + private readonly ITypedConverter _vectorConverter; - private readonly ITypedConverter _boxConverter; + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; public PolylineToSpeckleConverter( ITypedConverter lineConverter, ITypedConverter arcConverter, ITypedConverter vectorConverter, - ITypedConverter boxConverter, + IReferencePointConverter referencePointConverter, IConverterSettingsStore settingsStore ) { _lineConverter = lineConverter; _arcConverter = arcConverter; _vectorConverter = vectorConverter; - _boxConverter = boxConverter; + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -45,9 +46,11 @@ public class PolylineToSpeckleConverter List segments = new(); for (int i = 0; i < target.NumberOfVertices; i++) { - // get vertex value in the Object Coordinate System (OCS) - AG.Point2d vertex = target.GetPoint2dAt(i); - value.AddRange(vertex.ToArray()); + // get vertex value in the World Coordinate System (WCS) + AG.Point3d vertex = target.GetPoint3dAt(i); + value.Add(vertex.X); + value.Add(vertex.Y); + value.Add(vertex.Z); // get the bulge bulges.Add(target.GetBulgeAt(i)); @@ -71,22 +74,26 @@ public class PolylineToSpeckleConverter } SOG.Vector normal = _vectorConverter.Convert(target.Normal); - SOG.Box bbox = _boxConverter.Convert(target.GeometricExtents); + + // get the elevation transformed by ucs + double elevation = _referencePointConverter.ConvertOCSElevationDoubleToExternalCoordinates( + target.Elevation, + target.Normal + ); SOG.Autocad.AutocadPolycurve polycurve = new() { segments = segments, - value = value, + value = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(value), // convert with reference point bulges = bulges, normal = normal, tangents = null, - elevation = target.Elevation, + elevation = elevation, polyType = SOG.Autocad.AutocadPolyType.Light, closed = target.Closed, length = target.Length, area = target.Area, - bbox = bbox, units = _settingsStore.Current.SpeckleUnits }; diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/SubDMeshToSpeckleConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/SubDMeshToSpeckleConverter.cs index 608c31243..8514f4c93 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/SubDMeshToSpeckleConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Geometry/SubDMeshToSpeckleConverter.cs @@ -1,85 +1,20 @@ using Speckle.Converters.Common; using Speckle.Converters.Common.Objects; -using Speckle.Sdk; using Speckle.Sdk.Models; -namespace Speckle.Converters.Autocad.Geometry; +namespace Speckle.Converters.Autocad.ToSpeckle.Geometry; [NameAndRankValue(typeof(ADB.SubDMesh), NameAndRankValueAttribute.SPECKLE_DEFAULT_RANK)] -public class DBSubDMeshToSpeckleConverter : IToSpeckleTopLevelConverter +public class SubDMeshToSpeckleConverter : IToSpeckleTopLevelConverter { - private readonly IConverterSettingsStore _settingsStore; + private readonly ITypedConverter _subDMeshConverter; - public DBSubDMeshToSpeckleConverter(IConverterSettingsStore settingsStore) + public SubDMeshToSpeckleConverter(ITypedConverter subDMeshConverter) { - _settingsStore = settingsStore; + _subDMeshConverter = subDMeshConverter; } - public Base Convert(object target) => RawConvert((ADB.SubDMesh)target); + public Base Convert(object target) => Convert((ADB.SubDMesh)target); - public SOG.Mesh RawConvert(ADB.SubDMesh target) - { - //vertices - var vertices = new List(target.Vertices.Count * 3); - foreach (AG.Point3d vert in target.Vertices) - { - vertices.Add(vert.X); - vertices.Add(vert.Y); - vertices.Add(vert.Z); - } - - // faces - var faces = new List(); - int[] faceArr = target.FaceArray.ToArray(); // contains vertex indices - int edgeCount = 0; - for (int i = 0; i < faceArr.Length; i = i + edgeCount + 1) - { - List faceVertices = new(); - edgeCount = faceArr[i]; - for (int j = i + 1; j <= i + edgeCount; j++) - { - faceVertices.Add(faceArr[j]); - } - - if (edgeCount == 4) // quad face - { - faces.AddRange(new List { 4, faceVertices[0], faceVertices[1], faceVertices[2], faceVertices[3] }); - } - else // triangle face - { - faces.AddRange(new List { 3, faceVertices[0], faceVertices[1], faceVertices[2] }); - } - } - - // colors - var colors = target - .VertexColorArray.Select(o => - System - .Drawing.Color.FromArgb( - System.Convert.ToInt32(o.Red), - System.Convert.ToInt32(o.Green), - System.Convert.ToInt32(o.Blue) - ) - .ToArgb() - ) - .ToList(); - - SOG.Mesh speckleMesh = - new() - { - vertices = vertices, - faces = faces, - colors = colors, - units = _settingsStore.Current.SpeckleUnits, - area = target.ComputeSurfaceArea() - }; - - try - { - speckleMesh.volume = target.ComputeVolume(); - } - catch (Exception e) when (!e.IsFatal()) { } // for non-volumetric meshes - - return speckleMesh; - } + public SOG.Mesh Convert(ADB.SubDMesh target) => _subDMeshConverter.Convert(target); } diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/BrepToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/BrepToSpeckleRawConverter.cs index b97ed7727..fda77d849 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/BrepToSpeckleRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/BrepToSpeckleRawConverter.cs @@ -7,10 +7,15 @@ namespace Speckle.Converters.Autocad.ToSpeckle.Raw; public class BrepToSpeckleRawConverter : ITypedConverter { + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; - public BrepToSpeckleRawConverter(IConverterSettingsStore settingsStore) + public BrepToSpeckleRawConverter( + IReferencePointConverter referencePointConverter, + IConverterSettingsStore settingsStore + ) { + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -65,7 +70,7 @@ public class BrepToSpeckleRawConverter : ITypedConverter new() { faces = faces, - vertices = vertices, + vertices = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(vertices), // transform by reference point units = _settingsStore.Current.SpeckleUnits, area = target.GetSurfaceArea() }; diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/CircularArc2dToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/CircularArc2dToSpeckleRawConverter.cs index 5b16e80f6..39c474736 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/CircularArc2dToSpeckleRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/CircularArc2dToSpeckleRawConverter.cs @@ -5,14 +5,17 @@ namespace Speckle.Converters.Autocad.ToSpeckle.Raw; public class CircularArc2dToSpeckleRawConverter : ITypedConverter { + private readonly ITypedConverter _pointConverter; private readonly ITypedConverter _planeConverter; private readonly IConverterSettingsStore _settingsStore; public CircularArc2dToSpeckleRawConverter( + ITypedConverter pointConverter, ITypedConverter planeConverter, IConverterSettingsStore settingsStore ) { + _pointConverter = pointConverter; _planeConverter = planeConverter; _settingsStore = settingsStore; } @@ -35,27 +38,9 @@ public class CircularArc2dToSpeckleRawConverter : ITypedConverter { private readonly ITypedConverter _pointConverter; private readonly ITypedConverter _planeConverter; - private readonly ITypedConverter _boxConverter; private readonly IConverterSettingsStore _settingsStore; public DBArcToSpeckleRawConverter( ITypedConverter pointConverter, ITypedConverter planeConverter, - ITypedConverter boxConverter, IConverterSettingsStore settingsStore ) { _pointConverter = pointConverter; _planeConverter = planeConverter; - _boxConverter = boxConverter; _settingsStore = settingsStore; } @@ -33,7 +30,6 @@ public class DBArcToSpeckleRawConverter : ITypedConverter SOG.Point end = _pointConverter.Convert(target.EndPoint); SOG.Point mid = _pointConverter.Convert(target.GetPointAtDist(target.Length / 2.0)); SOP.Interval domain = new() { start = target.StartParam, end = target.EndParam }; - SOG.Box bbox = _boxConverter.Convert(target.GeometricExtents); SOG.Arc arc = new() @@ -43,7 +39,6 @@ public class DBArcToSpeckleRawConverter : ITypedConverter endPoint = end, midPoint = mid, domain = domain, - bbox = bbox, units = _settingsStore.Current.SpeckleUnits }; diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBCircleToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBCircleToSpeckleRawConverter.cs index 7d63f6ee8..b84bd4e9b 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBCircleToSpeckleRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBCircleToSpeckleRawConverter.cs @@ -7,17 +7,14 @@ namespace Speckle.Converters.Autocad.ToSpeckle.Raw; public class DBCircleToSpeckleRawConverter : ITypedConverter { private readonly ITypedConverter _planeConverter; - private readonly ITypedConverter _boxConverter; private readonly IConverterSettingsStore _settingsStore; public DBCircleToSpeckleRawConverter( ITypedConverter planeConverter, - ITypedConverter boxConverter, IConverterSettingsStore settingsStore ) { _planeConverter = planeConverter; - _boxConverter = boxConverter; _settingsStore = settingsStore; } @@ -26,14 +23,12 @@ public class DBCircleToSpeckleRawConverter : ITypedConverter _circleConverter; private readonly ITypedConverter _ellipseConverter; private readonly ITypedConverter _splineConverter; - private readonly IConverterSettingsStore _settingsStore; public DBCurveToSpeckleRawConverter( ITypedConverter lineConverter, @@ -25,8 +23,7 @@ public class DBCurveToSpeckleRawConverter : ITypedConverter arcConverter, ITypedConverter circleConverter, ITypedConverter ellipseConverter, - ITypedConverter splineConverter, - IConverterSettingsStore settingsStore + ITypedConverter splineConverter ) { _lineConverter = lineConverter; @@ -37,7 +34,6 @@ public class DBCurveToSpeckleRawConverter : ITypedConverter diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBEllipseToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBEllipseToSpeckleRawConverter.cs index 39acc0a66..9dc8ac5bd 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBEllipseToSpeckleRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBEllipseToSpeckleRawConverter.cs @@ -6,18 +6,18 @@ namespace Speckle.Converters.Autocad.ToSpeckle.Raw; public class DBEllipseToSpeckleRawConverter : ITypedConverter { - private readonly ITypedConverter _planeConverter; - private readonly ITypedConverter _boxConverter; + private readonly ITypedConverter _pointConverter; + private readonly ITypedConverter _vectorConverter; private readonly IConverterSettingsStore _settingsStore; public DBEllipseToSpeckleRawConverter( - ITypedConverter planeConverter, - ITypedConverter boxConverter, + ITypedConverter pointConverter, + ITypedConverter vectorConverter, IConverterSettingsStore settingsStore ) { - _planeConverter = planeConverter; - _boxConverter = boxConverter; + _pointConverter = pointConverter; + _vectorConverter = vectorConverter; _settingsStore = settingsStore; } @@ -25,8 +25,15 @@ public class DBEllipseToSpeckleRawConverter : ITypedConverter { private readonly ITypedConverter _pointConverter; - private readonly ITypedConverter _boxConverter; private readonly IConverterSettingsStore _settingsStore; public DBLineToSpeckleRawConverter( ITypedConverter pointConverter, - ITypedConverter boxConverter, IConverterSettingsStore settingsStore ) { _pointConverter = pointConverter; - _boxConverter = boxConverter; _settingsStore = settingsStore; } @@ -28,8 +25,7 @@ public class DBLineToSpeckleRawConverter : ITypedConverter { start = _pointConverter.Convert(target.StartPoint), end = _pointConverter.Convert(target.EndPoint), - units = _settingsStore.Current.SpeckleUnits, domain = new SOP.Interval { start = 0, end = target.Length }, - bbox = _boxConverter.Convert(target.GeometricExtents) + units = _settingsStore.Current.SpeckleUnits }; } diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBSplineToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBSplineToSpeckleRawConverter.cs index 608da74b8..41d5bb5dc 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBSplineToSpeckleRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBSplineToSpeckleRawConverter.cs @@ -8,18 +8,21 @@ namespace Speckle.Converters.Autocad.ToSpeckle.Raw; public class DBSplineToSpeckleRawConverter : ITypedConverter { + private readonly ITypedConverter, SOG.Polyline> _doublesConverter; private readonly ITypedConverter _intervalConverter; - private readonly ITypedConverter _boxConverter; + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; public DBSplineToSpeckleRawConverter( + ITypedConverter, SOG.Polyline> doublesConverter, ITypedConverter intervalConverter, - ITypedConverter boxConverter, + IReferencePointConverter referencePointConverter, IConverterSettingsStore settingsStore ) { + _doublesConverter = doublesConverter; _intervalConverter = intervalConverter; - _boxConverter = boxConverter; + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -44,11 +47,11 @@ public class DBSplineToSpeckleRawConverter : ITypedConverter points = new(); foreach (Point3d point in data.GetControlPoints().OfType()) { - points.Add(point); + points.Add(_referencePointConverter.ConvertWCSPointToExternalCoordinates(point)); } // NOTE: for closed periodic splines, autocad does not track last #degree points. @@ -108,7 +111,6 @@ public class DBSplineToSpeckleRawConverter : ITypedConverter +{ + private readonly IReferencePointConverter _referencePointConverter; + private readonly IConverterSettingsStore _settingsStore; + + public DBSubDMeshToSpeckleRawConverter( + IReferencePointConverter referencePointConverter, + IConverterSettingsStore settingsStore + ) + { + _referencePointConverter = referencePointConverter; + _settingsStore = settingsStore; + } + + public SOG.Mesh Convert(ADB.SubDMesh target) + { + // vertices + List vertices = new(target.Vertices.Count * 3); + foreach (AG.Point3d vert in target.Vertices) + { + vertices.Add(vert.X); + vertices.Add(vert.Y); + vertices.Add(vert.Z); + } + + // faces + List faces = new(); + int[] faceArr = target.FaceArray.ToArray(); // contains vertex indices + int edgeCount = 0; + for (int i = 0; i < faceArr.Length; i = i + edgeCount + 1) + { + List faceVertices = new(); + edgeCount = faceArr[i]; + for (int j = i + 1; j <= i + edgeCount; j++) + { + faceVertices.Add(faceArr[j]); + } + + if (edgeCount == 4) // quad face + { + faces.AddRange(new List { 4, faceVertices[0], faceVertices[1], faceVertices[2], faceVertices[3] }); + } + else // triangle face + { + faces.AddRange(new List { 3, faceVertices[0], faceVertices[1], faceVertices[2] }); + } + } + + // colors + var colors = target + .VertexColorArray.Select(o => + System + .Drawing.Color.FromArgb( + System.Convert.ToInt32(o.Red), + System.Convert.ToInt32(o.Green), + System.Convert.ToInt32(o.Blue) + ) + .ToArgb() + ) + .ToList(); + + SOG.Mesh speckleMesh = + new() + { + vertices = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(vertices), // transform with reference point + faces = faces, + colors = colors, + units = _settingsStore.Current.SpeckleUnits, + area = target.ComputeSurfaceArea() + }; + + try + { + speckleMesh.volume = target.ComputeVolume(); + } + catch (Exception e) when (!e.IsFatal()) { } // for non-volumetric meshes + + return speckleMesh; + } +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBTextToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBTextToSpeckleRawConverter.cs index e245808f3..f14fb7e41 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBTextToSpeckleRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DBTextToSpeckleRawConverter.cs @@ -1,3 +1,4 @@ +using Speckle.Converters.Autocad.Helpers; using Speckle.Converters.Common; using Speckle.Converters.Common.Objects; using Speckle.Objects.Annotation; @@ -7,17 +8,17 @@ namespace Speckle.Converters.Autocad.ToSpeckle.Raw; public class DBTextToSpeckleRawConverter : ITypedConverter { private readonly ITypedConverter _pointConverter; - private readonly ITypedConverter _planeConverter; + private readonly ITypedConverter _vectorConverter; private readonly IConverterSettingsStore _settingsStore; public DBTextToSpeckleRawConverter( ITypedConverter pointConverter, - ITypedConverter planeConverter, + ITypedConverter vectorConverter, IConverterSettingsStore settingsStore ) { _pointConverter = pointConverter; - _planeConverter = planeConverter; + _vectorConverter = vectorConverter; _settingsStore = settingsStore; } @@ -41,15 +42,24 @@ public class DBTextToSpeckleRawConverter : ITypedConverter units = _settingsStore.Current.SpeckleUnits }; + // For DBText, the following properties are stored in: + // - Position: WCS + // - Normal: WCS + // - Rotation: OCS -> WCS https://help.autodesk.com/view/OARX/2020/ENU/?guid=OARX-ManagedRefGuide-Autodesk_AutoCAD_DatabaseServices_DBText_Rotation private SOG.Plane GetTextPlane(ADB.DBText target) { - AG.Plane plane = new(target.Position, target.Normal); + // Rotation prop is in OCS: calculate the x and y axis based in WCS + AG.Matrix3d transform = TransformHelper.GetTransformFromOCSToWCS(target.Normal).Inverse(); + AG.Vector3d xDir = AG.Vector3d.XAxis.RotateBy(target.Rotation, target.Normal).TransformBy(transform); + AG.Vector3d yDir = AG.Vector3d.YAxis.RotateBy(target.Rotation, target.Normal).TransformBy(transform); - if (target.Rotation != 0) + return new() { - plane.RotateBy(target.Rotation, target.Normal, target.Position); - } - - return _planeConverter.Convert(plane); + origin = _pointConverter.Convert(target.Position), + normal = _vectorConverter.Convert(target.Normal), + xdir = _vectorConverter.Convert(xDir), + ydir = _vectorConverter.Convert(yDir), + units = _settingsStore.Current.SpeckleUnits, + }; } } diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DoublesToSpecklePolylineRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DoublesToSpecklePolylineRawConverter.cs new file mode 100644 index 000000000..c041ff39d --- /dev/null +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/DoublesToSpecklePolylineRawConverter.cs @@ -0,0 +1,32 @@ +using Speckle.Converters.Common; +using Speckle.Converters.Common.Objects; + +namespace Speckle.Converters.Autocad.ToSpeckle.Raw; + +public class DoublesToSpeckleRawConverter : ITypedConverter, SOG.Polyline> +{ + private readonly IReferencePointConverter _referencePointConverter; + private readonly IConverterSettingsStore _settingsStore; + + public DoublesToSpeckleRawConverter( + IConverterSettingsStore settingsStore, + IReferencePointConverter referencePointConverter + ) + { + _settingsStore = settingsStore; + _referencePointConverter = referencePointConverter; + } + + public SOG.Polyline Convert(List target) + { + // throw if list is malformed + if (target.Count % 3 != 0) + { + throw new ArgumentException("Point list of xyz values is malformed", nameof(target)); + } + + List value = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(target); + + return new() { value = value, units = _settingsStore.Current.SpeckleUnits }; + } +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/MTextToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/MTextToSpeckleRawConverter.cs index d4a55addc..e163f39c0 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/MTextToSpeckleRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/MTextToSpeckleRawConverter.cs @@ -6,17 +6,17 @@ namespace Speckle.Converters.Autocad.ToSpeckle.Raw; public class MTextToSpeckleRawConverter : ITypedConverter { private readonly ITypedConverter _pointConverter; - private readonly ITypedConverter _planeConverter; + private readonly ITypedConverter _vectorConverter; private readonly IConverterSettingsStore _settingsStore; public MTextToSpeckleRawConverter( ITypedConverter pointConverter, - ITypedConverter planeConverter, + ITypedConverter vectorConverter, IConverterSettingsStore settingsStore ) { _pointConverter = pointConverter; - _planeConverter = planeConverter; + _vectorConverter = vectorConverter; _settingsStore = settingsStore; } @@ -38,16 +38,28 @@ public class MTextToSpeckleRawConverter : ITypedConverter units = _settingsStore.Current.SpeckleUnits }; + // For MText, the following properties are stored in: + // - Position: WCS + // - Normal: WCS?? + // - Rotation: OCS -> UCS?? https://help.autodesk.com/view/OARX/2020/ENU/?guid=OARX-ManagedRefGuide-Autodesk_AutoCAD_DatabaseServices_MText_Rotation + // "Accesses the angle between the X axis of the OCS for the normal vector of the current AutoCAD editor's UCS + // and the projection of the MText object's direction vector onto the plane of the AutoCAD editor's current UCS." + // - Direction: WCS + // "Note that the direction vector need not be orthogonal to the normal vector." <- do not use FML private SOG.Plane GetTextPlane(ADB.MText target) { - AG.Plane plane = new(target.Location, target.Normal); + // Rotation prop is in UCS already: do NOT use vector converter or it will transform again! + AG.Vector3d xDir = AG.Vector3d.XAxis.RotateBy(target.Rotation, target.Normal); + AG.Vector3d yDir = AG.Vector3d.YAxis.RotateBy(target.Rotation, target.Normal); - if (target.Rotation != 0) + return new() { - plane.RotateBy(target.Rotation, target.Normal, target.Location); - } - - return _planeConverter.Convert(plane); + origin = _pointConverter.Convert(target.Location), + normal = _vectorConverter.Convert(target.Normal), + xdir = new(xDir.X, xDir.Y, xDir.Z, _settingsStore.Current.SpeckleUnits), + ydir = new(yDir.X, yDir.Y, yDir.Z, _settingsStore.Current.SpeckleUnits), + units = _settingsStore.Current.SpeckleUnits, + }; } /// diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/PlaneToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/PlaneToSpeckleRawConverter.cs index 6a24731ed..1b1377d1e 100644 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/PlaneToSpeckleRawConverter.cs +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/PlaneToSpeckleRawConverter.cs @@ -23,13 +23,16 @@ public class PlaneToSpeckleRawConverter : ITypedConverter public Base Convert(object target) => Convert((AG.Plane)target); - public SOG.Plane Convert(AG.Plane target) => - new() + public SOG.Plane Convert(AG.Plane target) + { + AG.CoordinateSystem3d cs = target.GetCoordinateSystem(); // TODO: validate if this returns the coordinate system in GCS or already transformed + return new() { origin = _pointConverter.Convert(target.PointOnPlane), normal = _vectorConverter.Convert(target.Normal), - xdir = _vectorConverter.Convert(target.GetCoordinateSystem().Xaxis), - ydir = _vectorConverter.Convert(target.GetCoordinateSystem().Yaxis), + xdir = _vectorConverter.Convert(cs.Xaxis), + ydir = _vectorConverter.Convert(cs.Yaxis), units = _settingsStore.Current.SpeckleUnits, }; + } } diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Point2dToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Point2dToSpeckleRawConverter.cs new file mode 100644 index 000000000..dd450d2b2 --- /dev/null +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Point2dToSpeckleRawConverter.cs @@ -0,0 +1,26 @@ +using Speckle.Converters.Common; +using Speckle.Converters.Common.Objects; + +namespace Speckle.Converters.Autocad.ToSpeckle.Raw; + +public class Point2dToSpeckleRawConverter : ITypedConverter +{ + private readonly IConverterSettingsStore _settingsStore; + private readonly IReferencePointConverter _referencePointConverter; + + public Point2dToSpeckleRawConverter( + IConverterSettingsStore settingsStore, + IReferencePointConverter referencePointConverter + ) + { + _settingsStore = settingsStore; + _referencePointConverter = referencePointConverter; + } + + public SOG.Point Convert(AG.Point2d target) + { + var extPt = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(new(3) { target.X, target.Y, 0 }); + + return new(extPt[0], extPt[1], extPt[2], _settingsStore.Current.SpeckleUnits); + } +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Point3dToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Point3dToSpeckleRawConverter.cs new file mode 100644 index 000000000..10118ea7e --- /dev/null +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Point3dToSpeckleRawConverter.cs @@ -0,0 +1,25 @@ +using Speckle.Converters.Common; +using Speckle.Converters.Common.Objects; + +namespace Speckle.Converters.Autocad.ToSpeckle.Raw; + +public class Point3dToSpeckleRawConverter : ITypedConverter +{ + private readonly IConverterSettingsStore _settingsStore; + private readonly IReferencePointConverter _referencePointConverter; + + public Point3dToSpeckleRawConverter( + IConverterSettingsStore settingsStore, + IReferencePointConverter referencePointConverter + ) + { + _settingsStore = settingsStore; + _referencePointConverter = referencePointConverter; + } + + public SOG.Point Convert(AG.Point3d target) + { + AG.Point3d extPt = _referencePointConverter.ConvertWCSPointToExternalCoordinates(target); + return new(extPt.X, extPt.Y, extPt.Z, _settingsStore.Current.SpeckleUnits); + } +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/PointToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/PointToSpeckleRawConverter.cs deleted file mode 100644 index a1e71fc87..000000000 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/PointToSpeckleRawConverter.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Speckle.Converters.Common; -using Speckle.Converters.Common.Objects; - -namespace Speckle.Converters.Autocad.ToSpeckle.Raw; - -public class PointToSpeckleRawConverter : ITypedConverter -{ - private readonly IConverterSettingsStore _settingsStore; - - public PointToSpeckleRawConverter(IConverterSettingsStore settingsStore) - { - _settingsStore = settingsStore; - } - - public SOG.Point Convert(AG.Point3d target) => new(target.X, target.Y, target.Z, _settingsStore.Current.SpeckleUnits); -} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Vector3dToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Vector3dToSpeckleRawConverter.cs new file mode 100644 index 000000000..817bcbcea --- /dev/null +++ b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/Vector3dToSpeckleRawConverter.cs @@ -0,0 +1,25 @@ +using Speckle.Converters.Common; +using Speckle.Converters.Common.Objects; + +namespace Speckle.Converters.Autocad.ToSpeckle.Raw; + +public class Vector3dToSpeckleRawConverter : ITypedConverter +{ + private readonly IConverterSettingsStore _settingsStore; + private readonly IReferencePointConverter _referencePointConverter; + + public Vector3dToSpeckleRawConverter( + IConverterSettingsStore settingsStore, + IReferencePointConverter referencePointConverter + ) + { + _settingsStore = settingsStore; + _referencePointConverter = referencePointConverter; + } + + public SOG.Vector Convert(AG.Vector3d target) + { + AG.Vector3d extVector = _referencePointConverter.ConvertWCSVectorToExternalCoordinates(target); + return new(extVector.X, extVector.Y, extVector.Z, _settingsStore.Current.SpeckleUnits); + } +} diff --git a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/VectorToSpeckleRawConverter.cs b/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/VectorToSpeckleRawConverter.cs deleted file mode 100644 index 6c9dddf68..000000000 --- a/Converters/Autocad/Speckle.Converters.AutocadShared/ToSpeckle/Raw/VectorToSpeckleRawConverter.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Speckle.Converters.Common; -using Speckle.Converters.Common.Objects; - -namespace Speckle.Converters.Autocad.ToSpeckle.Raw; - -public class VectorToSpeckleRawConverter : ITypedConverter -{ - private readonly IConverterSettingsStore _settingsStore; - - public VectorToSpeckleRawConverter(IConverterSettingsStore settingsStore) - { - _settingsStore = settingsStore; - } - - public SOG.Vector Convert(AG.Vector3d target) => - new(target.X, target.Y, target.Z, _settingsStore.Current.SpeckleUnits); -} diff --git a/Converters/Civil3d/Speckle.Converters.Civil3dShared/ServiceRegistration.cs b/Converters/Civil3d/Speckle.Converters.Civil3dShared/ServiceRegistration.cs index ef33264a0..bfcd4cfa1 100644 --- a/Converters/Civil3d/Speckle.Converters.Civil3dShared/ServiceRegistration.cs +++ b/Converters/Civil3d/Speckle.Converters.Civil3dShared/ServiceRegistration.cs @@ -34,6 +34,7 @@ public static class ServiceRegistration IConverterSettingsStore, ConverterSettingsStore >(); + serviceCollection.AddScoped(); // add other classes serviceCollection.AddScoped(); // for civil diff --git a/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/AlignmentSubentityArcToSpeckleRawConverter.cs b/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/AlignmentSubentityArcToSpeckleRawConverter.cs index 1bb7a4a4e..ca00e4bc4 100644 --- a/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/AlignmentSubentityArcToSpeckleRawConverter.cs +++ b/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/AlignmentSubentityArcToSpeckleRawConverter.cs @@ -6,14 +6,17 @@ namespace Speckle.Converters.Civil3dShared.ToSpeckle.Raw; public class AlignmentSubentityArcToSpeckleRawConverter : ITypedConverter { + private readonly ITypedConverter _pointConverter; private readonly ITypedConverter _planeConverter; private readonly IConverterSettingsStore _settingsStore; public AlignmentSubentityArcToSpeckleRawConverter( + ITypedConverter pointConverter, ITypedConverter planeConverter, IConverterSettingsStore settingsStore ) { + _pointConverter = pointConverter; _planeConverter = planeConverter; _settingsStore = settingsStore; } @@ -53,27 +56,9 @@ public class AlignmentSubentityArcToSpeckleRawConverter : ITypedConverter { private readonly IConverterSettingsStore _settingsStore; + private readonly ITypedConverter _pointConverter; - public AlignmentSubentityLineToSpeckleRawConverter(IConverterSettingsStore settingsStore) + public AlignmentSubentityLineToSpeckleRawConverter( + IConverterSettingsStore settingsStore, + ITypedConverter pointConverter + ) { _settingsStore = settingsStore; + _pointConverter = pointConverter; } public SOG.Line Convert(object target) => Convert((CDB.AlignmentSubEntityLine)target); public SOG.Line Convert(CDB.AlignmentSubEntityLine target) { - SOG.Point start = - new() - { - x = target.StartPoint.X, - y = target.StartPoint.Y, - z = 0, - units = _settingsStore.Current.SpeckleUnits - }; - - SOG.Point end = - new() - { - x = target.EndPoint.X, - y = target.EndPoint.Y, - z = 0, - units = _settingsStore.Current.SpeckleUnits - }; + SOG.Point start = _pointConverter.Convert(target.StartPoint); + SOG.Point end = _pointConverter.Convert(target.EndPoint); SOG.Line line = new() diff --git a/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/AlignmentSubentitySpiralToSpeckleRawConverter.cs b/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/AlignmentSubentitySpiralToSpeckleRawConverter.cs index 2a7f70b8a..0ec8a653b 100644 --- a/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/AlignmentSubentitySpiralToSpeckleRawConverter.cs +++ b/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/AlignmentSubentitySpiralToSpeckleRawConverter.cs @@ -1,3 +1,4 @@ +using Speckle.Converters.Autocad; using Speckle.Converters.Civil3dShared.Helpers; using Speckle.Converters.Common; using Speckle.Converters.Common.Objects; @@ -7,10 +8,15 @@ namespace Speckle.Converters.Civil3dShared.ToSpeckle.Raw; public class AlignmentSubentitySpiralToSpeckleRawConverter : ITypedConverter<(CDB.AlignmentSubEntitySpiral, CDB.Alignment), SOG.Polyline> { + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; - public AlignmentSubentitySpiralToSpeckleRawConverter(IConverterSettingsStore settingsStore) + public AlignmentSubentitySpiralToSpeckleRawConverter( + IReferencePointConverter referencePointConverter, + IConverterSettingsStore settingsStore + ) { + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -45,7 +51,7 @@ public class AlignmentSubentitySpiralToSpeckleRawConverter SOG.Polyline polyline = new() { - value = polylineValue, + value = _referencePointConverter.ConvertWCSDoublesToExternalCoordinates(polylineValue), // convert by ref point transform units = units, closed = spiral.StartPoint == spiral.EndPoint }; diff --git a/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/GridSurfaceToSpeckleMeshRawConverter.cs b/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/GridSurfaceToSpeckleMeshRawConverter.cs index 87f1637e1..de0bd426f 100644 --- a/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/GridSurfaceToSpeckleMeshRawConverter.cs +++ b/Converters/Civil3d/Speckle.Converters.Civil3dShared/ToSpeckle/Raw/GridSurfaceToSpeckleMeshRawConverter.cs @@ -1,4 +1,4 @@ -using Autodesk.AutoCAD.Geometry; +using Speckle.Converters.Autocad; using Speckle.Converters.Common; using Speckle.Converters.Common.Objects; @@ -6,10 +6,15 @@ namespace Speckle.Converters.Civil3dShared.ToSpeckle.Raw; public class GridSurfaceToSpeckleMeshRawConverter : ITypedConverter { + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; - public GridSurfaceToSpeckleMeshRawConverter(IConverterSettingsStore settingsStore) + public GridSurfaceToSpeckleMeshRawConverter( + IReferencePointConverter referencePointConverter, + IConverterSettingsStore settingsStore + ) { + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -19,14 +24,14 @@ public class GridSurfaceToSpeckleMeshRawConverter : ITypedConverter vertices = new(); List faces = new(); - Dictionary indices = new(); + Dictionary indices = new(); int indexCounter = 0; foreach (var cell in target.GetCells(false)) { try { - Point3d[] cellVertices = + AG.Point3d[] cellVertices = { cell.BottomLeftVertex.Location, cell.BottomRightVertex.Location, @@ -34,7 +39,7 @@ public class GridSurfaceToSpeckleMeshRawConverter : ITypedConverter { + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; - public Point3dCollectionToSpeckleRawConverter(IConverterSettingsStore settingsStore) + public Point3dCollectionToSpeckleRawConverter( + IReferencePointConverter referencePointConverter, + IConverterSettingsStore settingsStore + ) { + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -33,7 +39,7 @@ public class Point3dCollectionToSpeckleRawConverter : ITypedConverter { + private readonly IReferencePointConverter _referencePointConverter; private readonly IConverterSettingsStore _settingsStore; - public TinSurfaceToSpeckleMeshRawConverter(IConverterSettingsStore settingsStore) + public TinSurfaceToSpeckleMeshRawConverter( + IReferencePointConverter referencePointConverter, + IConverterSettingsStore settingsStore + ) { + _referencePointConverter = referencePointConverter; _settingsStore = settingsStore; } @@ -60,7 +66,7 @@ public class TinSurfaceToSpeckleMeshRawConverter : ITypedConverter +/// Responsible for extracting Revit BuiltInCategories. +/// +public sealed class CategoryExtractor +{ + public string? ExtractBuiltInCategory(DataObject? parentDataObject, Base atomicObject) + { + // Try parent DataObject first (for InstanceProxy displayValue case) + if (parentDataObject?.properties.TryGetValue("builtInCategory", out var cat) == true) + { + return cat?.ToString(); + } + + // Fallback to atomicObject properties + if ( + atomicObject["properties"] is Dictionary props + && props.TryGetValue("builtInCategory", out var fallbackCat) + ) + { + return fallbackCat?.ToString(); + } + + return null; + } +} diff --git a/Converters/Revit/Speckle.Converters.RevitShared/Helpers/DisplayValueExtractor.cs b/Converters/Revit/Speckle.Converters.RevitShared/Helpers/DisplayValueExtractor.cs index fe7aa1f79..0f193f587 100644 --- a/Converters/Revit/Speckle.Converters.RevitShared/Helpers/DisplayValueExtractor.cs +++ b/Converters/Revit/Speckle.Converters.RevitShared/Helpers/DisplayValueExtractor.cs @@ -68,6 +68,14 @@ public sealed class DisplayValueExtractor return [DisplayValueResult.WithoutTransform(GetCurveDisplayValue(modelCurve.GeometryCurve))]; case DB.Grid grid: return [DisplayValueResult.WithoutTransform(GetCurveDisplayValue(grid.Curve))]; + case DB.Architecture.Room room: + // api still returns geometry for unplaced rooms. + // return empty list so room object is sent but with null display value + if (room.Volume == 0) + { + return new List(); + } + return GetGeometryDisplayValue(room); case DB.Area area: return _converterSettings.Current.SendAreasAsMesh ? GetAreaMeshDisplayValue(area) diff --git a/Converters/Revit/Speckle.Converters.RevitShared/Helpers/RevitToHostCacheSingleton.cs b/Converters/Revit/Speckle.Converters.RevitShared/Helpers/RevitToHostCacheSingleton.cs index ae32f20e9..aceb05aab 100644 --- a/Converters/Revit/Speckle.Converters.RevitShared/Helpers/RevitToHostCacheSingleton.cs +++ b/Converters/Revit/Speckle.Converters.RevitShared/Helpers/RevitToHostCacheSingleton.cs @@ -9,4 +9,23 @@ public class RevitToHostCacheSingleton /// They needed to be set while creating "TessellatedFace". /// public Dictionary MaterialsByObjectId { get; } = new(); + + /// + /// Maps InstanceDefinitionProxy.applicationId to the created Revit Family. + /// Populated by RevitFamilyBaker during receive operations. + /// + public Dictionary FamiliesByDefinitionId { get; } = new(); + + /// + /// Maps InstanceDefinitionProxy.applicationId to the activated FamilySymbol (for placement). + /// Populated by RevitFamilyBaker during receive operations. + /// + public Dictionary SymbolsByDefinitionId { get; } = new(); + + public void Clear() + { + MaterialsByObjectId.Clear(); + FamiliesByDefinitionId.Clear(); + SymbolsByDefinitionId.Clear(); + } } diff --git a/Converters/Revit/Speckle.Converters.RevitShared/ServiceRegistration.cs b/Converters/Revit/Speckle.Converters.RevitShared/ServiceRegistration.cs index b6fa7e1b4..04d6c7137 100644 --- a/Converters/Revit/Speckle.Converters.RevitShared/ServiceRegistration.cs +++ b/Converters/Revit/Speckle.Converters.RevitShared/ServiceRegistration.cs @@ -54,6 +54,7 @@ public static class ServiceRegistration serviceCollection.AddScoped(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); + serviceCollection.AddSingleton(); return serviceCollection; } diff --git a/Converters/Revit/Speckle.Converters.RevitShared/Settings/RevitConversionSettings.cs b/Converters/Revit/Speckle.Converters.RevitShared/Settings/RevitConversionSettings.cs index 8889c8d2a..b5fafbcb8 100644 --- a/Converters/Revit/Speckle.Converters.RevitShared/Settings/RevitConversionSettings.cs +++ b/Converters/Revit/Speckle.Converters.RevitShared/Settings/RevitConversionSettings.cs @@ -1,4 +1,4 @@ -namespace Speckle.Converters.RevitShared.Settings; +namespace Speckle.Converters.RevitShared.Settings; public record RevitConversionSettings( DB.Document Document, @@ -9,5 +9,6 @@ public record RevitConversionSettings( bool SendLinkedModels, bool SendRebarsAsVolumetric, bool SendAreasAsMesh, + bool ReceiveInstancesAsFamilies, double Tolerance = 0.0164042 // 5mm in ft ); diff --git a/Converters/Revit/Speckle.Converters.RevitShared/Settings/RevitConversionSettingsFactory.cs b/Converters/Revit/Speckle.Converters.RevitShared/Settings/RevitConversionSettingsFactory.cs index 702b933e2..622b9b10c 100644 --- a/Converters/Revit/Speckle.Converters.RevitShared/Settings/RevitConversionSettingsFactory.cs +++ b/Converters/Revit/Speckle.Converters.RevitShared/Settings/RevitConversionSettingsFactory.cs @@ -1,4 +1,4 @@ -using Speckle.Converters.Common; +using Speckle.Converters.Common; using Speckle.Converters.RevitShared.Helpers; using Speckle.InterfaceGenerator; using Speckle.Sdk.Common; @@ -18,6 +18,7 @@ public class RevitConversionSettingsFactory( bool sendLinkedModels, bool sendRebarsAsVolumetric, bool sendAreasAsMesh, + bool receiveInstancesAsFamilies, double tolerance = 0.0164042 // 5mm in ft ) { @@ -31,6 +32,7 @@ public class RevitConversionSettingsFactory( sendLinkedModels, sendRebarsAsVolumetric, sendAreasAsMesh, + receiveInstancesAsFamilies, tolerance ); } diff --git a/Converters/Revit/Speckle.Converters.RevitShared/Speckle.Converters.RevitShared.projitems b/Converters/Revit/Speckle.Converters.RevitShared/Speckle.Converters.RevitShared.projitems index f8c273a8f..df5e6546b 100644 --- a/Converters/Revit/Speckle.Converters.RevitShared/Speckle.Converters.RevitShared.projitems +++ b/Converters/Revit/Speckle.Converters.RevitShared/Speckle.Converters.RevitShared.projitems @@ -9,6 +9,7 @@ Speckle.Converters.RevitShared + @@ -33,6 +34,7 @@ + diff --git a/Converters/Revit/Speckle.Converters.RevitShared/ToHost/Raw/Geometry/FreeformElementMeshToHostConverter.cs b/Converters/Revit/Speckle.Converters.RevitShared/ToHost/Raw/Geometry/FreeformElementMeshToHostConverter.cs new file mode 100644 index 000000000..0c1fe337b --- /dev/null +++ b/Converters/Revit/Speckle.Converters.RevitShared/ToHost/Raw/Geometry/FreeformElementMeshToHostConverter.cs @@ -0,0 +1,145 @@ +using Autodesk.Revit.DB; +using Microsoft.Extensions.Logging; +using Speckle.Converters.Common.Objects; +using Speckle.Converters.RevitShared.Services; + +namespace Speckle.Converters.RevitShared.ToHost.Raw.Geometry; + +/// +/// Converts a Speckle Mesh into a Revit GeometryObject (Solid or Mesh). +/// Specifically designed for Family creation (Freeform Elements) as it attempts to weld +/// vertices to form valid Solids, and ignores global project Reference Points. +/// +public class FreeformElementMeshToHostConverter : ITypedConverter +{ + private readonly ScalingServiceToHost _scalingService; + private readonly ILogger _logger; + + private const double WELD_TOLERANCE = 1e-4; + + public FreeformElementMeshToHostConverter( + ScalingServiceToHost scalingService, + ILogger logger + ) + { + _scalingService = scalingService; + _logger = logger; + } + + public GeometryObject Convert(SOG.Mesh speckleMesh) + { + if (speckleMesh.vertices.Count == 0 || speckleMesh.faces.Count == 0) + { + throw new ArgumentException("Mesh has no vertices or faces.", nameof(speckleMesh)); + } + + ForgeTypeId sourceUnitTypeId = _scalingService.UnitsToNative(speckleMesh.units); + + // Weld vertices + var weldedVertices = new List(); + var vertexMap = new int[speckleMesh.vertices.Count / 3]; + + for (int i = 0; i < speckleMesh.vertices.Count; i += 3) + { + var x = _scalingService.ScaleToNative(speckleMesh.vertices[i], sourceUnitTypeId); + var y = _scalingService.ScaleToNative(speckleMesh.vertices[i + 1], sourceUnitTypeId); + var z = _scalingService.ScaleToNative(speckleMesh.vertices[i + 2], sourceUnitTypeId); + var pt = new XYZ(x, y, z); + + int matchedIndex = FindOrAddVertex(pt, weldedVertices, WELD_TOLERANCE); + vertexMap[i / 3] = matchedIndex; + } + + using var builder = new TessellatedShapeBuilder(); + builder.OpenConnectedFaceSet(true); + + int j = 0; + while (j < speckleMesh.faces.Count) + { + int n = speckleMesh.faces[j]; + if (n < 3) + { + n += 3; + } + + int v0Index = speckleMesh.faces[j + 1]; + XYZ v0 = weldedVertices[vertexMap[v0Index]]; + + for (int k = 2; k < n; k++) + { + int v1Index = speckleMesh.faces[j + k]; + int v2Index = speckleMesh.faces[j + k + 1]; + + XYZ v1 = weldedVertices[vertexMap[v1Index]]; + XYZ v2 = weldedVertices[vertexMap[v2Index]]; + + var triangleVertices = new List { v0, v1, v2 }; + + if (IsValidTriangle(triangleVertices)) + { + try + { + builder.AddFace(new TessellatedFace(triangleVertices, ElementId.InvalidElementId)); + } + catch (Autodesk.Revit.Exceptions.ArgumentException) { } + } + } + + j += n + 1; + } + + builder.CloseConnectedFaceSet(); + + try + { + builder.Target = TessellatedShapeBuilderTarget.AnyGeometry; // Attempts Solid + builder.Fallback = TessellatedShapeBuilderFallback.Mesh; + builder.Build(); + } + catch (Autodesk.Revit.Exceptions.ApplicationException ex) + { + _logger.LogError(ex, "TessellatedShapeBuilder failed to build geometry"); + throw new Speckle.Sdk.Common.Exceptions.ConversionException("Failed to build mesh geometry", ex); + } + + var result = builder.GetBuildResult(); + + if (result.Outcome == TessellatedShapeBuilderOutcome.Nothing) + { + throw new Speckle.Sdk.Common.Exceptions.ConversionException("TessellatedShapeBuilder produced no geometry."); + } + + return result.GetGeometricalObjects().First(); + } + + private static int FindOrAddVertex(XYZ pt, List weldedVertices, double tolerance) + { + for (int i = 0; i < weldedVertices.Count; i++) + { + if (weldedVertices[i].IsAlmostEqualTo(pt, tolerance)) + { + return i; + } + } + weldedVertices.Add(pt); + return weldedVertices.Count - 1; + } + + private static bool IsValidTriangle(List vertices) + { + if (vertices.Count != 3) + { + return false; + } + + for (int i = 0; i < vertices.Count; i++) + { + if (vertices[i].IsAlmostEqualTo(vertices[(i + 1) % vertices.Count], WELD_TOLERANCE)) + { + return false; + } + } + var crossProduct = (vertices[1] - vertices[0]).CrossProduct(vertices[2] - vertices[0]); + return (crossProduct.GetLength() / 2.0) > 1e-6; + } +} diff --git a/Converters/Revit/Speckle.Converters.RevitShared/ToHost/Raw/LocalToGlobalToDirectShapeConverter.cs b/Converters/Revit/Speckle.Converters.RevitShared/ToHost/Raw/LocalToGlobalToDirectShapeConverter.cs index bf7590e6b..78e248a71 100644 --- a/Converters/Revit/Speckle.Converters.RevitShared/ToHost/Raw/LocalToGlobalToDirectShapeConverter.cs +++ b/Converters/Revit/Speckle.Converters.RevitShared/ToHost/Raw/LocalToGlobalToDirectShapeConverter.cs @@ -1,5 +1,6 @@ using Speckle.Converters.Common; using Speckle.Converters.Common.Objects; +using Speckle.Converters.RevitShared.Helpers; using Speckle.Converters.RevitShared.Settings; using Speckle.DoubleNumerics; using Speckle.Objects.Data; @@ -22,14 +23,17 @@ public class LocalToGlobalToDirectShapeConverter { private readonly IConverterSettingsStore _converterSettings; private readonly ITypedConverter<(Matrix4x4 matrix, string units), DB.Transform> _transformConverter; + private readonly CategoryExtractor _categoryExtractor; public LocalToGlobalToDirectShapeConverter( IConverterSettingsStore converterSettings, - ITypedConverter<(Matrix4x4 matrix, string units), DB.Transform> transformConverter + ITypedConverter<(Matrix4x4 matrix, string units), DB.Transform> transformConverter, + CategoryExtractor categoryExtractor ) { _converterSettings = converterSettings; _transformConverter = transformConverter; + _categoryExtractor = categoryExtractor; } public DB.DirectShape Convert( @@ -37,7 +41,7 @@ public class LocalToGlobalToDirectShapeConverter ) { // 1- set ds category - var category = ExtractBuiltInCategory(target.parentDataObject, target.atomicObject); + var category = _categoryExtractor.ExtractBuiltInCategory(target.parentDataObject, target.atomicObject); var name = target.parentDataObject?.name ?? target.atomicObject.TryGetName(); var dsCategory = DB.BuiltInCategory.OST_GenericModel; @@ -112,24 +116,4 @@ public class LocalToGlobalToDirectShapeConverter result.SetShape(transformedGeometries); return result; } - - private static string? ExtractBuiltInCategory(DataObject? parentDataObject, Base atomicObject) - { - // Try parent DataObject first (for InstanceProxy displayValue case) - if (parentDataObject?.properties.TryGetValue("builtInCategory", out var cat) == true) - { - return cat?.ToString(); - } - - // Fallback to atomicObject properties - if ( - atomicObject["properties"] is Dictionary props - && props.TryGetValue("builtInCategory", out var fallbackCat) - ) - { - return fallbackCat?.ToString(); - } - - return null; - } } diff --git a/DUI3/Speckle.Connectors.DUI/Models/DocumentInfo.cs b/DUI3/Speckle.Connectors.DUI/Models/DocumentInfo.cs index b15a76c27..a2286e87b 100644 --- a/DUI3/Speckle.Connectors.DUI/Models/DocumentInfo.cs +++ b/DUI3/Speckle.Connectors.DUI/Models/DocumentInfo.cs @@ -1,6 +1,6 @@ namespace Speckle.Connectors.DUI.Models; -public record DocumentInfo(string Location, string Name, string Id) +public record DocumentInfo(string Location, string Name, string Id, string? CloudFileId = null) { //?.Replace("\\", "\\\\"); // for some reason, when returning variables from a direct binding call //we don't need this. nevertheless, after switching to a post response back to the ui, diff --git a/Sdk/Speckle.Connectors.Common/Instances/IInstanceObjectsManager.cs b/Sdk/Speckle.Connectors.Common/Instances/IInstanceObjectsManager.cs index 6e02d9312..5e0ea74be 100644 --- a/Sdk/Speckle.Connectors.Common/Instances/IInstanceObjectsManager.cs +++ b/Sdk/Speckle.Connectors.Common/Instances/IInstanceObjectsManager.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using Speckle.Sdk.Models.Instances; namespace Speckle.Connectors.Common.Instances; @@ -8,6 +8,7 @@ public interface IInstanceObjectsManager void AddInstanceProxy(string objectId, InstanceProxy instanceProxy); void AddDefinitionProxy(string objectId, InstanceDefinitionProxy instanceDefinitionProxy); void AddAtomicObject(string objectId, THostObjectType obj); + void AddAtomicDefinitionObjectId(string objectId); void AddInstanceProxiesByDefinitionId(string definitionId, List instanceProxies); UnpackResult GetUnpackResult(); bool TryGetInstanceProxiesFromDefinitionId( diff --git a/Sdk/Speckle.Connectors.Common/Instances/InstanceObjectsManager.cs b/Sdk/Speckle.Connectors.Common/Instances/InstanceObjectsManager.cs index 2af8cb20e..b67ba455f 100644 --- a/Sdk/Speckle.Connectors.Common/Instances/InstanceObjectsManager.cs +++ b/Sdk/Speckle.Connectors.Common/Instances/InstanceObjectsManager.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using Speckle.Sdk.Models.Instances; namespace Speckle.Connectors.Common.Instances; @@ -10,6 +10,7 @@ public class InstanceObjectsManager private readonly Dictionary> _instanceProxiesByDefinitionId = new(); private readonly Dictionary _definitionProxies = new(); private readonly Dictionary _flatAtomicObjects = new(); + private readonly HashSet _flatAtomicDefinitionObjectIds = new(); public void AddInstanceProxy(string objectId, InstanceProxy instanceProxy) => _instanceProxies[objectId] = instanceProxy; @@ -19,11 +20,13 @@ public class InstanceObjectsManager public void AddAtomicObject(string objectId, THostObjectType obj) => _flatAtomicObjects[objectId] = obj; + public void AddAtomicDefinitionObjectId(string objectId) => _flatAtomicDefinitionObjectIds.Add(objectId); + public void AddInstanceProxiesByDefinitionId(string definitionId, List instanceProxies) => _instanceProxiesByDefinitionId[definitionId] = instanceProxies; public UnpackResult GetUnpackResult() => - new(GetAtomicObjects(), GetInstanceProxies(), GetDefinitionProxies()); + new(GetAtomicObjects(), GetAtomicDefinitionObjectIds(), GetInstanceProxies(), GetDefinitionProxies()); public bool TryGetInstanceProxiesFromDefinitionId( string definitionId, @@ -58,6 +61,8 @@ public class InstanceObjectsManager private List GetAtomicObjects() => _flatAtomicObjects.Values.ToList(); + private HashSet GetAtomicDefinitionObjectIds() => _flatAtomicDefinitionObjectIds; + private List GetDefinitionProxies() => _definitionProxies.Values.ToList(); private Dictionary GetInstanceProxies() => _instanceProxies; diff --git a/Sdk/Speckle.Connectors.Common/Instances/UnpackResult.cs b/Sdk/Speckle.Connectors.Common/Instances/UnpackResult.cs index 6d311c785..26246a81d 100644 --- a/Sdk/Speckle.Connectors.Common/Instances/UnpackResult.cs +++ b/Sdk/Speckle.Connectors.Common/Instances/UnpackResult.cs @@ -4,6 +4,7 @@ namespace Speckle.Connectors.Common.Instances; public record UnpackResult( List AtomicObjects, + HashSet AtomicDefinitionObjectIds, Dictionary InstanceProxies, List InstanceDefinitionProxies );