├── .gitattributes ├── .gitignore ├── CadDrawGeometry ├── CadDrawGeometry.csproj ├── CreateFromXml.cs ├── Helpers.cs └── Properties │ └── AssemblyInfo.cs ├── README.md ├── RevitExportGeometryToAutocad.sln ├── RevitGeometryExporter ├── ExportGeometryToXml.cs ├── ExportUnits.cs ├── GetGeometryFromObjects.cs ├── Properties │ └── AssemblyInfo.cs └── RevitGeometryExporter.csproj ├── RevitTestCommand ├── Properties │ └── AssemblyInfo.cs ├── RevitTestCommand.csproj ├── TextExportGeometryCommand.cs └── WallSelectionFilter.cs ├── StyleCop.ruleset └── docs ├── Screenshot_1.png └── Screenshot_2.png /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /CadDrawGeometry/CadDrawGeometry.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {ED8C979A-6B2C-47C2-869E-BE0B11C8A533} 8 | Library 9 | Properties 10 | CadDrawGeometry 11 | CadDrawGeometry 12 | v4.5 13 | 512 14 | $(SolutionDir)\StyleCop.ruleset 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 2.0.0 47 | runtime 48 | compile; build; native; contentfiles; analyzers; buildtransitive 49 | 50 | 51 | 1.2.0-beta.556 52 | runtime; build; native; contentfiles; analyzers; buildtransitive 53 | all 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /CadDrawGeometry/CreateFromXml.cs: -------------------------------------------------------------------------------- 1 | namespace CadDrawGeometry 2 | { 3 | using System.IO; 4 | using System.Windows.Forms; 5 | using System.Xml.Linq; 6 | using Autodesk.AutoCAD.DatabaseServices; 7 | using Autodesk.AutoCAD.Geometry; 8 | using Autodesk.AutoCAD.Runtime; 9 | 10 | public class CreateFromXml 11 | { 12 | /// Отрисовка геометрии из одного указанного xml-файла 13 | [CommandMethod("DrawFromOneXml")] 14 | public void Create() 15 | { 16 | OpenFileDialog ofd = new OpenFileDialog(); 17 | if (ofd.ShowDialog() != DialogResult.OK) 18 | return; 19 | DrawGeometryFromFile(ofd.FileName); 20 | } 21 | 22 | /// Отрисовка геометрии из указанной папки в который должны располагаться xml-файлы 23 | [CommandMethod("DrawXmlFromFolder")] 24 | public void CreateFromFolder() 25 | { 26 | FolderBrowserDialog fbd = new FolderBrowserDialog(); 27 | if (fbd.ShowDialog() == DialogResult.OK) 28 | { 29 | var files = Directory.GetFiles(fbd.SelectedPath, "*.xml", SearchOption.TopDirectoryOnly); 30 | foreach (string file in files) 31 | { 32 | DrawGeometryFromFile(file); 33 | } 34 | } 35 | } 36 | 37 | /// Отрисовка геометрии из нескольких указанных xml-файлов 38 | [CommandMethod("DrawFromSeveralXml")] 39 | public void CreateFromSeveralFiles() 40 | { 41 | OpenFileDialog ofd = new OpenFileDialog { Multiselect = true }; 42 | if (ofd.ShowDialog() != DialogResult.OK) 43 | return; 44 | foreach (string fileName in ofd.FileNames) 45 | { 46 | DrawGeometryFromFile(fileName); 47 | } 48 | } 49 | 50 | private void DrawGeometryFromFile(string file) 51 | { 52 | try 53 | { 54 | XElement fileXElement = XElement.Load(file); 55 | var doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; 56 | var db = doc.Database; 57 | using (var tr = doc.TransactionManager.StartTransaction()) 58 | { 59 | BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; 60 | if (bt != null) 61 | { 62 | BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; 63 | 64 | // from root 65 | CreateLines(fileXElement, tr, btr); 66 | CreateRays(fileXElement, tr, btr); 67 | CreateArcs(fileXElement, tr, btr); 68 | CreateCircles(fileXElement, tr, btr); 69 | CreatePoints(fileXElement, tr, btr); 70 | 71 | // all in one 72 | XElement lines = fileXElement.Element("Lines"); 73 | if (lines != null) 74 | { 75 | CreateLines(lines, tr, btr); 76 | CreateRays(lines, tr, btr); 77 | } 78 | 79 | XElement arcs = fileXElement.Element("Arcs"); 80 | if (arcs != null) 81 | { 82 | CreateArcs(arcs, tr, btr); 83 | CreateCircles(arcs, tr, btr); 84 | } 85 | 86 | XElement points = fileXElement.Element("Points"); 87 | if (points != null) 88 | CreatePoints(points, tr, btr); 89 | } 90 | 91 | tr.Commit(); 92 | } 93 | } 94 | catch (System.Exception exception) 95 | { 96 | exception.PrintException(); 97 | } 98 | } 99 | 100 | /// Создание отрезков 101 | private void CreateLines(XElement root, Transaction tr, BlockTableRecord btr) 102 | { 103 | foreach (XElement curveXelement in root.Elements("Line")) 104 | { 105 | XElement startPointXElement = curveXelement.Element("StartPoint"); 106 | Point3d startPoint = startPointXElement.GetAsPoint(); 107 | XElement endPointXElement = curveXelement.Element("EndPoint"); 108 | Point3d endPoint = endPointXElement.GetAsPoint(); 109 | using (Line line = new Line(startPoint, endPoint)) 110 | { 111 | btr.AppendEntity(line); 112 | tr.AddNewlyCreatedDBObject(line, true); 113 | } 114 | } 115 | } 116 | 117 | /// Создание дуг 118 | private void CreateArcs(XElement root, Transaction tr, BlockTableRecord btr) 119 | { 120 | foreach (XElement curveXelement in root.Elements("Arc")) 121 | { 122 | XElement startPointXElement = curveXelement.Element("StartPoint"); 123 | Point3d startPoint = startPointXElement.GetAsPoint(); 124 | XElement endPointXElement = curveXelement.Element("EndPoint"); 125 | Point3d endPoint = endPointXElement.GetAsPoint(); 126 | XElement pointOnArcXElement = curveXelement.Element("PointOnArc"); 127 | Point3d pointOnArc = pointOnArcXElement.GetAsPoint(); 128 | 129 | // create a CircularArc3d 130 | CircularArc3d carc = new CircularArc3d(startPoint, pointOnArc, endPoint); 131 | 132 | // now convert the CircularArc3d to an Arc 133 | Point3d cpt = carc.Center; 134 | Vector3d normal = carc.Normal; 135 | Vector3d refVec = carc.ReferenceVector; 136 | Plane plan = new Plane(cpt, normal); 137 | double ang = refVec.AngleOnPlane(plan); 138 | using (Arc arc = new Arc(cpt, normal, carc.Radius, carc.StartAngle + ang, carc.EndAngle + ang)) 139 | { 140 | btr.AppendEntity(arc); 141 | tr.AddNewlyCreatedDBObject(arc, true); 142 | } 143 | 144 | // dispose CircularArc3d 145 | carc.Dispose(); 146 | } 147 | } 148 | 149 | /// Создание окружностей 150 | private void CreateCircles(XElement root, Transaction tr, BlockTableRecord btr) 151 | { 152 | foreach (XElement curveXelement in root.Elements("Circle")) 153 | { 154 | XElement centerPointXElement = curveXelement.Element("CenterPoint"); 155 | Point3d centerPoint = centerPointXElement.GetAsPoint(); 156 | XElement vectorNormalXElement = curveXelement.Element("VectorNormal"); 157 | Vector3d vectorNormal = vectorNormalXElement.GetAsPoint().GetAsVector(); 158 | 159 | if (Helpers.TryParseDouble(curveXelement.Element("Radius")?.Value, out var d)) 160 | { 161 | using (Circle circle = new Circle(centerPoint, vectorNormal, d)) 162 | { 163 | btr.AppendEntity(circle); 164 | tr.AddNewlyCreatedDBObject(circle, true); 165 | } 166 | } 167 | } 168 | } 169 | 170 | /// Создание лучей 171 | private void CreateRays(XElement root, Transaction tr, BlockTableRecord btr) 172 | { 173 | foreach (XElement rayXElement in root.Elements("Ray")) 174 | { 175 | XElement originXElement = rayXElement.Element("Origin"); 176 | Point3d originPoint = originXElement.GetAsPoint(); 177 | XElement directionXElement = rayXElement.Element("Direction"); 178 | Vector3d direction = directionXElement.GetAsPoint().GetAsVector(); 179 | 180 | using (Ray ray = new Ray()) 181 | { 182 | ray.BasePoint = originPoint; 183 | ray.UnitDir = direction; 184 | btr.AppendEntity(ray); 185 | tr.AddNewlyCreatedDBObject(ray, true); 186 | } 187 | } 188 | } 189 | 190 | /// Создание точек 191 | private void CreatePoints(XElement root, Transaction tr, BlockTableRecord btr) 192 | { 193 | foreach (var xElement in root.Elements("Point")) 194 | { 195 | Point3d startPoint = xElement.GetAsPoint(); 196 | DBPoint dbPoint = new DBPoint(startPoint); 197 | btr.AppendEntity(dbPoint); 198 | tr.AddNewlyCreatedDBObject(dbPoint, true); 199 | } 200 | } 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /CadDrawGeometry/Helpers.cs: -------------------------------------------------------------------------------- 1 | namespace CadDrawGeometry 2 | { 3 | using System; 4 | using System.Globalization; 5 | using System.Xml.Linq; 6 | using Autodesk.AutoCAD.Geometry; 7 | 8 | /// 9 | /// Helpers 10 | /// 11 | public static class Helpers 12 | { 13 | /// 14 | /// Get from attributes of 15 | /// 16 | /// Instance of 17 | public static Point3d GetAsPoint(this XElement xEl) 18 | { 19 | if (xEl != null) 20 | { 21 | if (TryParseDouble(xEl.Attribute("X")?.Value, out var x) && 22 | TryParseDouble(xEl.Attribute("Y")?.Value, out var y) && 23 | TryParseDouble(xEl.Attribute("Z")?.Value, out var z)) 24 | { 25 | return new Point3d(x, y, z); 26 | } 27 | } 28 | 29 | return Point3d.Origin; 30 | } 31 | 32 | /// 33 | /// Try parse double extension 34 | /// 35 | /// String 36 | /// Out double value 37 | public static bool TryParseDouble(string value, out double d) 38 | { 39 | if (!string.IsNullOrEmpty(value)) 40 | return double.TryParse(value.Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out d); 41 | 42 | d = double.NaN; 43 | return false; 44 | } 45 | 46 | /// 47 | /// Print to AutoCAD command line 48 | /// 49 | /// Instance of 50 | public static void PrintException(this Exception exception) 51 | { 52 | Autodesk.AutoCAD.ApplicationServices.Core.Application 53 | .DocumentManager.MdiActiveDocument.Editor.WriteMessage($"\nError: {exception}"); 54 | 55 | if (exception.InnerException != null) 56 | PrintException(exception.InnerException); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /CadDrawGeometry/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // Общие сведения об этой сборке предоставляются следующим набором 6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, 7 | // связанные со сборкой. 8 | [assembly: AssemblyTitle("CadDrawGeometry")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CadDrawGeometry")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми 18 | // для компонентов COM. Если необходимо обратиться к типу в этой сборке через 19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа. 20 | [assembly: ComVisible(false)] 21 | 22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM 23 | [assembly: Guid("ed8c979a-6b2c-47c2-869e-be0b11c8a533")] 24 | 25 | // Сведения о версии сборки состоят из следующих четырех значений: 26 | // 27 | // Основной номер версии 28 | // Дополнительный номер версии 29 | // Номер сборки 30 | // Редакция 31 | // 32 | // Можно задать все значения или принять номер сборки и номер редакции по умолчанию. 33 | // используя "*", как показано ниже: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RevitExportGeometryToAutocad 2 | Вспомогательные библиотеки для отрисовки геометрии из Revit в AutoCAD в виде простых объектов (отрезок, дуга, точка) посредством экспорта в xml 3 | ## Описание 4 | Библиотеки пригодятся при разработке плагинов, связанных с геометрией, для удобного визуального восприятия результатов. На мой взгляд просматривать результат в AutoCAD намного удобнее. 5 | 6 | В данном проекте присутствует две библиотеки (одна для Revit, вторая для AutoCAD) и демо-проект для Revit. 7 | ## Версионность 8 | Проект для AutoCAD собран с использованием библиотек от AutoCAD 2013. Будет работать со всеми последующими версиями AutoCAD 9 | 10 | Проект Revit собран с использованием библиотек от Revit 2015. Должен работать со всеми последующими версиями (с 2015-2018 точно работает) 11 | ## Использование 12 | Решение также содержит демо-проект для Revit. Описание использования на примере этого проекта: 13 | 14 | **В Revit** 15 | * Подключить к проекту ссылку на библиотеку **RevitGeometryExporter.dll**. 16 | * Перед использованием методов экспорта нужно указать папку для экспорта xml 17 | ```csharp 18 | // setup export folder 19 | ExportGeometryToXml.FolderName = @"C:\Temp"; 20 | ``` 21 | По умолчанию в библиотеке прописан путь *C:\Temp\RevitExportXml*. В случае отсутствия директории она будет создана. 22 | * Указать единицы для выгрузки (футы или миллиметры) 23 | ``` csharp 24 | // setup export units 25 | ExportGeometryToXml.ExportUnits = ExportUnits.Mm; 26 | ``` 27 | По умолчанию единицы выгрузки установлены в футы. 28 | * Вызвать один или несколько методов экспорта геометрии. 29 | Например: 30 | ```csharp 31 | List wallsToExport = new List(); 32 | foreach (Reference reference in selectionResult) 33 | { 34 | Wall wall = (Wall)doc.GetElement(reference); 35 | wallsToExport.Add(wall); 36 | } 37 | ExportGeometryToXml.ExportWallsByFaces(wallsToExport, "walls"); 38 | ``` 39 | Или 40 | ```csharp 41 | List familyInstances = new List(); 42 | foreach (Reference reference in selectionResult) 43 | { 44 | Element el = doc.GetElement(reference); 45 | if(el is FamilyInstance familyInstance) 46 | familyInstances.Add(familyInstance); 47 | } 48 | ExportGeometryToXml.ExportFamilyInstancesByFaces(familyInstances, "families", false); 49 | ``` 50 | 51 | **В AutoCAD** 52 | * С помощью команды **NETLOAD** загрузить библиотеку **CadDrawGeometry.dll**. 53 | * Использовать одну из двух доступных команд: 54 | 55 | **DrawFromOneXml** – отрисовка геометрии из одного указанного xml-файла 56 | 57 | **DrawFromSeveralXml** – отрисовка геометрии из нескольких указанных xml-файлов. По аналогии с DrawFromOneXml, только в окне выбор файлов включена возможность мультивыбора (через Shift или Ctrl) 58 | 59 | **DrawXmlFromFolder** - отрисовка геометрии из указанной папки в который должны располагаться xml-файлы 60 | 61 | ## Пример 62 | Элементы в Revit: 63 | 64 | Screenshot_1 65 | 66 | Результат экспорта и отрисовки геометрии в AutoCAD: 67 | 68 | Screenshot_2 69 | -------------------------------------------------------------------------------- /RevitExportGeometryToAutocad.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27004.2002 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CadDrawGeometry", "CadDrawGeometry\CadDrawGeometry.csproj", "{ED8C979A-6B2C-47C2-869E-BE0B11C8A533}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RevitGeometryExporter", "RevitGeometryExporter\RevitGeometryExporter.csproj", "{D61C1834-9A91-483B-BFB3-96A06E9A9F3F}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RevitTestCommand", "RevitTestCommand\RevitTestCommand.csproj", "{3D0ABFC2-7933-4D74-A674-674ABF9A59DF}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {ED8C979A-6B2C-47C2-869E-BE0B11C8A533}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {ED8C979A-6B2C-47C2-869E-BE0B11C8A533}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {ED8C979A-6B2C-47C2-869E-BE0B11C8A533}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {ED8C979A-6B2C-47C2-869E-BE0B11C8A533}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {D61C1834-9A91-483B-BFB3-96A06E9A9F3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {D61C1834-9A91-483B-BFB3-96A06E9A9F3F}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {D61C1834-9A91-483B-BFB3-96A06E9A9F3F}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {D61C1834-9A91-483B-BFB3-96A06E9A9F3F}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {3D0ABFC2-7933-4D74-A674-674ABF9A59DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {3D0ABFC2-7933-4D74-A674-674ABF9A59DF}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {3D0ABFC2-7933-4D74-A674-674ABF9A59DF}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {3D0ABFC2-7933-4D74-A674-674ABF9A59DF}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {41FDCA6A-B1BC-4683-A7EB-36573AC79989} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /RevitGeometryExporter/ExportGeometryToXml.cs: -------------------------------------------------------------------------------- 1 | namespace RevitGeometryExporter 2 | { 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Xml.Linq; 9 | using Autodesk.Revit.DB; 10 | 11 | /// 12 | /// Экспорт геометрии в xml для последующей отрисовки в AutoCAD 13 | /// 14 | public static class ExportGeometryToXml 15 | { 16 | /// 17 | /// Full path to the folder where xml files will be saved. The default path is "C:\Temp\RevitExportXml" 18 | /// 19 | public static string FolderName = @"C:\Temp\RevitExportXml"; 20 | 21 | /// 22 | /// Output units 23 | /// 24 | public static ExportUnits ExportUnits = ExportUnits.Ft; 25 | 26 | /// 27 | /// Clear (remove all files) if folder exists 28 | /// 29 | public static void ClearFolder() 30 | { 31 | if (Directory.Exists(FolderName)) 32 | { 33 | foreach (var file in Directory.GetFiles(FolderName)) 34 | { 35 | File.Delete(file); 36 | } 37 | } 38 | } 39 | 40 | /// 41 | /// Initialize 42 | /// 43 | /// Full path to the folder where xml files will be saved. The default path is "C:\Temp\RevitExportXml" 44 | [Conditional("DEBUG")] 45 | public static void Init(string folderName) 46 | { 47 | FolderName = folderName; 48 | } 49 | 50 | /// 51 | /// Initialize 52 | /// 53 | /// Full path to the folder where xml files will be saved. The default path is "C:\Temp\RevitExportXml" 54 | /// Output units 55 | [Conditional("DEBUG")] 56 | public static void Init(string folderName, ExportUnits exportUnits) 57 | { 58 | FolderName = folderName; 59 | ExportUnits = exportUnits; 60 | } 61 | 62 | /// 63 | /// Initialize 64 | /// 65 | /// Full path to the folder where xml files will be saved. The default path is "C:\Temp\RevitExportXml" 66 | /// Output units 67 | /// Clear (remove all files) if folder exists 68 | [Conditional("DEBUG")] 69 | public static void Init(string folderName, ExportUnits exportUnits, bool clearFolder) 70 | { 71 | FolderName = folderName; 72 | ExportUnits = exportUnits; 73 | if (clearFolder) 74 | ClearFolder(); 75 | } 76 | 77 | #region Elements 78 | 79 | [Conditional("DEBUG")] 80 | public static void ExportWallsByFaces(IEnumerable walls, string header) 81 | { 82 | Options options = new Options(); 83 | List curves = new List(); 84 | foreach (Wall wall in walls) 85 | { 86 | IEnumerable geometry = wall.get_Geometry(options); 87 | foreach (GeometryObject geometryObject in geometry) 88 | { 89 | if (geometryObject is Solid solid) 90 | { 91 | foreach (Face face in solid.Faces) 92 | { 93 | foreach (EdgeArray edgeArray in face.EdgeLoops) 94 | { 95 | foreach (Edge edge in edgeArray) 96 | curves.Add(edge.AsCurve()); 97 | } 98 | } 99 | } 100 | } 101 | } 102 | 103 | ExportCurves(curves, header); 104 | } 105 | 106 | [Conditional("DEBUG")] 107 | public static void ExportWallByFaces(Wall wall, string header) 108 | { 109 | Options options = new Options(); 110 | List curves = new List(); 111 | 112 | IEnumerable geometry = wall.get_Geometry(options); 113 | foreach (GeometryObject geometryObject in geometry) 114 | { 115 | if (geometryObject is Solid solid) 116 | { 117 | foreach (Face face in solid.Faces) 118 | { 119 | foreach (EdgeArray edgeArray in face.EdgeLoops) 120 | { 121 | foreach (Edge edge in edgeArray) 122 | curves.Add(edge.AsCurve()); 123 | } 124 | } 125 | } 126 | } 127 | 128 | ExportCurves(curves, header); 129 | } 130 | 131 | [Conditional("DEBUG")] 132 | public static void ExportFamilyInstancesByFaces( 133 | IEnumerable families, string header, bool includeNonVisibleObjects) 134 | { 135 | Options options = new Options 136 | { 137 | IncludeNonVisibleObjects = includeNonVisibleObjects 138 | }; 139 | List curves = new List(); 140 | foreach (FamilyInstance familyInstance in families) 141 | { 142 | curves.AddRange(GetCurvesFromFamilyGeometry(familyInstance, options)); 143 | } 144 | 145 | ExportCurves(curves, header); 146 | } 147 | 148 | [Conditional("DEBUG")] 149 | public static void ExportFamilyInstanceByFaces( 150 | FamilyInstance familyInstance, string header, bool includeNonVisibleObjects) 151 | { 152 | Options options = new Options 153 | { 154 | IncludeNonVisibleObjects = includeNonVisibleObjects 155 | }; 156 | List curves = GetCurvesFromFamilyGeometry(familyInstance, options).ToList(); 157 | 158 | ExportCurves(curves, header); 159 | } 160 | 161 | #endregion 162 | 163 | #region Geometry objects 164 | 165 | [Conditional("DEBUG")] 166 | public static void ExportSolidsByFaces(IEnumerable solids, string header) 167 | { 168 | CreateFolder(); 169 | List faces = new List(); 170 | foreach (Solid solid in solids) 171 | { 172 | foreach (Face solidFace in solid.Faces) 173 | { 174 | faces.Add(solidFace); 175 | } 176 | } 177 | 178 | if (faces.Any()) 179 | ExportFaces(faces, header); 180 | } 181 | 182 | [Conditional("DEBUG")] 183 | public static void ExportSolid(Solid solid, string header) 184 | { 185 | CreateFolder(); 186 | List faces = new List(); 187 | 188 | foreach (Face solidFace in solid.Faces) 189 | { 190 | faces.Add(solidFace); 191 | } 192 | 193 | if (faces.Any()) 194 | ExportFaces(faces, header); 195 | } 196 | 197 | [Conditional("DEBUG")] 198 | public static void ExportFaces(IEnumerable faces, string header) 199 | { 200 | CreateFolder(); 201 | List wallCurves = new List(); 202 | 203 | foreach (Face face in faces) 204 | { 205 | EdgeArrayArray edgeArrayArray = face.EdgeLoops; 206 | foreach (EdgeArray edgeArray in edgeArrayArray) 207 | { 208 | foreach (Edge edge in edgeArray) 209 | { 210 | wallCurves.Add(edge.AsCurve()); 211 | } 212 | } 213 | } 214 | 215 | ExportCurves(wallCurves, header); 216 | } 217 | 218 | [Conditional("DEBUG")] 219 | public static void ExportFace(Face face, string header) 220 | { 221 | CreateFolder(); 222 | List wallCurves = new List(); 223 | 224 | EdgeArrayArray edgeArrayArray = face.EdgeLoops; 225 | foreach (EdgeArray edgeArray in edgeArrayArray) 226 | { 227 | foreach (Edge edge in edgeArray) 228 | { 229 | wallCurves.Add(edge.AsCurve()); 230 | } 231 | } 232 | 233 | ExportCurves(wallCurves, header); 234 | } 235 | 236 | [Conditional("DEBUG")] 237 | public static void ExportFaces(IEnumerable planarFaces, string header) 238 | { 239 | CreateFolder(); 240 | List wallCurves = new List(); 241 | 242 | foreach (PlanarFace planarFace in planarFaces) 243 | { 244 | EdgeArrayArray edgeArrayArray = planarFace.EdgeLoops; 245 | foreach (EdgeArray edgeArray in edgeArrayArray) 246 | { 247 | foreach (Edge edge in edgeArray) 248 | { 249 | wallCurves.Add(edge.AsCurve()); 250 | } 251 | } 252 | } 253 | 254 | ExportCurves(wallCurves, header); 255 | } 256 | 257 | [Conditional("DEBUG")] 258 | public static void ExportCurves(IEnumerable curves, string header) 259 | { 260 | CreateFolder(); 261 | XElement root = new XElement("Curves"); 262 | XElement linesRootXElement = new XElement("Lines"); 263 | XElement arcsRootXElement = new XElement("Arcs"); 264 | foreach (Curve curve in curves) 265 | { 266 | Line line = curve as Line; 267 | if (line != null) 268 | { 269 | var lineXel = GetGeometryFromObjects.GetXElementFromLine(line); 270 | if (lineXel != null) 271 | linesRootXElement.Add(lineXel); 272 | } 273 | 274 | Arc arc = curve as Arc; 275 | if (arc != null) 276 | { 277 | var arcXel = GetGeometryFromObjects.GetXElementFromArc(arc); 278 | if (arcXel != null) 279 | arcsRootXElement.Add(arcXel); 280 | } 281 | } 282 | 283 | if (linesRootXElement.HasElements) 284 | root.Add(linesRootXElement); 285 | if (arcsRootXElement.HasElements) 286 | root.Add(arcsRootXElement); 287 | 288 | root.Save(Path.Combine(FolderName, GetFileName(header))); 289 | } 290 | 291 | [Conditional("DEBUG")] 292 | public static void ExportCurve(Curve curve, string header) 293 | { 294 | CreateFolder(); 295 | XElement root = new XElement("Curves"); 296 | XElement linesRootXElement = new XElement("Lines"); 297 | XElement arcsRootXElement = new XElement("Arcs"); 298 | Line line = curve as Line; 299 | if (line != null) 300 | { 301 | var lineXel = GetGeometryFromObjects.GetXElementFromLine(line); 302 | if (lineXel != null) 303 | linesRootXElement.Add(lineXel); 304 | } 305 | 306 | Arc arc = curve as Arc; 307 | if (arc != null) 308 | { 309 | var arcXel = GetGeometryFromObjects.GetXElementFromArc(arc); 310 | if (arcXel != null) 311 | arcsRootXElement.Add(arcXel); 312 | } 313 | 314 | if (linesRootXElement.HasElements) 315 | root.Add(linesRootXElement); 316 | if (arcsRootXElement.HasElements) 317 | root.Add(arcsRootXElement); 318 | 319 | root.Save(Path.Combine(FolderName, GetFileName(header))); 320 | } 321 | 322 | [Conditional("DEBUG")] 323 | public static void ExportEdges(IEnumerable edges, string header) 324 | { 325 | CreateFolder(); 326 | List curves = new List(); 327 | foreach (Edge edge in edges) 328 | { 329 | curves.Add(edge.AsCurve()); 330 | } 331 | 332 | ExportCurves(curves, header); 333 | } 334 | 335 | [Conditional("DEBUG")] 336 | public static void ExportLines(IEnumerable lines, string header) 337 | { 338 | CreateFolder(); 339 | XElement rootXElement = new XElement("Lines"); 340 | foreach (Line line in lines) 341 | { 342 | rootXElement.Add(GetGeometryFromObjects.GetXElementFromLine(line)); 343 | } 344 | 345 | rootXElement.Save(Path.Combine(FolderName, GetFileName(header))); 346 | } 347 | 348 | [Conditional("DEBUG")] 349 | public static void ExportLine(Line line, string header) 350 | { 351 | CreateFolder(); 352 | XElement rootXElement = new XElement("Lines"); 353 | rootXElement.Add(GetGeometryFromObjects.GetXElementFromLine(line)); 354 | rootXElement.Save(Path.Combine(FolderName, GetFileName(header))); 355 | } 356 | 357 | [Conditional("DEBUG")] 358 | public static void ExportArcs(IEnumerable arcs, string header) 359 | { 360 | CreateFolder(); 361 | XElement rootXElement = new XElement("Arcs"); 362 | foreach (Arc arc in arcs) 363 | { 364 | rootXElement.Add(GetGeometryFromObjects.GetXElementFromArc(arc)); 365 | } 366 | 367 | rootXElement.Save(Path.Combine(FolderName, GetFileName(header))); 368 | } 369 | 370 | [Conditional("DEBUG")] 371 | public static void ExportPoints(IEnumerable points, string header) 372 | { 373 | CreateFolder(); 374 | XElement rootXElement = new XElement("Points"); 375 | foreach (XYZ point in points) 376 | { 377 | rootXElement.Add(GetGeometryFromObjects.GetXElementFromPoint(point)); 378 | } 379 | 380 | rootXElement.Save(Path.Combine(FolderName, GetFileName(header))); 381 | } 382 | 383 | [Conditional("DEBUG")] 384 | public static void ExportPoint(XYZ point, string header) 385 | { 386 | CreateFolder(); 387 | XElement rootXElement = new XElement("Points"); 388 | rootXElement.Add(GetGeometryFromObjects.GetXElementFromPoint(point)); 389 | rootXElement.Save(Path.Combine(FolderName, GetFileName(header))); 390 | } 391 | 392 | #endregion 393 | 394 | #region Helpers 395 | 396 | private static void CreateFolder() => Directory.CreateDirectory(FolderName); 397 | 398 | private static string GetFileName(string header) 399 | { 400 | header = RemoveInvalidChars(header); 401 | return $"{DateTime.Now.Minute}_{DateTime.Now.Second}_{DateTime.Now.Millisecond}_{header}.xml"; 402 | } 403 | 404 | private static IEnumerable GetCurvesFromFamilyGeometry(FamilyInstance familyInstance, Options options) 405 | { 406 | // Если брать сразу трансформированную геометрию с параметром Transform.Identity 407 | // то отпадает необходимость получения GeometryInstance 408 | var geometryElement = familyInstance.get_Geometry(options)?.GetTransformed(Transform.Identity); 409 | 410 | if (geometryElement != null) 411 | { 412 | foreach (GeometryObject geometryObject in geometryElement) 413 | { 414 | if (geometryObject is Solid solid) 415 | { 416 | foreach (Face solidFace in solid.Faces) 417 | { 418 | foreach (EdgeArray edgeArray in solidFace.EdgeLoops) 419 | { 420 | foreach (Edge edge in edgeArray) 421 | yield return edge.AsCurve(); 422 | } 423 | } 424 | } 425 | 426 | if (geometryObject is Face face) 427 | { 428 | foreach (EdgeArray edgeArray in face.EdgeLoops) 429 | { 430 | foreach (Edge edge in edgeArray) 431 | yield return edge.AsCurve(); 432 | } 433 | } 434 | } 435 | } 436 | } 437 | 438 | private static string RemoveInvalidChars(string filename) 439 | { 440 | return string.Concat(filename.Split(Path.GetInvalidFileNameChars())); 441 | } 442 | 443 | #endregion 444 | } 445 | } 446 | -------------------------------------------------------------------------------- /RevitGeometryExporter/ExportUnits.cs: -------------------------------------------------------------------------------- 1 | namespace RevitGeometryExporter 2 | { 3 | /// 4 | /// Единицы вывода 5 | /// 6 | public enum ExportUnits 7 | { 8 | /// 9 | /// Футы 10 | /// 11 | Ft = 0, 12 | 13 | /// 14 | /// Миллиметры 15 | /// 16 | Mm = 1 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /RevitGeometryExporter/GetGeometryFromObjects.cs: -------------------------------------------------------------------------------- 1 | namespace RevitGeometryExporter 2 | { 3 | using System; 4 | using System.Xml.Linq; 5 | using Autodesk.Revit.DB; 6 | 7 | internal static class GetGeometryFromObjects 8 | { 9 | internal static XElement GetXElementFromLine(Line line) 10 | { 11 | try 12 | { 13 | if (line.IsBound) 14 | { 15 | XElement lineXElement = new XElement("Line"); 16 | XElement startPointXElement = new XElement("StartPoint"); 17 | startPointXElement.SetAttributeValue("X", line.GetEndPoint(0).X.ConvertToExportUnits()); 18 | startPointXElement.SetAttributeValue("Y", line.GetEndPoint(0).Y.ConvertToExportUnits()); 19 | startPointXElement.SetAttributeValue("Z", line.GetEndPoint(0).Z.ConvertToExportUnits()); 20 | lineXElement.Add(startPointXElement); 21 | XElement endPointXElement = new XElement("EndPoint"); 22 | endPointXElement.SetAttributeValue("X", line.GetEndPoint(1).X.ConvertToExportUnits()); 23 | endPointXElement.SetAttributeValue("Y", line.GetEndPoint(1).Y.ConvertToExportUnits()); 24 | endPointXElement.SetAttributeValue("Z", line.GetEndPoint(1).Z.ConvertToExportUnits()); 25 | lineXElement.Add(endPointXElement); 26 | return lineXElement; 27 | } 28 | else 29 | { 30 | XElement rayXElement = new XElement("Ray"); 31 | XElement originPointXElement = new XElement("Origin"); 32 | originPointXElement.SetAttributeValue("X", line.Origin.X.ConvertToExportUnits()); 33 | originPointXElement.SetAttributeValue("Y", line.Origin.Y.ConvertToExportUnits()); 34 | originPointXElement.SetAttributeValue("Z", line.Origin.Z.ConvertToExportUnits()); 35 | rayXElement.Add(originPointXElement); 36 | XElement directionXElement = new XElement("Direction"); 37 | directionXElement.SetAttributeValue("X", line.Direction.X.ConvertToExportUnits()); 38 | directionXElement.SetAttributeValue("Y", line.Direction.Y.ConvertToExportUnits()); 39 | directionXElement.SetAttributeValue("Z", line.Direction.Z.ConvertToExportUnits()); 40 | rayXElement.Add(directionXElement); 41 | return rayXElement; 42 | } 43 | } 44 | catch (Exception) 45 | { 46 | return null; 47 | } 48 | } 49 | 50 | internal static XElement GetXElementFromArc(Arc arc) 51 | { 52 | try 53 | { 54 | if (arc.IsBound) //// arc! 55 | { 56 | XElement arcXElement = new XElement("Arc"); 57 | XElement element = new XElement("StartPoint"); 58 | element.SetAttributeValue("X", arc.GetEndPoint(0).X.ConvertToExportUnits()); 59 | element.SetAttributeValue("Y", arc.GetEndPoint(0).Y.ConvertToExportUnits()); 60 | element.SetAttributeValue("Z", arc.GetEndPoint(0).Z.ConvertToExportUnits()); 61 | arcXElement.Add(element); 62 | element = new XElement("EndPoint"); 63 | element.SetAttributeValue("X", arc.GetEndPoint(1).X.ConvertToExportUnits()); 64 | element.SetAttributeValue("Y", arc.GetEndPoint(1).Y.ConvertToExportUnits()); 65 | element.SetAttributeValue("Z", arc.GetEndPoint(1).Z.ConvertToExportUnits()); 66 | arcXElement.Add(element); 67 | element = new XElement("PointOnArc"); 68 | element.SetAttributeValue("X", arc.Tessellate()[1].X.ConvertToExportUnits()); 69 | element.SetAttributeValue("Y", arc.Tessellate()[1].Y.ConvertToExportUnits()); 70 | element.SetAttributeValue("Z", arc.Tessellate()[1].Z.ConvertToExportUnits()); 71 | arcXElement.Add(element); 72 | return arcXElement; 73 | } 74 | else //// circle! 75 | { 76 | XElement circleXElement = new XElement("Circle"); 77 | XElement centerPoint = new XElement("CenterPoint"); 78 | centerPoint.SetAttributeValue("X", arc.Center.X.ConvertToExportUnits()); 79 | centerPoint.SetAttributeValue("Y", arc.Center.Y.ConvertToExportUnits()); 80 | centerPoint.SetAttributeValue("Z", arc.Center.Z.ConvertToExportUnits()); 81 | circleXElement.Add(centerPoint); 82 | XElement vector = new XElement("VectorNormal"); 83 | vector.SetAttributeValue("X", arc.Normal.X.ConvertToExportUnits()); 84 | vector.SetAttributeValue("Y", arc.Normal.Y.ConvertToExportUnits()); 85 | vector.SetAttributeValue("Z", arc.Normal.Z.ConvertToExportUnits()); 86 | circleXElement.Add(vector); 87 | 88 | circleXElement.SetElementValue("Radius", arc.Radius); 89 | return circleXElement; 90 | } 91 | } 92 | catch (Exception) 93 | { 94 | return null; 95 | } 96 | } 97 | 98 | internal static XElement GetXElementFromPoint(XYZ point) 99 | { 100 | XElement pointXElement = new XElement("Point"); 101 | pointXElement.SetAttributeValue("X", point.X.ConvertToExportUnits()); 102 | pointXElement.SetAttributeValue("Y", point.Y.ConvertToExportUnits()); 103 | pointXElement.SetAttributeValue("Z", point.Z.ConvertToExportUnits()); 104 | return pointXElement; 105 | } 106 | 107 | private static double ConvertToExportUnits(this double valueInFt) 108 | { 109 | // UnitUtils.ConvertFromInternalUnits() is not used here so that there is no error in Revit 2021 and higher 110 | if (ExportGeometryToXml.ExportUnits == ExportUnits.Mm) 111 | return valueInFt * 304.8; 112 | 113 | return valueInFt; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /RevitGeometryExporter/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("RevitGeometryExporter")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("RevitGeometryExporter")] 10 | [assembly: AssemblyCopyright("Copyright © 2018")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | [assembly: ComVisible(false)] 14 | [assembly: Guid("d61c1834-9a91-483b-bfb3-96a06e9a9f3f")] 15 | [assembly: AssemblyVersion("1.2.0.0")] 16 | [assembly: AssemblyFileVersion("1.2.0.0")] 17 | -------------------------------------------------------------------------------- /RevitGeometryExporter/RevitGeometryExporter.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {D61C1834-9A91-483B-BFB3-96A06E9A9F3F} 8 | Library 9 | Properties 10 | RevitGeometryExporter 11 | RevitGeometryExporter 12 | v4.5 13 | 512 14 | $(SolutionDir)\StyleCop.ruleset 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 1.0.0 47 | runtime 48 | 49 | 50 | 1.2.0-beta.556 51 | runtime; build; native; contentfiles; analyzers; buildtransitive 52 | all 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /RevitTestCommand/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // Общие сведения об этой сборке предоставляются следующим набором 6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, 7 | // связанные со сборкой. 8 | [assembly: AssemblyTitle("RevitTestCommand")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("RevitTestCommand")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми 18 | // для компонентов COM. Если необходимо обратиться к типу в этой сборке через 19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа. 20 | [assembly: ComVisible(false)] 21 | 22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM 23 | [assembly: Guid("3d0abfc2-7933-4d74-a674-674abf9a59df")] 24 | 25 | // Сведения о версии сборки состоят из следующих четырех значений: 26 | // 27 | // Основной номер версии 28 | // Дополнительный номер версии 29 | // Номер сборки 30 | // Редакция 31 | // 32 | // Можно задать все значения или принять номер сборки и номер редакции по умолчанию. 33 | // используя "*", как показано ниже: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /RevitTestCommand/RevitTestCommand.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {3D0ABFC2-7933-4D74-A674-674ABF9A59DF} 8 | Library 9 | Properties 10 | RevitTestCommand 11 | RevitTestCommand 12 | v4.5 13 | 512 14 | $(SolutionDir)\StyleCop.ruleset 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | {d61c1834-9a91-483b-bfb3-96a06e9a9f3f} 44 | RevitGeometryExporter 45 | 46 | 47 | 48 | 49 | 1.0.0 50 | runtime 51 | 52 | 53 | 1.2.0-beta.556 54 | runtime; build; native; contentfiles; analyzers; buildtransitive 55 | all 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /RevitTestCommand/TextExportGeometryCommand.cs: -------------------------------------------------------------------------------- 1 | namespace RevitTestCommand 2 | { 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using Autodesk.Revit.Attributes; 7 | using Autodesk.Revit.DB; 8 | using Autodesk.Revit.UI; 9 | using Autodesk.Revit.UI.Selection; 10 | using RevitGeometryExporter; 11 | 12 | [Transaction(TransactionMode.Manual)] 13 | [Regeneration(RegenerationOption.Manual)] 14 | public class TextExportGeometryCommand : IExternalCommand 15 | { 16 | public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) 17 | { 18 | Document doc = commandData.Application.ActiveUIDocument.Document; 19 | Selection selection = commandData.Application.ActiveUIDocument.Selection; 20 | try 21 | { 22 | // setup export folder 23 | ExportGeometryToXml.FolderName = @"C:\Temp"; 24 | 25 | // select walls 26 | IList selectionResult = selection.PickObjects(ObjectType.Element, new WallSelectionFilter(), 27 | "Select walls:"); 28 | if (selectionResult.Any()) 29 | { 30 | List wallsToExport = new List(); 31 | foreach (Reference reference in selectionResult) 32 | { 33 | Wall wall = (Wall)doc.GetElement(reference); 34 | wallsToExport.Add(wall); 35 | } 36 | 37 | ExportGeometryToXml.ExportWallsByFaces(wallsToExport, "walls"); 38 | } 39 | 40 | // families 41 | selectionResult = selection.PickObjects(ObjectType.Element, "Select families:"); 42 | if (selectionResult.Any()) 43 | { 44 | List familyInstances = new List(); 45 | foreach (Reference reference in selectionResult) 46 | { 47 | Element el = doc.GetElement(reference); 48 | if (el is FamilyInstance familyInstance) 49 | familyInstances.Add(familyInstance); 50 | } 51 | 52 | ExportGeometryToXml.ExportFamilyInstancesByFaces(familyInstances, "families", false); 53 | } 54 | } 55 | catch (OperationCanceledException) 56 | { 57 | return Result.Cancelled; 58 | } 59 | catch (Exception exception) 60 | { 61 | message += exception.Message; 62 | return Result.Failed; 63 | } 64 | 65 | return Result.Succeeded; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /RevitTestCommand/WallSelectionFilter.cs: -------------------------------------------------------------------------------- 1 | namespace RevitTestCommand 2 | { 3 | using System; 4 | using Autodesk.Revit.DB; 5 | using Autodesk.Revit.UI.Selection; 6 | 7 | /// 8 | internal class WallSelectionFilter : ISelectionFilter 9 | { 10 | /// 11 | public bool AllowElement(Element elem) 12 | { 13 | return elem is Wall; 14 | } 15 | 16 | /// 17 | public bool AllowReference(Reference reference, XYZ position) 18 | { 19 | throw new NotImplementedException(); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /StyleCop.ruleset: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /docs/Screenshot_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pekshev/RevitExportGeometryToAutocad/f9ac4181be1a95076b89c9c91fa13d06f264a877/docs/Screenshot_1.png -------------------------------------------------------------------------------- /docs/Screenshot_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Pekshev/RevitExportGeometryToAutocad/f9ac4181be1a95076b89c9c91fa13d06f264a877/docs/Screenshot_2.png --------------------------------------------------------------------------------