Files
ShrlAlgoToolkit/ShrlAlgo.Addin.Test/RevitAddin.cs
2026-02-21 16:31:24 +08:00

324 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO;
using System.Reflection;
using System.Text;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
using Nice3point.Revit.Toolkit.External;
using ShrlAlgoToolkit.Core.Assists;
using ShrlAlgoToolkit.RevitCore.Assists;
using ShrlAlgoToolkit.Revit.Extensions;
namespace ShrlAlgo.Addin.Test;
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class RevitAddin : ExternalCommand
{
//private static readonly string AddInPath = Assembly.GetExecutingAssembly().Location;
//private static string _dirAssembly = Path.GetDirectoryName(AddInPath);
private static void GetPose(Transform dwgTransform, GeometryInstance ins, out XYZ loc, out double rotation)
{
var blockLocation = ins.Transform.Origin;
if (ins.Transform.Origin.GetLength() is > 1000 or 0) //块原点距离实际几何重心过远时
{
//存在标注的情况时,以多段线最准确
var b = ins.GetInstanceGeometry().Any(i => i is PolyLine);
foreach (var geometryObject in ins.GetInstanceGeometry())
{
if (b)
{
if (geometryObject is PolyLine pl)
{
blockLocation = (pl.GetOutline().MaximumPoint + pl.GetOutline().MinimumPoint) / 2;
break;
}
}
else
{
if (geometryObject is Line l)
{
blockLocation = l.Evaluate(0.5, true);
break;
}
if (geometryObject is Arc arc)
{
blockLocation = arc.Center;
break;
}
}
}
}
loc = dwgTransform.OfPoint(blockLocation);
loc = new XYZ(loc.X, loc.Y, 0);
rotation = Math.Abs(ins.Transform.BasisX.AngleOnPlaneTo(XYZ.BasisX, XYZ.BasisZ) - (2 * Math.PI));
}
/// <summary>
/// 获取块参照
/// </summary>
/// <param name="dwg"></param>
/// <param name="reference">选择的块参考</param>
/// <returns></returns>
private static List<GeometryInstance> GetBlocksByRef(ImportInstance dwg, Reference reference)
{
var geoElem = dwg.get_Geometry(new Options());
//dwg块
var geoObj = dwg.GetGeometryObjectFromReference(reference);
GeometryInstance referBlock = null;
foreach (var obj in geoElem)
{
if (obj is GeometryInstance dwgGeo) //dwg几何实例
{
foreach (var block in dwgGeo.SymbolGeometry) //块
{
if (block is GeometryInstance ins)
{
if (ins.GetHashCode() == geoObj.GetHashCode())
{
referBlock = ins;
break;
}
foreach (var subBlock in ins.SymbolGeometry) //嵌套块/子块
{
if (subBlock is GeometryInstance subIns && subIns.GetHashCode() == geoObj.GetHashCode())
{
referBlock = ins;
break;
}
}
}
}
}
}
if (referBlock == null)
{
return null;
}
List<GeometryInstance> blocks = [];
foreach (var obj in geoElem)
{
if (obj is GeometryInstance dwgGeo)
{
foreach (var block in dwgGeo.SymbolGeometry) //图元
{
if (block is GeometryInstance ins && ins.Symbol.Name == referBlock.Symbol.Name)
{
blocks.Add(ins);
}
}
}
}
return blocks;
}
public override void Execute()
{
try
{
var reference = UiDocument.Selection.PickObject(ObjectType.PointOnElement, new DwgElementSelection(), "请选择dwg链接的块参照");
var dwg = Document.GetElement(reference) as ImportInstance;
var dwgTransform = dwg!.GetTotalTransform();
var instance = dwg.GetGeometryObjectFromReference(reference) as GeometryInstance;
var inss = GetBlocksByRef(dwg, reference);
//MessageBox.Show(inss.Count.ToString());
Document.Invoke(
_ =>
{
var sb = new StringBuilder();
//foreach (var item in inss)
//{
// GetPose(dwgTransform, item, out var loc, out var r);
// loc += Document.ActiveView.GenLevel.Elevation * XYZ.BasisZ;
// sb.AppendLine($"{loc}:{item.GetHashCode()}");
// loc.DebugCreate(Document);
//}
foreach (var item in inss)
{
if (instance != null && item.GetHashCode() == instance.GetHashCode())
{
instance = item;
break;
}
}
GetPose(dwgTransform, instance, out var loc, out var _);
loc += Document.ActiveView.GenLevel.Elevation * XYZ.BasisZ;
//var pl = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, loc);
//foreach (var item in instance.GetInstanceGeometry())
//{
// sb.AppendLine(item.GetType().ToString());
// if (item is Curve c)
// {
// Document.Create.NewModelCurve(c, SketchPlane.Create(Document, pl));
// }
// if (item is PolyLine pline)
// {
// for (var i = 0; i < pline.NumberOfCoordinates - 1; i++)
// {
// var l = Line.CreateBound(pline.GetCoordinate(i), pline.GetCoordinate(i + 1));
// Document.Create.NewModelCurve(l, SketchPlane.Create(Document, pl));
// }
// }
//}
if (instance != null) sb.AppendLine($"{loc}:{instance.GetHashCode()}");
loc.DebugCreate(Document);
sb.WriteTextFile();
});
//foreach (var item in instance.SymbolGeometry)
//{
// MessageBox.Show(item.GetHashCode().ToString());
//}
//using (var ts = new Transaction(Document, nameof(RevitAddin)))
//{
// ts.Start();
// Document.Create.NewDetailCurve(ActiveView, Line.CreateBound(XYZ.Zero, XYZ.BasisX));
// ts.Commit();
//}
//var doc = uiApplication.ActiveUIDocument.Document;
//UiDocument.Selection.PickObject(
// Autodesk.Revit.UI.Selection.ObjectType.Element,
// new FuncFilter(
// (e) =>
// {
// if (e is Wall)
// {
// //true,false
// //TaskDialog.Show("test", $"{doc.IsReadOnly}-{doc.IsModified}-{doc.IsModifiable}");
// return true;
// }
// return false;
// }
// )
//);
}
catch (Exception)
{
throw;
}
//var name = doc.GetElement(geo.GraphicsStyleId).Name;
//var targetReference = uidoc.Selection.PickObject(ObjectType.Element);
//var id = doc.GetElement(targetReference).GetTypeId();
//var symbol = doc.GetElement(id) as FamilySymbol;
//var symbolId = symbol.Id;
//var family = symbol.Family;
//var instances = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).Cast<FamilyInstance>()
// .Where(f => family.GetFamilySymbolIds().Contains(f.Symbol.Id)).Select(e => e.Id).ToList();
//var collection = uidoc.Selection.PickObjects(ObjectType.Element, "选择族实例").Select(r => doc.GetElement(r).Id).ToList();
//var elems = uidoc.Selection.GetElementIds();
//List<ElementId> setIds = new();
//foreach (var elementId in elems)
//{
// var symbol = doc.GetElement(elementId);
// var filter = new FamilyInstanceFilter(doc, elementId);
// var collector = new FilteredElementCollector(doc).WherePasses(filter).ToElementIds();
// setIds.AddRange(collector);
// //using Transaction transaction = new Transaction(doc, "外部命令");
// //transaction.Start();
// //Element.ChangeTypeId(doc, collection, elementId);
// ////System.Windows.MessageBox.Show(collector.Count().ToString());
// //transaction.Commit();
//}
//uidoc.Selection.SetElementIds(setIds);
//System.Windows.MessageBox.Show($"{elems}");
//var elem = doc.GetElement(ids.FirstOrDefault());
//var list = new List<ElementId>();
//foreach (var elementId in ids)
//{
// var elem = doc.GetElement(elementId);
// if (elem is Pipe pipe)
// {
// if (Math.Abs((175 / 304.8) - pipe.Diameter) < 0.001)
// {
// list.Add(elementId);
// }
// }
//}
//var box = elem.get_BoundingBox(uidoc.ActiveGraphicalView);
////uidoc.Selection.SetElementIds(list);
//var uiView = uidoc.GetOpenUIViews().FirstOrDefault(ui => ui.ViewId == uidoc.ActiveGraphicalView.Id);
//var rectangle = uiView.GetWindowRectangle();
//System.Windows.MessageBox.Show($"{rectangle.Left}{rectangle.Top}{rectangle.Right}{rectangle.Bottom}");
//uiView.ZoomAndCenterRectangle(box.Min + (5 * box.Min.Normalize()), box.Max - (5 * box.Min.Normalize()));
//rectangle = uiView.GetWindowRectangle();
//System.Windows.MessageBox.Show($"{rectangle.Left}{rectangle.Top}{rectangle.Right}{rectangle.Bottom}");
//try
//{
// while (true)
// {
// var reference = uidoc.Selection.PickObject(ObjectType.Element);
// using Transaction transaction = new Transaction(doc, "旋转");
// transaction.Start();
// var elem = doc.GetElement(reference);
// var loc = elem.Location as LocationPoint;
// var p = loc?.Point;
// ElementTransformUtils.RotateElement(doc, elem.Id, Line.CreateUnbound(p, XYZ.BasisZ), Math.PI);
// transaction.Commit();
// }
//}
//catch (Autodesk.Revit.Exceptions.OperationCanceledException e)
//{
//}
//var instances = new FilteredElementCollector(doc)
// .OfClass(typeof(FamilyInstance))
// .ToElements();
//using Transaction transaction = new Transaction(doc, "外部命令");
//transaction.Start();
//StringBuilder sb = new();
//foreach (var instance in instances)
//{
// var param = instance.GetParameters("ID-100-编号").FirstOrDefault();
// Regex regex = new Regex(@"^\D+(\d)?");
// if (regex.IsMatch(instance.Name))
// {
// if (param != null)
// {
// param.Set(instance.Name);
// }
// else
// {
// sb.AppendLine($"{instance.Name}-{instance.Id}");
// }
// }
//}
//Element.ChangeTypeId(doc, collection, symbolId);
//foreach (var element in symbols)
//{
// var param = element.get_Parameter(BuiltInParameter.ALL_MODEL_URL);
// if (param is { IsReadOnly: false } && param.AsString() == "www.goujianwu.com")
// {
// param.Set(string.Empty);
// }
// var param1 = element.get_Parameter(BuiltInParameter.ALL_MODEL_DESCRIPTION);
// if (param1 is { IsReadOnly: false } && param1.AsString() == "biye")
// {
// param1.Set(string.Empty);
// }
//}
//transaction.Commit();
//System.Windows.MessageBox.Show(sb.ToString());
//AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
//var doc = commandData.Application.ActiveUIDocument.Document;
//ObjectSceneExportContext context = new ObjectSceneExportContext(doc, doc.ActiveView as View3D);
//ObjectSceneExporter exporter = new(doc, context);
//exporter.ExportToFile(doc.ActiveView as View3D, Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "//export.json");
}
}