using System.Text;
using System.Windows;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
namespace ShrlAlgoToolkit.RevitAddins.RvFamily;
///
/// 炸开族中的dwg或嵌套族图元
///
[Transaction(TransactionMode.Manual)]
public class ExplodeDwgCmd : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
StringBuilder sb = new StringBuilder();
try
{
ExternalCommandData data = commandData;
Document Document = data.Application.ActiveUIDocument.Document;
UIDocument UiDocument = data.Application.ActiveUIDocument;
if (!Document.IsFamilyDocument)
{
TaskDialog.Show("提示", "请在族文档中使用此命令");
return Result.Cancelled;
}
//bool useFreeFrom = true;
var refer = UiDocument.Selection.PickObject(ObjectType.Element, new GenericFilter(), "请选择导入图元");
var element = Document.GetElement(refer);
var geoElem = element.get_Geometry(new Options() { ComputeReferences = true, DetailLevel = ViewDetailLevel.Fine });
var f = Document.OwnerFamily;
Document.Invoke(
_ =>
{
foreach (var geoObj in geoElem)
{
if (geoObj is GeometryInstance instance)
{
foreach (var obj in instance.GetInstanceGeometry())
{
try
{
if (obj is Solid solid && solid.Faces.Size > 0 && solid.Volume > 10e-6)
{
FreeFormElement.Create(Document, solid);//和分解的功能一样,仅保留几何信息
//try
//{
// // 如果是项目文档,只能使用DirectShape创建,适用于导入的几何体,不能进行二次编辑
// // 如果是族文档,使用FreeFormElement创建,可以有更多的几何体支持,支持编辑手柄,族文档也支持DirectShape
// var shape = DirectShape.CreateElement(Document, f.FamilyCategory.Id);
// shape.SetShape([solid]);
//}
//catch (Exception)
//{
// FreeFormElement.Create(Document, solid);//和分解的功能一样,仅保留几何信息
//}
}
}
catch (Exception ex)
{
sb.AppendLine(ex.Message);
continue;
}
}
}
try
{
if (geoObj is Solid topSolid && topSolid.Faces.Size > 0 && topSolid.Volume > 10e-6)
{
FreeFormElement.Create(Document, topSolid);//和分解的功能一样,仅保留几何信息
//try
//{
// var directShape = DirectShape.CreateElement(Document, f.FamilyCategory.Id);
// directShape.SetShape([topSolid]);
//}
//catch (Exception)
//{
// FreeFormElement.Create(Document, topSolid);
//}
}
}
catch (Exception ex)
{
sb.AppendLine(ex.Message);
continue;
}
}
Document.Delete(element.Id);
});
}
catch (Autodesk.Revit.Exceptions.OperationCanceledException)
{
}
if (sb.Length > 0)
{
MessageBox.Show(sb.ToString(), "部分几何体创建失败");
}
return Result.Succeeded;
}
private void ProcessGeometry(Document doc, Category category, GeometryElement geometryElement)
{
foreach (var geoObj in geometryElement)
{
if (geoObj is GeometryInstance instance)
{
// 递归处理嵌套的GeometryInstance
ProcessGeometry(doc, category, instance.GetInstanceGeometry());
}
else if (geoObj is Solid solid && solid.Faces.Size > 0 && solid.Volume > 0)
{
try
{
var shape = DirectShape.CreateElement(doc, category.Id);
shape.SetShape([solid]);
}
catch (Exception)
{
continue;
}
}
}
}
}