/// <summary> /// Compare two <see cref="Autodesk.Revit.DB.Reference"/> objects to know it are referencing same <see cref="Autodesk.Revit.DB.Element"/> /// </summary> /// <param name="doc"></param> /// <param name="x"></param> /// <param name="y"></param> /// <returns>true if both references are equivalent</returns> public static bool AreEquivalentReferences(this Document doc, Reference x, Reference y) { var UniqueIdX = x?.ConvertToStableRepresentation(doc); var UniqueIdY = y?.ConvertToStableRepresentation(doc); return(UniqueIdX == UniqueIdY); }
private static PlanarFace FindFace(Document doc, Reference faceReference) { return(doc.GetElement(faceReference) .GetSolids() .SelectMany(x => x.Faces.Cast <Face>()) .OfType <PlanarFace>() .Single(x => x.Reference.ConvertToStableRepresentation(doc) == faceReference.ConvertToStableRepresentation(doc))); }
void f() { Document dbDoc = null; Reference myReference = null; string refString = myReference .ConvertToStableRepresentation(dbDoc); string[] refTokens = refString.Split( new char[] { ':' }); }
/// <summary> /// Return a `StableRepresentation` for a linked wall's exterior face. /// </summary> public string GetFaceRefRepresentation( Wall wall, Document doc, RevitLinkInstance instance ) { Reference faceRef = HostObjectUtils.GetSideFaces( wall, ShellLayerType.Exterior ).FirstOrDefault(); Reference stRef = faceRef.CreateLinkReference( instance ); string stable = stRef.ConvertToStableRepresentation( doc ); return stable; }
/// <summary> /// 获取链接文件实例 /// </summary> /// <param name="currDoc"></param> /// <param name="linkedRef"></param> /// <returns></returns> public static RevitLinkInstance GetRevitLinkInstance(Document currDoc, Reference linkedRef) { if (linkedRef.LinkedElementId == ElementId.InvalidElementId) { return(null); } string stableReflink = linkedRef.ConvertToStableRepresentation(currDoc).Split(':')[0]; Reference refLink = Reference.ParseFromStableRepresentation(currDoc, stableReflink); return(currDoc.GetElement(refLink) as RevitLinkInstance); }
/// <summary> /// create new instance on host face, with a face reference as input. /// </summary> public LineBasedFamilyCreator_onPlanarFace (FamilySymbol _fs, Line _offsetLocLine, XYZ _facing, Reference _hostFaceRef, Dictionary <string, ParameterEditRecorder> _params, OpContext _opContext) : base(_fs, _params, _opContext) { this.OffsetLocLine = _offsetLocLine; this.Facing = _facing; this.hostFaceRef = _hostFaceRef; this.referenceString = _hostFaceRef.ConvertToStableRepresentation(_fs.Document); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Get Environment Variables UIApplication uiApp = commandData.Application; Reference reference = uiApp.ActiveUIDocument.Selection.PickObject(ObjectType.Face, "Select Face"); if (reference != null) { string stable = reference.ConvertToStableRepresentation(uiApp.ActiveUIDocument.Document); Grevit.Reporting.MessageBox.ShowInTextBox("Stable Reference:", stable); } return(Result.Succeeded); }
public JsonExporter(Document doc, string fileName, Reference referenceface) { try { m_doc = doc; jsFileName = fileName; refFace = referenceface; refString = refFace.ConvertToStableRepresentation(m_doc); m_face = doc.GetElement(refFace).GetGeometryObjectFromReference(refFace) as Face; } catch (Exception ex) { MessageBox.Show("Failed to export to JSON.\n" + ex.Message, "JSON Exporter", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void WriteSolid(Solid solid) { foreach (Face face in solid.Faces) { Reference reference = face.Reference; if (reference != null) { m_writer.WriteLine("Geometry face - " + reference.ConvertToStableRepresentation(m_doc)); } else { m_writer.WriteLine("Geometry face - but reference is null"); } } }
public override sealed string ToString() { string typeName = ((IGH_Goo)this).TypeName; if (!IsValid) { return("Null " + typeName); } try { if (Document?.GetElement(Reference) is DB.Element element) { typeName = "Referenced "; switch (Reference.ElementReferenceType) { case DB.ElementReferenceType.REFERENCE_TYPE_NONE: typeName += "geometry"; break; case DB.ElementReferenceType.REFERENCE_TYPE_LINEAR: typeName += "edge"; break; case DB.ElementReferenceType.REFERENCE_TYPE_SURFACE: typeName += "face"; break; case DB.ElementReferenceType.REFERENCE_TYPE_FOREIGN: typeName += "external geometry"; break; case DB.ElementReferenceType.REFERENCE_TYPE_INSTANCE: typeName += "instance"; break; case DB.ElementReferenceType.REFERENCE_TYPE_CUT_EDGE: typeName += "trim"; break; case DB.ElementReferenceType.REFERENCE_TYPE_MESH: typeName += "mesh"; break; #if REVIT_2018 case DB.ElementReferenceType.REFERENCE_TYPE_SUBELEMENT: typeName += "subelement"; break; #endif } typeName += " at Revit " + element.GetType().Name + " \"" + element.Name + "\""; } #if DEBUG typeName += " (" + Reference.ConvertToStableRepresentation(Document) + ")"; #endif return(typeName); } catch (Autodesk.Revit.Exceptions.ApplicationException) { return("Invalid" + typeName); } }
public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems) { Result result; try { Snoop.CollectorExts.CollectorExt.m_app = cmdData.Application; Document doc = cmdData.Application.ActiveUIDocument.Document; Reference refElem = null; try { refElem = cmdData.Application.ActiveUIDocument .Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.LinkedElement); } catch { return(Result.Succeeded); } string stableReflink = refElem.ConvertToStableRepresentation(doc).Split(':')[0]; Reference refLink = Reference.ParseFromStableRepresentation(doc, stableReflink); RevitLinkInstance rli_return = doc.GetElement(refLink) as RevitLinkInstance; Snoop.CollectorExts.CollectorExt.m_activeDoc = rli_return.GetLinkDocument(); Element e = Snoop.CollectorExts.CollectorExt.m_activeDoc.GetElement(refElem.LinkedElementId); Snoop.Forms.Objects form = new Snoop.Forms.Objects(e); ActiveDoc.UIApp = cmdData.Application; form.ShowDialog(); result = Result.Succeeded; } catch (System.Exception e) { msg = e.Message; result = Result.Failed; } return(result); }
/***************************************************/ /**** Internal methods ****/ /***************************************************/ public static Reference PrepareForLinkDimensioning(this Reference reference, Document hostDocument) { if (reference.LinkedElementId.IntegerValue == -1) { return(null); } string[] ss = reference.ConvertToStableRepresentation(hostDocument).Split(':'); string res = string.Empty; bool first = true; foreach (string s in ss) { string t = s; if (s.Contains("RVTLINK")) { if (res.EndsWith(":0")) { t = "RVTLINK"; } else { t = "0:RVTLINK"; } } if (!first) { res = string.Concat(res, ":", t); } else { res = t; first = false; } } return(Reference.ParseFromStableRepresentation(hostDocument, res)); }
/// <summary> /// Prompting the user to pick a wall face /// </summary> /// <returns> /// Returns 'Cancelled' if the end-user escapes from face picking. /// Otherwise returns Succeeded or Failed depending on whether /// a face on a wall or face-wall was picked as expected /// </returns> private Result PickWallFace(UIDocument uidoc, out String sref) { sref = null; Reference faceref = null; try { faceref = uidoc.Selection.PickObject(ObjectType.Face, "Pick a face on a wall or face-wall element."); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } // we make sure we have the expected kind of face reference if (faceref != null) { Element pickedelem = uidoc.Document.GetElement(faceref.ElementId); FaceWall asfacewall = pickedelem as FaceWall; Wall aswall = pickedelem as Wall; // in this particular example, we accepts faces on wall elements only if ((aswall == null) && (asfacewall == null)) { return(Result.Failed); } } // we convert the reference object to a more stable string // representation that is more traceable across transactions sref = faceref.ConvertToStableRepresentation(uidoc.Document); return(Result.Succeeded); }
public void Execute(UIApplication uiapp) { try { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name); do { /// TECHNIQUE 09 OF 19 (EE09_Draw3D_ModelLines.cs) ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ DRAWING 3D MODEL LINES (A SIMILY FACE) ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ /// /// Interfaces and ENUM's: /// FailureHandlingOptions /// /// /// Demonstrates classes: /// Arc /// Line /// Curve /// Ellipse /// /// /// Key methods: /// Arc.Create(end02, end12, pointOnCurve2); /// Arc.Create(myTransform.OfPoint(new XYZ(-.6, 0.5, 0)), radius, startAngle, endAngle, xVec, yVec); /// Ellipse.CreateCurve(pickedRef.GlobalPoint, radiusEllipse, radiusEllipse2, xVec, yVec, param0, param1); /// doc.Create.NewModelCurve( /// /// /// /// * class is actually part of the .NET framework (not Revit API) /// https://github.com/joshnewzealand/Revit-API-Playpen-CSharp Reference pickedRef = null; try { pickedRef = uidoc.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Face, "Please select a Face"); } #region catch and finally catch (Exception ex) { } finally { } #endregion if (pickedRef == null) { break; } Element myElement = doc.GetElement(pickedRef.ElementId); Face myFace = myElement.GetGeometryObjectFromReference(pickedRef) as Face; if (myFace == null) { return; } Transform myXYZ_FamilyTransform = Transform.Identity; if (pickedRef.ConvertToStableRepresentation(doc).Contains("INSTANCE")) { myXYZ_FamilyTransform = (myElement as FamilyInstance).GetTotalTransform(); } Transform myTransform = Transform.Identity; if (myFace.GetType() != typeof(PlanarFace)) { continue; } PlanarFace myPlanarFace = myFace as PlanarFace; myTransform.Origin = pickedRef.GlobalPoint; myTransform.BasisX = myXYZ_FamilyTransform.OfVector(myPlanarFace.XVector); myTransform.BasisY = myXYZ_FamilyTransform.OfVector(myPlanarFace.YVector); myTransform.BasisZ = myXYZ_FamilyTransform.OfVector(myPlanarFace.FaceNormal); // Create a geometry line XYZ startPoint = new XYZ(0, 0, 0); XYZ endPoint = new XYZ(10, 10, 0); // Create a arc XYZ origin = myTransform.OfPoint(new XYZ(0, 0, 0)); XYZ normal = myTransform.OfPoint(new XYZ(1, 1, 0)); XYZ end02 = myTransform.OfPoint((new XYZ(-.7, -.9, 0))); XYZ end12 = myTransform.OfPoint((new XYZ(.7, -.9, 0))); XYZ pointOnCurve2 = myTransform.OfPoint((new XYZ(0, -1.25, 0))); Arc geomArc2 = Arc.Create(end02, end12, pointOnCurve2); // Create a geometry circle in Revit application XYZ xVec = myTransform.OfVector(XYZ.BasisX); XYZ yVec = myTransform.OfVector(XYZ.BasisY); double startAngle = 0; double endAngle = 2 * Math.PI; double radius = .3; Arc geomPlane2 = Arc.Create(myTransform.OfPoint(new XYZ(-.6, 0.5, 0)), radius, startAngle, endAngle, xVec, yVec); Arc geomPlane3 = Arc.Create(myTransform.OfPoint(new XYZ(.6, 0.5, 0)), radius, startAngle, endAngle, xVec, yVec); ////////////////////// straight lines Line L2 = Line.CreateBound(myTransform.OfPoint(new XYZ(-.2, -.5, 0)), myTransform.OfPoint(new XYZ(.2, -.5, 0))); Line L3 = Line.CreateBound(myTransform.OfPoint(new XYZ(.2, -.5, 0)), myTransform.OfPoint(new XYZ(0, .1, 0))); // Create a ellipse double param0 = 0.0; double param1 = 2 * Math.PI; double radiusEllipse = 1.4; double radiusEllipse2 = 1.4 * 1.2; Curve myCurve_Ellipse = Ellipse.CreateCurve(pickedRef.GlobalPoint, radiusEllipse, radiusEllipse2, xVec, yVec, param0, param1); using (Transaction y = new Transaction(doc, "Simily Face")) { y.Start(); FailureHandlingOptions options = y.GetFailureHandlingOptions(); options.SetFailuresPreprocessor(new MyPreProcessor()); y.SetFailureHandlingOptions(options); SketchPlane sketch = SketchPlane.Create(doc, pickedRef); try { doc.Create.NewModelCurve(geomArc2, sketch); doc.Create.NewModelCurve(myCurve_Ellipse, sketch); doc.Create.NewModelCurve(geomPlane2, sketch); doc.Create.NewModelCurve(geomPlane3, sketch); doc.Create.NewModelCurve(L2, sketch); doc.Create.NewModelCurve(L3, sketch); } #region catch and finally catch (Exception ex) { if (ex.Message != "Curve must be in the plane\r\nParameter name: pCurveCopy") { _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE01_Part1" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true); } } finally { } #endregion y.Commit(); } } while (true); } #region catch and finally catch (Exception ex) { if (ex.Message != "The user aborted the pick operation.") { _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE09_Draw3D_ModelLines" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true); } else { } } finally { } #endregion }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; app = commandData.Application.Application; doc = uidoc.Document; //Reference refer = uidoc.Selection.PickObject(ObjectType.Element, "Select a CAD Link"); //Element elem = doc.GetElement(refer); //GeometryElement geoElem = elem.get_Geometry(new Options()); Reference r = uidoc.Selection.PickObject(ObjectType.PointOnElement); string ss = r.ConvertToStableRepresentation(doc); Element elem = doc.GetElement(r); GeometryElement geoElem = elem.get_Geometry(new Options()); GeometryObject geoObj = elem.GetGeometryObjectFromReference(r); //获取选中的cad图层 Category targetCategory = null; ElementId graphicsStyleId = null; if (geoObj.GraphicsStyleId != ElementId.InvalidElementId) { graphicsStyleId = geoObj.GraphicsStyleId; GraphicsStyle gs = doc.GetElement(geoObj.GraphicsStyleId) as GraphicsStyle; if (gs != null) { targetCategory = gs.GraphicsStyleCategory; var name = gs.GraphicsStyleCategory.Name; } } //隐藏选中的cad图层 Transaction trans = new Transaction(doc, "隐藏图层"); trans.Start(); if (targetCategory != null) { doc.ActiveView.SetVisibility(targetCategory, false); } trans.Commit(); TransactionGroup transGroup = new TransactionGroup(doc, "绘制模型线"); transGroup.Start(); CurveArray curveArray = new CurveArray(); //判断元素类型 foreach (var gObj in geoElem) { GeometryInstance geomInstance = gObj as GeometryInstance; //坐标转换。如果选择的是“自动-中心到中心”,或者移动了importInstance,需要进行坐标转换 Transform transform = geomInstance.Transform; if (null != geomInstance) { foreach (var insObj in geomInstance.SymbolGeometry) { if (insObj.GraphicsStyleId.IntegerValue != graphicsStyleId.IntegerValue) { continue; } if (insObj.GetType().ToString() == "Autodesk.Revit.DB.NurbSpline") { //未实现 } if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Line") { Line line = insObj as Line; XYZ normal = XYZ.BasisZ; XYZ point = line.GetEndPoint(0); point = transform.OfPoint(point); curveArray.Append(TransformLine(transform, line)); CreateModelCurveArray(curveArray, normal, point); } if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Arc") { //未实现 } if (insObj.GetType().ToString() == "Autodesk.Revit.DB.PolyLine") { PolyLine polyLine = insObj as PolyLine; IList <XYZ> points = polyLine.GetCoordinates(); for (int i = 0; i < points.Count - 1; i++) { Line line = Line.CreateBound(points[i], points[i + 1]); line = TransformLine(transform, line); curveArray.Append(line); } XYZ normal = XYZ.BasisZ; XYZ point = points.First(); point = transform.OfPoint(point); CreateModelCurveArray(curveArray, normal, point); } } } } transGroup.Assimilate(); return(Result.Succeeded); }
public static Edge GetInstanceEdgeFromSymbolRef( Reference symbolRef, Document dbDoc) { Edge instEdge = null; Options gOptions = new Options(); gOptions.ComputeReferences = true; gOptions.DetailLevel = ViewDetailLevel.Undefined; gOptions.IncludeNonVisibleObjects = false; Element elem = dbDoc.GetElement(symbolRef.ElementId); string stableRefSymbol = symbolRef .ConvertToStableRepresentation(dbDoc); string[] tokenList = stableRefSymbol.Split( new char[] { ':' }); string stableRefInst = tokenList[3] + ":" + tokenList[4] + ":" + tokenList[5]; GeometryElement geomElem = elem.get_Geometry( gOptions); foreach (GeometryObject geomElemObj in geomElem) { GeometryInstance geomInst = geomElemObj as GeometryInstance; if (geomInst != null) { GeometryElement gInstGeom = geomInst .GetInstanceGeometry(); foreach (GeometryObject gGeomObject in gInstGeom) { Solid solid = gGeomObject as Solid; if (solid != null) { foreach (Edge edge in solid.Edges) { string stableRef = edge.Reference .ConvertToStableRepresentation( dbDoc); if (stableRef == stableRefInst) { instEdge = edge; break; } } } if (instEdge != null) { // already found, exit early break; } } } if (instEdge != null) { // already found, exit early break; } } return(instEdge); }
public void Execute(UIApplication uiapp) { try { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name); if (uidoc.Selection.GetElementIds().Count != 1) { MessageBox.Show("Please select ONE Wall."); return; } Element myElementWall = doc.GetElement(uidoc.Selection.GetElementIds().First()); if (myElementWall.GetType() == typeof(FamilyInstance)) { FamilyInstance myFamilyInstance = myElementWall as FamilyInstance; myElementWall = myFamilyInstance.Host; if (myElementWall == null) { MessageBox.Show("Family instance must be hosted to a wall."); return; } } /// TECHNIQUE 08 OF 19 (EE08_MoveElementAroundHostingSurface.cs) ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ MOVING ELEMENTS AROUND A HOSTING SURFACE ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ /// The people walk around the perimeter of the wall, and it will work on any surface /// /// /// Interfaces and ENUM's: /// /// /// Demonstrates classes: /// Reference /// Face /// Transform /// PlanarFace /// CurveLoop /// /// /// Key methods: /// myElementWall.GetGeometryObjectFromReference(pickedRef) as Face /// pickedRef.ConvertToStableRepresentation(doc).Contains("INSTANCE")) /// (myElementWall as FamilyInstance).GetTotalTransform(); /// myFace.GetBoundingBox().Min /// myFace.Evaluate(myUV_Min) /// /// myXYZ_FamilyTransform.OfPoint(myXYZ_CornerOne) /// myXYZ_FamilyTransform.OfVector(myPlanarFace.XVector); /// myCurveLoop.GetExactLength(); /// /// /// L1.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); /// ElementTransformUtils.MoveElement(doc, myFamilyInstance.Id, myXYZ_MoveThisMuch); /// /// * class is actually part of the .NET framework (not Revit API) /// /// /// /// https://github.com/joshnewzealand/Revit-API-Playpen-CSharp List <Element> myListOfStuffOnWall = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_GenericModel).Where(x => (((FamilyInstance)x).Host != null)).Where(x => ((FamilyInstance)x).Host.Id == myElementWall.Id).ToList(); List <Element> myListOfFurniture = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_Furniture).Where(x => (((FamilyInstance)x).Host != null)).Where(x => ((FamilyInstance)x).Host.Id == myElementWall.Id).ToList(); myListOfStuffOnWall.AddRange(myListOfFurniture); if (myListOfStuffOnWall.Count() > 0) { using (Transaction tx = new Transaction(doc)) { tx.Start("Rotate People"); foreach (FamilyInstance myFI in myListOfStuffOnWall) { FamilyInstance myFamilyInstance = myFI as FamilyInstance; Reference pickedRef = myFI.HostFace; ////doc.Delete(myListElementID); ////myListElementID.Clear(); Face myFace = myElementWall.GetGeometryObjectFromReference(pickedRef) as Face; if (myFace == null) { return; } Transform myXYZ_FamilyTransform = Transform.Identity; if (pickedRef.ConvertToStableRepresentation(doc).Contains("INSTANCE")) { myXYZ_FamilyTransform = (myElementWall as FamilyInstance).GetTotalTransform(); } Transform myTransform = Transform.Identity; if (myFace.GetType() != typeof(PlanarFace)) { return; } PlanarFace myPlanarFace = myFace as PlanarFace; UV myUV_Min = myFace.GetBoundingBox().Min; UV myUV_Max = myFace.GetBoundingBox().Max; XYZ myXYZ_CornerOne = myFace.Evaluate(myUV_Min); myTransform.Origin = myXYZ_FamilyTransform.OfPoint(myXYZ_CornerOne); myTransform.BasisX = myXYZ_FamilyTransform.OfVector(myPlanarFace.XVector); myTransform.BasisY = myXYZ_FamilyTransform.OfVector(myPlanarFace.YVector); myTransform.BasisZ = myXYZ_FamilyTransform.OfVector(myPlanarFace.FaceNormal); XYZ myXYZ_Centre = XYZ.Zero; XYZ myXYZ_Min = new XYZ(myUV_Min.U, myUV_Min.V, 0); XYZ myXYZ_Max = new XYZ(myUV_Max.U, myUV_Max.V, 0); XYZ myXYZ_UV_CornerOne = (((myXYZ_Max - myXYZ_Min) * 0.1)); //; + myXYZ_Min; XYZ myXYZ_UV_CornerTwo = (((myXYZ_Max - myXYZ_Min) * 0.9)); // + myXYZ_Min; XYZ myXYZ_UV_Corner01 = new XYZ(myXYZ_UV_CornerOne.X, myXYZ_UV_CornerOne.Y, 0); XYZ myXYZ_UV_Corner02 = new XYZ(myXYZ_UV_CornerTwo.X, myXYZ_UV_CornerOne.Y, 0); XYZ myXYZ_UV_Corner03 = new XYZ(myXYZ_UV_CornerTwo.X, myXYZ_UV_CornerTwo.Y, 0); XYZ myXYZ_UV_Corner04 = new XYZ(myXYZ_UV_CornerOne.X, myXYZ_UV_CornerTwo.Y, 0); Line L1 = Line.CreateBound(myTransform.OfPoint(myXYZ_UV_Corner01), myTransform.OfPoint(myXYZ_UV_Corner02)); Line L2 = Line.CreateBound(myTransform.OfPoint(myXYZ_UV_Corner02), myTransform.OfPoint(myXYZ_UV_Corner03)); Line L3 = Line.CreateBound(myTransform.OfPoint(myXYZ_UV_Corner03), myTransform.OfPoint(myXYZ_UV_Corner04)); Line L4 = Line.CreateBound(myTransform.OfPoint(myXYZ_UV_Corner04), myTransform.OfPoint(myXYZ_UV_Corner01)); CurveLoop myCurveLoop = new CurveLoop(); myCurveLoop.Append(L1); myCurveLoop.Append(L2); myCurveLoop.Append(L3); myCurveLoop.Append(L4); double myDouble_ExactLength = myCurveLoop.GetExactLength(); double myDouble_ExactLength_Twenty = myDouble_ExactLength / 40; XYZ myXYZ_Result = myTransform.OfPoint((myXYZ_Max - myXYZ_Min) / 2); int myIntCurrentSpinnerValue = myWindow1.myIntegerUpDown_OneToTwentyCount.Value.Value; int myInt_Positioning = (40 / myListOfStuffOnWall.Count()) * (myListOfStuffOnWall.IndexOf(myFI) + 1); myIntCurrentSpinnerValue = (40 - myInt_Positioning) + myIntCurrentSpinnerValue; if (myIntCurrentSpinnerValue > 40) { myIntCurrentSpinnerValue = myIntCurrentSpinnerValue - 40; } double myDouble_FutureForeach = myDouble_ExactLength_Twenty * myIntCurrentSpinnerValue; double myDouble_ThisFarAlong; switch (myDouble_FutureForeach) { case double n when n < L1.Length: myDouble_ThisFarAlong = myDouble_FutureForeach; myXYZ_Result = L1.GetEndPoint(0) + (L1.GetEndPoint(1) - L1.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); break; case double n when n >= L1.Length& n < L1.Length + L2.Length: myDouble_ThisFarAlong = myDouble_FutureForeach - L1.Length; myXYZ_Result = L2.GetEndPoint(0) + (L2.GetEndPoint(1) - L2.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); break; case double n when n >= L1.Length + L2.Length& n < L1.Length + L2.Length + L3.Length: myDouble_ThisFarAlong = myDouble_FutureForeach - L1.Length - L2.Length; myXYZ_Result = L3.GetEndPoint(0) + (L3.GetEndPoint(1) - L3.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); break; case double n when n >= L1.Length + L2.Length + L3.Length: myDouble_ThisFarAlong = myDouble_FutureForeach - L1.Length - L2.Length - L3.Length; myXYZ_Result = L4.GetEndPoint(0) + (L4.GetEndPoint(1) - L4.GetEndPoint(0)).Normalize().Multiply(myDouble_ThisFarAlong); break; } XYZ myXYZ_MoveThisMuch = myXYZ_Result - ((LocationPoint)myFamilyInstance.Location).Point; ElementTransformUtils.MoveElement(doc, myFamilyInstance.Id, myXYZ_MoveThisMuch); //SketchPlane mySketchPlane = SketchPlane.Create(doc, pickedRef); //myListElementID.Add(doc.Create.NewModelCurve(L1, mySketchPlane).Id); //myListElementID.Add(doc.Create.NewModelCurve(L2, mySketchPlane).Id); //myListElementID.Add(doc.Create.NewModelCurve(L3, mySketchPlane).Id); //myListElementID.Add(doc.Create.NewModelCurve(L4, mySketchPlane).Id); } tx.Commit(); } if (myWindow1.myIntegerUpDown_OneToTwentyCount.Value.Value == 40) { myWindow1.myIntegerUpDown_OneToTwentyCount.Value = 0; } myWindow1.myIntegerUpDown_OneToTwentyCount.Value++; } } #region catch and finally catch (Exception ex) { DatabaseMethods.writeDebug("EE08_MoveElementAroundHostingSurface" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true); } finally { } #endregion }
/***************************************************/ /**** Private methods ****/ /***************************************************/ private static XYZ CeilingPatternAlignment(this Ceiling ceiling, Material material, RevitSettings settings, out double rotation) { rotation = 0; if (ceiling == null || material == null) { return(null); } Document doc = ceiling.Document; FillPatternElement fillPatternElement; #if (REVIT2020 || REVIT2021) fillPatternElement = doc.GetElement(material.SurfaceForegroundPatternId) as FillPatternElement; #else fillPatternElement = doc.GetElement(material.SurfacePatternId) as FillPatternElement; #endif FillPattern fp = fillPatternElement?.GetFillPattern(); if (fp == null || fp.GridCount != 2) { return(null); } XYZ result = null; settings = settings.DefaultIfNull(); Options o = new Options(); o.ComputeReferences = true; Document hostDoc = doc.IsLinked ? doc.HostDocument() : doc; RevitLinkInstance linkInstance = doc.IsLinked ? doc.LinkInstance() : null; Transform linkTransform = linkInstance == null ? Transform.Identity : linkInstance.GetTotalTransform(); foreach (GeometryObject go in ceiling.get_Geometry(o)) { if (go is Solid) { foreach (Autodesk.Revit.DB.Face f in ((Solid)go).Faces) { PlanarFace pf = f as PlanarFace; if (pf == null) { continue; } if (1 + pf.FaceNormal.DotProduct(XYZ.BasisZ) > settings.AngleTolerance) { continue; } Reference faceRef = f.Reference; if (doc.IsLinked) { faceRef = faceRef.CreateLinkReference(linkInstance).PrepareForLinkDimensioning(hostDoc); } string stableRef = faceRef.ConvertToStableRepresentation(hostDoc); ReferenceArray horR = new ReferenceArray(); horR.Append(Reference.ParseFromStableRepresentation(hostDoc, stableRef + "/2")); horR.Append(Reference.ParseFromStableRepresentation(hostDoc, stableRef + "/" + (2 + fp.GridCount * 2).ToString())); ReferenceArray verR = new ReferenceArray(); verR.Append(Reference.ParseFromStableRepresentation(hostDoc, stableRef + "/1")); verR.Append(Reference.ParseFromStableRepresentation(hostDoc, stableRef + "/" + (1 + fp.GridCount * 2).ToString())); using (Transaction t = new Transaction(hostDoc, "temp dim")) { t.Start(); Dimension horDim = hostDoc.Create.NewDimension(hostDoc.ActiveView, Autodesk.Revit.DB.Line.CreateBound(XYZ.Zero, pf.XVector), horR); Dimension verDim = hostDoc.Create.NewDimension(hostDoc.ActiveView, Autodesk.Revit.DB.Line.CreateBound(XYZ.Zero, pf.YVector), verR); ElementTransformUtils.MoveElement(hostDoc, horDim.Id, XYZ.BasisX); ElementTransformUtils.MoveElement(hostDoc, verDim.Id, XYZ.BasisX); rotation = -(horDim.Curve as Autodesk.Revit.DB.Line).Direction.AngleOnPlaneTo(XYZ.BasisX, XYZ.BasisZ); rotation += linkTransform.BasisX.AngleOnPlaneTo(XYZ.BasisX, XYZ.BasisZ); Transform tr = Transform.CreateRotation(XYZ.BasisZ, rotation); double x = tr.Inverse.OfPoint(linkTransform.Inverse.OfPoint(horDim.Origin)).X; double y = tr.Inverse.OfPoint(linkTransform.Inverse.OfPoint(verDim.Origin)).Y; t.RollBack(); foreach (FillGrid fg in fp.GetFillGrids()) { if (fg.Angle.ToSI(UnitType.UT_Angle) > settings.AngleTolerance) { y += fg.Offset * 0.5; } else { x += fg.Offset * 0.5; } } result = tr.OfPoint(new XYZ(x, y, 0)); break; } } } } return(result); }
private static bool IsTheSameReference(Document doc, Reference faceReference, Face face) { return(faceReference.ConvertToStableRepresentation(doc).EndsWith(face.Reference.ConvertToStableRepresentation(doc))); }
/***************************************************/ private static Line ClosestLineOn(this Element element, Line refLine, out Reference reference) { double minDist = double.MaxValue; reference = null; Options opt = new Options(); opt.ComputeReferences = true; List <Face> faces = element.Faces(opt); IntersectionResult ir1, ir2; XYZ start = refLine.GetEndPoint(0); XYZ end = refLine.GetEndPoint(1); XYZ startOnFace = null; XYZ endOnFace = null; foreach (Face face in faces) { if (!(face is PlanarFace)) { continue; } ir1 = face.Project(start); ir2 = face.Project(end); if (ir1?.XYZPoint == null || ir2?.XYZPoint == null) { continue; } double totDist = ir1.Distance + ir2.Distance; if (totDist < minDist) { minDist = totDist; startOnFace = ir1.XYZPoint; endOnFace = ir2.XYZPoint; reference = face.Reference; } } if (startOnFace == null || endOnFace == null || reference == null) { return(null); } if (element is FamilyInstance && !((FamilyInstance)element).HasModifiedGeometry()) { string instRef = ((FamilyInstance)element).UniqueId + ":0:INSTANCE:" + reference.ConvertToStableRepresentation(element.Document); reference = Reference.ParseFromStableRepresentation(element.Document, instRef); } return(Line.CreateBound(startOnFace, endOnFace)); }
public static void Execute( ExternalCommandData commandData) { Transaction trans = null; UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { Selection choices = uidoc.Selection; Reference faceref = choices.PickObject( ObjectType.Face); string rep = faceref .ConvertToStableRepresentation(doc); Debug.Assert(rep.EndsWith(":SURFACE"), "expected stable representation to end with SURFACE"); Debug.Print("Face reference picked: " + rep); Element el = doc.GetElement( faceref.ElementId); using (trans = new Transaction(doc)) { trans.Start("Create elements"); TessellatedShapeBuilder builder = new TessellatedShapeBuilder(); builder.OpenConnectedFaceSet(false); // This may return a face in the family // symbol definition with no family instance // transform applied. Use the GeometryElement // GetTransformed method to retrieve the face // with the instance transformation applied. Face face = el.GetGeometryObjectFromReference( faceref) as Face; Debug.Print("Face reference property: " + ((null == face.Reference) ? "<nil>" : face.Reference.ConvertToStableRepresentation(doc))); Transform t = null; FamilyInstance fi = el as FamilyInstance; if (null != fi) { // Will this handle a face selected // in a nested family instance? // Some, yes, but not all. //t = fi.GetTransform(); // This also works for some instances // but not all. //Transform t1 = fi.GetTotalTransform(); Options opt = new Options(); opt.ComputeReferences = true; GeometryElement geo = el.get_Geometry(opt); GeometryElement geo2 = geo.GetTransformed( Transform.Identity); Stack <Transform> tstack = new Stack <Transform>(); if (GetTransformStackForObject(tstack, geo, doc, rep) && 0 < tstack.Count) { Debug.Print("GetTransformStackForObject " + "returned true with tstack count {0}", tstack.Count); t = Transform.Identity; while (0 < tstack.Count) { t *= tstack.Pop(); } } } Mesh mesh = face.Triangulate(); if (null != t) { mesh = mesh.get_Transformed(t); } XYZ[] triangleCorners = new XYZ[3]; for (int i = 0; i < mesh.NumTriangles; i++) { MeshTriangle triangle = mesh.get_Triangle(i); triangleCorners[0] = triangle.get_Vertex(0); triangleCorners[1] = triangle.get_Vertex(1); triangleCorners[2] = triangle.get_Vertex(2); XYZ normal = GetNormal(triangleCorners); SketchPlane sketchPlane = GetSketchPlane( doc, triangleCorners[0], normal); DrawModelLineLoop(sketchPlane, triangleCorners); TessellatedFace tesseFace = new TessellatedFace(triangleCorners, ElementId.InvalidElementId); if (builder.DoesFaceHaveEnoughLoopsAndVertices( tesseFace)) { builder.AddFace(tesseFace); } } builder.CloseConnectedFaceSet(); //TessellatedShapeBuilderResult result // = builder.Build( // TessellatedShapeBuilderTarget.AnyGeometry, // TessellatedShapeBuilderFallback.Mesh, // ElementId.InvalidElementId ); // 2016 builder.Target = TessellatedShapeBuilderTarget.AnyGeometry; // 2018 builder.Fallback = TessellatedShapeBuilderFallback.Mesh; // 2018 builder.Build(); // 2018 TessellatedShapeBuilderResult result = builder.GetBuildResult(); // 2018 ElementId categoryId = new ElementId( BuiltInCategory.OST_GenericModel); //DirectShape ds = DirectShape.CreateElement( // doc, categoryId, // Assembly.GetExecutingAssembly().GetType().GUID.ToString(), // Guid.NewGuid().ToString() ); // 2016 DirectShape ds = DirectShape.CreateElement( doc, categoryId); // 2018 ds.ApplicationId = Assembly.GetExecutingAssembly() .GetType().GUID.ToString(); // 2018 ds.ApplicationDataId = Guid.NewGuid().ToString(); // 2018 ds.SetShape(result.GetGeometricalObjects()); ds.Name = "MyShape"; trans.Commit(); } } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } }
public void Execute(UIApplication uiapp) { try { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; // myListView_ALL_Fam_Master.Items.Add(doc.GetElement(uidoc.Selection.GetElementIds().First()).Name); if (doc.ActiveView.GetType() != typeof(View3D)) { MessageBox.Show("ActiveView is not typeof View3D."); return; } FamilyInstance myFamilyInstance_NerfGun = null; if (uidoc.Selection.GetElementIds().Count == 0) { string myString_RememberLast = doc.ProjectInformation.get_Parameter(BuiltInParameter.PROJECT_NUMBER).AsString(); int n; if (int.TryParse(myString_RememberLast, out n)) { myFamilyInstance_NerfGun = doc.GetElement(new ElementId(n)) as FamilyInstance; } } else { myFamilyInstance_NerfGun = doc.GetElement(uidoc.Selection.GetElementIds().First()) as FamilyInstance; } if (myFamilyInstance_NerfGun == null) { MessageBox.Show("Please perform step 5 of 19 first." + Environment.NewLine + Environment.NewLine + "(Placing Nerf Gun)"); return; } /// TECHNIQUE 14 OF 19 (EE14_Draw3D_IntersectorLines.cs) ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ DRAW INTERSECTOR LINES FROM NERF GUN ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ /// /// Interfaces and ENUM's: /// BuiltInParameter.POINT_ELEMENT_DRIVEN /// IFailuresPreprocessor /// /// /// Demonstrates classes: /// ReferencePoint /// AdaptiveComponentInstanceUtils /// Transform /// TransactionGroup /// Random* /// ElementMulticategoryFilter /// ReferenceIntersector /// /// /// Key methods: /// AdaptiveComponentInstanceUtils.GetInstancePointElementRefIds( /// myReferencePoint.GetCoordinateSystem( /// refIntersector.FindNearest( /// myReferenceWithContext.GetReference( /// uidoc.RefreshActiveView(); /// /// /// /// * class is actually part of the .NET framework (not Revit API) /// /// /// https://github.com/joshnewzealand/Revit-API-Playpen-CSharp uidoc.Selection.SetElementIds(new List <ElementId>()); ReferencePoint myReferencePoint = doc.GetElement(AdaptiveComponentInstanceUtils.GetInstancePointElementRefIds(myFamilyInstance_NerfGun).First()) as ReferencePoint; Transform myTransform_FromNurfGun = myReferencePoint.GetCoordinateSystem(); using (TransactionGroup transGroup = new TransactionGroup(doc)) { transGroup.Start("Transaction Group"); if (!myReferencePoint.get_Parameter(BuiltInParameter.POINT_ELEMENT_DRIVEN).IsReadOnly) { using (Transaction tx = new Transaction(doc)) { tx.Start("Unhost"); myReferencePoint.get_Parameter(BuiltInParameter.POINT_ELEMENT_DRIVEN).Set(0); tx.Commit(); uidoc.RefreshActiveView(); } } MyPreProcessor preproccessor = new MyPreProcessor(); for (int i = 1; i <= 100; i++) { if (i > 100) { MessageBox.Show("Stopped at 'i > 100' because more will cause Revit to 'freeze up'."); break; } Random rnd = new Random(); OverrideGraphicSettings ogs = new OverrideGraphicSettings(); ogs.SetProjectionLineColor(new Autodesk.Revit.DB.Color((byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256))); using (Transaction tx = new Transaction(doc)) { FailureHandlingOptions options = tx.GetFailureHandlingOptions(); options.SetFailuresPreprocessor(preproccessor); tx.SetFailureHandlingOptions(options); tx.Start("Splatter Gun"); Line myLine_BasisX = Line.CreateUnbound(myTransform_FromNurfGun.Origin, myTransform_FromNurfGun.BasisX); myReferencePoint.Location.Rotate(myLine_BasisX, GetRandomNumber()); Line myLine_BasisZ = Line.CreateUnbound(myTransform_FromNurfGun.Origin, myTransform_FromNurfGun.BasisZ); myReferencePoint.Location.Rotate(myLine_BasisZ, GetRandomNumber()); myTransform_FromNurfGun = myReferencePoint.GetCoordinateSystem(); List <BuiltInCategory> builtInCats = new List <BuiltInCategory>(); builtInCats.Add(BuiltInCategory.OST_Roofs); builtInCats.Add(BuiltInCategory.OST_Ceilings); builtInCats.Add(BuiltInCategory.OST_Floors); builtInCats.Add(BuiltInCategory.OST_Walls); builtInCats.Add(BuiltInCategory.OST_Doors); builtInCats.Add(BuiltInCategory.OST_Windows); builtInCats.Add(BuiltInCategory.OST_CurtainWallPanels); builtInCats.Add(BuiltInCategory.OST_CurtainWallMullions); ElementMulticategoryFilter intersectFilter = new ElementMulticategoryFilter(builtInCats); ReferenceIntersector refIntersector = new ReferenceIntersector(intersectFilter, FindReferenceTarget.Face, doc.ActiveView as View3D); ReferenceWithContext myReferenceWithContext = refIntersector.FindNearest(myTransform_FromNurfGun.Origin, myTransform_FromNurfGun.BasisZ); if (myReferenceWithContext != null) { Reference myReferenceHosting_Normal = myReferenceWithContext.GetReference(); Element myElement_ContainingFace = doc.GetElement(myReferenceHosting_Normal.ElementId); Face myFace = myElement_ContainingFace.GetGeometryObjectFromReference(myReferenceHosting_Normal) as Face; if (myFace.GetType() != typeof(PlanarFace)) { return; // continue; } Plane plane = Plane.CreateByNormalAndOrigin(myTransform_FromNurfGun.BasisX, myTransform_FromNurfGun.Origin); SketchPlane sketchPlane = SketchPlane.Create(doc, plane); if (myTransform_FromNurfGun.Origin.DistanceTo(myReferenceHosting_Normal.GlobalPoint) > 0.0026)//minimum lenth check { Line line = Line.CreateBound(myTransform_FromNurfGun.Origin, myReferenceHosting_Normal.GlobalPoint); ModelLine myModelLine = doc.Create.NewModelCurve(line, sketchPlane) as ModelLine; doc.ActiveView.SetElementOverrides(myModelLine.Id, ogs); myWindow1.myListElementID_SketchPlanesToDelete.Add(sketchPlane.Id); Transform myXYZ_FamilyTransform = Transform.Identity; if (myReferenceHosting_Normal.ConvertToStableRepresentation(doc).Contains("INSTANCE")) { myXYZ_FamilyTransform = (myElement_ContainingFace as FamilyInstance).GetTotalTransform(); } PlanarFace myPlanarFace = myFace as PlanarFace; Transform myTransform = Transform.Identity; myTransform.Origin = myReferenceHosting_Normal.GlobalPoint; myTransform.BasisX = myXYZ_FamilyTransform.OfVector(myPlanarFace.XVector); myTransform.BasisY = myXYZ_FamilyTransform.OfVector(myPlanarFace.YVector); myTransform.BasisZ = myXYZ_FamilyTransform.OfVector(myPlanarFace.FaceNormal); SketchPlane mySketchPlane = SketchPlane.Create(doc, myReferenceHosting_Normal); // Create a geometry circle in Revit application XYZ xVec = myTransform.OfVector(XYZ.BasisX); XYZ yVec = myTransform.OfVector(XYZ.BasisY); double startAngle2 = 0; double endAngle2 = 2 * Math.PI; double radius2 = 1.23; Arc geomPlane3 = Arc.Create(myTransform.OfPoint(new XYZ(0, 0, 0)), radius2, startAngle2, endAngle2, xVec, yVec); ModelArc arc = doc.Create.NewModelCurve(geomPlane3, mySketchPlane) as ModelArc; //doc.Delete(sketch2.Id); doc.ActiveView.SetElementOverrides(arc.Id, ogs); } } tx.Commit(); uidoc.RefreshActiveView(); } } transGroup.Assimilate(); } } #region catch and finally catch (Exception ex) { _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE05_Part1" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true); } finally { } #endregion }
private void CreatingCircles_ReturnsBreak(Reference pickedRef) { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; /// TECHNIQUE 11 OF 19 (EE11_GridOutCirclesOnFace.cs) ///↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ GRID OUT CIRCLES ON FACE ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ /// /// Interfaces and ENUM's: /// /// /// Demonstrates classes: /// Xceed.Wpf.Toolkit.IntegerUpDown* /// /// /// Key methods: /// doc.Delete( /// /// A 2 DIMENSION MATRIX IS A LOOP WITIN A LOOP /// for (int int_Outer = 1; int_Outer <= myWindow1.my11IntegerUpDown_Columns.Value.Value * (myBool_OneTwoOneLayout ? 2 : 1); int_Outer++) /// { /// for (int int_Inner = 1; int_Inner <= myWindow1.my11IntegerUpDown_Rows.Value.Value * (myBool_OneTwoOneLayout ? 2 : 1); int_Inner++) /// { /// XYZ myXYZ_GridPoint = new XYZ(myXYZ_DifferernceColumn.X * int_Outer, myXYZ_DifferernceRow.Y * int_Inner, 0); /// Arc geomPlane3 = Arc.Create(myTransform.OfPoint(myXYZ_GridPoint), radius, startAngle, endAngle, myTransform.BasisX, myTransform.BasisY); /// doc.Create.NewModelCurve(geomPlane3, mySketchPlane).Id; /// } /// } /// /// /// /// * class is part xceed.wpf.toolkit (not Revit API) /// https://github.com/joshnewzealand/Revit-API-Playpen-CSharp using (Transaction tx = new Transaction(doc)) { tx.Start("Delete the previous circles."); doc.Delete(myListElementID); myListElementID.Clear(); tx.Commit(); } Element myElement = doc.GetElement(pickedRef.ElementId); Face myFace = myElement.GetGeometryObjectFromReference(pickedRef) as Face; if (myFace == null) { return; } Transform myXYZ_FamilyTransform = Transform.Identity; if (pickedRef.ConvertToStableRepresentation(doc).Contains("INSTANCE")) { myXYZ_FamilyTransform = (myElement as FamilyInstance).GetTotalTransform(); } Transform myTransform = Transform.Identity; if (myFace.GetType() != typeof(PlanarFace)) { return; } PlanarFace myPlanarFace = myFace as PlanarFace; UV myUV_Min = myFace.GetBoundingBox().Min; UV myUV_Max = myFace.GetBoundingBox().Max; XYZ myXYZ_CornerOne = myFace.Evaluate(myUV_Min); XYZ myXYZ_CornerTwo = myFace.Evaluate(myUV_Max); XYZ myXYZ_CornerOne_Transformed = myXYZ_FamilyTransform.OfPoint(myXYZ_CornerOne); XYZ myXYZ_CornerTwo_Transformed = myXYZ_FamilyTransform.OfPoint(myXYZ_CornerTwo); myTransform.Origin = myXYZ_CornerOne_Transformed; myTransform.BasisX = myXYZ_FamilyTransform.OfVector(myPlanarFace.XVector); myTransform.BasisY = myXYZ_FamilyTransform.OfVector(myPlanarFace.YVector); myTransform.BasisZ = myXYZ_FamilyTransform.OfVector(myPlanarFace.FaceNormal); XYZ myXYZ_Centre = XYZ.Zero; XYZ myXYZ_Min = new XYZ(myUV_Min.U, myUV_Min.V, 0); XYZ myXYZ_Max = new XYZ(myUV_Max.U, myUV_Max.V, 0); bool myBool_OneTwoOneLayout = myWindow1.my11CheckBox_OneTwoOne.IsChecked.Value; int myInt_Columns = myWindow1.my11IntegerUpDown_Columns.Value.Value; int myInt_Rows = myWindow1.my11IntegerUpDown_Rows.Value.Value; int myIntDivideColumn = myBool_OneTwoOneLayout ? myInt_Columns * 2 : myInt_Columns + 1; int myIntDivideRow = myBool_OneTwoOneLayout ? myInt_Rows * 2 : myInt_Rows + 1; XYZ myXYZ_DifferernceColumn = (myXYZ_Max - myXYZ_Min) / myIntDivideColumn; double myDouble_WidthColumn = myXYZ_DifferernceColumn.X; XYZ myXYZ_DifferernceRow = (myXYZ_Max - myXYZ_Min) / myIntDivideRow; double myDouble_WidthRow = myXYZ_DifferernceRow.Y; double myDouble_SmallestWins = myDouble_WidthColumn < myDouble_WidthRow ? myDouble_WidthColumn : myDouble_WidthRow; double startAngle = 0; double endAngle = 2 * Math.PI; double radius = myDouble_SmallestWins / (myBool_OneTwoOneLayout ? 1 : 2); using (Transaction tx = new Transaction(doc)) { tx.Start("Draw Grid of Circles On Face"); SketchPlane mySketchPlane = SketchPlane.Create(doc, pickedRef); for (int int_Outer = 1; int_Outer <= myWindow1.my11IntegerUpDown_Columns.Value.Value * (myBool_OneTwoOneLayout ? 2 : 1); int_Outer++) { if (int_Outer % 2 != 0 | !myBool_OneTwoOneLayout) //here { for (int int_Inner = 1; int_Inner <= myWindow1.my11IntegerUpDown_Rows.Value.Value * (myBool_OneTwoOneLayout ? 2 : 1); int_Inner++) { XYZ myXYZ_GridPoint = new XYZ(myXYZ_DifferernceColumn.X * int_Outer, myXYZ_DifferernceRow.Y * int_Inner, 0); if (int_Inner % 2 != 0 | !myBool_OneTwoOneLayout) //here { Arc geomPlane3 = Arc.Create(myTransform.OfPoint(myXYZ_GridPoint), radius, startAngle, endAngle, myTransform.BasisX, myTransform.BasisY); myListElementID.Add(doc.Create.NewModelCurve(geomPlane3, mySketchPlane).Id); } } } } tx.Commit(); } return; }
/// <summary> /// Return a reference to the topmost face of the given element. /// </summary> private Reference FindTopMostReference(Element e) { Reference ret = null; Document doc = e.Document; #region Revit 2012 #if _2012 using (SubTransaction t = new SubTransaction(doc)) { t.Start(); // Create temporary 3D view //View3D view3D = doc.Create.NewView3D( // 2012 // viewDirection ); // 2012 ViewFamilyType vft = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .FirstOrDefault <ViewFamilyType>(x => ViewFamily.ThreeDimensional == x.ViewFamily); Debug.Assert(null != vft, "expected to find a valid 3D view family type"); View3D view = View3D.CreateIsometric(doc, vft.Id); // 2013 XYZ eyePosition = XYZ.BasisZ; XYZ upDirection = XYZ.BasisY; XYZ forwardDirection = -XYZ.BasisZ; view.SetOrientation(new ViewOrientation3D( eyePosition, upDirection, forwardDirection)); XYZ viewDirection = -XYZ.BasisZ; BoundingBoxXYZ bb = e.get_BoundingBox(view); XYZ max = bb.Max; XYZ minAtMaxElevation = Create.NewXYZ( bb.Min.X, bb.Min.Y, max.Z); XYZ centerOfTopOfBox = 0.5 * (minAtMaxElevation + max); centerOfTopOfBox += 10 * XYZ.BasisZ; // Cast a ray through the model // to find the topmost surface #if DEBUG //ReferenceArray references // = doc.FindReferencesByDirection( // centerOfTopOfBox, viewDirection, view3D ); // 2011 IList <ReferenceWithContext> references = doc.FindReferencesWithContextByDirection( centerOfTopOfBox, viewDirection, view); // 2012 double closest = double.PositiveInfinity; //foreach( Reference r in references ) //{ // // 'Autodesk.Revit.DB.Reference.Element' is // // obsolete: Property will be removed. Use // // Document.GetElement(Reference) instead. // //Element re = r.Element; // 2011 // Element re = doc.GetElement( r ); // 2012 // if( re.Id.IntegerValue == e.Id.IntegerValue // && r.ProximityParameter < closest ) // { // ret = r; // closest = r.ProximityParameter; // } //} foreach (ReferenceWithContext r in references) { Element re = doc.GetElement( r.GetReference()); // 2012 if (re.Id.IntegerValue == e.Id.IntegerValue && r.Proximity < closest) { ret = r.GetReference(); closest = r.Proximity; } } string stable_reference = null == ret ? null : ret.ConvertToStableRepresentation(doc); #endif // DEBUG ReferenceIntersector ri = new ReferenceIntersector( e.Id, FindReferenceTarget.Element, view); ReferenceWithContext r2 = ri.FindNearest( centerOfTopOfBox, viewDirection); if (null == r2) { Debug.Print("ReferenceIntersector.FindNearest returned null!"); } else { ret = r2.GetReference(); Debug.Assert(stable_reference.Equals(ret .ConvertToStableRepresentation(doc)), "expected same reference from " + "FindReferencesWithContextByDirection and " + "ReferenceIntersector"); } t.RollBack(); } #endif // _2012 #endregion // Revit 2012 Options opt = doc.Application.Create .NewGeometryOptions(); opt.ComputeReferences = true; GeometryElement geo = e.get_Geometry(opt); foreach (GeometryObject obj in geo) { GeometryInstance inst = obj as GeometryInstance; if (null != inst) { geo = inst.GetSymbolGeometry(); break; } } Solid solid = geo.OfType <Solid>() .First <Solid>(sol => null != sol); double z = double.MinValue; foreach (Face f in solid.Faces) { BoundingBoxUV b = f.GetBoundingBox(); UV p = b.Min; UV q = b.Max; UV midparam = p + 0.5 * (q - p); XYZ midpoint = f.Evaluate(midparam); XYZ normal = f.ComputeNormal(midparam); if (Util.PointsUpwards(normal)) { if (midpoint.Z > z) { z = midpoint.Z; ret = f.Reference; } } } return(ret); }
/***************************************************/ /**** Private Methods - Others ****/ /***************************************************/ private static XYZ ClosestPointOn(this Element element, XYZ refPoint, out Reference reference, out bool closest, XYZ normal = null, RevitSettings settings = null) { closest = true; settings = settings.DefaultIfNull(); normal = normal?.Normalize(); double minFactoredDist = double.MaxValue; double minDist = double.MaxValue; reference = null; Options opt = new Options(); opt.ComputeReferences = true; List <Face> faces = element.Faces(opt); IntersectionResult ir; XYZ pointOnFace = null; foreach (Face face in faces) { ir = face.Project(refPoint); if (ir == null || ir.XYZPoint == null) { continue; } if (ir.Distance < minDist) { minDist = ir.Distance; } double factoredDist = ir.Distance; if (normal != null) { double normalFactor = normal.DotProduct(face.ComputeNormal(ir.UVPoint)); if (normalFactor < settings.AngleTolerance) { continue; } factoredDist /= normalFactor; } if (factoredDist < minFactoredDist) { minFactoredDist = factoredDist; pointOnFace = ir.XYZPoint; reference = face.Reference; } } if (pointOnFace == null || reference == null) { return(null); } closest = !(refPoint.DistanceTo(pointOnFace) - minDist > settings.DistanceTolerance); if (element is FamilyInstance && !((FamilyInstance)element).HasModifiedGeometry()) { string instRef = ((FamilyInstance)element).UniqueId + ":0:INSTANCE:" + reference.ConvertToStableRepresentation(element.Document); reference = Reference.ParseFromStableRepresentation(element.Document, instRef); } return(pointOnFace); }