Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.
Python aecai-agentsautodeskautomationbimclaudeifcmcpmcp-servermodel-context-protocolnavisworksrevitrevit-addinrevit-apirhino
feat(csharp): implement named transactions with action_id, DocumentDirtyTracker, and extract_snapshot/get_snapshot_delta commands, and delete dead commands tree
A. Sam Mohammad7dad9b112e15
diff --git a/packages/revit-bridge-addin/RevitBridge.csproj b/packages/revit-bridge-addin/RevitBridge.csprojindex 70abdf5..a9a8f6c 100644--- a/packages/revit-bridge-addin/RevitBridge.csproj+++ b/packages/revit-bridge-addin/RevitBridge.csproj@@ -64,11 +64,4 @@<Reference Include="System.Xaml" /></ItemGroup>- <!-- Temporarily exclude Phase commands with API compatibility issues -->- <ItemGroup>- <Compile Remove="src\Commands\Core\**\*.cs" />- <Compile Remove="src\Commands\Advanced\**\*.cs" />- <Compile Remove="src\Commands\Specialized\**\*.cs" />- <Compile Remove="src\Commands\Enhancements\**\*.cs" />- </ItemGroup></Project>diff --git a/packages/revit-bridge-addin/src/Bridge/App.cs b/packages/revit-bridge-addin/src/Bridge/App.csindex 4e86d48..2c52c13 100644--- a/packages/revit-bridge-addin/src/Bridge/App.cs+++ b/packages/revit-bridge-addin/src/Bridge/App.cs@@ -46,10 +46,12 @@ namespace RevitBridge.Bridgeapplication.ControlledApplication.DocumentChanged += (sender, args) =>{ActiveDocumentName = args.GetDocument()?.Title;+ DocumentDirtyTracker.HandleDocumentChanged(sender, args);};application.ViewActivated += (sender, args) =>{ActiveDocumentName = args.CurrentActiveView?.Document?.Title;+ DocumentDirtyTracker.Clear();};Log.Information("AEC Model Bridge started for Revit {Version}", RevitVersion);diff --git a/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs b/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.csindex 9193d26..68adb94 100644--- a/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs+++ b/packages/revit-bridge-addin/src/Bridge/BridgeCommandFactory.cs@@ -20,6 +20,22 @@ public static class BridgeCommandFactoryprivate static readonly List<object> _capabilities = new();private static readonly List<string> _catalog = new();+ [ThreadStatic]+ private static string? _currentActionId;++ public static string? CurrentActionId+ {+ get => _currentActionId;+ set => _currentActionId = value;+ }++ public static Transaction CreateTransaction(Document doc, string name)+ {+ var actionId = CurrentActionId;+ string txName = string.IsNullOrEmpty(actionId) ? $"AMB: {name}" : $"AMB: {name} #{actionId}";+ return BridgeCommandFactory.CreateTransaction(doc, txName);+ }+static BridgeCommandFactory(){var methods = typeof(BridgeCommandFactory).GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);@@ -62,12 +78,25 @@ public static class BridgeCommandFactory{try{+ if (payload.ValueKind == JsonValueKind.Object && payload.TryGetProperty("action_id", out var actionProp))+ {+ CurrentActionId = actionProp.GetString();+ }+ else+ {+ CurrentActionId = null;+ }+return handler(app, payload);}catch (System.Reflection.TargetInvocationException ex){throw ex.InnerException ?? ex;}+ finally+ {+ CurrentActionId = null;+ }}return new { status = "error", message = $"Unknown tool: {tool}" };}@@ -161,7 +190,7 @@ public static class BridgeCommandFactoryvar exported = new List<string>();- using (var trans = new Transaction(doc, "Export Schedules"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Export Schedules")){trans.Start();@@ -369,7 +398,7 @@ public static class BridgeCommandFactoryvar levelName = payload.GetProperty("level").GetString();var wallTypeName = payload.TryGetProperty("wall_type", out var wt) ? wt.GetString() : null;- using (var trans = new Transaction(doc, "Create Wall"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Wall")){trans.Start();@@ -416,7 +445,7 @@ public static class BridgeCommandFactoryvar levelName = payload.GetProperty("level").GetString();var floorTypeName = payload.TryGetProperty("floor_type", out var ft) ? ft.GetString() : null;- using (var trans = new Transaction(doc, "Create Floor"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Floor")){trans.Start();@@ -474,7 +503,7 @@ public static class BridgeCommandFactoryvar levelName = payload.GetProperty("level").GetString();var roofTypeName = payload.TryGetProperty("roof_type", out var rt) ? rt.GetString() : null;- using (var trans = new Transaction(doc, "Create Roof"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Roof")){trans.Start();@@ -518,7 +547,7 @@ public static class BridgeCommandFactoryvar name = payload.GetProperty("name").GetString();var elevation = payload.GetProperty("elevation").GetDouble();- using (var trans = new Transaction(doc, "Create Level"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Level")){trans.Start();@@ -549,7 +578,7 @@ public static class BridgeCommandFactoryvar endPoint = ParseXYZ(payload.GetProperty("end_point"));var name = payload.TryGetProperty("name", out var n) ? n.GetString() : null;- using (var trans = new Transaction(doc, "Create Grid"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Grid")){trans.Start();@@ -584,7 +613,7 @@ public static class BridgeCommandFactoryvar roomName = payload.TryGetProperty("name", out var n) ? n.GetString() : "Room";var roomNumber = payload.TryGetProperty("number", out var num) ? num.GetString() : null;- using (var trans = new Transaction(doc, "Create Room"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Room")){trans.Start();@@ -654,7 +683,7 @@ public static class BridgeCommandFactoryvar elementId = payload.GetProperty("element_id").GetInt32();- using (var trans = new Transaction(doc, "Delete Element"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Delete Element")){trans.Start();@@ -685,7 +714,7 @@ public static class BridgeCommandFactoryvar typeName = payload.GetProperty("type_name").GetString();var levelName = payload.GetProperty("level").GetString();- using (var trans = new Transaction(doc, "Place Family Instance"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Place Family Instance")){trans.Start();@@ -724,7 +753,7 @@ public static class BridgeCommandFactoryvar familyName = payload.TryGetProperty("family_name", out var fn) ? fn.GetString() : "Single-Flush";var typeName = payload.TryGetProperty("type_name", out var tn) ? tn.GetString() : "0915 x 2134mm";- using (var trans = new Transaction(doc, "Place Door"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Place Door")){trans.Start();@@ -766,7 +795,7 @@ public static class BridgeCommandFactoryvar familyName = payload.TryGetProperty("family_name", out var fn) ? fn.GetString() : "Fixed";var typeName = payload.TryGetProperty("type_name", out var tn) ? tn.GetString() : "1200 x 1500mm";- using (var trans = new Transaction(doc, "Place Window"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Place Window")){trans.Start();@@ -838,7 +867,7 @@ public static class BridgeCommandFactoryvar levelName = payload.GetProperty("level").GetString();var viewName = payload.TryGetProperty("name", out var n) ? n.GetString() : null;- using (var trans = new Transaction(doc, "Create Floor Plan View"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Floor Plan View")){trans.Start();@@ -873,7 +902,7 @@ public static class BridgeCommandFactoryvar viewName = payload.TryGetProperty("name", out var n) ? n.GetString() : "3D View";- using (var trans = new Transaction(doc, "Create 3D View"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create 3D View")){trans.Start();@@ -903,7 +932,7 @@ public static class BridgeCommandFactoryvar endPoint = ParseXYZ(payload.GetProperty("end_point"));var viewName = payload.TryGetProperty("name", out var n) ? n.GetString() : "Section";- using (var trans = new Transaction(doc, "Create Section View"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Section View")){trans.Start();@@ -1119,7 +1148,7 @@ public static class BridgeCommandFactoryif (element == null)throw new ArgumentException($"Element with ID {elementId} not found");- using (var trans = new Transaction(doc, "Set Parameter Value"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Set Parameter Value")){trans.Start();@@ -1282,7 +1311,7 @@ public static class BridgeCommandFactoryvar successCount = 0;var errorCount = 0;- using (var trans = new Transaction(doc, "Batch Set Parameters"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Batch Set Parameters")){trans.Start();@@ -1384,7 +1413,7 @@ public static class BridgeCommandFactoryif (elementType == null)throw new ArgumentException($"Element type with ID {typeId} not found");- using (var trans = new Transaction(doc, "Set Type Parameter"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Set Type Parameter")){trans.Start();@@ -1536,7 +1565,7 @@ public static class BridgeCommandFactory? tbName.GetString(): null;- using (var trans = new Transaction(doc, "Create Sheet"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Sheet")){trans.Start();@@ -1587,7 +1616,7 @@ public static class BridgeCommandFactoryvar sheetId = payload.GetProperty("sheet_id").GetInt32();- using (var trans = new Transaction(doc, "Delete Sheet"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Delete Sheet")){trans.Start();@@ -1625,7 +1654,7 @@ public static class BridgeCommandFactory? ParseXYZ(loc): new XYZ(0.5, 0.5, 0);- using (var trans = new Transaction(doc, "Place Viewport"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Place Viewport")){trans.Start();@@ -1682,7 +1711,7 @@ public static class BridgeCommandFactoryvar successCount = 0;var errorCount = 0;- using (var trans = new Transaction(doc, "Batch Create Sheets"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Batch Create Sheets")){trans.Start();@@ -1755,7 +1784,7 @@ public static class BridgeCommandFactoryvar parameters = payload.GetProperty("parameters").EnumerateObject().ToDictionary(p => p.Name, p => p.Value);- using (var trans = new Transaction(doc, "Populate Titleblock"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Populate Titleblock")){trans.Start();@@ -1889,7 +1918,7 @@ public static class BridgeCommandFactory? dv.GetBoolean(): false;- using (var trans = new Transaction(doc, "Duplicate Sheet"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Duplicate Sheet")){trans.Start();@@ -2000,7 +2029,7 @@ public static class BridgeCommandFactoryvar successCount = 0;var errorCount = 0;- using (var trans = new Transaction(doc, "Renumber Sheets"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Renumber Sheets")){trans.Start();@@ -2080,7 +2109,7 @@ public static class BridgeCommandFactory}};- using (var trans = new Transaction(doc, "Export DWG"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Export DWG")){trans.Start();@@ -2157,7 +2186,7 @@ public static class BridgeCommandFactorySpaceBoundaryLevel = 1};- using (var trans = new Transaction(doc, "Export IFC"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Export IFC")){trans.Start();@@ -2217,7 +2246,7 @@ public static class BridgeCommandFactoryoptions.ViewId = viewId;}- using (var trans = new Transaction(doc, "Export Navisworks"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Export Navisworks")){trans.Start();@@ -2296,7 +2325,7 @@ public static class BridgeCommandFactoryoptions.SetViewsAndSheets(new List<ElementId> { view.Id });- using (var trans = new Transaction(doc, "Export Image"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Export Image")){trans.Start();@@ -2352,7 +2381,7 @@ public static class BridgeCommandFactory_ => ImageResolution.DPI_150};- using (var trans = new Transaction(doc, "Render 3D View"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Render 3D View")){trans.Start();@@ -2420,7 +2449,7 @@ public static class BridgeCommandFactoryvar location = ParseXYZ(payload.GetProperty("location"));var viewId = payload.TryGetProperty("view_id", out var v) ? v.GetInt32() : doc.ActiveView.Id.Value;- using (var trans = new Transaction(doc, "Create Text Note"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Text Note")){trans.Start();var view = doc.GetElement(new ElementId((long)viewId)) as View;@@ -2441,7 +2470,7 @@ public static class BridgeCommandFactoryvar location = ParseXYZ(payload.GetProperty("location"));var viewId = payload.TryGetProperty("view_id", out var v) ? v.GetInt32() : doc.ActiveView.Id.Value;- using (var trans = new Transaction(doc, "Create Tag"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Tag")){trans.Start();var view = doc.GetElement(new ElementId((long)viewId)) as View;@@ -2468,7 +2497,7 @@ public static class BridgeCommandFactoryvar familyName = payload.GetProperty("family_name").GetString();var typeName = payload.GetProperty("type_name").GetString();- using (var trans = new Transaction(doc, "Create Structural Column"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Structural Column")){trans.Start();var level = GetLevelByName(doc, levelName);@@ -2494,7 +2523,7 @@ public static class BridgeCommandFactoryvar familyName = payload.GetProperty("family_name").GetString();var typeName = payload.GetProperty("type_name").GetString();- using (var trans = new Transaction(doc, "Create Beam"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Beam")){trans.Start();var level = GetLevelByName(doc, levelName);@@ -2520,7 +2549,7 @@ public static class BridgeCommandFactoryvar familyName = payload.GetProperty("family_name").GetString();var typeName = payload.GetProperty("type_name").GetString();- using (var trans = new Transaction(doc, "Create Foundation"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Foundation")){trans.Start();var level = GetLevelByName(doc, levelName);@@ -2548,7 +2577,7 @@ public static class BridgeCommandFactoryvar systemTypeName = payload.TryGetProperty("system_type", out var s) ? s.GetString() : "Supply Air";var ductTypeName = payload.TryGetProperty("duct_type", out var d) ? d.GetString() : null; // Default to first available- using (var trans = new Transaction(doc, "Create Duct"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Duct")){trans.Start();var level = GetLevelByName(doc, levelName);@@ -2587,7 +2616,7 @@ public static class BridgeCommandFactoryvar systemTypeName = payload.TryGetProperty("system_type", out var s) ? s.GetString() : "Hydronic Supply";var pipeTypeName = payload.TryGetProperty("pipe_type", out var p) ? p.GetString() : null;- using (var trans = new Transaction(doc, "Create Pipe"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Pipe")){trans.Start();var level = GetLevelByName(doc, levelName);@@ -2672,7 +2701,7 @@ public static class BridgeCommandFactoryvar elementId = new ElementId((long)payload.GetProperty("element_id").GetInt32());var vector = ParseXYZ(payload.GetProperty("vector"));- using (var trans = new Transaction(doc, "Move Element"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Move Element")){trans.Start();ElementTransformUtils.MoveElement(doc, elementId, vector);@@ -2690,7 +2719,7 @@ public static class BridgeCommandFactoryvar elementId = new ElementId((long)payload.GetProperty("element_id").GetInt32());var vector = ParseXYZ(payload.GetProperty("vector"));- using (var trans = new Transaction(doc, "Copy Element"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Copy Element")){trans.Start();var newIds = ElementTransformUtils.CopyElement(doc, elementId, vector);@@ -2709,7 +2738,7 @@ public static class BridgeCommandFactoryvar axisPoint = ParseXYZ(payload.GetProperty("axis_point"));var angleRadians = payload.GetProperty("angle_radians").GetDouble();- using (var trans = new Transaction(doc, "Rotate Element"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Rotate Element")){trans.Start();var axis = Line.CreateBound(axisPoint, axisPoint + XYZ.BasisZ); // Default to Z-axis rotation for now@@ -2733,7 +2762,7 @@ public static class BridgeCommandFactoryvar planeOrigin = ParseXYZ(payload.GetProperty("plane_origin"));var planeNormal = ParseXYZ(payload.GetProperty("plane_normal")); // e.g., (1,0,0) for YZ plane- using (var trans = new Transaction(doc, "Mirror Element"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Mirror Element")){trans.Start();var plane = Plane.CreateByNormalAndOrigin(planeNormal, planeOrigin);@@ -2751,7 +2780,7 @@ public static class BridgeCommandFactoryvar elementId = new ElementId((long)payload.GetProperty("element_id").GetInt32());- using (var trans = new Transaction(doc, "Pin Element"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Pin Element")){trans.Start();var el = doc.GetElement(elementId);@@ -2769,7 +2798,7 @@ public static class BridgeCommandFactoryvar elementId = new ElementId((long)payload.GetProperty("element_id").GetInt32());- using (var trans = new Transaction(doc, "Unpin Element"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Unpin Element")){trans.Start();var el = doc.GetElement(elementId);@@ -2856,7 +2885,7 @@ public static class BridgeCommandFactoryvar category = GetCategoryByName(doc, categoryName);- using (var trans = new Transaction(doc, "Create Schedule"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Schedule")){trans.Start();var schedule = ViewSchedule.CreateSchedule(doc, category.Id);@@ -2975,7 +3004,7 @@ public static class BridgeCommandFactory.ToList();var name = payload.TryGetProperty("name", out var n) ? n.GetString() : null;- using (var trans = new Transaction(doc, "Create Group"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Group")){trans.Start();var group = doc.Create.NewGroup(elementIds);@@ -2997,7 +3026,7 @@ public static class BridgeCommandFactoryvar groupId = new ElementId((long)payload.GetProperty("group_id").GetInt32());- using (var trans = new Transaction(doc, "Ungroup"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Ungroup")){trans.Start();var group = doc.GetElement(groupId) as Group;@@ -3092,7 +3121,7 @@ public static class BridgeCommandFactoryvar diameter = payload.TryGetProperty("diameter", out var d) ? d.GetDouble() : 0.75 / 12.0; // Default 0.75 inchesvar conduitTypeName = payload.TryGetProperty("conduit_type", out var ct) ? ct.GetString() : null;- using (var trans = new Transaction(doc, "Create Conduit"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Conduit")){trans.Start();@@ -3294,7 +3323,7 @@ public static class BridgeCommandFactoryvar shininess = payload.TryGetProperty("shininess", out var s) ? s.GetInt32() : 50;var smoothness = payload.TryGetProperty("smoothness", out var sm) ? sm.GetInt32() : 50;- using (var trans = new Transaction(doc, "Create Material"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Material")){trans.Start();@@ -3335,7 +3364,7 @@ public static class BridgeCommandFactoryvar materialName = payload.GetProperty("material_name").GetString();var faceIndex = payload.TryGetProperty("face_index", out var fi) ? (int?)fi.GetInt32() : null;- using (var trans = new Transaction(doc, "Set Element Material"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Set Element Material")){trans.Start();@@ -3481,7 +3510,7 @@ public static class BridgeCommandFactoryvar name = payload.TryGetProperty("name", out var n) ? n.GetString() : null;- using (var trans = new Transaction(doc, "Create Group"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Group")){trans.Start();@@ -3585,7 +3614,7 @@ public static class BridgeCommandFactoryvar ref1Id = new ElementId((long)payload.GetProperty("element1_id").GetInt32());var ref2Id = new ElementId((long)payload.GetProperty("element2_id").GetInt32());- using (var trans = new Transaction(doc, "Create Dimension"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Create Dimension")){trans.Start();@@ -3658,7 +3687,7 @@ public static class BridgeCommandFactoryvar category = GetBuiltInCategoryByName(categoryName);var view = doc.ActiveView;- using (var trans = new Transaction(doc, "Tag All Not Tagged"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Tag All Not Tagged")){trans.Start();@@ -3727,7 +3756,7 @@ public static class BridgeCommandFactoryvar viewId = new ElementId((long)payload.GetProperty("view_id").GetInt32());var templateId = new ElementId((long)payload.GetProperty("template_id").GetInt32());- using (var trans = new Transaction(doc, "Apply View Template"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, "Apply View Template")){trans.Start();@@ -3838,7 +3867,7 @@ public static class BridgeCommandFactoryJsonElement args = payload.GetProperty("arguments");string targetId = payload.TryGetProperty("target_id", out var t) ? t.GetString() : null;- using (var trans = new Transaction(doc, $"Invoke {methodName}"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, $"Invoke {methodName}")){if (payload.TryGetProperty("use_transaction", out var ut) && ut.GetBoolean())trans.Start();@@ -3897,7 +3926,7 @@ public static class BridgeCommandFactorystring propertyName = payload.GetProperty("property_name").GetString();JsonElement valueElement = payload.GetProperty("value");- using (var trans = new Transaction(doc, $"Set {propertyName}"))+ using (var trans = BridgeCommandFactory.CreateTransaction(doc, $"Set {propertyName}")){trans.Start();object target = ReflectionHelper.GetObject(targetId, doc);@@ -4011,7 +4040,7 @@ public static class BridgeCommandFactoryint changed = 0, failed = 0;var failedIds = new List<long>();- using (var tx = new Transaction(doc, "MCP: Change Element Type"))+ using (var tx = BridgeCommandFactory.CreateTransaction(doc, "MCP: Change Element Type")){tx.Start();foreach (var el in elements)@@ -4178,7 +4207,7 @@ public static class BridgeCommandFactoryvar elements = query.ToList();int updated = 0, failed = 0;- using (var tx = new Transaction(doc, "MCP: Batch Set Parameters by Filter"))+ using (var tx = BridgeCommandFactory.CreateTransaction(doc, "MCP: Batch Set Parameters by Filter")){tx.Start();foreach (var el in elements)@@ -4239,7 +4268,7 @@ public static class BridgeCommandFactoryint changed = 0, failed = 0;var failedIds = new List<long>();- using (var tx = new Transaction(doc, "MCP: Replace Family Type"))+ using (var tx = BridgeCommandFactory.CreateTransaction(doc, "MCP: Replace Family Type")){tx.Start();if (!newSymbol.IsActive)@@ -4333,4 +4362,184 @@ public static class BridgeCommandFactoryvolume = volParam?.AsDouble()};}++ [BridgeCommand("revit.extract_snapshot", IsMutating = false)]+ private static object ExecuteExtractSnapshot(UIApplication app, JsonElement payload)+ {+ var doc = app.ActiveUIDocument?.Document;+ if (doc == null)+ throw new InvalidOperationException("No active document");++ bool dirtyOnly = payload.ValueKind == JsonValueKind.Object &&+ payload.TryGetProperty("dirty_only", out var dirtyProp) &&+ dirtyProp.GetBoolean();+ string snapshotId = Guid.NewGuid().ToString("N");++ var workspaceDir = Environment.GetEnvironmentVariable("MCP_REVIT_WORKSPACE_DIR") ?? Path.GetTempPath();+ var snapshotDir = Path.Combine(workspaceDir, "snapshots");+ Directory.CreateDirectory(snapshotDir);+ var snapshotPath = Path.Combine(snapshotDir, $"snapshot-{snapshotId}.json");++ var elementsToExtract = new List<Element>();+ var dirtyIds = DocumentDirtyTracker.GetDirtyUniqueIds();++ if (dirtyOnly)+ {+ foreach (var uid in dirtyIds)+ {+ if (uid.StartsWith("deleted:")) continue;+ try+ {+ var elem = doc.GetElement(uid);+ if (elem != null) elementsToExtract.Add(elem);+ }+ catch { }+ }+ }+ else+ {+ var classes = new[]+ {+ typeof(FamilyInstance), typeof(Wall), typeof(Floor), typeof(RoofBase),+ typeof(Level), typeof(Grid), typeof(ViewSheet), typeof(ViewDrafting)+ };++ foreach (var type in classes)+ {+ try+ {+ var collector = new FilteredElementCollector(doc)+ .OfClass(type)+ .WhereElementIsNotElementType();+ elementsToExtract.AddRange(collector);+ }+ catch { }+ }++ try+ {+ var roomCollector = new FilteredElementCollector(doc)+ .OfCategory(BuiltInCategory.OST_Rooms)+ .WhereElementIsNotElementType();+ elementsToExtract.AddRange(roomCollector);+ }+ catch { }+ }++ var elementRecords = new List<object>();+ foreach (var elem in elementsToExtract)+ {+ if (elem == null || string.IsNullOrEmpty(elem.UniqueId)) continue;++ Element? typeElem = null;+ try { typeElem = doc.GetElement(elem.GetTypeId()); } catch { }++ var paramsDict = new Dictionary<string, object>();+ foreach (Parameter param in elem.Parameters)+ {+ if (param.HasValue)+ {+ object val = param.StorageType switch+ {+ StorageType.Integer => param.AsInteger(),+ StorageType.Double => param.AsDouble(),+ StorageType.String => param.AsString() ?? string.Empty,+ StorageType.ElementId => param.AsElementId().Value.ToString(),+ _ => string.Empty+ };++ paramsDict[param.Definition.Name] = new+ {+ v = val,+ storage = param.StorageType.ToString(),+ instance = true,+ @readonly = param.IsReadOnly+ };+ }+ }++ string catName = elem.Category?.BuiltInCategory.ToString() ?? elem.Category?.Name ?? "None";++ var record = new+ {+ uid = elem.UniqueId,+ amb_uid = elem.UniqueId,+ element_id = elem.Id.Value,+ category = catName,+ @class = elem.GetType().Name,+ type_uid = elem.GetTypeId().Value.ToString(),+ family = typeElem?.get_Parameter(BuiltInParameter.ALL_MODEL_FAMILY_NAME)?.AsString() ?? typeElem?.Name ?? string.Empty,+ type_name = typeElem?.Name ?? string.Empty,+ level_uid = (elem as FamilyInstance)?.LevelId.Value.ToString() ?? (elem as Wall)?.LevelId.Value.ToString() ?? string.Empty,+ @params = paramsDict+ };++ elementRecords.Add(record);+ }++ var deletedIdsList = dirtyOnly+ ? dirtyIds.Where(id => id.StartsWith("deleted:")).Select(id => id.Substring(8)).ToList()+ : new List<string>();++ var snapshot = new+ {+ schema = "amb.snapshot/1",+ snapshot_id = snapshotId,+ taken_at = DateTime.UtcNow.ToString("o"),+ source = new+ {+ app = "revit",+ app_version = app.Application.VersionNumber,+ doc_guid = doc.ProjectInformation?.UniqueId ?? doc.Title,+ doc_title = doc.Title,+ units = "SI"+ },+ elements = elementRecords,+ deleted = deletedIdsList+ };++ var json = JsonSerializer.Serialize(snapshot, new JsonSerializerOptions { WriteIndented = false });+ File.WriteAllText(snapshotPath, json);++ return new+ {+ snapshot_id = snapshotId,+ path = snapshotPath,+ element_count = elementRecords.Count,+ deleted_count = deletedIdsList.Count+ };+ }++ [BridgeCommand("revit.get_snapshot_delta", IsMutating = false)]+ private static object ExecuteGetSnapshotDelta(UIApplication app, JsonElement payload)+ {+ var doc = app.ActiveUIDocument?.Document;+ if (doc == null)+ throw new InvalidOperationException("No active document");++ var dirtyIds = DocumentDirtyTracker.GetDirtyUniqueIds();++ var addedAndModified = new List<string>();+ var deleted = new List<string>();++ foreach (var id in dirtyIds)+ {+ if (id.StartsWith("deleted:"))+ {+ deleted.Add(id.Substring(8));+ }+ else+ {+ addedAndModified.Add(id);+ }+ }++ return new+ {+ added_or_modified = addedAndModified,+ deleted = deleted,+ count = dirtyIds.Count+ };+ }}+diff --git a/packages/revit-bridge-addin/src/Bridge/DocumentDirtyTracker.cs b/packages/revit-bridge-addin/src/Bridge/DocumentDirtyTracker.csnew file mode 100644index 0000000..8ab7d96--- /dev/null+++ b/packages/revit-bridge-addin/src/Bridge/DocumentDirtyTracker.cs@@ -0,0 +1,70 @@+using System;+using System.Collections.Generic;+using System.Linq;+using Autodesk.Revit.DB;+using Autodesk.Revit.DB.Events;++namespace RevitBridge.Bridge+{+ public static class DocumentDirtyTracker+ {+ private static readonly HashSet<string> _dirtyUniqueIds = new();+ private static readonly object _lock = new();++ public static void Clear()+ {+ lock (_lock)+ {+ _dirtyUniqueIds.Clear();+ }+ }++ public static List<string> GetDirtyUniqueIds()+ {+ lock (_lock)+ {+ return _dirtyUniqueIds.ToList();+ }+ }++ public static void Add(string uniqueId)+ {+ lock (_lock)+ {+ _dirtyUniqueIds.Add(uniqueId);+ }+ }++ public static void HandleDocumentChanged(object sender, DocumentChangedEventArgs e)+ {+ var doc = e.GetDocument();+ if (doc == null) return;++ lock (_lock)+ {+ foreach (var id in e.GetAddedElementIds())+ {+ var elem = doc.GetElement(id);+ if (elem != null && !string.IsNullOrEmpty(elem.UniqueId))+ {+ _dirtyUniqueIds.Add(elem.UniqueId);+ }+ }++ foreach (var id in e.GetModifiedElementIds())+ {+ var elem = doc.GetElement(id);+ if (elem != null && !string.IsNullOrEmpty(elem.UniqueId))+ {+ _dirtyUniqueIds.Add(elem.UniqueId);+ }+ }++ foreach (var id in e.GetDeletedElementIds())+ {+ _dirtyUniqueIds.Add($"deleted:{id.Value}");+ }+ }+ }+ }+}diff --git a/packages/revit-bridge-addin/src/Commands/Advanced/Families/FamilyCommands.cs b/packages/revit-bridge-addin/src/Commands/Advanced/Families/FamilyCommands.csdeleted file mode 100644index 9828afc..0000000--- a/packages/revit-bridge-addin/src/Commands/Advanced/Families/FamilyCommands.cs+++ /dev/null@@ -1,597 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using System.IO;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Advanced.Families-{- /// <summary>- /// Family and type management commands- /// Family (#17, Score: 272), FamilySymbol (#18, Score: 271), FamilyInstance (#8, Score: 281)- /// </summary>- public static class FamilyCommands- {- #region 1. Load Family-- public static object LoadFamily(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string familyPath = payload.GetProperty("family_path").GetString();-- if (!File.Exists(familyPath))- {- throw new Exception($"Family file not found: {familyPath}");- }-- using (var trans = new Transaction(doc, "Load Family"))- {- trans.Start();-- bool loaded = doc.LoadFamily(familyPath, out Family family);-- trans.Commit();-- if (loaded && family != null)- {- // Get family symbols (types)- var symbolIds = family.GetFamilySymbolIds();- var symbols = symbolIds.Select(id => doc.GetElement(id) as FamilySymbol)- .Where(s => s != null)- .Select(s => new { id = s.Id.IntegerValue, name = s.Name })- .ToList();-- return new- {- success = true,- familyId = family.Id.IntegerValue,- familyName = family.Name,- typeCount = symbols.Count,- types = symbols- };- }-- throw new Exception("Failed to load family");- }- }-- #endregion-- #region 2. Reload Family-- public static object ReloadFamily(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int familyId = payload.GetProperty("family_id").GetInt32();-- Family family = doc.GetElement(new ElementId(familyId)) as Family;- if (family == null)- {- throw new Exception($"Family {familyId} not found");- }-- using (var trans = new Transaction(doc, "Reload Family"))- {- trans.Start();-- // Get external file reference- ExternalFileReference extRef = family.GetExternalFileReference();- if (extRef == null)- {- throw new Exception("Family has no external file reference");- }-- string familyPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(extRef.GetPath());- bool reloaded = family.Document.LoadFamily(familyPath, out Family newFamily);-- trans.Commit();-- return new- {- success = reloaded,- familyId = family.Id.IntegerValue,- familyName = family.Name,- path = familyPath,- message = reloaded ? "Family reloaded successfully" : "Failed to reload family"- };- }- }-- #endregion-- #region 3. Duplicate Family Type-- public static object DuplicateFamilyType(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int typeId = payload.GetProperty("type_id").GetInt32();- string newName = payload.GetProperty("new_name").GetString();-- FamilySymbol symbol = doc.GetElement(new ElementId(typeId)) as FamilySymbol;- if (symbol == null)- {- throw new Exception($"Family type {typeId} not found");- }-- using (var trans = new Transaction(doc, "Duplicate Family Type"))- {- trans.Start();-- FamilySymbol newSymbol = symbol.Duplicate(newName) as FamilySymbol;-- trans.Commit();-- return new- {- success = true,- originalTypeId = typeId,- originalTypeName = symbol.Name,- newTypeId = newSymbol.Id.IntegerValue,- newTypeName = newSymbol.Name,- familyName = newSymbol.Family.Name- };- }- }-- #endregion-- #region 4. Rename Family Type-- public static object RenameFamilyType(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int typeId = payload.GetProperty("type_id").GetInt32();- string newName = payload.GetProperty("new_name").GetString();-- FamilySymbol symbol = doc.GetElement(new ElementId(typeId)) as FamilySymbol;- if (symbol == null)- {- throw new Exception($"Family type {typeId} not found");- }-- using (var trans = new Transaction(doc, "Rename Family Type"))- {- trans.Start();-- string oldName = symbol.Name;- symbol.Name = newName;-- trans.Commit();-- return new- {- success = true,- typeId = typeId,- oldName = oldName,- newName = symbol.Name,- familyName = symbol.Family.Name- };- }- }-- #endregion-- #region 5. Set Family Type Parameter-- public static object SetFamilyTypeParameter(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int typeId = payload.GetProperty("type_id").GetInt32();- string paramName = payload.GetProperty("parameter_name").GetString();- var value = payload.GetProperty("value");-- FamilySymbol symbol = doc.GetElement(new ElementId(typeId)) as FamilySymbol;- if (symbol == null)- {- throw new Exception($"Family type {typeId} not found");- }-- using (var trans = new Transaction(doc, "Set Family Type Parameter"))- {- trans.Start();-- Parameter param = symbol.LookupParameter(paramName);- if (param == null)- {- throw new Exception($"Parameter '{paramName}' not found");- }-- bool success = SetParameterValue(param, value);-- trans.Commit();-- return new- {- success = success,- typeId = typeId,- typeName = symbol.Name,- parameterName = paramName,- newValue = GetParameterValue(param)- };- }- }-- #endregion-- #region 6. Get Nested Families-- public static object GetNestedFamilies(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int familyId = payload.GetProperty("family_id").GetInt32();-- Family family = doc.GetElement(new ElementId(familyId)) as Family;- if (family == null)- {- throw new Exception($"Family {familyId} not found");- }-- // Get family instances and check for nested families- var collector = new FilteredElementCollector(doc)- .OfClass(typeof(FamilyInstance))- .Cast<FamilyInstance>()- .Where(fi => fi.Symbol.Family.Id == family.Id);-- var nestedFamilies = new List<object>();-- // This is a simplified approach - full nested family detection requires family document access- foreach (var instance in collector)- {- var symbol = instance.Symbol;- nestedFamilies.Add(new- {- instanceId = instance.Id.IntegerValue,- symbolId = symbol.Id.IntegerValue,- symbolName = symbol.Name,- familyName = symbol.Family.Name- });- }-- return new- {- familyId = familyId,- familyName = family.Name,- instanceCount = nestedFamilies.Count,- instances = nestedFamilies.Take(100).ToList() // Limit for performance- };- }-- #endregion-- #region 7. Replace Family-- public static object ReplaceFamily(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int oldFamilyId = payload.GetProperty("old_family_id").GetInt32();- int newFamilyId = payload.GetProperty("new_family_id").GetInt32();-- Family oldFamily = doc.GetElement(new ElementId(oldFamilyId)) as Family;- Family newFamily = doc.GetElement(new ElementId(newFamilyId)) as Family;-- if (oldFamily == null || newFamily == null)- {- throw new Exception("One or both families not found");- }-- using (var trans = new Transaction(doc, "Replace Family"))- {- trans.Start();-- // Get all instances of old family- var instances = new FilteredElementCollector(doc)- .OfClass(typeof(FamilyInstance))- .Cast<FamilyInstance>()- .Where(fi => fi.Symbol.Family.Id == oldFamily.Id)- .ToList();-- // Get corresponding types from new family- var oldTypes = oldFamily.GetFamilySymbolIds().Select(id => doc.GetElement(id) as FamilySymbol).ToList();- var newTypes = newFamily.GetFamilySymbolIds().Select(id => doc.GetElement(id) as FamilySymbol).ToList();-- int replaced = 0;- foreach (var instance in instances)- {- // Find matching type in new family (by name)- string oldTypeName = instance.Symbol.Name;- var newType = newTypes.FirstOrDefault(t => t.Name == oldTypeName) ?? newTypes.FirstOrDefault();-- if (newType != null)- {- if (!newType.IsActive) newType.Activate();- instance.Symbol = newType;- replaced++;- }- }-- trans.Commit();-- return new- {- success = true,- oldFamily = new { id = oldFamilyId, name = oldFamily.Name },- newFamily = new { id = newFamilyId, name = newFamily.Name },- instancesReplaced = replaced- };- }- }-- #endregion-- #region 8. Transfer Standards-- public static object TransferStandards(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string sourceDocPath = payload.GetProperty("source_document_path").GetString();-- if (!File.Exists(sourceDocPath))- {- throw new Exception($"Source document not found: {sourceDocPath}");- }-- using (var trans = new Transaction(doc, "Transfer Standards"))- {- trans.Start();-- // Open source document- Document sourceDoc = app.Application.OpenDocumentFile(sourceDocPath);-- // Copy standards- CopyPasteOptions options = new CopyPasteOptions();- options.SetDuplicateTypeNamesHandler(new HideAndAcceptDuplicateTypeNamesHandler());-- // Transfer line patterns, fill patterns, etc.- // This is a simplified version - full implementation would transfer specific standards-- trans.Commit();-- // Close source document- sourceDoc.Close(false);-- return new- {- success = true,- sourceDocument = Path.GetFileName(sourceDocPath),- targetDocument = doc.Title,- message = "Standards transferred successfully"- };- }- }-- private class HideAndAcceptDuplicateTypeNamesHandler : IDuplicateTypeNamesHandler- {- public DuplicateTypeAction OnDuplicateTypeNamesFound(DuplicateTypeNamesHandlerArgs args)- {- return DuplicateTypeAction.UseDestinationTypes;- }- }-- #endregion-- #region 9. Purge Unused Families-- public static object PurgeUnusedFamilies(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- using (var trans = new Transaction(doc, "Purge Unused Families"))- {- trans.Start();-- // Get all families- var allFamilies = new FilteredElementCollector(doc)- .OfClass(typeof(Family))- .Cast<Family>()- .ToList();-- int purgedCount = 0;- var purgedFamilies = new List<object>();-- foreach (var family in allFamilies)- {- // Check if family has instances- var instances = new FilteredElementCollector(doc)- .OfClass(typeof(FamilyInstance))- .Cast<FamilyInstance>()- .Any(fi => fi.Symbol.Family.Id == family.Id);-- if (!instances)- {- try- {- doc.Delete(family.Id);- purgedCount++;- purgedFamilies.Add(new { id = family.Id.IntegerValue, name = family.Name });- }- catch- {- // Skip if family cannot be deleted- }- }- }-- trans.Commit();-- return new- {- success = true,- purgedCount = purgedCount,- purgedFamilies = purgedFamilies.Take(50).ToList() // Limit for performance- };- }- }-- #endregion-- #region 10. Get Family Category-- public static object GetFamilyCategory(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int familyId = payload.GetProperty("family_id").GetInt32();-- Family family = doc.GetElement(new ElementId(familyId)) as Family;- if (family == null)- {- throw new Exception($"Family {familyId} not found");- }-- return new- {- familyId = familyId,- familyName = family.Name,- categoryId = family.FamilyCategory.Id.IntegerValue,- categoryName = family.FamilyCategory.Name,- categoryType = family.FamilyCategory.CategoryType.ToString()- };- }-- #endregion-- #region 11. List Family Instances-- public static object ListFamilyInstances(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int familyId = payload.GetProperty("family_id").GetInt32();- int limit = payload.TryGetProperty("limit", out var lim) ? lim.GetInt32() : 100;-- Family family = doc.GetElement(new ElementId(familyId)) as Family;- if (family == null)- {- throw new Exception($"Family {familyId} not found");- }-- var instances = new FilteredElementCollector(doc)- .OfClass(typeof(FamilyInstance))- .Cast<FamilyInstance>()- .Where(fi => fi.Symbol.Family.Id == family.Id)- .Take(limit)- .Select(fi => new- {- id = fi.Id.IntegerValue,- typeId = fi.Symbol.Id.IntegerValue,- typeName = fi.Symbol.Name,- level = (doc.GetElement(fi.LevelId) as Level)?.Name ?? "None",- location = GetInstanceLocation(fi)- })- .ToList();-- return new- {- familyId = familyId,- familyName = family.Name,- totalInstances = instances.Count,- instances = instances- };- }-- #endregion-- #region 12. Swap Family Type-- public static object SwapFamilyType(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var instanceIds = payload.GetProperty("instance_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- int newTypeId = payload.GetProperty("new_type_id").GetInt32();-- FamilySymbol newSymbol = doc.GetElement(new ElementId(newTypeId)) as FamilySymbol;- if (newSymbol == null)- {- throw new Exception($"Family type {newTypeId} not found");- }-- using (var trans = new Transaction(doc, "Swap Family Type"))- {- trans.Start();-- if (!newSymbol.IsActive) newSymbol.Activate();-- int swapped = 0;- foreach (var id in instanceIds)- {- if (doc.GetElement(id) is FamilyInstance instance)- {- instance.Symbol = newSymbol;- swapped++;- }- }-- trans.Commit();-- return new- {- success = true,- newTypeId = newTypeId,- newTypeName = newSymbol.Name,- instancesSwapped = swapped- };- }- }-- #endregion-- #region Helper Methods-- private static bool SetParameterValue(Parameter param, JsonElement value)- {- switch (param.StorageType)- {- case StorageType.Integer:- return param.Set(value.GetInt32());- case StorageType.Double:- return param.Set(value.GetDouble());- case StorageType.String:- return param.Set(value.GetString());- case StorageType.ElementId:- return param.Set(new ElementId(value.GetInt32()));- default:- return false;- }- }-- private static object GetParameterValue(Parameter param)- {- switch (param.StorageType)- {- case StorageType.Integer:- return param.AsInteger();- case StorageType.Double:- return param.AsDouble();- case StorageType.String:- return param.AsString();- case StorageType.ElementId:- return param.AsElementId().IntegerValue;- default:- return null;- }- }-- private static object GetInstanceLocation(FamilyInstance instance)- {- var location = instance.Location;- if (location is LocationPoint lp)- {- return new { x = lp.Point.X, y = lp.Point.Y, z = lp.Point.Z };- }- else if (location is LocationCurve lc)- {- var start = lc.Curve.GetEndPoint(0);- var end = lc.Curve.GetEndPoint(1);- return new- {- type = "curve",- start = new { x = start.X, y = start.Y, z = start.Z },- end = new { x = end.X, y = end.Y, z = end.Z }- };- }- return null;- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Advanced/Geometry/GeometryCommands.cs b/packages/revit-bridge-addin/src/Commands/Advanced/Geometry/GeometryCommands.csdeleted file mode 100644index e2dde39..0000000--- a/packages/revit-bridge-addin/src/Commands/Advanced/Geometry/GeometryCommands.cs+++ /dev/null@@ -1,776 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Advanced.Geometry-{- /// <summary>- /// Advanced geometry manipulation commands- /// ElementTransformUtils (#3, Score: 286), JoinGeometryUtils (#10, Score: 280)- /// </summary>- public static class GeometryCommands- {- #region 1. Get Element Geometry-- public static object GetElementGeometry(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- string detailLevel = payload.TryGetProperty("detail_level", out var dl) ? dl.GetString() : "Fine";-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- Options geomOptions = new Options- {- ComputeReferences = true,- DetailLevel = detailLevel.ToLower() switch- {- "coarse" => ViewDetailLevel.Coarse,- "medium" => ViewDetailLevel.Medium,- _ => ViewDetailLevel.Fine- }- };-- GeometryElement geomElem = element.get_Geometry(geomOptions);- if (geomElem == null)- {- throw new Exception("Element has no geometry");- }-- var geometryData = new- {- elementId = elementId,- elementName = element.Name,- solids = ExtractSolids(geomElem),- faces = ExtractFaces(geomElem),- curves = ExtractCurves(geomElem),- instances = ExtractInstances(geomElem)- };-- return geometryData;- }-- private static List<object> ExtractSolids(GeometryElement geomElem)- {- var solids = new List<object>();- foreach (GeometryObject geomObj in geomElem)- {- if (geomObj is Solid solid && solid.Volume > 0.0001)- {- solids.Add(new- {- volume = solid.Volume,- surfaceArea = solid.SurfaceArea,- faceCount = solid.Faces.Size,- edgeCount = solid.Edges.Size- });- }- }- return solids;- }-- private static List<object> ExtractFaces(GeometryElement geomElem)- {- var faces = new List<object>();- foreach (GeometryObject geomObj in geomElem)- {- if (geomObj is Solid solid)- {- foreach (Face face in solid.Faces)- {- faces.Add(new- {- area = face.Area,- type = face.GetType().Name- });- }- }- }- return faces;- }-- private static List<object> ExtractCurves(GeometryElement geomElem)- {- var curves = new List<object>();- foreach (GeometryObject geomObj in geomElem)- {- if (geomObj is Curve curve)- {- curves.Add(new- {- length = curve.Length,- isBound = curve.IsBound,- type = curve.GetType().Name- });- }- }- return curves;- }-- private static int ExtractInstances(GeometryElement geomElem)- {- int count = 0;- foreach (GeometryObject geomObj in geomElem)- {- if (geomObj is GeometryInstance) count++;- }- return count;- }-- #endregion-- #region 2-3. Join/Unjoin Geometry-- public static object JoinGeometry(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int element1Id = payload.GetProperty("element1_id").GetInt32();- int element2Id = payload.GetProperty("element2_id").GetInt32();-- Element element1 = doc.GetElement(new ElementId(element1Id));- Element element2 = doc.GetElement(new ElementId(element2Id));-- if (element1 == null || element2 == null)- {- throw new Exception("One or both elements not found");- }-- using (var trans = new Transaction(doc, "Join Geometry"))- {- trans.Start();-- JoinGeometryUtils.JoinGeometry(doc, element1, element2);-- trans.Commit();-- return new- {- success = true,- element1 = new { id = element1Id, name = element1.Name },- element2 = new { id = element2Id, name = element2.Name },- message = "Geometry joined successfully"- };- }- }-- public static object UnjoinGeometry(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int element1Id = payload.GetProperty("element1_id").GetInt32();- int element2Id = payload.GetProperty("element2_id").GetInt32();-- Element element1 = doc.GetElement(new ElementId(element1Id));- Element element2 = doc.GetElement(new ElementId(element2Id));-- if (element1 == null || element2 == null)- {- throw new Exception("One or both elements not found");- }-- using (var trans = new Transaction(doc, "Unjoin Geometry"))- {- trans.Start();-- JoinGeometryUtils.UnjoinGeometry(doc, element1, element2);-- trans.Commit();-- return new- {- success = true,- element1 = new { id = element1Id, name = element1.Name },- element2 = new { id = element2Id, name = element2.Name },- message = "Geometry unjoined successfully"- };- }- }-- #endregion-- #region 4. Cut Geometry-- public static object CutGeometry(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int cuttingElementId = payload.GetProperty("cutting_element_id").GetInt32();- int cutElementId = payload.GetProperty("cut_element_id").GetInt32();-- Element cuttingElement = doc.GetElement(new ElementId(cuttingElementId));- Element cutElement = doc.GetElement(new ElementId(cutElementId));-- if (cuttingElement == null || cutElement == null)- {- throw new Exception("One or both elements not found");- }-- using (var trans = new Transaction(doc, "Cut Geometry"))- {- trans.Start();-- SolidSolidCutUtils.AddCutBetweenSolids(doc, cuttingElement, cutElement);-- trans.Commit();-- return new- {- success = true,- cuttingElement = new { id = cuttingElementId, name = cuttingElement.Name },- cutElement = new { id = cutElementId, name = cutElement.Name },- message = "Cut applied successfully"- };- }- }-- #endregion-- #region 5-6. Array Elements-- public static object ArrayElementsLinear(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- int count = payload.GetProperty("count").GetInt32();- var vector = payload.GetProperty("vector");-- XYZ displacement = new XYZ(- vector.GetProperty("x").GetDouble(),- vector.GetProperty("y").GetDouble(),- vector.GetProperty("z").GetDouble()- );-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- using (var trans = new Transaction(doc, "Linear Array"))- {- trans.Start();-- var newElementIds = new List<int>();-- for (int i = 1; i < count; i++)- {- XYZ offset = displacement * i;- var copiedIds = ElementTransformUtils.CopyElement(doc, element.Id, offset);- newElementIds.AddRange(copiedIds.Select(id => id.IntegerValue));- }-- trans.Commit();-- return new- {- success = true,- originalElement = new { id = elementId, name = element.Name },- copiesCreated = newElementIds.Count,- newElementIds = newElementIds- };- }- }-- public static object ArrayElementsRadial(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- int count = payload.GetProperty("count").GetInt32();- var centerPoint = payload.GetProperty("center_point");- double totalAngle = payload.TryGetProperty("total_angle", out var ta) ? ta.GetDouble() : 360.0;-- XYZ center = new XYZ(- centerPoint.GetProperty("x").GetDouble(),- centerPoint.GetProperty("y").GetDouble(),- centerPoint.GetProperty("z").GetDouble()- );-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- using (var trans = new Transaction(doc, "Radial Array"))- {- trans.Start();-- var newElementIds = new List<int>();- Line axis = Line.CreateBound(center, center + XYZ.BasisZ);- double angleIncrement = (totalAngle * Math.PI / 180.0) / count;-- for (int i = 1; i < count; i++)- {- double angle = angleIncrement * i;- var copiedIds = ElementTransformUtils.CopyElement(doc, element.Id, XYZ.Zero);- ElementTransformUtils.RotateElement(doc, copiedIds.First(), axis, angle);- newElementIds.AddRange(copiedIds.Select(id => id.IntegerValue));- }-- trans.Commit();-- return new- {- success = true,- originalElement = new { id = elementId, name = element.Name },- copiesCreated = newElementIds.Count,- centerPoint = new { center.X, center.Y, center.Z },- totalAngle = totalAngle,- newElementIds = newElementIds- };- }- }-- #endregion-- #region 7-8. Align and Distribute Elements-- public static object AlignElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- string alignment = payload.GetProperty("alignment").GetString(); // left, right, top, bottom, center_x, center_y-- if (elementIds.Count < 2)- {- throw new Exception("Need at least 2 elements to align");- }-- using (var trans = new Transaction(doc, "Align Elements"))- {- trans.Start();-- // Get bounding boxes- var elements = elementIds.Select(id => doc.GetElement(id)).ToList();- var bboxes = elements.Select(e => e.get_BoundingBox(null)).ToList();-- // Calculate reference position from first element- BoundingBoxXYZ refBox = bboxes[0];- double refPos = alignment.ToLower() switch- {- "left" => refBox.Min.X,- "right" => refBox.Max.X,- "bottom" => refBox.Min.Y,- "top" => refBox.Max.Y,- "center_x" => (refBox.Min.X + refBox.Max.X) / 2,- "center_y" => (refBox.Min.Y + refBox.Max.Y) / 2,- _ => refBox.Min.X- };-- // Move other elements- for (int i = 1; i < elements.Count; i++)- {- BoundingBoxXYZ bbox = bboxes[i];- double currentPos = alignment.ToLower() switch- {- "left" => bbox.Min.X,- "right" => bbox.Max.X,- "bottom" => bbox.Min.Y,- "top" => bbox.Max.Y,- "center_x" => (bbox.Min.X + bbox.Max.X) / 2,- "center_y" => (bbox.Min.Y + bbox.Max.Y) / 2,- _ => bbox.Min.X- };-- XYZ offset = alignment.ToLower() switch- {- "left" or "right" or "center_x" => new XYZ(refPos - currentPos, 0, 0),- "bottom" or "top" or "center_y" => new XYZ(0, refPos - currentPos, 0),- _ => XYZ.Zero- };-- ElementTransformUtils.MoveElement(doc, elementIds[i], offset);- }-- trans.Commit();-- return new- {- success = true,- alignedCount = elementIds.Count,- alignment = alignment,- elementIds = elementIds.Select(id => id.IntegerValue).ToList()- };- }- }-- public static object DistributeElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- string direction = payload.GetProperty("direction").GetString(); // horizontal, vertical-- if (elementIds.Count < 3)- {- throw new Exception("Need at least 3 elements to distribute");- }-- using (var trans = new Transaction(doc, "Distribute Elements"))- {- trans.Start();-- var elements = elementIds.Select(id => doc.GetElement(id)).ToList();- var bboxes = elements.Select(e => e.get_BoundingBox(null)).ToList();-- // Sort by position- bool isHorizontal = direction.ToLower() == "horizontal";- var sorted = elements.Zip(bboxes, (elem, bbox) => new { elem, bbox, elementId = elem.Id })- .OrderBy(x => isHorizontal ? x.bbox.Min.X : x.bbox.Min.Y)- .ToList();-- // Calculate spacing- double start = isHorizontal ? sorted.First().bbox.Min.X : sorted.First().bbox.Min.Y;- double end = isHorizontal ? sorted.Last().bbox.Max.X : sorted.Last().bbox.Max.Y;- double totalSpan = end - start;-- // Calculate centers and redistribute- double spacing = totalSpan / (sorted.Count - 1);-- for (int i = 1; i < sorted.Count - 1; i++)- {- double targetPos = start + spacing * i;- double currentPos = isHorizontal- ? (sorted[i].bbox.Min.X + sorted[i].bbox.Max.X) / 2- : (sorted[i].bbox.Min.Y + sorted[i].bbox.Max.Y) / 2;-- XYZ offset = isHorizontal- ? new XYZ(targetPos - currentPos, 0, 0)- : new XYZ(0, targetPos - currentPos, 0);-- ElementTransformUtils.MoveElement(doc, sorted[i].elementId, offset);- }-- trans.Commit();-- return new- {- success = true,- distributedCount = elementIds.Count,- direction = direction,- spacing = spacing,- elementIds = sorted.Select(x => x.elementId.IntegerValue).ToList()- };- }- }-- #endregion-- #region 9. Offset Curves-- public static object OffsetCurves(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- double offset = payload.GetProperty("offset").GetDouble();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- if (!(element is CurveElement curveElement))- {- throw new Exception("Element is not a curve element");- }-- using (var trans = new Transaction(doc, "Offset Curves"))- {- trans.Start();-- Curve originalCurve = curveElement.GeometryCurve;- XYZ normal = XYZ.BasisZ; // Offset in plan-- Curve offsetCurve = originalCurve.CreateOffset(offset, normal);-- // Create new curve element- SketchPlane sketchPlane = element is ModelCurve mc ? mc.SketchPlane : null;- ModelCurve newCurve = doc.Create.NewModelCurve(offsetCurve, sketchPlane);-- trans.Commit();-- return new- {- success = true,- originalElement = new { id = elementId, name = element.Name },- newElementId = newCurve.Id.IntegerValue,- offset = offset- };- }- }-- #endregion-- #region 10-14. Direct Shape and Solid Creation-- public static object CreateDirectShape(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string name = payload.GetProperty("name").GetString();- string categoryName = payload.GetProperty("category").GetString();-- if (!Enum.TryParse(categoryName, out BuiltInCategory builtInCat))- {- throw new Exception($"Unknown category: {categoryName}");- }-- using (var trans = new Transaction(doc, "Create Direct Shape"))- {- trans.Start();-- DirectShape ds = DirectShape.CreateElement(doc, new ElementId(builtInCat));- ds.Name = name;-- // Note: Actual geometry would be added via SetShape() with GeometryObject list- // This is a template - geometry construction requires more complex payload-- trans.Commit();-- return new- {- success = true,- directShapeId = ds.Id.IntegerValue,- name = name,- category = categoryName,- message = "DirectShape created - use SetShape to add geometry"- };- }- }-- public static object CreateSolidExtrusion(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string name = payload.GetProperty("name").GetString();- var profilePoints = payload.GetProperty("profile_points").EnumerateArray();- double height = payload.GetProperty("height").GetDouble();-- using (var trans = new Transaction(doc, "Create Solid Extrusion"))- {- trans.Start();-- // Create profile curve loop- List<Curve> curves = new List<Curve>();- XYZ previousPoint = null;- XYZ firstPoint = null;-- foreach (var pt in profilePoints)- {- XYZ point = new XYZ(- pt.GetProperty("x").GetDouble(),- pt.GetProperty("y").GetDouble(),- pt.GetProperty("z").GetDouble()- );-- if (firstPoint == null) firstPoint = point;-- if (previousPoint != null)- {- curves.Add(Line.CreateBound(previousPoint, point));- }-- previousPoint = point;- }-- // Close the loop- if (previousPoint != null && firstPoint != null)- {- curves.Add(Line.CreateBound(previousPoint, firstPoint));- }-- CurveLoop profile = CurveLoop.Create(curves);- List<CurveLoop> loops = new List<CurveLoop> { profile };-- // Create extrusion as DirectShape- Solid solid = GeometryCreationUtilities.CreateExtrusionGeometry(loops, XYZ.BasisZ, height);-- DirectShape ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel));- ds.SetShape(new List<GeometryObject> { solid });- ds.Name = name;-- trans.Commit();-- return new- {- success = true,- directShapeId = ds.Id.IntegerValue,- name = name,- volume = solid.Volume,- height = height- };- }- }-- // Simplified implementations for remaining geometry tools- public static object CreateSolidRevolution(UIApplication app, JsonElement payload)- {- return new { success = true, message = "Solid revolution - implementation requires complex profile definition" };- }-- public static object CreateSolidSweep(UIApplication app, JsonElement payload)- {- return new { success = true, message = "Solid sweep - implementation requires path and profile definition" };- }-- public static object CreateSolidBlend(UIApplication app, JsonElement payload)- {- return new { success = true, message = "Solid blend - implementation requires two profiles definition" };- }-- #endregion-- #region 15-17. Boolean Operations-- public static object BooleanUnion(UIApplication app, JsonElement payload)- {- return new { success = true, message = "Boolean union - requires BooleanOperationsUtils.ExecuteBooleanOperation" };- }-- public static object BooleanIntersect(UIApplication app, JsonElement payload)- {- return new { success = true, message = "Boolean intersect - requires BooleanOperationsUtils.ExecuteBooleanOperation" };- }-- public static object BooleanSubtract(UIApplication app, JsonElement payload)- {- return new { success = true, message = "Boolean subtract - requires BooleanOperationsUtils.ExecuteBooleanOperation" };- }-- #endregion-- #region 18-20. Additional Geometry Tools-- public static object GetElementFaces(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- Options geomOptions = new Options { ComputeReferences = true };- GeometryElement geomElem = element.get_Geometry(geomOptions);-- var faces = new List<object>();- foreach (GeometryObject geomObj in geomElem)- {- if (geomObj is Solid solid)- {- int faceIndex = 0;- foreach (Face face in solid.Faces)- {- faces.Add(new- {- index = faceIndex++,- area = face.Area,- type = face.GetType().Name,- materialId = face.MaterialElementId.IntegerValue- });- }- }- }-- return new- {- elementId = elementId,- elementName = element.Name,- faceCount = faces.Count,- faces = faces- };- }-- public static object GetElementEdges(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- Options geomOptions = new Options { ComputeReferences = true };- GeometryElement geomElem = element.get_Geometry(geomOptions);-- var edges = new List<object>();- foreach (GeometryObject geomObj in geomElem)- {- if (geomObj is Solid solid)- {- foreach (Edge edge in solid.Edges)- {- Curve curve = edge.AsCurve();- edges.Add(new- {- length = curve.Length,- isBound = curve.IsBound- });- }- }- }-- return new- {- elementId = elementId,- elementName = element.Name,- edgeCount = edges.Count,- totalLength = edges.Sum(e => (double)((dynamic)e).length)- };- }-- public static object CreateCurveLoop(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var points = payload.GetProperty("points").EnumerateArray();-- List<Curve> curves = new List<Curve>();- XYZ previousPoint = null;- XYZ firstPoint = null;-- foreach (var pt in points)- {- XYZ point = new XYZ(- pt.GetProperty("x").GetDouble(),- pt.GetProperty("y").GetDouble(),- pt.GetProperty("z").GetDouble()- );-- if (firstPoint == null) firstPoint = point;-- if (previousPoint != null)- {- curves.Add(Line.CreateBound(previousPoint, point));- }-- previousPoint = point;- }-- // Close the loop- if (previousPoint != null && firstPoint != null)- {- curves.Add(Line.CreateBound(previousPoint, firstPoint));- }-- CurveLoop loop = CurveLoop.Create(curves);-- return new- {- success = true,- curveCount = curves.Count,- isOpen = loop.IsOpen(),- length = curves.Sum(c => c.Length),- message = "CurveLoop created (in-memory object)"- };- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Advanced/Links/LinkCommands.cs b/packages/revit-bridge-addin/src/Commands/Advanced/Links/LinkCommands.csdeleted file mode 100644index 1230341..0000000--- a/packages/revit-bridge-addin/src/Commands/Advanced/Links/LinkCommands.cs+++ /dev/null@@ -1,404 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using System.IO;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Advanced.Links-{- /// <summary>- /// Link and import management commands- /// RevitLinkType (#19, Score: 267), RevitLinkInstance (#20, Score: 266)- /// </summary>- public static class LinkCommands- {- #region 1. Load Link-- public static object LoadLink(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string linkPath = payload.GetProperty("link_path").GetString();- bool absolute = payload.TryGetProperty("absolute_path", out var abs) ? abs.GetBoolean() : true;-- if (!File.Exists(linkPath))- {- throw new Exception($"Link file not found: {linkPath}");- }-- using (var trans = new Transaction(doc, "Load Link"))- {- trans.Start();-- ModelPath modelPath = absolute- ? ModelPathUtils.ConvertUserVisiblePathToModelPath(linkPath)- : ModelPathUtils.ConvertUserVisiblePathToModelPath(Path.GetFileName(linkPath));-- RevitLinkOptions options = new RevitLinkOptions(false);- LinkLoadResult result = RevitLinkType.Create(doc, modelPath, options);-- trans.Commit();-- if (result != null)- {- return new- {- success = true,- linkTypeId = result.ElementId.IntegerValue,- loadResult = result.LoadResult.ToString(),- linkPath = linkPath- };- }-- throw new Exception("Failed to create link");- }- }-- #endregion-- #region 2. Unload Link-- public static object UnloadLink(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int linkInstanceId = payload.GetProperty("link_instance_id").GetInt32();-- RevitLinkInstance linkInstance = doc.GetElement(new ElementId(linkInstanceId)) as RevitLinkInstance;- if (linkInstance == null)- {- throw new Exception($"Link instance {linkInstanceId} not found");- }-- using (var trans = new Transaction(doc, "Unload Link"))- {- trans.Start();-- RevitLinkType linkType = doc.GetElement(linkInstance.GetTypeId()) as RevitLinkType;- if (linkType != null)- {- linkType.Unload(null);- }-- trans.Commit();-- return new- {- success = true,- linkInstanceId = linkInstanceId,- linkTypeName = linkType?.Name ?? "Unknown",- message = "Link unloaded successfully"- };- }- }-- #endregion-- #region 3. Reload Link-- public static object ReloadLink(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int linkInstanceId = payload.GetProperty("link_instance_id").GetInt32();-- RevitLinkInstance linkInstance = doc.GetElement(new ElementId(linkInstanceId)) as RevitLinkInstance;- if (linkInstance == null)- {- throw new Exception($"Link instance {linkInstanceId} not found");- }-- using (var trans = new Transaction(doc, "Reload Link"))- {- trans.Start();-- RevitLinkType linkType = doc.GetElement(linkInstance.GetTypeId()) as RevitLinkType;- if (linkType != null)- {- linkType.Reload();- }-- trans.Commit();-- return new- {- success = true,- linkInstanceId = linkInstanceId,- linkTypeName = linkType?.Name ?? "Unknown",- isLoaded = linkType?.IsLoaded ?? false,- message = "Link reloaded successfully"- };- }- }-- #endregion-- #region 4. Get Link Transform-- public static object GetLinkTransform(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int linkInstanceId = payload.GetProperty("link_instance_id").GetInt32();-- RevitLinkInstance linkInstance = doc.GetElement(new ElementId(linkInstanceId)) as RevitLinkInstance;- if (linkInstance == null)- {- throw new Exception($"Link instance {linkInstanceId} not found");- }-- Transform transform = linkInstance.GetTotalTransform();-- return new- {- linkInstanceId = linkInstanceId,- linkName = linkInstance.Name,- translation = new- {- x = transform.Origin.X,- y = transform.Origin.Y,- z = transform.Origin.Z- },- rotation = new- {- basisX = new { x = transform.BasisX.X, y = transform.BasisX.Y, z = transform.BasisX.Z },- basisY = new { x = transform.BasisY.X, y = transform.BasisY.Y, z = transform.BasisY.Z },- basisZ = new { x = transform.BasisZ.X, y = transform.BasisZ.Y, z = transform.BasisZ.Z }- },- scale = transform.Scale,- isIdentity = transform.IsIdentity- };- }-- #endregion-- #region 5. Set Link Visibility-- public static object SetLinkVisibility(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int linkInstanceId = payload.GetProperty("link_instance_id").GetInt32();- int viewId = payload.GetProperty("view_id").GetInt32();- bool visible = payload.GetProperty("visible").GetBoolean();-- RevitLinkInstance linkInstance = doc.GetElement(new ElementId(linkInstanceId)) as RevitLinkInstance;- View view = doc.GetElement(new ElementId(viewId)) as View;-- if (linkInstance == null || view == null)- {- throw new Exception("Link instance or view not found");- }-- using (var trans = new Transaction(doc, "Set Link Visibility"))- {- trans.Start();-- if (visible)- {- view.UnhideElements(new List<ElementId> { linkInstance.Id });- }- else- {- view.HideElements(new List<ElementId> { linkInstance.Id });- }-- trans.Commit();-- return new- {- success = true,- linkInstanceId = linkInstanceId,- linkName = linkInstance.Name,- viewId = viewId,- viewName = view.Name,- visible = visible- };- }- }-- #endregion-- #region 6. Import CAD-- public static object ImportCAD(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string cadPath = payload.GetProperty("cad_path").GetString();- string importMode = payload.TryGetProperty("import_mode", out var im) ? im.GetString() : "link";-- if (!File.Exists(cadPath))- {- throw new Exception($"CAD file not found: {cadPath}");- }-- using (var trans = new Transaction(doc, "Import CAD"))- {- trans.Start();-- DWGImportOptions importOptions = new DWGImportOptions- {- ColorMode = ImportColorMode.Preserved,- Unit = ImportUnit.Default,- Placement = ImportPlacement.Origin- };-- ElementId importedId = ElementId.InvalidElementId;-- if (importMode.ToLower() == "link")- {- doc.Link(cadPath, importOptions, doc.ActiveView, out importedId);- }- else- {- doc.Import(cadPath, importOptions, doc.ActiveView, out importedId);- }-- trans.Commit();-- return new- {- success = true,- importedElementId = importedId.IntegerValue,- cadPath = cadPath,- importMode = importMode,- viewId = doc.ActiveView.Id.IntegerValue,- viewName = doc.ActiveView.Name- };- }- }-- #endregion-- #region 7. Manage CAD Import-- public static object ManageCADImport(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int importInstanceId = payload.GetProperty("import_instance_id").GetInt32();- string action = payload.GetProperty("action").GetString(); // show_layers, hide_layers, delete-- ImportInstance importInstance = doc.GetElement(new ElementId(importInstanceId)) as ImportInstance;- if (importInstance == null)- {- throw new Exception($"Import instance {importInstanceId} not found");- }-- using (var trans = new Transaction(doc, "Manage CAD Import"))- {- trans.Start();-- switch (action.ToLower())- {- case "delete":- doc.Delete(importInstance.Id);- break;-- case "explode":- // Explode import (if supported)- break;-- default:- throw new Exception($"Unknown action: {action}");- }-- trans.Commit();-- return new- {- success = true,- importInstanceId = importInstanceId,- action = action,- message = $"Action '{action}' completed"- };- }- }-- #endregion-- #region 8. Bind Link-- public static object BindLink(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int linkInstanceId = payload.GetProperty("link_instance_id").GetInt32();-- RevitLinkInstance linkInstance = doc.GetElement(new ElementId(linkInstanceId)) as RevitLinkInstance;- if (linkInstance == null)- {- throw new Exception($"Link instance {linkInstanceId} not found");- }-- using (var trans = new Transaction(doc, "Bind Link"))- {- trans.Start();-- // Binding converts link to group - this is a simplified version- // Full implementation would require copying all elements from linked document-- trans.Commit();-- return new- {- success = true,- linkInstanceId = linkInstanceId,- linkName = linkInstance.Name,- message = "Link bind operation initiated (partial implementation)"- };- }- }-- #endregion-- #region 9. Get Link Elements (Already implemented in Phase 1)-- public static object GetLinkElementsAdvanced(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int linkInstanceId = payload.GetProperty("link_instance_id").GetInt32();- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;- int limit = payload.TryGetProperty("limit", out var lim) ? lim.GetInt32() : 1000;-- RevitLinkInstance linkInstance = doc.GetElement(new ElementId(linkInstanceId)) as RevitLinkInstance;- if (linkInstance == null)- {- throw new Exception($"Link instance {linkInstanceId} not found");- }-- Document linkedDoc = linkInstance.GetLinkDocument();- if (linkedDoc == null)- {- throw new Exception("Linked document is not loaded");- }-- var collector = new FilteredElementCollector(linkedDoc).WhereElementIsNotElementType();-- if (!string.IsNullOrEmpty(category))- {- if (Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }- }-- var elements = collector.Take(limit)- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId,- level = (linkedDoc.GetElement(e.LevelId) as Level)?.Name ?? "None"- })- .ToList();-- return new- {- linkInstanceId = linkInstanceId,- linkName = linkedDoc.Title,- totalElements = collector.GetElementCount(),- returnedElements = elements.Count,- elements = elements- };- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Advanced/Phase2CommandRegistry.cs b/packages/revit-bridge-addin/src/Commands/Advanced/Phase2CommandRegistry.csdeleted file mode 100644index a763c32..0000000--- a/packages/revit-bridge-addin/src/Commands/Advanced/Phase2CommandRegistry.cs+++ /dev/null@@ -1,160 +0,0 @@-using System;-using System.Text.Json;-using Autodesk.Revit.UI;-using RevitBridge.Commands.Advanced.Geometry;-using RevitBridge.Commands.Advanced.Families;-using RevitBridge.Commands.Advanced.Worksharing;-using RevitBridge.Commands.Advanced.Links;--namespace RevitBridge.Commands.Advanced-{- /// <summary>- /// Registry for Phase 2 commands (51 professional tools)- /// High-value additions for advanced professional workflows- /// </summary>- public static class Phase2CommandRegistry- {- public static object Execute(UIApplication app, string tool, JsonElement payload)- {- return tool switch- {- // === GEOMETRY COMMANDS (20 tools) - Advanced Modeling ===- // ElementTransformUtils (#3, Score: 286), JoinGeometryUtils (#10, Score: 280)-- "revit.get_element_geometry" => GeometryCommands.GetElementGeometry(app, payload),- "revit.get_element_faces" => GeometryCommands.GetElementFaces(app, payload),- "revit.get_element_edges" => GeometryCommands.GetElementEdges(app, payload),- "revit.join_geometry" => GeometryCommands.JoinGeometry(app, payload),- "revit.unjoin_geometry" => GeometryCommands.UnjoinGeometry(app, payload),- "revit.cut_geometry" => GeometryCommands.CutGeometry(app, payload),- "revit.array_elements_linear" => GeometryCommands.ArrayElementsLinear(app, payload),- "revit.array_elements_radial" => GeometryCommands.ArrayElementsRadial(app, payload),- "revit.align_elements" => GeometryCommands.AlignElements(app, payload),- "revit.distribute_elements" => GeometryCommands.DistributeElements(app, payload),- "revit.offset_curves" => GeometryCommands.OffsetCurves(app, payload),- "revit.create_direct_shape" => GeometryCommands.CreateDirectShape(app, payload),- "revit.create_solid_extrusion" => GeometryCommands.CreateSolidExtrusion(app, payload),- "revit.create_solid_revolution" => GeometryCommands.CreateSolidRevolution(app, payload),- "revit.create_solid_sweep" => GeometryCommands.CreateSolidSweep(app, payload),- "revit.create_solid_blend" => GeometryCommands.CreateSolidBlend(app, payload),- "revit.boolean_union" => GeometryCommands.BooleanUnion(app, payload),- "revit.boolean_intersect" => GeometryCommands.BooleanIntersect(app, payload),- "revit.boolean_subtract" => GeometryCommands.BooleanSubtract(app, payload),- "revit.create_curve_loop" => GeometryCommands.CreateCurveLoop(app, payload),-- // === FAMILY COMMANDS (12 tools) - Content Management ===- // Family (#17, Score: 272), FamilySymbol (#18, Score: 271)-- "revit.load_family" => FamilyCommands.LoadFamily(app, payload),- "revit.reload_family" => FamilyCommands.ReloadFamily(app, payload),- "revit.duplicate_family_type" => FamilyCommands.DuplicateFamilyType(app, payload),- "revit.rename_family_type" => FamilyCommands.RenameFamilyType(app, payload),- "revit.set_family_type_parameter" => FamilyCommands.SetFamilyTypeParameter(app, payload),- "revit.get_nested_families" => FamilyCommands.GetNestedFamilies(app, payload),- "revit.replace_family" => FamilyCommands.ReplaceFamily(app, payload),- "revit.transfer_standards" => FamilyCommands.TransferStandards(app, payload),- "revit.purge_unused_families" => FamilyCommands.PurgeUnusedFamilies(app, payload),- "revit.get_family_category" => FamilyCommands.GetFamilyCategory(app, payload),- "revit.list_family_instances" => FamilyCommands.ListFamilyInstances(app, payload),- "revit.swap_family_type" => FamilyCommands.SwapFamilyType(app, payload),-- // === WORKSHARING COMMANDS (10 tools) - Collaboration ===- // WorksharingUtils (#16, Score: 273)-- "revit.create_workset" => WorksharingCommands.CreateWorkset(app, payload),- "revit.rename_workset" => WorksharingCommands.RenameWorkset(app, payload),- "revit.set_element_workset" => WorksharingCommands.SetElementWorkset(app, payload),- "revit.get_element_workset" => WorksharingCommands.GetElementWorkset(app, payload),- "revit.checkout_elements" => WorksharingCommands.CheckoutElements(app, payload),- "revit.get_workset_owner" => WorksharingCommands.GetWorksetOwner(app, payload),- "revit.enable_worksharing" => WorksharingCommands.EnableWorksharing(app, payload),- "revit.get_central_path" => WorksharingCommands.GetCentralPath(app, payload),- "revit.set_workset_visibility" => WorksharingCommands.SetWorksetVisibility(app, payload),- "revit.get_workset_visibility" => WorksharingCommands.GetWorksetVisibility(app, payload),-- // === LINK COMMANDS (9 tools) - Integration ===- // RevitLinkType (#19, Score: 267), RevitLinkInstance (#20, Score: 266)-- "revit.load_link" => LinkCommands.LoadLink(app, payload),- "revit.unload_link" => LinkCommands.UnloadLink(app, payload),- "revit.reload_link" => LinkCommands.ReloadLink(app, payload),- "revit.get_link_transform" => LinkCommands.GetLinkTransform(app, payload),- "revit.set_link_visibility" => LinkCommands.SetLinkVisibility(app, payload),- "revit.import_cad" => LinkCommands.ImportCAD(app, payload),- "revit.manage_cad_import" => LinkCommands.ManageCADImport(app, payload),- "revit.bind_link" => LinkCommands.BindLink(app, payload),- "revit.get_link_elements_advanced" => LinkCommands.GetLinkElementsAdvanced(app, payload),-- _ => null // Return null to let main factory handle unknown commands- };- }-- /// <summary>- /// Get list of all Phase 2 command names for documentation/validation- /// </summary>- public static string[] GetCommandNames()- {- return new[]- {- // Geometry (20)- "revit.get_element_geometry",- "revit.get_element_faces",- "revit.get_element_edges",- "revit.join_geometry",- "revit.unjoin_geometry",- "revit.cut_geometry",- "revit.array_elements_linear",- "revit.array_elements_radial",- "revit.align_elements",- "revit.distribute_elements",- "revit.offset_curves",- "revit.create_direct_shape",- "revit.create_solid_extrusion",- "revit.create_solid_revolution",- "revit.create_solid_sweep",- "revit.create_solid_blend",- "revit.boolean_union",- "revit.boolean_intersect",- "revit.boolean_subtract",- "revit.create_curve_loop",-- // Families (12)- "revit.load_family",- "revit.reload_family",- "revit.duplicate_family_type",- "revit.rename_family_type",- "revit.set_family_type_parameter",- "revit.get_nested_families",- "revit.replace_family",- "revit.transfer_standards",- "revit.purge_unused_families",- "revit.get_family_category",- "revit.list_family_instances",- "revit.swap_family_type",-- // Worksharing (10)- "revit.create_workset",- "revit.rename_workset",- "revit.set_element_workset",- "revit.get_element_workset",- "revit.checkout_elements",- "revit.get_workset_owner",- "revit.enable_worksharing",- "revit.get_central_path",- "revit.set_workset_visibility",- "revit.get_workset_visibility",-- // Links (9)- "revit.load_link",- "revit.unload_link",- "revit.reload_link",- "revit.get_link_transform",- "revit.set_link_visibility",- "revit.import_cad",- "revit.manage_cad_import",- "revit.bind_link",- "revit.get_link_elements_advanced"- };- }- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Advanced/Worksharing/WorksharingCommands.cs b/packages/revit-bridge-addin/src/Commands/Advanced/Worksharing/WorksharingCommands.csdeleted file mode 100644index 7769c87..0000000--- a/packages/revit-bridge-addin/src/Commands/Advanced/Worksharing/WorksharingCommands.cs+++ /dev/null@@ -1,384 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Advanced.Worksharing-{- /// <summary>- /// Worksharing and workset management commands- /// WorksharingUtils (#16, Score: 273), Workset (#440, Score: 187)- /// </summary>- public static class WorksharingCommands- {- #region 1. Create Workset-- public static object CreateWorkset(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string worksetName = payload.GetProperty("name").GetString();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- using (var trans = new Transaction(doc, "Create Workset"))- {- trans.Start();-- Workset newWorkset = Workset.Create(doc, worksetName);-- trans.Commit();-- return new- {- success = true,- worksetId = newWorkset.Id.IntegerValue,- worksetName = newWorkset.Name,- kind = newWorkset.Kind.ToString(),- isOpen = newWorkset.IsOpen- };- }- }-- #endregion-- #region 2. Rename Workset-- public static object RenameWorkset(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int worksetId = payload.GetProperty("workset_id").GetInt32();- string newName = payload.GetProperty("new_name").GetString();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- using (var trans = new Transaction(doc, "Rename Workset"))- {- trans.Start();-- WorksetTable worksetTable = doc.GetWorksetTable();- Workset workset = worksetTable.GetWorkset(new WorksetId(worksetId));-- string oldName = workset.Name;- WorksetTable.RenameWorkset(doc, new WorksetId(worksetId), newName);-- trans.Commit();-- return new- {- success = true,- worksetId = worksetId,- oldName = oldName,- newName = newName- };- }- }-- #endregion-- #region 3. Set Element Workset-- public static object SetElementWorkset(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- int worksetId = payload.GetProperty("workset_id").GetInt32();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- using (var trans = new Transaction(doc, "Set Element Workset"))- {- trans.Start();-- Parameter worksetParam = element.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);- if (worksetParam != null)- {- worksetParam.Set(worksetId);- }-- trans.Commit();-- return new- {- success = true,- elementId = elementId,- elementName = element.Name,- worksetId = worksetId,- worksetName = doc.GetWorksetTable().GetWorkset(new WorksetId(worksetId)).Name- };- }- }-- #endregion-- #region 4. Get Element Workset-- public static object GetElementWorkset(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- Parameter worksetParam = element.get_Parameter(BuiltInParameter.ELEM_PARTITION_PARAM);- if (worksetParam == null)- {- return new { elementId = elementId, workset = "None" };- }-- WorksetId worksetId = new WorksetId(worksetParam.AsInteger());- Workset workset = doc.GetWorksetTable().GetWorkset(worksetId);-- return new- {- elementId = elementId,- elementName = element.Name,- worksetId = worksetId.IntegerValue,- worksetName = workset.Name,- isOpen = workset.IsOpen,- isEditable = workset.IsEditable- };- }-- #endregion-- #region 5. Checkout Elements-- public static object CheckoutElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray()- .Select(e => new ElementId(e.GetInt32())).ToList();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- using (var trans = new Transaction(doc, "Checkout Elements"))- {- trans.Start();-- int checkedOut = 0;- var results = new List<object>();-- foreach (var id in elementIds)- {- Element element = doc.GetElement(id);- if (element != null)- {- WorksharingUtils.CheckoutElements(doc, new List<ElementId> { id });- checkedOut++;- results.Add(new { id = id.IntegerValue, name = element.Name, status = "checked_out" });- }- }-- trans.Commit();-- return new- {- success = true,- requestedCount = elementIds.Count,- checkedOutCount = checkedOut,- elements = results- };- }- }-- #endregion-- #region 6. Get Workset Owner-- public static object GetWorksetOwner(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int worksetId = payload.GetProperty("workset_id").GetInt32();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- WorksetTable worksetTable = doc.GetWorksetTable();- Workset workset = worksetTable.GetWorkset(new WorksetId(worksetId));-- string owner = WorksharingUtils.GetWorksharingTooltipInfo(doc, new WorksetId(worksetId)).Owner;-- return new- {- worksetId = worksetId,- worksetName = workset.Name,- owner = owner,- isOpen = workset.IsOpen,- isEditable = workset.IsEditable,- kind = workset.Kind.ToString()- };- }-- #endregion-- #region 7. Enable Worksharing-- public static object EnableWorksharing(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string defaultWorksetName = payload.TryGetProperty("default_workset_name", out var dwn)- ? dwn.GetString()- : "Shared Levels and Grids";-- if (doc.IsWorkshared)- {- return new { success = false, message = "Document is already workshared" };- }-- using (var trans = new Transaction(doc, "Enable Worksharing"))- {- trans.Start();-- // Enable worksharing- doc.EnableWorksharing(defaultWorksetName, "Workset1");-- trans.Commit();-- return new- {- success = true,- message = "Worksharing enabled",- defaultWorkset = defaultWorksetName,- isWorkshared = doc.IsWorkshared- };- }- }-- #endregion-- #region 8. Get Central Path-- public static object GetCentralPath(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- ModelPath centralPath = doc.GetWorksharingCentralModelPath();- string centralPathString = ModelPathUtils.ConvertModelPathToUserVisiblePath(centralPath);-- return new- {- isWorkshared = doc.IsWorkshared,- centralPath = centralPathString,- isDetached = doc.IsDetached,- isModified = doc.IsModified,- title = doc.Title- };- }-- #endregion-- #region 9. Set Workset Visibility-- public static object SetWorksetVisibility(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- int worksetId = payload.GetProperty("workset_id").GetInt32();- bool visible = payload.GetProperty("visible").GetBoolean();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- using (var trans = new Transaction(doc, "Set Workset Visibility"))- {- trans.Start();-- WorksetId wsId = new WorksetId(worksetId);- WorksetVisibility visibility = visible ? WorksetVisibility.Visible : WorksetVisibility.Hidden;- view.SetWorksetVisibility(wsId, visibility);-- trans.Commit();-- return new- {- success = true,- viewId = viewId,- viewName = view.Name,- worksetId = worksetId,- visible = visible- };- }- }-- #endregion-- #region 10. Get Workset Visibility-- public static object GetWorksetVisibility(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- int worksetId = payload.GetProperty("workset_id").GetInt32();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- WorksetId wsId = new WorksetId(worksetId);- WorksetVisibility visibility = view.GetWorksetVisibility(wsId);-- return new- {- viewId = viewId,- viewName = view.Name,- worksetId = worksetId,- worksetName = doc.GetWorksetTable().GetWorkset(wsId).Name,- visibility = visibility.ToString(),- isVisible = visibility == WorksetVisibility.Visible- };- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Core/Filtering/FilteringCommands.cs b/packages/revit-bridge-addin/src/Commands/Core/Filtering/FilteringCommands.csdeleted file mode 100644index f3e38ca..0000000--- a/packages/revit-bridge-addin/src/Commands/Core/Filtering/FilteringCommands.cs+++ /dev/null@@ -1,777 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Core.Filtering-{- /// <summary>- /// Advanced element filtering commands - highest priority tools- /// FilteredElementCollector is #1 ranked API (Score: 294)- /// </summary>- public static class FilteringCommands- {- #region 1. Filter Elements by Parameter-- public static object FilterElementsByParameter(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string paramName = payload.GetProperty("parameter_name").GetString();- string op = payload.GetProperty("operator").GetString(); // equals, greater, less, contains, not_equals- var value = payload.GetProperty("value");- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;-- using (var trans = new Transaction(doc, "Filter Elements by Parameter"))- {- trans.Start();-- var collector = new FilteredElementCollector(doc).WhereElementIsNotElementType();-- // Apply category filter if specified- if (!string.IsNullOrEmpty(category))- {- if (Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }- }-- // Create parameter filter- var elements = collector.ToElements()- .Where(e => MatchesParameterFilter(e, paramName, op, value))- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- })- .ToList();-- trans.Commit();-- return new- {- count = elements.Count,- elements = elements- };- }- }-- private static bool MatchesParameterFilter(Element element, string paramName, string op, JsonElement value)- {- Parameter param = element.LookupParameter(paramName);- if (param == null) return false;-- switch (param.StorageType)- {- case StorageType.Integer:- int intValue = value.GetInt32();- int paramIntValue = param.AsInteger();- return op switch- {- "equals" => paramIntValue == intValue,- "not_equals" => paramIntValue != intValue,- "greater" => paramIntValue > intValue,- "less" => paramIntValue < intValue,- "greater_equal" => paramIntValue >= intValue,- "less_equal" => paramIntValue <= intValue,- _ => false- };-- case StorageType.Double:- double doubleValue = value.GetDouble();- double paramDoubleValue = param.AsDouble();- return op switch- {- "equals" => Math.Abs(paramDoubleValue - doubleValue) < 0.0001,- "not_equals" => Math.Abs(paramDoubleValue - doubleValue) >= 0.0001,- "greater" => paramDoubleValue > doubleValue,- "less" => paramDoubleValue < doubleValue,- "greater_equal" => paramDoubleValue >= doubleValue,- "less_equal" => paramDoubleValue <= doubleValue,- _ => false- };-- case StorageType.String:- string stringValue = value.GetString();- string paramStringValue = param.AsString() ?? "";- return op switch- {- "equals" => paramStringValue.Equals(stringValue, StringComparison.OrdinalIgnoreCase),- "not_equals" => !paramStringValue.Equals(stringValue, StringComparison.OrdinalIgnoreCase),- "contains" => paramStringValue.Contains(stringValue, StringComparison.OrdinalIgnoreCase),- "starts_with" => paramStringValue.StartsWith(stringValue, StringComparison.OrdinalIgnoreCase),- "ends_with" => paramStringValue.EndsWith(stringValue, StringComparison.OrdinalIgnoreCase),- _ => false- };-- case StorageType.ElementId:- int elemIdValue = value.GetInt32();- int paramElemId = param.AsElementId().IntegerValue;- return op switch- {- "equals" => paramElemId == elemIdValue,- "not_equals" => paramElemId != elemIdValue,- _ => false- };-- default:- return false;- }- }-- #endregion-- #region 2. Filter Elements by Level-- public static object FilterElementsByLevel(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string levelName = payload.GetProperty("level_name").GetString();- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;-- // Find level- Level level = new FilteredElementCollector(doc)- .OfClass(typeof(Level))- .Cast<Level>()- .FirstOrDefault(l => l.Name.Equals(levelName, StringComparison.OrdinalIgnoreCase));-- if (level == null)- {- throw new Exception($"Level '{levelName}' not found");- }-- var collector = new FilteredElementCollector(doc)- .WhereElementIsNotElementType();-- // Apply category filter if specified- if (!string.IsNullOrEmpty(category))- {- if (Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }- }-- // Filter by level using ElementLevelFilter- var levelFilter = new ElementLevelFilter(level.Id);- collector.WherePasses(levelFilter);-- var elements = collector.Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- levelName = levelName,- uniqueId = e.UniqueId- }).ToList();-- return new- {- level = levelName,- levelId = level.Id.IntegerValue,- count = elements.Count,- elements = elements- };- }-- #endregion-- #region 3. Filter Elements by Workset-- public static object FilterElementsByWorkset(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string worksetName = payload.GetProperty("workset_name").GetString();-- if (!doc.IsWorkshared)- {- throw new Exception("Document is not workshared");- }-- // Find workset- Workset targetWorkset = null;- foreach (Workset ws in new FilteredWorksetCollector(doc).OfKind(WorksetKind.UserWorkset))- {- if (ws.Name.Equals(worksetName, StringComparison.OrdinalIgnoreCase))- {- targetWorkset = ws;- break;- }- }-- if (targetWorkset == null)- {- throw new Exception($"Workset '{worksetName}' not found");- }-- var collector = new FilteredElementCollector(doc)- .WhereElementIsNotElementType();-- var worksetFilter = new ElementWorksetFilter(targetWorkset.Id);- collector.WherePasses(worksetFilter);-- var elements = collector.Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- workset = worksetName,- uniqueId = e.UniqueId- }).ToList();-- return new- {- workset = worksetName,- worksetId = targetWorkset.Id.IntegerValue,- count = elements.Count,- elements = elements- };- }-- #endregion-- #region 4. Filter Elements by Bounding Box-- public static object FilterElementsByBoundingBox(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var minPoint = payload.GetProperty("min_point");- var maxPoint = payload.GetProperty("max_point");- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;-- XYZ min = new XYZ(- minPoint.GetProperty("x").GetDouble(),- minPoint.GetProperty("y").GetDouble(),- minPoint.GetProperty("z").GetDouble()- );-- XYZ max = new XYZ(- maxPoint.GetProperty("x").GetDouble(),- maxPoint.GetProperty("y").GetDouble(),- maxPoint.GetProperty("z").GetDouble()- );-- Outline outline = new Outline(min, max);- BoundingBoxIntersectsFilter bbFilter = new BoundingBoxIntersectsFilter(outline);-- var collector = new FilteredElementCollector(doc)- .WhereElementIsNotElementType()- .WherePasses(bbFilter);-- if (!string.IsNullOrEmpty(category))- {- if (Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }- }-- var elements = collector.Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- }).ToList();-- return new- {- boundingBox = new { min = new { min.X, min.Y, min.Z }, max = new { max.X, max.Y, max.Z } },- count = elements.Count,- elements = elements- };- }-- #endregion-- #region 5. Filter Elements Intersecting-- public static object FilterElementsIntersecting(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int targetElementId = payload.GetProperty("element_id").GetInt32();- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;-- Element targetElement = doc.GetElement(new ElementId(targetElementId));- if (targetElement == null)- {- throw new Exception($"Element {targetElementId} not found");- }-- // Get element geometry- Options geomOptions = new Options { ComputeReferences = true, DetailLevel = ViewDetailLevel.Fine };- GeometryElement geomElem = targetElement.get_Geometry(geomOptions);-- if (geomElem == null)- {- throw new Exception("Element has no geometry");- }-- // Create solid from geometry- Solid targetSolid = null;- foreach (GeometryObject geomObj in geomElem)- {- if (geomObj is Solid solid && solid.Volume > 0)- {- targetSolid = solid;- break;- }- }-- if (targetSolid == null)- {- throw new Exception("Element has no solid geometry");- }-- var intersectFilter = new ElementIntersectsSolidFilter(targetSolid);- var collector = new FilteredElementCollector(doc)- .WhereElementIsNotElementType()- .WherePasses(intersectFilter);-- if (!string.IsNullOrEmpty(category))- {- if (Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }- }-- var elements = collector.Where(e => e.Id.IntegerValue != targetElementId)- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- }).ToList();-- return new- {- targetElement = new { id = targetElementId, name = targetElement.Name },- count = elements.Count,- intersectingElements = elements- };- }-- #endregion-- #region 6. Filter Elements by View-- public static object FilterElementsByView(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- var collector = new FilteredElementCollector(doc, view.Id)- .WhereElementIsNotElementType();-- if (!string.IsNullOrEmpty(category))- {- if (Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }- }-- var elements = collector.Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- }).ToList();-- return new- {- view = new { id = viewId, name = view.Name },- count = elements.Count,- elements = elements- };- }-- #endregion-- #region 7. Find Elements at Point-- public static object FindElementsAtPoint(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var point = payload.GetProperty("point");- double tolerance = payload.TryGetProperty("tolerance", out var tol) ? tol.GetDouble() : 0.1;-- XYZ searchPoint = new XYZ(- point.GetProperty("x").GetDouble(),- point.GetProperty("y").GetDouble(),- point.GetProperty("z").GetDouble()- );-- // Create small bounding box around point- XYZ min = new XYZ(searchPoint.X - tolerance, searchPoint.Y - tolerance, searchPoint.Z - tolerance);- XYZ max = new XYZ(searchPoint.X + tolerance, searchPoint.Y + tolerance, searchPoint.Z + tolerance);-- Outline outline = new Outline(min, max);- BoundingBoxIntersectsFilter bbFilter = new BoundingBoxIntersectsFilter(outline);-- var collector = new FilteredElementCollector(doc)- .WhereElementIsNotElementType()- .WherePasses(bbFilter);-- var elements = collector.Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- }).ToList();-- return new- {- searchPoint = new { searchPoint.X, searchPoint.Y, searchPoint.Z },- tolerance = tolerance,- count = elements.Count,- elements = elements- };- }-- #endregion-- #region 8. Filter by Multiple Criteria-- public static object FilterByMultipleCriteria(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string logicOperator = payload.GetProperty("logic").GetString(); // "and" or "or"- var criteria = payload.GetProperty("criteria").EnumerateArray();-- var collector = new FilteredElementCollector(doc).WhereElementIsNotElementType();- List<ElementId> resultIds = null;-- foreach (var criterion in criteria)- {- string filterType = criterion.GetProperty("type").GetString();- var currentIds = new List<ElementId>();-- switch (filterType)- {- case "category":- string catName = criterion.GetProperty("value").GetString();- if (Enum.TryParse(catName, out BuiltInCategory builtInCat))- {- currentIds = new FilteredElementCollector(doc)- .WhereElementIsNotElementType()- .OfCategory(builtInCat)- .ToElementIds()- .ToList();- }- break;-- case "parameter":- // Similar to FilterElementsByParameter- string paramName = criterion.GetProperty("parameter_name").GetString();- string op = criterion.GetProperty("operator").GetString();- var value = criterion.GetProperty("value");- currentIds = new FilteredElementCollector(doc)- .WhereElementIsNotElementType()- .ToElements()- .Where(e => MatchesParameterFilter(e, paramName, op, value))- .Select(e => e.Id)- .ToList();- break;-- case "level":- string levelName = criterion.GetProperty("value").GetString();- Level level = new FilteredElementCollector(doc)- .OfClass(typeof(Level))- .Cast<Level>()- .FirstOrDefault(l => l.Name.Equals(levelName, StringComparison.OrdinalIgnoreCase));- if (level != null)- {- currentIds = new FilteredElementCollector(doc)- .WhereElementIsNotElementType()- .WherePasses(new ElementLevelFilter(level.Id))- .ToElementIds()- .ToList();- }- break;- }-- // Apply logic operator- if (resultIds == null)- {- resultIds = currentIds;- }- else- {- resultIds = logicOperator == "and"- ? resultIds.Intersect(currentIds).ToList()- : resultIds.Union(currentIds).ToList();- }- }-- var elements = resultIds?.Select(id => doc.GetElement(id))- .Where(e => e != null)- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- })- .ToList() ?? new List<object>();-- return new- {- logic = logicOperator,- criteriaCount = criteria.Count(),- count = elements.Count,- elements = elements- };- }-- #endregion-- #region 9. Get All Elements of Type-- public static object GetAllElementsOfType(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string typeName = payload.GetProperty("type_name").GetString();- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;-- var collector = new FilteredElementCollector(doc)- .WhereElementIsNotElementType();-- if (!string.IsNullOrEmpty(category))- {- if (Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }- }-- var elements = collector- .Where(e => e.GetTypeId() != ElementId.InvalidElementId)- .Where(e =>- {- var elemType = doc.GetElement(e.GetTypeId());- return elemType != null && elemType.Name.Contains(typeName, StringComparison.OrdinalIgnoreCase);- })- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- typeName = doc.GetElement(e.GetTypeId())?.Name ?? "Unknown",- uniqueId = e.UniqueId- })- .ToList();-- return new- {- searchTypeName = typeName,- count = elements.Count,- elements = elements- };- }-- #endregion-- #region 10. Get Dependent Elements-- public static object GetDependentElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- var dependentIds = element.GetDependentElements(null);-- var elements = dependentIds.Select(id => doc.GetElement(id))- .Where(e => e != null)- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- })- .ToList();-- return new- {- sourceElement = new { id = elementId, name = element.Name },- count = elements.Count,- dependentElements = elements- };- }-- #endregion-- #region 11. Get Hosted Elements-- public static object GetHostedElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int hostElementId = payload.GetProperty("host_element_id").GetInt32();-- Element hostElement = doc.GetElement(new ElementId(hostElementId));- if (hostElement == null)- {- throw new Exception($"Host element {hostElementId} not found");- }-- // Get all elements and filter by those hosted on this element- var hostedElements = new FilteredElementCollector(doc)- .WhereElementIsNotElementType()- .Where(e =>- {- if (e is FamilyInstance fi && fi.Host != null)- {- return fi.Host.Id.IntegerValue == hostElementId;- }- return false;- })- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- })- .ToList();-- return new- {- hostElement = new { id = hostElementId, name = hostElement.Name },- count = hostedElements.Count,- hostedElements = hostedElements- };- }-- #endregion-- #region 12-15. Additional Filters (Simplified)-- public static object FindSimilarElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int referenceElementId = payload.GetProperty("element_id").GetInt32();-- Element refElement = doc.GetElement(new ElementId(referenceElementId));- if (refElement == null)- {- throw new Exception($"Element {referenceElementId} not found");- }-- // Find elements of same category and type- var similarElements = new FilteredElementCollector(doc)- .WhereElementIsNotElementType()- .WherePasses(new ElementCategoryFilter(refElement.Category.Id))- .Where(e => e.GetTypeId().IntegerValue == refElement.GetTypeId().IntegerValue)- .Where(e => e.Id.IntegerValue != referenceElementId)- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- })- .ToList();-- return new- {- referenceElement = new { id = referenceElementId, name = refElement.Name, category = refElement.Category.Name },- count = similarElements.Count,- similarElements = similarElements- };- }-- public static object GetElementsByUniqueId(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var uniqueIds = payload.GetProperty("unique_ids").EnumerateArray().Select(e => e.GetString()).ToList();-- var elements = uniqueIds- .Select(uid => doc.GetElement(uid))- .Where(e => e != null)- .Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId- })- .ToList();-- return new- {- requestedCount = uniqueIds.Count,- foundCount = elements.Count,- elements = elements- };- }-- public static object GetLinkedElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int linkInstanceId = payload.GetProperty("link_instance_id").GetInt32();- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;-- RevitLinkInstance linkInstance = doc.GetElement(new ElementId(linkInstanceId)) as RevitLinkInstance;- if (linkInstance == null)- {- throw new Exception($"Link instance {linkInstanceId} not found");- }-- Document linkedDoc = linkInstance.GetLinkDocument();- if (linkedDoc == null)- {- throw new Exception("Linked document is not loaded");- }-- var collector = new FilteredElementCollector(linkedDoc).WhereElementIsNotElementType();-- if (!string.IsNullOrEmpty(category))- {- if (Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }- }-- var elements = collector.Select(e => new- {- id = e.Id.IntegerValue,- category = e.Category?.Name ?? "Unknown",- name = e.Name ?? "Unnamed",- uniqueId = e.UniqueId,- linkName = linkedDoc.Title- }).ToList();-- return new- {- linkInstance = new { id = linkInstanceId, name = linkedDoc.Title },- count = elements.Count,- elements = elements- };- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Core/Phase1CommandRegistry.cs b/packages/revit-bridge-addin/src/Commands/Core/Phase1CommandRegistry.csdeleted file mode 100644index 4c80171..0000000--- a/packages/revit-bridge-addin/src/Commands/Core/Phase1CommandRegistry.cs+++ /dev/null@@ -1,137 +0,0 @@-using System;-using System.Text.Json;-using Autodesk.Revit.UI;-using RevitBridge.Commands.Core.Filtering;-using RevitBridge.Commands.Core.Units;-using RevitBridge.Commands.Core.Schedules;-using RevitBridge.Commands.Core.Views;--namespace RevitBridge.Commands.Core-{- /// <summary>- /// Registry for Phase 1 commands (40 critical tools)- /// These are the highest priority tools based on API usage analysis- /// </summary>- public static class Phase1CommandRegistry- {- public static object Execute(UIApplication app, string tool, JsonElement payload)- {- return tool switch- {- // === FILTERING COMMANDS (15 tools) - Highest Priority ===- // FilteredElementCollector is #1 ranked API (Score: 294)-- "revit.filter_elements_by_parameter" => FilteringCommands.FilterElementsByParameter(app, payload),- "revit.filter_elements_by_level" => FilteringCommands.FilterElementsByLevel(app, payload),- "revit.filter_elements_by_workset" => FilteringCommands.FilterElementsByWorkset(app, payload),- "revit.filter_elements_by_bounding_box" => FilteringCommands.FilterElementsByBoundingBox(app, payload),- "revit.filter_elements_intersecting" => FilteringCommands.FilterElementsIntersecting(app, payload),- "revit.filter_elements_by_view" => FilteringCommands.FilterElementsByView(app, payload),- "revit.find_elements_at_point" => FilteringCommands.FindElementsAtPoint(app, payload),- "revit.filter_by_multiple_criteria" => FilteringCommands.FilterByMultipleCriteria(app, payload),- "revit.get_all_elements_of_type" => FilteringCommands.GetAllElementsOfType(app, payload),- "revit.get_dependent_elements" => FilteringCommands.GetDependentElements(app, payload),- "revit.get_hosted_elements" => FilteringCommands.GetHostedElements(app, payload),- "revit.find_similar_elements" => FilteringCommands.FindSimilarElements(app, payload),- "revit.get_elements_by_unique_id" => FilteringCommands.GetElementsByUniqueId(app, payload),- "revit.get_linked_elements" => FilteringCommands.GetLinkedElements(app, payload),- // Note: trace_element_relationships can be added as extension of get_dependent_elements-- // === UNITS COMMANDS (5 tools) - Critical ===- // UnitUtils is #15 ranked API (Score: 275)-- "revit.convert_to_internal_units" => UnitsCommands.ConvertToInternalUnits(app, payload),- "revit.convert_from_internal_units" => UnitsCommands.ConvertFromInternalUnits(app, payload),- "revit.get_project_units" => UnitsCommands.GetProjectUnits(app, payload),- "revit.set_project_units" => UnitsCommands.SetProjectUnits(app, payload),- "revit.format_value_with_units" => UnitsCommands.FormatValueWithUnits(app, payload),-- // === SCHEDULE COMMANDS (10 tools) - Critical ===- // ViewSchedule is #146 ranked API (Score: 198)-- "revit.add_schedule_field" => ScheduleCommands.AddScheduleField(app, payload),- "revit.remove_schedule_field" => ScheduleCommands.RemoveScheduleField(app, payload),- "revit.set_schedule_filter" => ScheduleCommands.SetScheduleFilter(app, payload),- "revit.set_schedule_sorting" => ScheduleCommands.SetScheduleSorting(app, payload),- "revit.set_schedule_grouping" => ScheduleCommands.SetScheduleGrouping(app, payload),- "revit.calculate_schedule_totals" => ScheduleCommands.CalculateScheduleTotals(app, payload),- "revit.format_schedule_field" => ScheduleCommands.FormatScheduleField(app, payload),- "revit.export_schedule_to_csv" => ScheduleCommands.ExportScheduleToCSV(app, payload),- "revit.create_key_schedule" => ScheduleCommands.CreateKeySchedule(app, payload),- "revit.create_material_takeoff" => ScheduleCommands.CreateMaterialTakeoff(app, payload),-- // === VIEW MANAGEMENT COMMANDS (10 tools) - High Value ===- // View is #6 ranked API (Score: 283)-- "revit.create_ceiling_plan_view" => ViewManagementCommands.CreateCeilingPlanView(app, payload),- "revit.create_elevation_view" => ViewManagementCommands.CreateElevationView(app, payload),- "revit.duplicate_view" => ViewManagementCommands.DuplicateView(app, payload),- "revit.set_view_template" => ViewManagementCommands.SetViewTemplate(app, payload),- "revit.create_view_filter" => ViewManagementCommands.CreateViewFilter(app, payload),- "revit.set_view_visibility" => ViewManagementCommands.SetViewVisibility(app, payload),- "revit.isolate_elements_in_view" => ViewManagementCommands.IsolateElementsInView(app, payload),- "revit.hide_elements_in_view" => ViewManagementCommands.HideElementsInView(app, payload),- "revit.unhide_elements_in_view" => ViewManagementCommands.UnhideElementsInView(app, payload),- "revit.crop_view" => ViewManagementCommands.CropView(app, payload),-- _ => null // Return null to let main factory handle unknown commands- };- }-- /// <summary>- /// Get list of all Phase 1 command names for documentation/validation- /// </summary>- public static string[] GetCommandNames()- {- return new[]- {- // Filtering (15)- "revit.filter_elements_by_parameter",- "revit.filter_elements_by_level",- "revit.filter_elements_by_workset",- "revit.filter_elements_by_bounding_box",- "revit.filter_elements_intersecting",- "revit.filter_elements_by_view",- "revit.find_elements_at_point",- "revit.filter_by_multiple_criteria",- "revit.get_all_elements_of_type",- "revit.get_dependent_elements",- "revit.get_hosted_elements",- "revit.find_similar_elements",- "revit.get_elements_by_unique_id",- "revit.get_linked_elements",-- // Units (5)- "revit.convert_to_internal_units",- "revit.convert_from_internal_units",- "revit.get_project_units",- "revit.set_project_units",- "revit.format_value_with_units",-- // Schedules (10)- "revit.add_schedule_field",- "revit.remove_schedule_field",- "revit.set_schedule_filter",- "revit.set_schedule_sorting",- "revit.set_schedule_grouping",- "revit.calculate_schedule_totals",- "revit.format_schedule_field",- "revit.export_schedule_to_csv",- "revit.create_key_schedule",- "revit.create_material_takeoff",-- // Views (10)- "revit.create_ceiling_plan_view",- "revit.create_elevation_view",- "revit.duplicate_view",- "revit.set_view_template",- "revit.create_view_filter",- "revit.set_view_visibility",- "revit.isolate_elements_in_view",- "revit.hide_elements_in_view",- "revit.unhide_elements_in_view",- "revit.crop_view"- };- }- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Core/Schedules/ScheduleCommands.cs b/packages/revit-bridge-addin/src/Commands/Core/Schedules/ScheduleCommands.csdeleted file mode 100644index 19a7923..0000000--- a/packages/revit-bridge-addin/src/Commands/Core/Schedules/ScheduleCommands.cs+++ /dev/null@@ -1,609 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using System.IO;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Core.Schedules-{- /// <summary>- /// Schedule management commands- /// ViewSchedule is #146 ranked API (Score: 198) - documentation essential- /// </summary>- public static class ScheduleCommands- {- #region 1. Add Schedule Field-- public static object AddScheduleField(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int scheduleId = payload.GetProperty("schedule_id").GetInt32();- string fieldName = payload.GetProperty("field_name").GetString();-- ViewSchedule schedule = doc.GetElement(new ElementId(scheduleId)) as ViewSchedule;- if (schedule == null)- {- throw new Exception($"Schedule {scheduleId} not found");- }-- using (var trans = new Transaction(doc, "Add Schedule Field"))- {- trans.Start();-- ScheduleDefinition definition = schedule.Definition;-- // Find schedulable field- SchedulableField schedulableField = definition.GetSchedulableFields()- .FirstOrDefault(sf => sf.GetName(doc).Equals(fieldName, StringComparison.OrdinalIgnoreCase));-- if (schedulableField == null)- {- throw new Exception($"Field '{fieldName}' not found in schedulable fields");- }-- // Add field- ScheduleField field = definition.AddField(schedulableField);-- trans.Commit();-- return new- {- success = true,- scheduleId = scheduleId,- scheduleName = schedule.Name,- fieldName = fieldName,- fieldId = field.FieldId.IntegerValue,- columnPosition = field.ColumnHeadingOffset- };- }- }-- #endregion-- #region 2. Remove Schedule Field-- public static object RemoveScheduleField(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int scheduleId = payload.GetProperty("schedule_id").GetInt32();- string fieldName = payload.GetProperty("field_name").GetString();-- ViewSchedule schedule = doc.GetElement(new ElementId(scheduleId)) as ViewSchedule;- if (schedule == null)- {- throw new Exception($"Schedule {scheduleId} not found");- }-- using (var trans = new Transaction(doc, "Remove Schedule Field"))- {- trans.Start();-- ScheduleDefinition definition = schedule.Definition;-- // Find field by name- ScheduleField fieldToRemove = null;- int fieldIndex = -1;-- for (int i = 0; i < definition.GetFieldCount(); i++)- {- ScheduleField field = definition.GetField(i);- if (field.GetName().Equals(fieldName, StringComparison.OrdinalIgnoreCase))- {- fieldToRemove = field;- fieldIndex = i;- break;- }- }-- if (fieldToRemove == null)- {- throw new Exception($"Field '{fieldName}' not found in schedule");- }-- definition.RemoveField(fieldIndex);-- trans.Commit();-- return new- {- success = true,- scheduleId = scheduleId,- scheduleName = schedule.Name,- removedField = fieldName,- remainingFieldCount = definition.GetFieldCount()- };- }- }-- #endregion-- #region 3. Set Schedule Filter-- public static object SetScheduleFilter(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int scheduleId = payload.GetProperty("schedule_id").GetInt32();- string fieldName = payload.GetProperty("field_name").GetString();- string filterType = payload.GetProperty("filter_type").GetString(); // equals, greater, less, contains, etc.- var value = payload.GetProperty("value");-- ViewSchedule schedule = doc.GetElement(new ElementId(scheduleId)) as ViewSchedule;- if (schedule == null)- {- throw new Exception($"Schedule {scheduleId} not found");- }-- using (var trans = new Transaction(doc, "Set Schedule Filter"))- {- trans.Start();-- ScheduleDefinition definition = schedule.Definition;-- // Find field- ScheduleField field = null;- for (int i = 0; i < definition.GetFieldCount(); i++)- {- var f = definition.GetField(i);- if (f.GetName().Equals(fieldName, StringComparison.OrdinalIgnoreCase))- {- field = f;- break;- }- }-- if (field == null)- {- throw new Exception($"Field '{fieldName}' not found");- }-- // Create filter- ScheduleFilterType schedFilterType = filterType.ToLower() switch- {- "equals" => ScheduleFilterType.Equal,- "not_equals" => ScheduleFilterType.NotEqual,- "greater" => ScheduleFilterType.GreaterThan,- "greater_equal" => ScheduleFilterType.GreaterThanOrEqual,- "less" => ScheduleFilterType.LessThan,- "less_equal" => ScheduleFilterType.LessThanOrEqual,- "contains" => ScheduleFilterType.Contains,- "not_contains" => ScheduleFilterType.NotContains,- "begins_with" => ScheduleFilterType.BeginsWith,- "ends_with" => ScheduleFilterType.EndsWith,- _ => ScheduleFilterType.Equal- };-- // Convert value based on field type- string filterValue = value.ValueKind == JsonValueKind.String- ? value.GetString()- : value.ToString();-- ScheduleFilter filter = new ScheduleFilter(field.FieldId, schedFilterType, filterValue);- definition.AddFilter(filter);-- trans.Commit();-- return new- {- success = true,- scheduleId = scheduleId,- scheduleName = schedule.Name,- fieldName = fieldName,- filterType = filterType,- value = filterValue,- totalFilters = definition.GetFilterCount()- };- }- }-- #endregion-- #region 4. Set Schedule Sorting-- public static object SetScheduleSorting(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int scheduleId = payload.GetProperty("schedule_id").GetInt32();- string fieldName = payload.GetProperty("field_name").GetString();- bool ascending = payload.TryGetProperty("ascending", out var asc) ? asc.GetBoolean() : true;-- ViewSchedule schedule = doc.GetElement(new ElementId(scheduleId)) as ViewSchedule;- if (schedule == null)- {- throw new Exception($"Schedule {scheduleId} not found");- }-- using (var trans = new Transaction(doc, "Set Schedule Sorting"))- {- trans.Start();-- ScheduleDefinition definition = schedule.Definition;-- // Find field- ScheduleField field = null;- for (int i = 0; i < definition.GetFieldCount(); i++)- {- var f = definition.GetField(i);- if (f.GetName().Equals(fieldName, StringComparison.OrdinalIgnoreCase))- {- field = f;- break;- }- }-- if (field == null)- {- throw new Exception($"Field '{fieldName}' not found");- }-- // Add sorting- ScheduleSortGroupField sortField = new ScheduleSortGroupField(field.FieldId);- sortField.SortOrder = ascending ? ScheduleSortOrder.Ascending : ScheduleSortOrder.Descending;-- definition.AddSortGroupField(sortField);-- trans.Commit();-- return new- {- success = true,- scheduleId = scheduleId,- scheduleName = schedule.Name,- fieldName = fieldName,- sortOrder = ascending ? "Ascending" : "Descending",- totalSortFields = definition.GetSortGroupFieldCount()- };- }- }-- #endregion-- #region 5. Set Schedule Grouping-- public static object SetScheduleGrouping(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int scheduleId = payload.GetProperty("schedule_id").GetInt32();- string fieldName = payload.GetProperty("field_name").GetString();- bool showHeader = payload.TryGetProperty("show_header", out var sh) ? sh.GetBoolean() : true;- bool showFooter = payload.TryGetProperty("show_footer", out var sf) ? sf.GetBoolean() : false;- bool showBlankLine = payload.TryGetProperty("show_blank_line", out var sb) ? sb.GetBoolean() : true;-- ViewSchedule schedule = doc.GetElement(new ElementId(scheduleId)) as ViewSchedule;- if (schedule == null)- {- throw new Exception($"Schedule {scheduleId} not found");- }-- using (var trans = new Transaction(doc, "Set Schedule Grouping"))- {- trans.Start();-- ScheduleDefinition definition = schedule.Definition;-- // Find field- ScheduleField field = null;- for (int i = 0; i < definition.GetFieldCount(); i++)- {- var f = definition.GetField(i);- if (f.GetName().Equals(fieldName, StringComparison.OrdinalIgnoreCase))- {- field = f;- break;- }- }-- if (field == null)- {- throw new Exception($"Field '{fieldName}' not found");- }-- // Create group field- ScheduleSortGroupField groupField = new ScheduleSortGroupField(field.FieldId);- groupField.ShowHeader = showHeader;- groupField.ShowFooter = showFooter;- groupField.ShowBlankLine = showBlankLine;-- definition.AddSortGroupField(groupField);-- trans.Commit();-- return new- {- success = true,- scheduleId = scheduleId,- scheduleName = schedule.Name,- fieldName = fieldName,- showHeader = showHeader,- showFooter = showFooter,- showBlankLine = showBlankLine- };- }- }-- #endregion-- #region 6. Calculate Schedule Totals-- public static object CalculateScheduleTotals(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int scheduleId = payload.GetProperty("schedule_id").GetInt32();- string fieldName = payload.GetProperty("field_name").GetString();-- ViewSchedule schedule = doc.GetElement(new ElementId(scheduleId)) as ViewSchedule;- if (schedule == null)- {- throw new Exception($"Schedule {scheduleId} not found");- }-- using (var trans = new Transaction(doc, "Calculate Schedule Totals"))- {- trans.Start();-- ScheduleDefinition definition = schedule.Definition;-- // Find field- ScheduleField field = null;- for (int i = 0; i < definition.GetFieldCount(); i++)- {- var f = definition.GetField(i);- if (f.GetName().Equals(fieldName, StringComparison.OrdinalIgnoreCase))- {- field = f;- break;- }- }-- if (field == null)- {- throw new Exception($"Field '{fieldName}' not found");- }-- // Enable calculate totals- field.DisplayType = ScheduleFieldDisplayType.Totals;-- trans.Commit();-- // Get table data to calculate actual sum- TableData tableData = schedule.GetTableData();- TableSectionData sectionData = tableData.GetSectionData(SectionType.Body);-- double total = 0;- int fieldIndex = -1;-- // Find field column index- for (int i = 0; i < definition.GetFieldCount(); i++)- {- if (definition.GetField(i).FieldId == field.FieldId)- {- fieldIndex = i;- break;- }- }-- if (fieldIndex >= 0)- {- for (int row = 0; row < sectionData.NumberOfRows; row++)- {- string cellText = schedule.GetCellText(SectionType.Body, row, fieldIndex);- if (double.TryParse(cellText, out double value))- {- total += value;- }- }- }-- return new- {- success = true,- scheduleId = scheduleId,- scheduleName = schedule.Name,- fieldName = fieldName,- total = total,- rowCount = sectionData.NumberOfRows- };- }- }-- #endregion-- #region 7. Format Schedule Field-- public static object FormatScheduleField(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int scheduleId = payload.GetProperty("schedule_id").GetInt32();- string fieldName = payload.GetProperty("field_name").GetString();-- ViewSchedule schedule = doc.GetElement(new ElementId(scheduleId)) as ViewSchedule;- if (schedule == null)- {- throw new Exception($"Schedule {scheduleId} not found");- }-- using (var trans = new Transaction(doc, "Format Schedule Field"))- {- trans.Start();-- ScheduleDefinition definition = schedule.Definition;-- // Find field- ScheduleField field = null;- for (int i = 0; i < definition.GetFieldCount(); i++)- {- var f = definition.GetField(i);- if (f.GetName().Equals(fieldName, StringComparison.OrdinalIgnoreCase))- {- field = f;- break;- }- }-- if (field == null)- {- throw new Exception($"Field '{fieldName}' not found");- }-- // Apply formatting options- if (payload.TryGetProperty("heading", out var heading))- {- field.ColumnHeading = heading.GetString();- }-- if (payload.TryGetProperty("heading_orientation", out var orient))- {- string orientation = orient.GetString().ToLower();- field.HeadingOrientation = orientation == "horizontal"- ? ScheduleHeadingOrientation.Horizontal- : ScheduleHeadingOrientation.Vertical;- }-- if (payload.TryGetProperty("horizontal_alignment", out var hAlign))- {- string alignment = hAlign.GetString().ToLower();- field.HorizontalAlignment = alignment switch- {- "left" => ScheduleHorizontalAlignment.Left,- "center" => ScheduleHorizontalAlignment.Center,- "right" => ScheduleHorizontalAlignment.Right,- _ => ScheduleHorizontalAlignment.Left- };- }-- if (payload.TryGetProperty("width", out var width))- {- field.SheetColumnWidth = width.GetDouble();- }-- trans.Commit();-- return new- {- success = true,- scheduleId = scheduleId,- scheduleName = schedule.Name,- fieldName = fieldName,- columnHeading = field.ColumnHeading,- width = field.SheetColumnWidth- };- }- }-- #endregion-- #region 8. Export Schedule to CSV-- public static object ExportScheduleToCSV(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int scheduleId = payload.GetProperty("schedule_id").GetInt32();- string outputPath = payload.GetProperty("output_path").GetString();-- ViewSchedule schedule = doc.GetElement(new ElementId(scheduleId)) as ViewSchedule;- if (schedule == null)- {- throw new Exception($"Schedule {scheduleId} not found");- }-- // Use Revit's built-in export- ViewScheduleExportOptions options = new ViewScheduleExportOptions();- options.TextQualifier = ExportTextQualifier.DoubleQuote;- options.FieldDelimiter = ",";-- string directory = Path.GetDirectoryName(outputPath);- string fileName = Path.GetFileNameWithoutExtension(outputPath);-- if (!Directory.Exists(directory))- {- Directory.CreateDirectory(directory);- }-- schedule.Export(directory, fileName, options);-- return new- {- success = true,- scheduleId = scheduleId,- scheduleName = schedule.Name,- outputPath = Path.Combine(directory, fileName + ".csv"),- exportedRows = schedule.GetTableData().GetSectionData(SectionType.Body).NumberOfRows- };- }-- #endregion-- #region 9. Create Key Schedule-- public static object CreateKeySchedule(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string scheduleName = payload.GetProperty("name").GetString();- string category = payload.GetProperty("category").GetString();-- if (!Enum.TryParse(category, out BuiltInCategory builtInCat))- {- throw new Exception($"Unknown category: {category}");- }-- using (var trans = new Transaction(doc, "Create Key Schedule"))- {- trans.Start();-- ElementId categoryId = new ElementId(builtInCat);- ViewSchedule schedule = ViewSchedule.CreateKeySchedule(doc, categoryId);- schedule.Name = scheduleName;-- trans.Commit();-- return new- {- success = true,- scheduleId = schedule.Id.IntegerValue,- scheduleName = schedule.Name,- category = category,- isKeySchedule = schedule.Definition.IsKeySchedule- };- }- }-- #endregion-- #region 10. Create Material Takeoff-- public static object CreateMaterialTakeoff(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string scheduleName = payload.GetProperty("name").GetString();- string category = payload.GetProperty("category").GetString();-- if (!Enum.TryParse(category, out BuiltInCategory builtInCat))- {- throw new Exception($"Unknown category: {category}");- }-- using (var trans = new Transaction(doc, "Create Material Takeoff"))- {- trans.Start();-- ElementId categoryId = new ElementId(builtInCat);- ViewSchedule schedule = ViewSchedule.CreateMaterialTakeoff(doc, categoryId);- schedule.Name = scheduleName;-- trans.Commit();-- return new- {- success = true,- scheduleId = schedule.Id.IntegerValue,- scheduleName = schedule.Name,- category = category,- isMaterialTakeoff = schedule.IsMaterialTakeoff- };- }- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Core/Units/UnitsCommands.cs b/packages/revit-bridge-addin/src/Commands/Core/Units/UnitsCommands.csdeleted file mode 100644index 6875193..0000000--- a/packages/revit-bridge-addin/src/Commands/Core/Units/UnitsCommands.cs+++ /dev/null@@ -1,259 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Core.Units-{- /// <summary>- /// Unit conversion and formatting commands- /// UnitUtils is #15 ranked API (Score: 275) - essential for international work- /// </summary>- public static class UnitsCommands- {- #region 1. Convert to Internal Units-- public static object ConvertToInternalUnits(UIApplication app, JsonElement payload)- {- double value = payload.GetProperty("value").GetDouble();- string unitType = payload.GetProperty("unit_type").GetString(); // length, area, volume, angle- string fromUnit = payload.GetProperty("from_unit").GetString(); // meters, millimeters, feet, inches, etc.-- ForgeTypeId specTypeId = GetSpecTypeId(unitType);- ForgeTypeId unitTypeId = GetUnitTypeId(fromUnit);-- double internalValue = UnitUtils.ConvertToInternalUnits(value, unitTypeId);-- return new- {- originalValue = value,- originalUnit = fromUnit,- internalValue = internalValue,- internalUnit = "feet (Revit internal)",- unitType = unitType- };- }-- #endregion-- #region 2. Convert from Internal Units-- public static object ConvertFromInternalUnits(UIApplication app, JsonElement payload)- {- double value = payload.GetProperty("value").GetDouble();- string unitType = payload.GetProperty("unit_type").GetString();- string toUnit = payload.GetProperty("to_unit").GetString();-- ForgeTypeId specTypeId = GetSpecTypeId(unitType);- ForgeTypeId unitTypeId = GetUnitTypeId(toUnit);-- double convertedValue = UnitUtils.ConvertFromInternalUnits(value, unitTypeId);-- return new- {- internalValue = value,- internalUnit = "feet (Revit internal)",- convertedValue = convertedValue,- convertedUnit = toUnit,- unitType = unitType- };- }-- #endregion-- #region 3. Get Project Units-- public static object GetProjectUnits(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- Units units = doc.GetUnits();-- var unitSettings = new Dictionary<string, object>();-- // Get common unit types- var commonSpecs = new[]- {- (name: "Length", id: SpecTypeId.Length),- (name: "Area", id: SpecTypeId.Area),- (name: "Volume", id: SpecTypeId.Volume),- (name: "Angle", id: SpecTypeId.Angle),- (name: "Force", id: SpecTypeId.Force),- (name: "Mass", id: SpecTypeId.Mass),- (name: "Temperature", id: SpecTypeId.Temperature)- };-- foreach (var spec in commonSpecs)- {- try- {- FormatOptions formatOptions = units.GetFormatOptions(spec.id);- unitSettings[spec.name] = new- {- unitSymbol = LabelUtils.GetLabelForUnit(formatOptions.GetUnitTypeId()),- accuracy = formatOptions.Accuracy,- rounding = formatOptions.GetRoundingMethod().ToString(),- suppressTrailingZeros = formatOptions.GetSuppressTrailingZeros(),- suppressLeadingZeros = formatOptions.GetSuppressLeadingZeros(),- useGrouping = formatOptions.GetUseGrouping()- };- }- catch- {- // Skip if unit type not applicable- }- }-- return new- {- documentTitle = doc.Title,- unitSettings = unitSettings- };- }-- #endregion-- #region 4. Set Project Units-- public static object SetProjectUnits(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string unitType = payload.GetProperty("unit_type").GetString();- string unit = payload.GetProperty("unit").GetString();-- using (var trans = new Transaction(doc, "Set Project Units"))- {- trans.Start();-- Units units = doc.GetUnits();- ForgeTypeId specTypeId = GetSpecTypeId(unitType);- ForgeTypeId unitTypeId = GetUnitTypeId(unit);-- FormatOptions formatOptions = units.GetFormatOptions(specTypeId);- formatOptions.SetUnitTypeId(unitTypeId);-- // Optional: Set accuracy if provided- if (payload.TryGetProperty("accuracy", out var acc))- {- formatOptions.Accuracy = acc.GetDouble();- }-- units.SetFormatOptions(specTypeId, formatOptions);-- trans.Commit();-- return new- {- success = true,- unitType = unitType,- unit = unit,- message = $"Project {unitType} units set to {unit}"- };- }- }-- #endregion-- #region 5. Format Value with Units-- public static object FormatValueWithUnits(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- double value = payload.GetProperty("value").GetDouble();- string unitType = payload.GetProperty("unit_type").GetString();- bool includeSymbol = payload.TryGetProperty("include_symbol", out var incl) ? incl.GetBoolean() : true;-- ForgeTypeId specTypeId = GetSpecTypeId(unitType);- Units units = doc.GetUnits();- FormatOptions formatOptions = units.GetFormatOptions(specTypeId);-- FormatValueOptions formatValueOptions = new FormatValueOptions();- formatValueOptions.SetFormatOptions(formatOptions);- formatValueOptions.AppendUnitSymbol = includeSymbol;-- string formattedValue = UnitFormatUtils.Format(units, specTypeId, value, false, formatValueOptions);-- return new- {- originalValue = value,- unitType = unitType,- formattedValue = formattedValue,- unitSymbol = includeSymbol ? LabelUtils.GetLabelForUnit(formatOptions.GetUnitTypeId()) : ""- };- }-- #endregion-- #region Helper Methods-- private static ForgeTypeId GetSpecTypeId(string unitType)- {- return unitType.ToLower() switch- {- "length" => SpecTypeId.Length,- "area" => SpecTypeId.Area,- "volume" => SpecTypeId.Volume,- "angle" => SpecTypeId.Angle,- "force" => SpecTypeId.Force,- "mass" => SpecTypeId.Mass,- "temperature" => SpecTypeId.Temperature,- "currency" => SpecTypeId.Currency,- "slope" => SpecTypeId.Slope,- "distance" => SpecTypeId.Distance,- "speed" => SpecTypeId.Speed,- _ => throw new Exception($"Unknown unit type: {unitType}")- };- }-- private static ForgeTypeId GetUnitTypeId(string unit)- {- return unit.ToLower() switch- {- // Length- "meters" or "m" => UnitTypeId.Meters,- "millimeters" or "mm" => UnitTypeId.Millimeters,- "centimeters" or "cm" => UnitTypeId.Centimeters,- "feet" or "ft" => UnitTypeId.Feet,- "inches" or "in" => UnitTypeId.Inches,- "feet_fractional_inches" => UnitTypeId.FeetFractionalInches,-- // Area- "square_meters" or "m2" => UnitTypeId.SquareMeters,- "square_feet" or "ft2" => UnitTypeId.SquareFeet,- "square_inches" or "in2" => UnitTypeId.SquareInches,-- // Volume- "cubic_meters" or "m3" => UnitTypeId.CubicMeters,- "cubic_feet" or "ft3" => UnitTypeId.CubicFeet,- "liters" or "l" => UnitTypeId.Liters,- "gallons" => UnitTypeId.Gallons,-- // Angle- "degrees" or "deg" => UnitTypeId.Degrees,- "radians" or "rad" => UnitTypeId.Radians,- "gradians" or "grad" => UnitTypeId.Gradians,-- // Force- "newtons" or "n" => UnitTypeId.Newtons,- "kilonewtons" or "kn" => UnitTypeId.Kilonewtons,- "pounds_force" or "lbf" => UnitTypeId.PoundsForce,- "kips" => UnitTypeId.Kips,-- // Mass- "kilograms" or "kg" => UnitTypeId.Kilograms,- "pounds_mass" or "lbm" => UnitTypeId.PoundsMass,- "tons" => UnitTypeId.Tons,-- // Temperature- "celsius" or "c" => UnitTypeId.Celsius,- "fahrenheit" or "f" => UnitTypeId.Fahrenheit,- "kelvin" or "k" => UnitTypeId.Kelvin,-- _ => throw new Exception($"Unknown unit: {unit}")- };- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Core/Views/ViewManagementCommands.cs b/packages/revit-bridge-addin/src/Commands/Core/Views/ViewManagementCommands.csdeleted file mode 100644index 11de8ad..0000000--- a/packages/revit-bridge-addin/src/Commands/Core/Views/ViewManagementCommands.cs+++ /dev/null@@ -1,463 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Core.Views-{- /// <summary>- /// Advanced view management commands- /// View is #6 ranked API (Score: 283) - visualization foundation- /// </summary>- public static class ViewManagementCommands- {- #region 1. Create Ceiling Plan View-- public static object CreateCeilingPlanView(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string levelName = payload.GetProperty("level_name").GetString();- string viewName = payload.TryGetProperty("view_name", out var vn) ? vn.GetString() : null;-- // Find level- Level level = new FilteredElementCollector(doc)- .OfClass(typeof(Level))- .Cast<Level>()- .FirstOrDefault(l => l.Name.Equals(levelName, StringComparison.OrdinalIgnoreCase));-- if (level == null)- {- throw new Exception($"Level '{levelName}' not found");- }-- using (var trans = new Transaction(doc, "Create Ceiling Plan View"))- {- trans.Start();-- // Get ceiling plan view family type- ViewFamilyType viewFamilyType = new FilteredElementCollector(doc)- .OfClass(typeof(ViewFamilyType))- .Cast<ViewFamilyType>()- .FirstOrDefault(vft => vft.ViewFamily == ViewFamily.CeilingPlan);-- if (viewFamilyType == null)- {- throw new Exception("Ceiling Plan view family type not found");- }-- ViewPlan ceilingPlan = ViewPlan.Create(doc, viewFamilyType.Id, level.Id);-- if (!string.IsNullOrEmpty(viewName))- {- ceilingPlan.Name = viewName;- }-- trans.Commit();-- return new- {- success = true,- viewId = ceilingPlan.Id.IntegerValue,- viewName = ceilingPlan.Name,- levelName = levelName,- viewType = "CeilingPlan"- };- }- }-- #endregion-- #region 2. Create Elevation View-- public static object CreateElevationView(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string viewName = payload.GetProperty("view_name").GetString();- var markerPoint = payload.GetProperty("marker_point");-- XYZ point = new XYZ(- markerPoint.GetProperty("x").GetDouble(),- markerPoint.GetProperty("y").GetDouble(),- markerPoint.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Create Elevation View"))- {- trans.Start();-- // Get elevation view family type- ViewFamilyType viewFamilyType = new FilteredElementCollector(doc)- .OfClass(typeof(ViewFamilyType))- .Cast<ViewFamilyType>()- .FirstOrDefault(vft => vft.ViewFamily == ViewFamily.Elevation);-- if (viewFamilyType == null)- {- throw new Exception("Elevation view family type not found");- }-- // Create elevation marker- ElevationMarker marker = ElevationMarker.CreateElevationMarker(doc, viewFamilyType.Id, point, 50);-- // Create elevation view (index 0 = North, 1 = East, 2 = South, 3 = West)- ViewSection elevationView = marker.CreateElevation(doc, doc.ActiveView.Id, 0);- elevationView.Name = viewName;-- trans.Commit();-- return new- {- success = true,- viewId = elevationView.Id.IntegerValue,- viewName = elevationView.Name,- markerId = marker.Id.IntegerValue,- markerLocation = new { point.X, point.Y, point.Z },- viewType = "Elevation"- };- }- }-- #endregion-- #region 3. Duplicate View-- public static object DuplicateView(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- string duplicateOption = payload.TryGetProperty("duplicate_option", out var opt) ? opt.GetString() : "Duplicate";- string newName = payload.TryGetProperty("new_name", out var nn) ? nn.GetString() : null;-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- ViewDuplicateOption dupOption = duplicateOption.ToLower() switch- {- "duplicate" => ViewDuplicateOption.Duplicate,- "with_detailing" => ViewDuplicateOption.WithDetailing,- "as_dependent" => ViewDuplicateOption.AsDependent,- _ => ViewDuplicateOption.Duplicate- };-- using (var trans = new Transaction(doc, "Duplicate View"))- {- trans.Start();-- ElementId newViewId = view.Duplicate(dupOption);- View newView = doc.GetElement(newViewId) as View;-- if (!string.IsNullOrEmpty(newName))- {- newView.Name = newName;- }-- trans.Commit();-- return new- {- success = true,- originalViewId = viewId,- originalViewName = view.Name,- newViewId = newView.Id.IntegerValue,- newViewName = newView.Name,- duplicateOption = duplicateOption- };- }- }-- #endregion-- #region 4. Set View Template-- public static object SetViewTemplate(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- int templateId = payload.GetProperty("template_id").GetInt32();-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- View template = doc.GetElement(new ElementId(templateId)) as View;- if (template == null || !template.IsTemplate)- {- throw new Exception($"Template {templateId} not found or is not a template");- }-- using (var trans = new Transaction(doc, "Set View Template"))- {- trans.Start();-- view.ViewTemplateId = template.Id;-- trans.Commit();-- return new- {- success = true,- viewId = viewId,- viewName = view.Name,- templateId = templateId,- templateName = template.Name- };- }- }-- #endregion-- #region 5. Create View Filter-- public static object CreateViewFilter(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string filterName = payload.GetProperty("filter_name").GetString();- var categories = payload.GetProperty("categories").EnumerateArray();-- using (var trans = new Transaction(doc, "Create View Filter"))- {- trans.Start();-- // Create category set- List<ElementId> categoryIds = new List<ElementId>();- foreach (var cat in categories)- {- string catName = cat.GetString();- if (Enum.TryParse(catName, out BuiltInCategory builtInCat))- {- categoryIds.Add(new ElementId(builtInCat));- }- }-- // Create parameter filter element- ParameterFilterElement filter = ParameterFilterElement.Create(doc, filterName, categoryIds);-- trans.Commit();-- return new- {- success = true,- filterId = filter.Id.IntegerValue,- filterName = filter.Name,- categories = categories.Select(c => c.GetString()).ToList()- };- }- }-- #endregion-- #region 6. Set View Visibility-- public static object SetViewVisibility(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- string category = payload.GetProperty("category").GetString();- bool visible = payload.GetProperty("visible").GetBoolean();-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- if (!Enum.TryParse(category, out BuiltInCategory builtInCat))- {- throw new Exception($"Unknown category: {category}");- }-- using (var trans = new Transaction(doc, "Set View Visibility"))- {- trans.Start();-- Category cat = Category.GetCategory(doc, builtInCat);- if (cat != null)- {- view.SetCategoryHidden(cat.Id, !visible);- }-- trans.Commit();-- return new- {- success = true,- viewId = viewId,- viewName = view.Name,- category = category,- visible = visible- };- }- }-- #endregion-- #region 7. Isolate Elements in View-- public static object IsolateElementsInView(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- using (var trans = new Transaction(doc, "Isolate Elements in View"))- {- trans.Start();-- view.IsolateElementsTemporary(elementIds);-- trans.Commit();-- return new- {- success = true,- viewId = viewId,- viewName = view.Name,- isolatedElementCount = elementIds.Count- };- }- }-- #endregion-- #region 8. Hide Elements in View-- public static object HideElementsInView(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- using (var trans = new Transaction(doc, "Hide Elements in View"))- {- trans.Start();-- view.HideElementsTemporary(elementIds);-- trans.Commit();-- return new- {- success = true,- viewId = viewId,- viewName = view.Name,- hiddenElementCount = elementIds.Count- };- }- }-- #endregion-- #region 9. Unhide Elements in View-- public static object UnhideElementsInView(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- using (var trans = new Transaction(doc, "Unhide Elements in View"))- {- trans.Start();-- view.UnhideElements(elementIds);-- trans.Commit();-- return new- {- success = true,- viewId = viewId,- viewName = view.Name,- unhiddenElementCount = elementIds.Count- };- }- }-- #endregion-- #region 10. Crop View-- public static object CropView(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int viewId = payload.GetProperty("view_id").GetInt32();- bool enabled = payload.TryGetProperty("enabled", out var en) ? en.GetBoolean() : true;-- View view = doc.GetElement(new ElementId(viewId)) as View;- if (view == null)- {- throw new Exception($"View {viewId} not found");- }-- using (var trans = new Transaction(doc, "Crop View"))- {- trans.Start();-- view.CropBoxActive = enabled;- view.CropBoxVisible = enabled;-- // If custom crop region is provided- if (enabled && payload.TryGetProperty("crop_box", out var cropBox))- {- var min = cropBox.GetProperty("min");- var max = cropBox.GetProperty("max");-- XYZ minPoint = new XYZ(- min.GetProperty("x").GetDouble(),- min.GetProperty("y").GetDouble(),- min.GetProperty("z").GetDouble()- );-- XYZ maxPoint = new XYZ(- max.GetProperty("x").GetDouble(),- max.GetProperty("y").GetDouble(),- max.GetProperty("z").GetDouble()- );-- BoundingBoxXYZ bbox = view.CropBox;- bbox.Min = minPoint;- bbox.Max = maxPoint;- view.CropBox = bbox;- }-- trans.Commit();-- return new- {- success = true,- viewId = viewId,- viewName = view.Name,- cropEnabled = view.CropBoxActive,- cropVisible = view.CropBoxVisible- };- }- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Enhancements/Analysis/AnalysisCommands.cs b/packages/revit-bridge-addin/src/Commands/Enhancements/Analysis/AnalysisCommands.csdeleted file mode 100644index 0aee6d9..0000000--- a/packages/revit-bridge-addin/src/Commands/Enhancements/Analysis/AnalysisCommands.cs+++ /dev/null@@ -1,466 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Enhancements.Analysis-{- /// <summary>- /// Analysis and validation commands for model quality- /// Reference (#92, Score: 217), ReferenceIntersector (#93, Score: 217)- /// </summary>- public static class AnalysisCommands- {- #region 1. Analyze Model Performance-- public static object AnalyzeModelPerformance(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- try- {- // Count elements by category- FilteredElementCollector collector = new FilteredElementCollector(doc);- var allElements = collector.WhereElementIsNotElementType().ToElements();-- var categoryCount = allElements- .Where(e => e.Category != null)- .GroupBy(e => e.Category.Name)- .Select(g => new { category = g.Key, count = g.Count() })- .OrderByDescending(x => x.count)- .ToList();-- // Count views- FilteredElementCollector viewCollector = new FilteredElementCollector(doc);- int viewCount = viewCollector.OfClass(typeof(View)).ToElements().Count;-- // Count families- FilteredElementCollector familyCollector = new FilteredElementCollector(doc);- int familyCount = familyCollector.OfClass(typeof(Family)).ToElements().Count;-- return new- {- success = true,- totalElements = allElements.Count,- viewCount = viewCount,- familyCount = familyCount,- topCategories = categoryCount.Take(10).ToList(),- fileSize = "N/A - requires file system access"- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 2. Find Element Intersections-- public static object FindElementIntersections(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- string targetCategory = payload.TryGetProperty("target_category", out var tc) ? tc.GetString() : null;-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- try- {- // Get element's bounding box- BoundingBoxXYZ bbox = element.get_BoundingBox(null);- if (bbox == null)- {- return new { success = false, error = "Element has no bounding box" };- }-- // Use outline for intersection test- Outline outline = new Outline(bbox.Min, bbox.Max);- BoundingBoxIntersectsFilter filter = new BoundingBoxIntersectsFilter(outline);-- FilteredElementCollector collector = new FilteredElementCollector(doc);- collector.WherePasses(filter);-- if (!string.IsNullOrEmpty(targetCategory) && Enum.TryParse(targetCategory, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }-- var intersectingElements = collector- .WhereElementIsNotElementType()- .Where(e => e.Id.IntegerValue != elementId)- .Select(e => new- {- elementId = e.Id.IntegerValue,- category = e.Category?.Name,- elementType = e.GetType().Name- })- .ToList();-- return new- {- success = true,- sourceElementId = elementId,- intersectingCount = intersectingElements.Count,- intersectingElements = intersectingElements- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 3. Validate Elements-- public static object ValidateElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();-- var validationResults = new List<object>();-- foreach (var elemId in elementIds)- {- Element element = doc.GetElement(elemId);- if (element == null)- {- validationResults.Add(new- {- elementId = elemId.IntegerValue,- isValid = false,- issues = new[] { "Element not found" }- });- continue;- }-- var issues = new List<string>();-- // Check for missing parameters- if (element.Category == null)- {- issues.Add("Missing category");- }-- // Check for geometry- Options options = new Options();- GeometryElement geomElem = element.get_Geometry(options);- if (geomElem == null || !geomElem.Any())- {- issues.Add("No geometry");- }-- // Check if element is valid- if (!element.IsValidObject)- {- issues.Add("Invalid object");- }-- validationResults.Add(new- {- elementId = elemId.IntegerValue,- isValid = issues.Count == 0,- category = element.Category?.Name,- issues = issues- });- }-- return new- {- success = true,- validatedCount = validationResults.Count,- validCount = validationResults.Count(r => ((dynamic)r).isValid),- invalidCount = validationResults.Count(r => !((dynamic)r).isValid),- results = validationResults- };- }-- #endregion-- #region 4. Find Duplicate Elements-- public static object FindDuplicateElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;- double tolerance = payload.TryGetProperty("tolerance", out var tol) ? tol.GetDouble() : 0.01; // feet-- try- {- FilteredElementCollector collector = new FilteredElementCollector(doc);- collector.WhereElementIsNotElementType();-- if (!string.IsNullOrEmpty(category) && Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }-- var elements = collector.ToElements();-- // Group by location- var duplicateGroups = new List<object>();- var processed = new HashSet<int>();-- foreach (var element in elements)- {- if (processed.Contains(element.Id.IntegerValue))- continue;-- LocationPoint locPoint = element.Location as LocationPoint;- if (locPoint == null)- continue;-- XYZ point1 = locPoint.Point;- var duplicates = new List<int> { element.Id.IntegerValue };- processed.Add(element.Id.IntegerValue);-- foreach (var otherElement in elements)- {- if (processed.Contains(otherElement.Id.IntegerValue))- continue;-- LocationPoint otherLocPoint = otherElement.Location as LocationPoint;- if (otherLocPoint == null)- continue;-- XYZ point2 = otherLocPoint.Point;- if (point1.DistanceTo(point2) < tolerance)- {- duplicates.Add(otherElement.Id.IntegerValue);- processed.Add(otherElement.Id.IntegerValue);- }- }-- if (duplicates.Count > 1)- {- duplicateGroups.Add(new- {- location = new { x = point1.X, y = point1.Y, z = point1.Z },- duplicateCount = duplicates.Count,- elementIds = duplicates- });- }- }-- return new- {- success = true,- duplicateGroupCount = duplicateGroups.Count,- totalDuplicates = duplicateGroups.Sum(g => ((dynamic)g).duplicateCount - 1),- duplicateGroups = duplicateGroups- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 5. Analyze Element Dependencies-- public static object AnalyzeElementDependencies(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- try- {- // Get dependent elements- var dependentIds = element.GetDependentElements(null);-- var dependents = dependentIds- .Select(id => doc.GetElement(id))- .Where(e => e != null)- .Select(e => new- {- elementId = e.Id.IntegerValue,- category = e.Category?.Name,- elementType = e.GetType().Name- })- .ToList();-- // Get host element- Element host = null;- if (element is FamilyInstance fi && fi.Host != null)- {- host = fi.Host;- }-- return new- {- success = true,- elementId = elementId,- dependentCount = dependents.Count,- dependents = dependents,- hostElementId = host?.Id.IntegerValue,- hostCategory = host?.Category?.Name- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 6. Check Model Integrity-- public static object CheckModelIntegrity(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- try- {- var issues = new List<object>();-- // Check for elements without geometry- FilteredElementCollector collector = new FilteredElementCollector(doc);- var elements = collector.WhereElementIsNotElementType().ToElements();-- int noGeometryCount = 0;- foreach (var element in elements)- {- Options options = new Options();- GeometryElement geomElem = element.get_Geometry(options);- if (geomElem == null || !geomElem.Any())- {- noGeometryCount++;- }- }-- if (noGeometryCount > 0)- {- issues.Add(new- {- issueType = "Elements without geometry",- count = noGeometryCount,- severity = "Warning"- });- }-- // Check warnings- IList<FailureMessage> warnings = doc.GetWarnings();- if (warnings.Count > 0)- {- issues.Add(new- {- issueType = "Document warnings",- count = warnings.Count,- severity = "Warning"- });- }-- // Check for unplaced rooms- FilteredElementCollector roomCollector = new FilteredElementCollector(doc);- var rooms = roomCollector.OfCategory(BuiltInCategory.OST_Rooms).ToElements();- int unplacedRooms = rooms.Count(r =>- {- Room room = r as Room;- return room != null && room.Area == 0;- });-- if (unplacedRooms > 0)- {- issues.Add(new- {- issueType = "Unplaced rooms",- count = unplacedRooms,- severity = "Error"- });- }-- return new- {- success = true,- totalIssues = issues.Count,- isHealthy = issues.Count == 0,- issues = issues- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 7. Get Element Statistics-- public static object GetElementStatistics(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string category = payload.TryGetProperty("category", out var cat) ? cat.GetString() : null;-- try- {- FilteredElementCollector collector = new FilteredElementCollector(doc);- collector.WhereElementIsNotElementType();-- if (!string.IsNullOrEmpty(category) && Enum.TryParse(category, out BuiltInCategory builtInCat))- {- collector.OfCategory(builtInCat);- }-- var elements = collector.ToElements();-- // Calculate statistics- var typeGroups = elements- .GroupBy(e => e.GetTypeId().IntegerValue)- .Select(g => new- {- typeId = g.Key,- typeName = doc.GetElement(new ElementId(g.Key))?.Name,- count = g.Count()- })- .OrderByDescending(x => x.count)- .ToList();-- var levelGroups = elements- .Where(e => e.LevelId != null && e.LevelId != ElementId.InvalidElementId)- .GroupBy(e => e.LevelId.IntegerValue)- .Select(g => new- {- levelId = g.Key,- levelName = doc.GetElement(new ElementId(g.Key))?.Name,- count = g.Count()- })- .OrderByDescending(x => x.count)- .ToList();-- return new- {- success = true,- totalCount = elements.Count,- uniqueTypes = typeGroups.Count,- topTypes = typeGroups.Take(10).ToList(),- distributionByLevel = levelGroups- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Enhancements/Batch/BatchCommands.cs b/packages/revit-bridge-addin/src/Commands/Enhancements/Batch/BatchCommands.csdeleted file mode 100644index d47f0b2..0000000--- a/packages/revit-bridge-addin/src/Commands/Enhancements/Batch/BatchCommands.cs+++ /dev/null@@ -1,460 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Enhancements.Batch-{- /// <summary>- /// Batch operation commands for high-performance bulk modifications- /// ElementId (#4, Score: 285), Element (#5, Score: 284)- /// </summary>- public static class BatchCommands- {- #region 1. Batch Set Parameters-- public static object BatchSetParameters(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- string parameterName = payload.GetProperty("parameter_name").GetString();- var value = payload.GetProperty("value");-- using (var trans = new Transaction(doc, "Batch Set Parameters"))- {- trans.Start();-- int successCount = 0;- var failures = new List<object>();-- foreach (var elemId in elementIds)- {- try- {- Element element = doc.GetElement(elemId);- if (element == null)- {- failures.Add(new { elementId = elemId.IntegerValue, error = "Element not found" });- continue;- }-- Parameter param = element.LookupParameter(parameterName);- if (param == null || param.IsReadOnly)- {- failures.Add(new { elementId = elemId.IntegerValue, error = "Parameter not found or read-only" });- continue;- }-- // Set value based on parameter type- if (param.StorageType == StorageType.Double)- {- param.Set(value.GetDouble());- }- else if (param.StorageType == StorageType.Integer)- {- param.Set(value.GetInt32());- }- else if (param.StorageType == StorageType.String)- {- param.Set(value.GetString());- }-- successCount++;- }- catch (Exception ex)- {- failures.Add(new { elementId = elemId.IntegerValue, error = ex.Message });- }- }-- trans.Commit();-- return new- {- success = true,- totalElements = elementIds.Count,- successCount = successCount,- failureCount = failures.Count,- failures = failures- };- }- }-- #endregion-- #region 2. Batch Delete Elements-- public static object BatchDeleteElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();-- using (var trans = new Transaction(doc, "Batch Delete Elements"))- {- trans.Start();-- try- {- ICollection<ElementId> deletedIds = doc.Delete(elementIds);-- trans.Commit();-- return new- {- success = true,- requestedCount = elementIds.Count,- deletedCount = deletedIds.Count,- deletedElementIds = deletedIds.Select(id => id.IntegerValue).ToList()- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 3. Batch Copy Elements-- public static object BatchCopyElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- var translation = payload.GetProperty("translation");-- XYZ offset = new XYZ(- translation.GetProperty("x").GetDouble(),- translation.GetProperty("y").GetDouble(),- translation.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Batch Copy Elements"))- {- trans.Start();-- try- {- ICollection<ElementId> copiedIds = ElementTransformUtils.CopyElements(doc, elementIds, offset);-- trans.Commit();-- return new- {- success = true,- originalCount = elementIds.Count,- copiedCount = copiedIds.Count,- copiedElementIds = copiedIds.Select(id => id.IntegerValue).ToList()- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 4. Batch Move Elements-- public static object BatchMoveElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- var translation = payload.GetProperty("translation");-- XYZ offset = new XYZ(- translation.GetProperty("x").GetDouble(),- translation.GetProperty("y").GetDouble(),- translation.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Batch Move Elements"))- {- trans.Start();-- try- {- ElementTransformUtils.MoveElements(doc, elementIds, offset);-- trans.Commit();-- return new- {- success = true,- movedCount = elementIds.Count,- translation = new { x = offset.X, y = offset.Y, z = offset.Z }- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 5. Batch Rotate Elements-- public static object BatchRotateElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- var axisStart = payload.GetProperty("axis_start");- var axisEnd = payload.GetProperty("axis_end");- double angle = payload.GetProperty("angle").GetDouble(); // radians-- XYZ start = new XYZ(- axisStart.GetProperty("x").GetDouble(),- axisStart.GetProperty("y").GetDouble(),- axisStart.GetProperty("z").GetDouble()- );-- XYZ end = new XYZ(- axisEnd.GetProperty("x").GetDouble(),- axisEnd.GetProperty("y").GetDouble(),- axisEnd.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Batch Rotate Elements"))- {- trans.Start();-- try- {- Line axis = Line.CreateBound(start, end);- ElementTransformUtils.RotateElements(doc, elementIds, axis, angle);-- trans.Commit();-- return new- {- success = true,- rotatedCount = elementIds.Count,- angle = angle,- angleDegrees = angle * 180.0 / Math.PI- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 6. Batch Mirror Elements-- public static object BatchMirrorElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- var planeOrigin = payload.GetProperty("plane_origin");- var planeNormal = payload.GetProperty("plane_normal");-- XYZ origin = new XYZ(- planeOrigin.GetProperty("x").GetDouble(),- planeOrigin.GetProperty("y").GetDouble(),- planeOrigin.GetProperty("z").GetDouble()- );-- XYZ normal = new XYZ(- planeNormal.GetProperty("x").GetDouble(),- planeNormal.GetProperty("y").GetDouble(),- planeNormal.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Batch Mirror Elements"))- {- trans.Start();-- try- {- Plane plane = Plane.CreateByNormalAndOrigin(normal, origin);- ElementTransformUtils.MirrorElements(doc, elementIds, plane, true); // true = copy-- trans.Commit();-- return new- {- success = true,- mirroredCount = elementIds.Count,- planeOrigin = new { x = origin.X, y = origin.Y, z = origin.Z },- planeNormal = new { x = normal.X, y = normal.Y, z = normal.Z }- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 7. Batch Change Type-- public static object BatchChangeType(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- int newTypeId = payload.GetProperty("new_type_id").GetInt32();-- using (var trans = new Transaction(doc, "Batch Change Type"))- {- trans.Start();-- int successCount = 0;- var failures = new List<object>();-- foreach (var elemId in elementIds)- {- try- {- Element element = doc.GetElement(elemId);- if (element == null)- {- failures.Add(new { elementId = elemId.IntegerValue, error = "Element not found" });- continue;- }-- element.ChangeTypeId(new ElementId(newTypeId));- successCount++;- }- catch (Exception ex)- {- failures.Add(new { elementId = elemId.IntegerValue, error = ex.Message });- }- }-- trans.Commit();-- return new- {- success = true,- totalElements = elementIds.Count,- successCount = successCount,- failureCount = failures.Count,- newTypeId = newTypeId,- failures = failures- };- }- }-- #endregion-- #region 8. Batch Isolate in Views-- public static object BatchIsolateInViews(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- var viewIds = payload.GetProperty("view_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();-- using (var trans = new Transaction(doc, "Batch Isolate in Views"))- {- trans.Start();-- int successCount = 0;- var failures = new List<object>();-- foreach (var viewId in viewIds)- {- try- {- View view = doc.GetElement(viewId) as View;- if (view == null)- {- failures.Add(new { viewId = viewId.IntegerValue, error = "View not found" });- continue;- }-- view.IsolateElementsTemporary(elementIds);- successCount++;- }- catch (Exception ex)- {- failures.Add(new { viewId = viewId.IntegerValue, error = ex.Message });- }- }-- trans.Commit();-- return new- {- success = true,- totalViews = viewIds.Count,- successCount = successCount,- failureCount = failures.Count,- isolatedElementCount = elementIds.Count,- failures = failures- };- }- }-- #endregion-- #region 9. Batch Export to CSV-- public static object BatchExportToCSV(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();- var parameterNames = payload.GetProperty("parameter_names").EnumerateArray().Select(e => e.GetString()).ToList();-- try- {- var rows = new List<object>();-- foreach (var elemId in elementIds)- {- Element element = doc.GetElement(elemId);- if (element == null)- continue;-- var rowData = new Dictionary<string, object>- {- { "ElementId", element.Id.IntegerValue },- { "Category", element.Category?.Name },- { "Type", doc.GetElement(element.GetTypeId())?.Name }- };-- foreach (var paramName in parameterNames)- {- Parameter param = element.LookupParameter(paramName);- if (param != null)- {- rowData[paramName] = param.AsValueString() ?? param.AsString() ?? "N/A";- }- else- {- rowData[paramName] = "N/A";- }- }-- rows.Add(rowData);- }-- return new- {- success = true,- rowCount = rows.Count,- data = rows,- message = "Export to CSV requires file writing - data returned as JSON"- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Enhancements/Phase4CommandRegistry.cs b/packages/revit-bridge-addin/src/Commands/Enhancements/Phase4CommandRegistry.csdeleted file mode 100644index 5822c33..0000000--- a/packages/revit-bridge-addin/src/Commands/Enhancements/Phase4CommandRegistry.cs+++ /dev/null@@ -1,99 +0,0 @@-using System;-using System.Text.Json;-using Autodesk.Revit.UI;-using RevitBridge.Commands.Enhancements.Transactions;-using RevitBridge.Commands.Enhancements.Analysis;-using RevitBridge.Commands.Enhancements.Batch;--namespace RevitBridge.Commands.Enhancements-{- /// <summary>- /// Registry for Phase 4 commands (24 enhancement tools)- /// These are advanced control and optimization tools for power users- /// </summary>- public static class Phase4CommandRegistry- {- public static object Execute(UIApplication app, string tool, JsonElement payload)- {- return tool switch- {- // === TRANSACTION CONTROL COMMANDS (8 tools) - Advanced Change Management ===- // Transaction (#2, Score: 293), TransactionGroup (#82, Score: 222)-- "revit.begin_transaction_group" => TransactionCommands.BeginTransactionGroup(app, payload),- "revit.commit_transaction_group" => TransactionCommands.CommitTransactionGroup(app, payload),- "revit.rollback_transaction_group" => TransactionCommands.RollbackTransactionGroup(app, payload),- "revit.get_document_changes" => TransactionCommands.GetDocumentChanges(app, payload),- "revit.get_undo_record" => TransactionCommands.GetUndoRecord(app, payload),- "revit.clear_undo_stack" => TransactionCommands.ClearUndoStack(app, payload),- "revit.set_failure_handling_options" => TransactionCommands.SetFailureHandlingOptions(app, payload),- "revit.get_warnings" => TransactionCommands.GetWarnings(app, payload),-- // === ANALYSIS & VALIDATION COMMANDS (7 tools) - Model Quality ===- // Reference (#92, Score: 217), ReferenceIntersector (#93, Score: 217)-- "revit.analyze_model_performance" => AnalysisCommands.AnalyzeModelPerformance(app, payload),- "revit.find_element_intersections" => AnalysisCommands.FindElementIntersections(app, payload),- "revit.validate_elements" => AnalysisCommands.ValidateElements(app, payload),- "revit.find_duplicate_elements" => AnalysisCommands.FindDuplicateElements(app, payload),- "revit.analyze_element_dependencies" => AnalysisCommands.AnalyzeElementDependencies(app, payload),- "revit.check_model_integrity" => AnalysisCommands.CheckModelIntegrity(app, payload),- "revit.get_element_statistics" => AnalysisCommands.GetElementStatistics(app, payload),-- // === BATCH OPERATIONS COMMANDS (9 tools) - High-Performance Bulk Ops ===- // ElementId (#4, Score: 285), Element (#5, Score: 284)-- "revit.batch_set_parameters" => BatchCommands.BatchSetParameters(app, payload),- "revit.batch_delete_elements" => BatchCommands.BatchDeleteElements(app, payload),- "revit.batch_copy_elements" => BatchCommands.BatchCopyElements(app, payload),- "revit.batch_move_elements" => BatchCommands.BatchMoveElements(app, payload),- "revit.batch_rotate_elements" => BatchCommands.BatchRotateElements(app, payload),- "revit.batch_mirror_elements" => BatchCommands.BatchMirrorElements(app, payload),- "revit.batch_change_type" => BatchCommands.BatchChangeType(app, payload),- "revit.batch_isolate_in_views" => BatchCommands.BatchIsolateInViews(app, payload),- "revit.batch_export_to_csv" => BatchCommands.BatchExportToCSV(app, payload),-- _ => null // Return null to let main factory handle unknown commands- };- }-- /// <summary>- /// Get list of all Phase 4 command names for documentation/validation- /// </summary>- public static string[] GetCommandNames()- {- return new[]- {- // Transaction Control (8)- "revit.begin_transaction_group",- "revit.commit_transaction_group",- "revit.rollback_transaction_group",- "revit.get_document_changes",- "revit.get_undo_record",- "revit.clear_undo_stack",- "revit.set_failure_handling_options",- "revit.get_warnings",-- // Analysis & Validation (7)- "revit.analyze_model_performance",- "revit.find_element_intersections",- "revit.validate_elements",- "revit.find_duplicate_elements",- "revit.analyze_element_dependencies",- "revit.check_model_integrity",- "revit.get_element_statistics",-- // Batch Operations (9)- "revit.batch_set_parameters",- "revit.batch_delete_elements",- "revit.batch_copy_elements",- "revit.batch_move_elements",- "revit.batch_rotate_elements",- "revit.batch_mirror_elements",- "revit.batch_change_type",- "revit.batch_isolate_in_views",- "revit.batch_export_to_csv"- };- }- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Enhancements/Transactions/TransactionCommands.cs b/packages/revit-bridge-addin/src/Commands/Enhancements/Transactions/TransactionCommands.csdeleted file mode 100644index e7da014..0000000--- a/packages/revit-bridge-addin/src/Commands/Enhancements/Transactions/TransactionCommands.cs+++ /dev/null@@ -1,233 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Enhancements.Transactions-{- /// <summary>- /// Advanced transaction and change control commands- /// Transaction (#2, Score: 293), TransactionGroup (#82, Score: 222)- /// </summary>- public static class TransactionCommands- {- #region 1. Begin Transaction Group-- public static object BeginTransactionGroup(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string groupName = payload.GetProperty("group_name").GetString();-- try- {- TransactionGroup transGroup = new TransactionGroup(doc, groupName);- transGroup.Start();-- // Store transaction group reference (in real implementation, would need session management)- return new- {- success = true,- groupName = groupName,- message = "Transaction group started - must be committed or rolled back"- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 2. Commit Transaction Group-- public static object CommitTransactionGroup(UIApplication app, JsonElement payload)- {- // Note: In real implementation, would need to track active transaction groups- // This is a template showing the pattern-- return new- {- success = true,- message = "Transaction group commit requires session-based group tracking"- };- }-- #endregion-- #region 3. Rollback Transaction Group-- public static object RollbackTransactionGroup(UIApplication app, JsonElement payload)- {- // Note: In real implementation, would need to track active transaction groups- // This is a template showing the pattern-- return new- {- success = true,- message = "Transaction group rollback requires session-based group tracking"- };- }-- #endregion-- #region 4. Get Document Changes-- public static object GetDocumentChanges(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- try- {- // Get modified elements since last transaction- ICollection<ElementId> modifiedElementIds = doc.GetChangedElementIds(- doc.ActiveView != null ? doc.ActiveView.Id : ElementId.InvalidElementId- );-- var modifiedElements = modifiedElementIds- .Select(id => doc.GetElement(id))- .Where(e => e != null)- .Select(e => new- {- elementId = e.Id.IntegerValue,- elementType = e.GetType().Name,- category = e.Category?.Name- })- .ToList();-- return new- {- success = true,- modifiedCount = modifiedElements.Count,- modifiedElements = modifiedElements- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 5. Get Undo Record-- public static object GetUndoRecord(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- try- {- // Get information about the undo stack- bool canUndo = doc.CanUndo();- string undoRecordName = canUndo ? doc.GetUndoRecordName() : null;-- return new- {- success = true,- canUndo = canUndo,- undoRecordName = undoRecordName- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 6. Clear Undo Stack-- public static object ClearUndoStack(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- using (var trans = new Transaction(doc, "Clear Undo Stack"))- {- trans.Start();-- try- {- // Note: Revit doesn't provide direct API to clear undo stack- // This would require workaround or is informational-- trans.Commit();-- return new- {- success = true,- message = "Undo stack clearing requires external method"- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 7. Set Failure Handling Options-- public static object SetFailureHandlingOptions(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- bool continueOnFailure = payload.TryGetProperty("continue_on_failure", out var cof) ? cof.GetBoolean() : false;-- try- {- // Create failure handling options- FailureHandlingOptions options = app.Application.FailureHandlingOptions;-- return new- {- success = true,- continueOnFailure = continueOnFailure,- message = "Failure handling options configured"- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 8. Get Warnings-- public static object GetWarnings(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- try- {- IList<FailureMessage> warnings = doc.GetWarnings();-- var warningList = warnings.Select(w => new- {- severity = w.GetSeverity().ToString(),- description = w.GetDescriptionText(),- failingElementIds = w.GetFailingElements().Select(id => id.IntegerValue).ToList()- }).ToList();-- return new- {- success = true,- warningCount = warnings.Count,- warnings = warningList- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Specialized/MEP/MEPCommands.cs b/packages/revit-bridge-addin/src/Commands/Specialized/MEP/MEPCommands.csdeleted file mode 100644index 0bb1992..0000000--- a/packages/revit-bridge-addin/src/Commands/Specialized/MEP/MEPCommands.cs+++ /dev/null@@ -1,549 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.DB.Mechanical;-using Autodesk.Revit.DB.Plumbing;-using Autodesk.Revit.DB.Electrical;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Specialized.MEP-{- /// <summary>- /// MEP-specific commands for HVAC, Plumbing, and Electrical systems- /// MechanicalSystem (#228, Score: 183), Connector (#229, Score: 183)- /// </summary>- public static class MEPCommands- {- #region 1. Create MEP System-- public static object CreateMEPSystem(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string systemType = payload.GetProperty("system_type").GetString(); // "Supply Air", "Return Air", "Exhaust Air", "Hydronic Supply", etc.- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();-- using (var trans = new Transaction(doc, "Create MEP System"))- {- trans.Start();-- MechanicalSystem system = null;-- try- {- // Get the first element to determine system type- Element firstElement = doc.GetElement(elementIds.First());-- if (firstElement is FamilyInstance fi && fi.MEPModel is MechanicalEquipment)- {- // Create mechanical system- system = doc.Create.NewMechanicalSystem(null, elementIds, DuctSystemType.SupplyAir);- }-- trans.Commit();-- if (system != null)- {- return new- {- success = true,- systemId = system.Id.IntegerValue,- systemName = system.Name,- elementCount = elementIds.Count,- systemType = systemType- };- }- else- {- return new { success = false, error = "Failed to create MEP system" };- }- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 2. Add Elements to System-- public static object AddElementsToSystem(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int systemId = payload.GetProperty("system_id").GetInt32();- var elementIds = payload.GetProperty("element_ids").EnumerateArray().Select(e => new ElementId(e.GetInt32())).ToList();-- MEPSystem system = doc.GetElement(new ElementId(systemId)) as MEPSystem;- if (system == null)- {- throw new Exception($"MEP System {systemId} not found");- }-- using (var trans = new Transaction(doc, "Add Elements to System"))- {- trans.Start();-- int addedCount = 0;- foreach (var elemId in elementIds)- {- try- {- system.Add(elemId);- addedCount++;- }- catch- {- // Element may not be compatible with system- }- }-- trans.Commit();-- return new- {- success = true,- systemId = systemId,- systemName = system.Name,- elementsAdded = addedCount,- totalElements = system.Elements.Count- };- }- }-- #endregion-- #region 3. Connect MEP Elements-- public static object ConnectMEPElements(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int element1Id = payload.GetProperty("element1_id").GetInt32();- int element2Id = payload.GetProperty("element2_id").GetInt32();- int connector1Index = payload.TryGetProperty("connector1_index", out var c1) ? c1.GetInt32() : 0;- int connector2Index = payload.TryGetProperty("connector2_index", out var c2) ? c2.GetInt32() : 0;-- Element element1 = doc.GetElement(new ElementId(element1Id));- Element element2 = doc.GetElement(new ElementId(element2Id));-- using (var trans = new Transaction(doc, "Connect MEP Elements"))- {- trans.Start();-- try- {- // Get connectors from elements- ConnectorSet connectors1 = GetConnectors(element1);- ConnectorSet connectors2 = GetConnectors(element2);-- if (connectors1 == null || connectors2 == null)- {- throw new Exception("Elements do not have MEP connectors");- }-- Connector conn1 = GetConnectorAtIndex(connectors1, connector1Index);- Connector conn2 = GetConnectorAtIndex(connectors2, connector2Index);-- if (conn1 != null && conn2 != null)- {- conn1.ConnectTo(conn2);- }-- trans.Commit();-- return new- {- success = true,- element1Id = element1Id,- element2Id = element2Id,- connected = true- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 4. Size MEP Element-- public static object SizeMEPElement(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- double size = payload.GetProperty("size").GetDouble(); // In internal units (feet)-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- using (var trans = new Transaction(doc, "Size MEP Element"))- {- trans.Start();-- try- {- // For ducts and pipes, set diameter or size- if (element is Duct duct)- {- Parameter diamParam = duct.get_Parameter(BuiltInParameter.RBS_CURVE_DIAMETER_PARAM);- if (diamParam != null && !diamParam.IsReadOnly)- {- diamParam.Set(size);- }- }- else if (element is Pipe pipe)- {- Parameter diamParam = pipe.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM);- if (diamParam != null && !diamParam.IsReadOnly)- {- diamParam.Set(size);- }- }-- trans.Commit();-- return new- {- success = true,- elementId = elementId,- newSize = size,- elementType = element.GetType().Name- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 5. Route MEP-- public static object RouteMEP(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int startConnectorElementId = payload.GetProperty("start_element_id").GetInt32();- int endConnectorElementId = payload.GetProperty("end_element_id").GetInt32();- string mepType = payload.GetProperty("mep_type").GetString(); // "duct", "pipe", "conduit", "cabletray"-- using (var trans = new Transaction(doc, "Route MEP"))- {- trans.Start();-- try- {- Element startElement = doc.GetElement(new ElementId(startConnectorElementId));- Element endElement = doc.GetElement(new ElementId(endConnectorElementId));-- // Get connectors- ConnectorSet startConnectors = GetConnectors(startElement);- ConnectorSet endConnectors = GetConnectors(endElement);-- Connector startConn = GetConnectorAtIndex(startConnectors, 0);- Connector endConn = GetConnectorAtIndex(endConnectors, 0);-- if (startConn == null || endConn == null)- {- throw new Exception("Could not find connectors for routing");- }-- // Create routing path- XYZ startPoint = startConn.Origin;- XYZ endPoint = endConn.Origin;-- // Simple routing - create MEP element between points- ElementId createdId = ElementId.InvalidElementId;-- if (mepType.ToLower() == "duct")- {- // Get duct type- FilteredElementCollector collector = new FilteredElementCollector(doc);- DuctType ductType = collector.OfClass(typeof(DuctType)).FirstElement() as DuctType;-- if (ductType != null)- {- Duct duct = Duct.Create(doc, ductType.Id, startElement.LevelId, startConn, endConn);- createdId = duct.Id;- }- }- else if (mepType.ToLower() == "pipe")- {- // Get pipe type- FilteredElementCollector collector = new FilteredElementCollector(doc);- PipeType pipeType = collector.OfClass(typeof(PipeType)).FirstElement() as PipeType;-- if (pipeType != null)- {- Pipe pipe = Pipe.Create(doc, pipeType.Id, startElement.LevelId, startConn, endConn);- createdId = pipe.Id;- }- }-- trans.Commit();-- return new- {- success = true,- createdElementId = createdId.IntegerValue,- mepType = mepType,- startElementId = startConnectorElementId,- endElementId = endConnectorElementId- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 6. Create Space-- public static object CreateSpace(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int levelId = payload.GetProperty("level_id").GetInt32();- var locationPoint = payload.GetProperty("location");-- XYZ location = new XYZ(- locationPoint.GetProperty("x").GetDouble(),- locationPoint.GetProperty("y").GetDouble(),- locationPoint.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Create Space"))- {- trans.Start();-- Level level = doc.GetElement(new ElementId(levelId)) as Level;- if (level == null)- {- throw new Exception($"Level {levelId} not found");- }-- // Create space at location- Space space = doc.Create.NewSpace(level, new UV(location.X, location.Y));-- trans.Commit();-- return new- {- success = true,- spaceId = space.Id.IntegerValue,- spaceName = space.Name,- levelId = levelId,- area = space.Area,- volume = space.Volume- };- }- }-- #endregion-- #region 7. Calculate Space Loads-- public static object CalculateSpaceLoads(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int spaceId = payload.GetProperty("space_id").GetInt32();-- Space space = doc.GetElement(new ElementId(spaceId)) as Space;- if (space == null)- {- throw new Exception($"Space {spaceId} not found");- }-- // Get load parameters- Parameter coolingLoadParam = space.get_Parameter(BuiltInParameter.ROOM_DESIGN_COOLING_LOAD);- Parameter heatingLoadParam = space.get_Parameter(BuiltInParameter.ROOM_DESIGN_HEATING_LOAD);- Parameter airflowParam = space.get_Parameter(BuiltInParameter.ROOM_DESIGN_SUPPLY_AIRFLOW);-- return new- {- success = true,- spaceId = spaceId,- spaceName = space.Name,- coolingLoad = coolingLoadParam?.AsDouble() ?? 0,- heatingLoad = heatingLoadParam?.AsDouble() ?? 0,- supplyAirflow = airflowParam?.AsDouble() ?? 0,- area = space.Area,- volume = space.Volume- };- }-- #endregion-- #region 8. Get MEP System Info-- public static object GetMEPSystemInfo(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int systemId = payload.GetProperty("system_id").GetInt32();-- MEPSystem system = doc.GetElement(new ElementId(systemId)) as MEPSystem;- if (system == null)- {- throw new Exception($"MEP System {systemId} not found");- }-- var elements = system.Elements.Cast<ElementId>().Select(id => new- {- elementId = id.IntegerValue,- elementType = doc.GetElement(id)?.GetType().Name- }).ToList();-- return new- {- success = true,- systemId = systemId,- systemName = system.Name,- elementCount = system.Elements.Count,- elements = elements,- systemType = system.GetType().Name- };- }-- #endregion-- #region 9. Set MEP Flow-- public static object SetMEPFlow(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- double flow = payload.GetProperty("flow").GetDouble(); // CFM for air, GPM for water-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- using (var trans = new Transaction(doc, "Set MEP Flow"))- {- trans.Start();-- Parameter flowParam = null;-- if (element is Duct)- {- flowParam = element.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_PARAM);- }- else if (element is Pipe)- {- flowParam = element.get_Parameter(BuiltInParameter.RBS_PIPE_FLOW_PARAM);- }- else if (element is FamilyInstance fi)- {- flowParam = fi.get_Parameter(BuiltInParameter.RBS_DUCT_FLOW_PARAM) ??- fi.get_Parameter(BuiltInParameter.RBS_PIPE_FLOW_PARAM);- }-- if (flowParam != null && !flowParam.IsReadOnly)- {- flowParam.Set(flow);- }-- trans.Commit();-- return new- {- success = true,- elementId = elementId,- flow = flow,- elementType = element.GetType().Name- };- }- }-- #endregion-- #region 10. Get Connector Info-- public static object GetConnectorInfo(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- ConnectorSet connectors = GetConnectors(element);- if (connectors == null)- {- return new { success = false, error = "Element has no connectors" };- }-- var connectorList = new List<object>();- foreach (Connector connector in connectors)- {- connectorList.Add(new- {- origin = new { x = connector.Origin.X, y = connector.Origin.Y, z = connector.Origin.Z },- shape = connector.Shape.ToString(),- domain = connector.Domain.ToString(),- isConnected = connector.IsConnected,- flow = connector.Flow,- radius = connector.Radius,- height = connector.Height,- width = connector.Width- });- }-- return new- {- success = true,- elementId = elementId,- connectorCount = connectorList.Count,- connectors = connectorList- };- }-- #endregion-- #region Helper Methods-- private static ConnectorSet GetConnectors(Element element)- {- if (element is FamilyInstance fi && fi.MEPModel != null)- {- return fi.MEPModel.ConnectorManager?.Connectors;- }- else if (element is MEPCurve mepCurve)- {- return mepCurve.ConnectorManager?.Connectors;- }-- return null;- }-- private static Connector GetConnectorAtIndex(ConnectorSet connectors, int index)- {- int i = 0;- foreach (Connector conn in connectors)- {- if (i == index)- return conn;- i++;- }- return null;- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Specialized/Phase3CommandRegistry.cs b/packages/revit-bridge-addin/src/Commands/Specialized/Phase3CommandRegistry.csdeleted file mode 100644index 379f08d..0000000--- a/packages/revit-bridge-addin/src/Commands/Specialized/Phase3CommandRegistry.cs+++ /dev/null@@ -1,124 +0,0 @@-using System;-using System.Text.Json;-using Autodesk.Revit.UI;-using RevitBridge.Commands.Specialized.MEP;-using RevitBridge.Commands.Specialized.Structural;-using RevitBridge.Commands.Specialized.Stairs;-using RevitBridge.Commands.Specialized.Phasing;--namespace RevitBridge.Commands.Specialized-{- /// <summary>- /// Registry for Phase 3 commands (28 specialized tools)- /// These are discipline-specific tools for advanced professional workflows- /// </summary>- public static class Phase3CommandRegistry- {- public static object Execute(UIApplication app, string tool, JsonElement payload)- {- return tool switch- {- // === MEP COMMANDS (10 tools) - HVAC, Plumbing, Electrical ===- // MechanicalSystem (#228, Score: 183), Connector (#229, Score: 183)-- "revit.create_mep_system" => MEPCommands.CreateMEPSystem(app, payload),- "revit.add_elements_to_system" => MEPCommands.AddElementsToSystem(app, payload),- "revit.connect_mep_elements" => MEPCommands.ConnectMEPElements(app, payload),- "revit.size_mep_element" => MEPCommands.SizeMEPElement(app, payload),- "revit.route_mep" => MEPCommands.RouteMEP(app, payload),- "revit.create_space" => MEPCommands.CreateSpace(app, payload),- "revit.calculate_space_loads" => MEPCommands.CalculateSpaceLoads(app, payload),- "revit.get_mep_system_info" => MEPCommands.GetMEPSystemInfo(app, payload),- "revit.set_mep_flow" => MEPCommands.SetMEPFlow(app, payload),- "revit.get_connector_info" => MEPCommands.GetConnectorInfo(app, payload),-- // === STRUCTURAL COMMANDS (8 tools) - Framing, Loads, Analysis ===- // StructuralType (#344, Score: 159), AnalyticalModel (#372, Score: 155)-- "revit.create_structural_framing" => StructuralCommands.CreateStructuralFraming(app, payload),- "revit.create_structural_column" => StructuralCommands.CreateStructuralColumn(app, payload),- "revit.create_truss" => StructuralCommands.CreateTruss(app, payload),- "revit.place_rebar" => StructuralCommands.PlaceRebar(app, payload),- "revit.create_load_case" => StructuralCommands.CreateLoadCase(app, payload),- "revit.apply_point_load" => StructuralCommands.ApplyPointLoad(app, payload),- "revit.apply_line_load" => StructuralCommands.ApplyLineLoad(app, payload),- "revit.get_analytical_model" => StructuralCommands.GetAnalyticalModel(app, payload),-- // === STAIRS & RAILINGS COMMANDS (6 tools) - Circulation Design ===- // Stairs (#539, Score: 133), StairsRun (#540, Score: 133), Railing (#541, Score: 133)-- "revit.create_stairs_by_sketch" => StairsCommands.CreateStairsBySketch(app, payload),- "revit.create_railing" => StairsCommands.CreateRailing(app, payload),- "revit.set_stairs_path" => StairsCommands.SetStairsPath(app, payload),- "revit.modify_stairs_run" => StairsCommands.ModifyStairsRun(app, payload),- "revit.get_stairs_info" => StairsCommands.GetStairsInfo(app, payload),- "revit.get_railing_info" => StairsCommands.GetRailingInfo(app, payload),-- // === PHASING & DESIGN OPTIONS COMMANDS (9 tools) - Project Timeline ===- // Phase (#480, Score: 141), DesignOption (#481, Score: 141)-- "revit.create_phase" => PhasingCommands.CreatePhase(app, payload),- "revit.set_element_phase" => PhasingCommands.SetElementPhase(app, payload),- "revit.get_element_phase_info" => PhasingCommands.GetElementPhaseInfo(app, payload),- "revit.create_design_option_set" => PhasingCommands.CreateDesignOptionSet(app, payload),- "revit.create_design_option" => PhasingCommands.CreateDesignOption(app, payload),- "revit.set_element_design_option" => PhasingCommands.SetElementDesignOption(app, payload),- "revit.get_design_option_info" => PhasingCommands.GetDesignOptionInfo(app, payload),- "revit.list_all_phases" => PhasingCommands.ListAllPhases(app, payload),- "revit.list_all_design_option_sets" => PhasingCommands.ListAllDesignOptionSets(app, payload),-- _ => null // Return null to let main factory handle unknown commands- };- }-- /// <summary>- /// Get list of all Phase 3 command names for documentation/validation- /// </summary>- public static string[] GetCommandNames()- {- return new[]- {- // MEP (10)- "revit.create_mep_system",- "revit.add_elements_to_system",- "revit.connect_mep_elements",- "revit.size_mep_element",- "revit.route_mep",- "revit.create_space",- "revit.calculate_space_loads",- "revit.get_mep_system_info",- "revit.set_mep_flow",- "revit.get_connector_info",-- // Structural (8)- "revit.create_structural_framing",- "revit.create_structural_column",- "revit.create_truss",- "revit.place_rebar",- "revit.create_load_case",- "revit.apply_point_load",- "revit.apply_line_load",- "revit.get_analytical_model",-- // Stairs & Railings (6)- "revit.create_stairs_by_sketch",- "revit.create_railing",- "revit.set_stairs_path",- "revit.modify_stairs_run",- "revit.get_stairs_info",- "revit.get_railing_info",-- // Phasing & Design Options (9)- "revit.create_phase",- "revit.set_element_phase",- "revit.get_element_phase_info",- "revit.create_design_option_set",- "revit.create_design_option",- "revit.set_element_design_option",- "revit.get_design_option_info",- "revit.list_all_phases",- "revit.list_all_design_option_sets"- };- }- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Specialized/Phasing/PhasingCommands.cs b/packages/revit-bridge-addin/src/Commands/Specialized/Phasing/PhasingCommands.csdeleted file mode 100644index 005a535..0000000--- a/packages/revit-bridge-addin/src/Commands/Specialized/Phasing/PhasingCommands.cs+++ /dev/null@@ -1,445 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Specialized.Phasing-{- /// <summary>- /// Phasing and design options commands for project timeline management- /// Phase (#480, Score: 141), DesignOption (#481, Score: 141)- /// </summary>- public static class PhasingCommands- {- #region 1. Create Phase-- public static object CreatePhase(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string phaseName = payload.GetProperty("phase_name").GetString();- int? afterPhaseId = payload.TryGetProperty("after_phase_id", out var ap) ? ap.GetInt32() : null;-- using (var trans = new Transaction(doc, "Create Phase"))- {- trans.Start();-- try- {- PhaseArray phases = doc.Phases;- Phase newPhase = null;-- if (afterPhaseId.HasValue)- {- Phase afterPhase = doc.GetElement(new ElementId(afterPhaseId.Value)) as Phase;- if (afterPhase != null)- {- // Insert phase after specified phase- int index = -1;- for (int i = 0; i < phases.Size; i++)- {- if (phases.get_Item(i).Id.IntegerValue == afterPhaseId.Value)- {- index = i + 1;- break;- }- }-- if (index >= 0 && index <= phases.Size)- {- newPhase = phases.Insert(index);- newPhase.Name = phaseName;- }- }- }- else- {- // Append new phase at the end- newPhase = phases.Insert(phases.Size);- newPhase.Name = phaseName;- }-- trans.Commit();-- if (newPhase != null)- {- return new- {- success = true,- phaseId = newPhase.Id.IntegerValue,- phaseName = newPhase.Name,- sequenceNumber = newPhase.SequenceNumber- };- }- else- {- return new { success = false, error = "Failed to create phase" };- }- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 2. Set Element Phase-- public static object SetElementPhase(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- int phaseCreatedId = payload.TryGetProperty("phase_created_id", out var pc) ? pc.GetInt32() : -1;- int phaseDemolishedId = payload.TryGetProperty("phase_demolished_id", out var pd) ? pd.GetInt32() : -1;-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- using (var trans = new Transaction(doc, "Set Element Phase"))- {- trans.Start();-- try- {- // Set phase created- if (phaseCreatedId > 0)- {- Parameter phaseCreatedParam = element.get_Parameter(BuiltInParameter.PHASE_CREATED);- if (phaseCreatedParam != null && !phaseCreatedParam.IsReadOnly)- {- phaseCreatedParam.Set(new ElementId(phaseCreatedId));- }- }-- // Set phase demolished- if (phaseDemolishedId > 0)- {- Parameter phaseDemolishedParam = element.get_Parameter(BuiltInParameter.PHASE_DEMOLISHED);- if (phaseDemolishedParam != null && !phaseDemolishedParam.IsReadOnly)- {- phaseDemolishedParam.Set(new ElementId(phaseDemolishedId));- }- }-- trans.Commit();-- return new- {- success = true,- elementId = elementId,- phaseCreatedId = phaseCreatedId,- phaseDemolishedId = phaseDemolishedId- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 3. Get Element Phase Info-- public static object GetElementPhaseInfo(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- try- {- Parameter phaseCreatedParam = element.get_Parameter(BuiltInParameter.PHASE_CREATED);- Parameter phaseDemolishedParam = element.get_Parameter(BuiltInParameter.PHASE_DEMOLISHED);-- ElementId phaseCreatedId = phaseCreatedParam?.AsElementId();- ElementId phaseDemolishedId = phaseDemolishedParam?.AsElementId();-- Phase phaseCreated = phaseCreatedId != null && phaseCreatedId != ElementId.InvalidElementId- ? doc.GetElement(phaseCreatedId) as Phase- : null;-- Phase phaseDemolished = phaseDemolishedId != null && phaseDemolishedId != ElementId.InvalidElementId- ? doc.GetElement(phaseDemolishedId) as Phase- : null;-- return new- {- success = true,- elementId = elementId,- phaseCreatedId = phaseCreated?.Id.IntegerValue,- phaseCreatedName = phaseCreated?.Name,- phaseDemolishedId = phaseDemolished?.Id.IntegerValue,- phaseDemolishedName = phaseDemolished?.Name- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 4. Create Design Option Set-- public static object CreateDesignOptionSet(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string optionSetName = payload.GetProperty("option_set_name").GetString();-- using (var trans = new Transaction(doc, "Create Design Option Set"))- {- trans.Start();-- try- {- DesignOptionSet optionSet = DesignOptionSet.Create(doc, optionSetName);-- trans.Commit();-- return new- {- success = true,- optionSetId = optionSet.Id.IntegerValue,- optionSetName = optionSet.Name,- defaultOptionId = optionSet.get_Parameter(BuiltInParameter.OPTION_SET_DEFAULT_OPTION)?.AsElementId().IntegerValue- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 5. Create Design Option-- public static object CreateDesignOption(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int optionSetId = payload.GetProperty("option_set_id").GetInt32();- string optionName = payload.GetProperty("option_name").GetString();-- using (var trans = new Transaction(doc, "Create Design Option"))- {- trans.Start();-- try- {- DesignOptionSet optionSet = doc.GetElement(new ElementId(optionSetId)) as DesignOptionSet;- if (optionSet == null)- {- throw new Exception($"Design option set {optionSetId} not found");- }-- DesignOption option = DesignOption.Create(doc, optionSet.Id);- option.Name = optionName;-- trans.Commit();-- return new- {- success = true,- optionId = option.Id.IntegerValue,- optionName = option.Name,- optionSetId = optionSetId,- isPrimary = option.IsPrimary- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 6. Set Element Design Option-- public static object SetElementDesignOption(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();- int designOptionId = payload.GetProperty("design_option_id").GetInt32();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- using (var trans = new Transaction(doc, "Set Element Design Option"))- {- trans.Start();-- try- {- DesignOption designOption = doc.GetElement(new ElementId(designOptionId)) as DesignOption;- if (designOption == null)- {- throw new Exception($"Design option {designOptionId} not found");- }-- // Set element's design option- Parameter designOptionParam = element.get_Parameter(BuiltInParameter.DESIGN_OPTION_ID);- if (designOptionParam != null && !designOptionParam.IsReadOnly)- {- designOptionParam.Set(new ElementId(designOptionId));- }-- trans.Commit();-- return new- {- success = true,- elementId = elementId,- designOptionId = designOptionId,- designOptionName = designOption.Name- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 7. Get Design Option Info-- public static object GetDesignOptionInfo(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int designOptionId = payload.GetProperty("design_option_id").GetInt32();-- DesignOption designOption = doc.GetElement(new ElementId(designOptionId)) as DesignOption;- if (designOption == null)- {- throw new Exception($"Design option {designOptionId} not found");- }-- try- {- // Get option set- Parameter optionSetParam = designOption.get_Parameter(BuiltInParameter.OPTION_SET_ID);- ElementId optionSetId = optionSetParam?.AsElementId();- DesignOptionSet optionSet = optionSetId != null && optionSetId != ElementId.InvalidElementId- ? doc.GetElement(optionSetId) as DesignOptionSet- : null;-- // Get elements in this design option- FilteredElementCollector collector = new FilteredElementCollector(doc);- ICollection<ElementId> elements = collector- .WhereElementIsNotElementType()- .Where(e => e.DesignOption?.Id.IntegerValue == designOptionId)- .ToElementIds();-- return new- {- success = true,- optionId = designOptionId,- optionName = designOption.Name,- isPrimary = designOption.IsPrimary,- optionSetId = optionSet?.Id.IntegerValue,- optionSetName = optionSet?.Name,- elementCount = elements.Count- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 8. List All Phases-- public static object ListAllPhases(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- try- {- PhaseArray phases = doc.Phases;- var phaseList = new List<object>();-- for (int i = 0; i < phases.Size; i++)- {- Phase phase = phases.get_Item(i);- phaseList.Add(new- {- phaseId = phase.Id.IntegerValue,- phaseName = phase.Name,- sequenceNumber = phase.SequenceNumber- });- }-- return new- {- success = true,- phaseCount = phaseList.Count,- phases = phaseList- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 9. List All Design Option Sets-- public static object ListAllDesignOptionSets(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;-- try- {- FilteredElementCollector collector = new FilteredElementCollector(doc);- var optionSets = collector- .OfClass(typeof(DesignOptionSet))- .Cast<DesignOptionSet>()- .Select(os => new- {- optionSetId = os.Id.IntegerValue,- optionSetName = os.Name,- defaultOptionId = os.get_Parameter(BuiltInParameter.OPTION_SET_DEFAULT_OPTION)?.AsElementId().IntegerValue- })- .ToList();-- return new- {- success = true,- optionSetCount = optionSets.Count,- optionSets = optionSets- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Specialized/Stairs/StairsCommands.cs b/packages/revit-bridge-addin/src/Commands/Specialized/Stairs/StairsCommands.csdeleted file mode 100644index 5e60763..0000000--- a/packages/revit-bridge-addin/src/Commands/Specialized/Stairs/StairsCommands.cs+++ /dev/null@@ -1,367 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.DB.Architecture;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Specialized.Stairs-{- /// <summary>- /// Stairs and railing commands for circulation design- /// Stairs (#539, Score: 133), StairsRun (#540, Score: 133), Railing (#541, Score: 133)- /// </summary>- public static class StairsCommands- {- #region 1. Create Stairs by Sketch-- public static object CreateStairsBySketch(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int baseLevelId = payload.GetProperty("base_level_id").GetInt32();- int topLevelId = payload.GetProperty("top_level_id").GetInt32();- int stairsTypeId = payload.GetProperty("stairs_type_id").GetInt32();-- using (var trans = new Transaction(doc, "Create Stairs by Sketch"))- {- trans.Start();-- try- {- Level baseLevel = doc.GetElement(new ElementId(baseLevelId)) as Level;- Level topLevel = doc.GetElement(new ElementId(topLevelId)) as Level;- StairsType stairsType = doc.GetElement(new ElementId(stairsTypeId)) as StairsType;-- if (baseLevel == null || topLevel == null || stairsType == null)- {- throw new Exception("Base level, top level, or stairs type not found");- }-- // Create stairs edit scope- StairsEditScope stairsEdit = doc.Create.NewStairsEditScope();-- // Note: Actual sketch creation requires user interaction in Revit UI- // This is a template that would need to be completed with actual sketch curves-- Stairs stairs = stairsEdit.CommitStairs(doc);-- trans.Commit();-- return new- {- success = true,- stairsId = stairs.Id.IntegerValue,- baseLevelId = baseLevelId,- topLevelId = topLevelId,- message = "Stairs sketch mode started - requires manual sketch completion"- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 2. Create Railing-- public static object CreateRailing(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int hostElementId = payload.GetProperty("host_element_id").GetInt32();- int railingTypeId = payload.GetProperty("railing_type_id").GetInt32();-- using (var trans = new Transaction(doc, "Create Railing"))- {- trans.Start();-- try- {- Element hostElement = doc.GetElement(new ElementId(hostElementId));- RailingType railingType = doc.GetElement(new ElementId(railingTypeId)) as RailingType;-- if (hostElement == null || railingType == null)- {- throw new Exception("Host element or railing type not found");- }-- // Get path from host (stairs, ramp, or floor/roof)- Railing railing = null;-- if (hostElement is Stairs stairs)- {- // Create railing on stairs- ICollection<ElementId> stairsRuns = stairs.GetStairsRuns();- if (stairsRuns.Count > 0)- {- StairsRun run = doc.GetElement(stairsRuns.First()) as StairsRun;- if (run != null)- {- CurveLoop path = run.GetStairsPath();- List<Curve> curves = path.ToList();-- if (curves.Count > 0)- {- railing = Railing.Create(doc, curves, railingType.Id, hostElement.LevelId);- }- }- }- }-- trans.Commit();-- if (railing != null)- {- return new- {- success = true,- railingId = railing.Id.IntegerValue,- hostElementId = hostElementId,- railingTypeName = railingType.Name- };- }- else- {- return new { success = false, error = "Failed to create railing" };- }- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 3. Set Stairs Path-- public static object SetStairsPath(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int stairsId = payload.GetProperty("stairs_id").GetInt32();- var pathPoints = payload.GetProperty("path_points").EnumerateArray();-- using (var trans = new Transaction(doc, "Set Stairs Path"))- {- trans.Start();-- try- {- Stairs stairs = doc.GetElement(new ElementId(stairsId)) as Stairs;- if (stairs == null)- {- throw new Exception($"Stairs {stairsId} not found");- }-- // Convert JSON points to XYZ- List<XYZ> points = new List<XYZ>();- foreach (var point in pathPoints)- {- points.Add(new XYZ(- point.GetProperty("x").GetDouble(),- point.GetProperty("y").GetDouble(),- point.GetProperty("z").GetDouble()- ));- }-- // Create curves from points- List<Curve> curves = new List<Curve>();- for (int i = 0; i < points.Count - 1; i++)- {- curves.Add(Line.CreateBound(points[i], points[i + 1]));- }-- // Note: Modifying existing stairs path requires StairsEditScope- // This is a template implementation-- trans.Commit();-- return new- {- success = true,- stairsId = stairsId,- pathPointCount = points.Count,- message = "Stairs path modification requires StairsEditScope"- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 4. Modify Stairs Run-- public static object ModifyStairsRun(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int stairsRunId = payload.GetProperty("stairs_run_id").GetInt32();- int? numberOfRisers = payload.TryGetProperty("number_of_risers", out var nr) ? nr.GetInt32() : null;- double? runWidth = payload.TryGetProperty("run_width", out var rw) ? rw.GetDouble() : null;-- using (var trans = new Transaction(doc, "Modify Stairs Run"))- {- trans.Start();-- try- {- StairsRun stairsRun = doc.GetElement(new ElementId(stairsRunId)) as StairsRun;- if (stairsRun == null)- {- throw new Exception($"Stairs run {stairsRunId} not found");- }-- // Set number of risers- if (numberOfRisers.HasValue)- {- Parameter risersParam = stairsRun.get_Parameter(BuiltInParameter.STAIRS_ACTUAL_NUM_RISERS);- if (risersParam != null && !risersParam.IsReadOnly)- {- risersParam.Set(numberOfRisers.Value);- }- }-- // Set run width- if (runWidth.HasValue)- {- Parameter widthParam = stairsRun.get_Parameter(BuiltInParameter.STAIRS_ATTR_RUN_WIDTH);- if (widthParam != null && !widthParam.IsReadOnly)- {- widthParam.Set(runWidth.Value);- }- }-- trans.Commit();-- return new- {- success = true,- stairsRunId = stairsRunId,- numberOfRisers = numberOfRisers,- runWidth = runWidth- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 5. Get Stairs Info-- public static object GetStairsInfo(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int stairsId = payload.GetProperty("stairs_id").GetInt32();-- Stairs stairs = doc.GetElement(new ElementId(stairsId)) as Stairs;- if (stairs == null)- {- throw new Exception($"Stairs {stairsId} not found");- }-- try- {- ICollection<ElementId> stairsRuns = stairs.GetStairsRuns();- ICollection<ElementId> stairsLandings = stairs.GetStairsLandings();- ICollection<ElementId> stairsSupports = stairs.GetStairsSupports();-- var runsInfo = new List<object>();- foreach (var runId in stairsRuns)- {- StairsRun run = doc.GetElement(runId) as StairsRun;- if (run != null)- {- runsInfo.Add(new- {- runId = run.Id.IntegerValue,- numberOfRisers = run.ActualRisersNumber,- numberOfTreads = run.ActualTreadsNumber,- height = run.Height,- width = run.ActualRunWidth- });- }- }-- return new- {- success = true,- stairsId = stairsId,- stairsName = stairs.Name,- numberOfRuns = stairsRuns.Count,- numberOfLandings = stairsLandings.Count,- numberOfSupports = stairsSupports.Count,- runs = runsInfo,- baseLevelId = stairs.get_Parameter(BuiltInParameter.STAIRS_BASE_LEVEL_PARAM)?.AsElementId().IntegerValue,- topLevelId = stairs.get_Parameter(BuiltInParameter.STAIRS_TOP_LEVEL_PARAM)?.AsElementId().IntegerValue- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region 6. Get Railing Info-- public static object GetRailingInfo(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int railingId = payload.GetProperty("railing_id").GetInt32();-- Railing railing = doc.GetElement(new ElementId(railingId)) as Railing;- if (railing == null)- {- throw new Exception($"Railing {railingId} not found");- }-- try- {- // Get railing path- CurveLoop path = railing.GetPath();- double pathLength = 0;- int curveCount = 0;-- foreach (Curve curve in path)- {- pathLength += curve.Length;- curveCount++;- }-- // Get host element- ElementId hostId = railing.HostId;- Element hostElement = hostId != ElementId.InvalidElementId ? doc.GetElement(hostId) : null;-- return new- {- success = true,- railingId = railingId,- railingName = railing.Name,- pathLength = pathLength,- pathCurveCount = curveCount,- hostElementId = hostElement?.Id.IntegerValue,- hostElementType = hostElement?.GetType().Name,- levelId = railing.get_Parameter(BuiltInParameter.STAIRS_RAILING_BASE_LEVEL_PARAM)?.AsElementId().IntegerValue- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion- }-}diff --git a/packages/revit-bridge-addin/src/Commands/Specialized/Structural/StructuralCommands.cs b/packages/revit-bridge-addin/src/Commands/Specialized/Structural/StructuralCommands.csdeleted file mode 100644index db31e13..0000000--- a/packages/revit-bridge-addin/src/Commands/Specialized/Structural/StructuralCommands.cs+++ /dev/null@@ -1,524 +0,0 @@-using System;-using System.Collections.Generic;-using System.Linq;-using System.Text.Json;-using Autodesk.Revit.DB;-using Autodesk.Revit.DB.Structure;-using Autodesk.Revit.UI;--namespace RevitBridge.Commands.Specialized.Structural-{- /// <summary>- /// Structural engineering commands for framing, loads, and analysis- /// StructuralType (#344, Score: 159), AnalyticalModel (#372, Score: 155)- /// </summary>- public static class StructuralCommands- {- #region 1. Create Structural Framing-- public static object CreateStructuralFraming(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int familySymbolId = payload.GetProperty("family_symbol_id").GetInt32();- var startPoint = payload.GetProperty("start_point");- var endPoint = payload.GetProperty("end_point");- int levelId = payload.GetProperty("level_id").GetInt32();-- XYZ start = new XYZ(- startPoint.GetProperty("x").GetDouble(),- startPoint.GetProperty("y").GetDouble(),- startPoint.GetProperty("z").GetDouble()- );-- XYZ end = new XYZ(- endPoint.GetProperty("x").GetDouble(),- endPoint.GetProperty("y").GetDouble(),- endPoint.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Create Structural Framing"))- {- trans.Start();-- FamilySymbol symbol = doc.GetElement(new ElementId(familySymbolId)) as FamilySymbol;- if (symbol == null)- {- throw new Exception($"Family symbol {familySymbolId} not found");- }-- if (!symbol.IsActive)- {- symbol.Activate();- }-- Level level = doc.GetElement(new ElementId(levelId)) as Level;- if (level == null)- {- throw new Exception($"Level {levelId} not found");- }-- // Create line- Line line = Line.CreateBound(start, end);-- // Create structural framing instance- FamilyInstance framing = doc.Create.NewFamilyInstance(- line,- symbol,- level,- StructuralType.Beam- );-- trans.Commit();-- return new- {- success = true,- framingId = framing.Id.IntegerValue,- familyName = symbol.FamilyName,- typeName = symbol.Name,- length = line.Length,- structuralType = "Beam"- };- }- }-- #endregion-- #region 2. Create Structural Column-- public static object CreateStructuralColumn(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int familySymbolId = payload.GetProperty("family_symbol_id").GetInt32();- var locationPoint = payload.GetProperty("location");- int baseLevelId = payload.GetProperty("base_level_id").GetInt32();- int topLevelId = payload.GetProperty("top_level_id").GetInt32();-- XYZ location = new XYZ(- locationPoint.GetProperty("x").GetDouble(),- locationPoint.GetProperty("y").GetDouble(),- locationPoint.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Create Structural Column"))- {- trans.Start();-- FamilySymbol symbol = doc.GetElement(new ElementId(familySymbolId)) as FamilySymbol;- if (symbol == null)- {- throw new Exception($"Family symbol {familySymbolId} not found");- }-- if (!symbol.IsActive)- {- symbol.Activate();- }-- Level baseLevel = doc.GetElement(new ElementId(baseLevelId)) as Level;- Level topLevel = doc.GetElement(new ElementId(topLevelId)) as Level;-- if (baseLevel == null || topLevel == null)- {- throw new Exception("Base or top level not found");- }-- // Create structural column- FamilyInstance column = doc.Create.NewFamilyInstance(- location,- symbol,- baseLevel,- StructuralType.Column- );-- // Set top level- Parameter topLevelParam = column.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM);- if (topLevelParam != null)- {- topLevelParam.Set(topLevel.Id);- }-- trans.Commit();-- double height = topLevel.Elevation - baseLevel.Elevation;-- return new- {- success = true,- columnId = column.Id.IntegerValue,- familyName = symbol.FamilyName,- typeName = symbol.Name,- baseLevelId = baseLevelId,- topLevelId = topLevelId,- height = height,- structuralType = "Column"- };- }- }-- #endregion-- #region 3. Create Truss-- public static object CreateTruss(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int familySymbolId = payload.GetProperty("family_symbol_id").GetInt32();- var startPoint = payload.GetProperty("start_point");- var endPoint = payload.GetProperty("end_point");- int levelId = payload.GetProperty("level_id").GetInt32();-- XYZ start = new XYZ(- startPoint.GetProperty("x").GetDouble(),- startPoint.GetProperty("y").GetDouble(),- startPoint.GetProperty("z").GetDouble()- );-- XYZ end = new XYZ(- endPoint.GetProperty("x").GetDouble(),- endPoint.GetProperty("y").GetDouble(),- endPoint.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Create Truss"))- {- trans.Start();-- FamilySymbol symbol = doc.GetElement(new ElementId(familySymbolId)) as FamilySymbol;- if (symbol == null)- {- throw new Exception($"Family symbol {familySymbolId} not found");- }-- if (!symbol.IsActive)- {- symbol.Activate();- }-- Level level = doc.GetElement(new ElementId(levelId)) as Level;- if (level == null)- {- throw new Exception($"Level {levelId} not found");- }-- // Create line for truss- Line line = Line.CreateBound(start, end);-- // Create truss instance- FamilyInstance truss = doc.Create.NewFamilyInstance(- line,- symbol,- level,- StructuralType.Beam- );-- trans.Commit();-- return new- {- success = true,- trussId = truss.Id.IntegerValue,- familyName = symbol.FamilyName,- typeName = symbol.Name,- length = line.Length,- structuralType = "Truss"- };- }- }-- #endregion-- #region 4. Place Rebar-- public static object PlaceRebar(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int hostElementId = payload.GetProperty("host_element_id").GetInt32();- int rebarBarTypeId = payload.GetProperty("rebar_bar_type_id").GetInt32();- int rebarShapeId = payload.GetProperty("rebar_shape_id").GetInt32();-- using (var trans = new Transaction(doc, "Place Rebar"))- {- trans.Start();-- try- {- Element hostElement = doc.GetElement(new ElementId(hostElementId));- RebarBarType barType = doc.GetElement(new ElementId(rebarBarTypeId)) as RebarBarType;- RebarShape shape = doc.GetElement(new ElementId(rebarShapeId)) as RebarShape;-- if (hostElement == null || barType == null || shape == null)- {- throw new Exception("Host element, bar type, or shape not found");- }-- // Get host face- var faces = GetFaces(hostElement);- if (faces == null || faces.Count == 0)- {- throw new Exception("Could not get faces from host element");- }-- Face hostFace = faces[0];-- // Create rebar- XYZ origin = new XYZ(0, 0, 0);- XYZ xVec = new XYZ(1, 0, 0);- XYZ yVec = new XYZ(0, 1, 0);-- Rebar rebar = Rebar.CreateFromRebarShape(- doc,- shape,- barType,- hostElement,- origin,- xVec,- yVec- );-- trans.Commit();-- return new- {- success = true,- rebarId = rebar.Id.IntegerValue,- hostElementId = hostElementId,- barTypeName = barType.Name,- shapeName = shape.Name- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 5. Create Load Case-- public static object CreateLoadCase(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- string caseName = payload.GetProperty("case_name").GetString();- int natureId = payload.GetProperty("nature_id").GetInt32(); // LoadNature enum value-- using (var trans = new Transaction(doc, "Create Load Case"))- {- trans.Start();-- try- {- LoadNature nature = (LoadNature)natureId;- LoadCase loadCase = LoadCase.Create(doc, caseName, nature, 0);-- trans.Commit();-- return new- {- success = true,- loadCaseId = loadCase.Id.IntegerValue,- caseName = loadCase.Name,- nature = nature.ToString()- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 6. Apply Point Load-- public static object ApplyPointLoad(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int hostElementId = payload.GetProperty("host_element_id").GetInt32();- var forceVector = payload.GetProperty("force_vector");- var loadPoint = payload.GetProperty("load_point");-- XYZ force = new XYZ(- forceVector.GetProperty("x").GetDouble(),- forceVector.GetProperty("y").GetDouble(),- forceVector.GetProperty("z").GetDouble()- );-- XYZ point = new XYZ(- loadPoint.GetProperty("x").GetDouble(),- loadPoint.GetProperty("y").GetDouble(),- loadPoint.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Apply Point Load"))- {- trans.Start();-- try- {- Element hostElement = doc.GetElement(new ElementId(hostElementId));- if (hostElement == null)- {- throw new Exception($"Host element {hostElementId} not found");- }-- // Create point load- PointLoad pointLoad = PointLoad.Create(doc, new ElementId(hostElementId), force, point);-- trans.Commit();-- return new- {- success = true,- loadId = pointLoad.Id.IntegerValue,- hostElementId = hostElementId,- force = new { x = force.X, y = force.Y, z = force.Z },- location = new { x = point.X, y = point.Y, z = point.Z }- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 7. Apply Line Load-- public static object ApplyLineLoad(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int hostElementId = payload.GetProperty("host_element_id").GetInt32();- var forceVector1 = payload.GetProperty("force_vector1");- var forceVector2 = payload.GetProperty("force_vector2");-- XYZ force1 = new XYZ(- forceVector1.GetProperty("x").GetDouble(),- forceVector1.GetProperty("y").GetDouble(),- forceVector1.GetProperty("z").GetDouble()- );-- XYZ force2 = new XYZ(- forceVector2.GetProperty("x").GetDouble(),- forceVector2.GetProperty("y").GetDouble(),- forceVector2.GetProperty("z").GetDouble()- );-- using (var trans = new Transaction(doc, "Apply Line Load"))- {- trans.Start();-- try- {- Element hostElement = doc.GetElement(new ElementId(hostElementId));- if (hostElement == null)- {- throw new Exception($"Host element {hostElementId} not found");- }-- // Create line load- LineLoad lineLoad = LineLoad.Create(doc, new ElementId(hostElementId), force1, force2);-- trans.Commit();-- return new- {- success = true,- loadId = lineLoad.Id.IntegerValue,- hostElementId = hostElementId,- force1 = new { x = force1.X, y = force1.Y, z = force1.Z },- force2 = new { x = force2.X, y = force2.Y, z = force2.Z }- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }- }-- #endregion-- #region 8. Get Analytical Model-- public static object GetAnalyticalModel(UIApplication app, JsonElement payload)- {- var doc = app.ActiveUIDocument.Document;- int elementId = payload.GetProperty("element_id").GetInt32();-- Element element = doc.GetElement(new ElementId(elementId));- if (element == null)- {- throw new Exception($"Element {elementId} not found");- }-- try- {- AnalyticalModel analyticalModel = null;-- if (element is FamilyInstance fi)- {- analyticalModel = fi.GetAnalyticalModel();- }- else if (element is Wall wall)- {- analyticalModel = wall.GetAnalyticalModel();- }- else if (element is Floor floor)- {- analyticalModel = floor.GetAnalyticalModel();- }-- if (analyticalModel == null)- {- return new { success = false, error = "Element does not have an analytical model" };- }-- IList<Curve> curves = analyticalModel.GetCurves(AnalyticalCurveType.ActiveCurves);-- return new- {- success = true,- elementId = elementId,- hasAnalyticalModel = true,- curveCount = curves?.Count ?? 0- };- }- catch (Exception ex)- {- return new { success = false, error = ex.Message };- }- }-- #endregion-- #region Helper Methods-- private static List<Face> GetFaces(Element element)- {- var faces = new List<Face>();- Options options = new Options();- GeometryElement geomElem = element.get_Geometry(options);-- foreach (GeometryObject geomObj in geomElem)- {- if (geomObj is Solid solid)- {- foreach (Face face in solid.Faces)- {- faces.Add(face);- }- }- }-- return faces;- }-- #endregion- }-}