private void Application_Idling(object sender, IdlingEventArgs e) { //var app = sender as Application; //var uiApp = new UIApplication(app); var uiApp = sender as UIApplication; var uiDoc = uiApp.ActiveUIDocument; var view = uiDoc.ActiveView; var doc = uiDoc.Document; e.SetRaiseWithoutDelay(); if (Math.Abs(lastCursor.X - System.Windows.Forms.Cursor.Position.X) >= 1) { var curPt = GetCurrentCursorPosition(uiDoc); using (var t = new Transaction(doc, "TestIdling")) { t.Start(); var l = Line.CreateBound(pt1, curPt); if (line == null) { line = doc.Create.NewDetailCurve(view, l); } else { line.GeometryCurve = l; } t.Commit(); } } lastCursor = System.Windows.Forms.Cursor.Position; }
/// <summary> /// Get all selected lines and arcs /// </summary> /// <param name="document">Revit's document</param> /// <returns>CurveArray contains all selected lines and arcs</returns> private static CurveArray GetSelectedCurves(Document document) { CurveArray selectedCurves = new CurveArray(); UIDocument newUIdocument = new UIDocument(document); ElementSet elements = new ElementSet(); foreach (ElementId elementId in newUIdocument.Selection.GetElementIds()) { elements.Insert(newUIdocument.Document.GetElement(elementId)); } foreach (Autodesk.Revit.DB.Element element in elements) { if ((element is ModelLine) || (element is ModelArc)) { ModelCurve modelCurve = element as ModelCurve; Curve curve = modelCurve.GeometryCurve; if (curve != null) { selectedCurves.Append(curve); } } else if ((element is DetailLine) || (element is DetailArc)) { DetailCurve detailCurve = element as DetailCurve; Curve curve = detailCurve.GeometryCurve; if (curve != null) { selectedCurves.Append(curve); } } } return(selectedCurves); }
ICollection <ElementId> GetLineStyles(UIApplication m_rvtApp, Document m_rvtDoc) { Transaction tr = new Transaction(m_rvtDoc, "Get Line Styles"); tr.Start(); // Create a detail line View view = m_rvtDoc.ActiveView; XYZ pt1 = XYZ.Zero; XYZ pt2 = new XYZ(10.0, 0.0, 0.0); XYZ[] pts = new XYZ[] { pt1, pt2, }; List <Curve> profile = new List <Curve>(pts.Length); // 2013 for (int ii = 0; ii <= pts.Length - 2; ii++) { profile.Add(Line.CreateBound(pts[ii], pts[ii + 1])); } DetailCurve dc = m_rvtDoc.Create.NewDetailCurve(view, profile[0]); ICollection <ElementId> lineStyles = dc.GetLineStyleIds(); tr.RollBack(); return(lineStyles); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; if (doc.IsFamilyDocument) { TaskDialog.Show("Error", "This tool only works in Project environment."); return(Result.Cancelled); } Transaction t1 = new Transaction(doc, "Draw Insulation"); try { Reference refinsulation = uidoc.Selection.PickObject(ObjectType.Element, new SelectionFilterAnnotation(), "Select Insulation Batting"); Reference refcurve = uidoc.Selection.PickObject(ObjectType.Element, new SelectionFilterCurve(), "Select Curve"); DetailCurve insulationdetailcurve = doc.GetElement(refinsulation) as DetailCurve; DetailCurve detailcurve = doc.GetElement(refcurve) as DetailCurve; double width = insulationdetailcurve.LookupParameter("Insulation Width").AsDouble(); double ratio = insulationdetailcurve.LookupParameter("Insulation Bulge to Width Ratio (1/x)").AsDouble(); Curve curve = detailcurve.GeometryCurve; t1.Start(); if (curve is Arc && curve.IsBound) { List <Line> lines = SplitArc(curve, width, ratio); foreach (Line l in lines) { DetailCurve newcurve = doc.GetElement(ElementTransformUtils.CopyElement(doc, insulationdetailcurve.Id, new XYZ()).First()) as DetailCurve; newcurve.GeometryCurve = l; } } if (curve is Line && curve.IsBound) { Line l = curve as Line; DetailCurve newcurve = doc.GetElement(ElementTransformUtils.CopyElement(doc, insulationdetailcurve.Id, new XYZ()).First()) as DetailCurve; newcurve.GeometryCurve = l; } t1.Commit(); return(Result.Succeeded); } catch (Exception e) { t1.RollBack(); return(Result.Cancelled); } }
/// <summary> /// Get all selected lines and arcs /// </summary> /// <param name="document">Revit's document</param> /// <returns>CurveArray contains all selected lines and arcs</returns> private CurveArray GetSelectedCurves(ThisDocument document) { CurveArray selectedCurves = m_doc.Document.Application.Create.NewCurveArray(); ElementSet elements = new ElementSet(); foreach (var elementid in document.Selection.GetElementIds()) { elements.Insert(m_doc.Document.GetElement(elementid)); } foreach (Autodesk.Revit.DB.Element element in elements) { if ((element is ModelLine) || (element is ModelArc)) { ModelCurve modelCurve = element as ModelCurve; Curve curve = modelCurve.GeometryCurve; if (curve != null) { selectedCurves.Append(curve); } } else if ((element is DetailLine) || (element is DetailArc)) { DetailCurve detailCurve = element as DetailCurve; Curve curve = detailCurve.GeometryCurve; if (curve != null) { selectedCurves.Append(curve); } } } return(selectedCurves); }
public static DetailCurve createdetailcurve(Document doc, XYZ xyz1, XYZ xyz2, Plane plane) { Line line = Line.CreateBound(xyz1, xyz2); line = ProjectLineOnPlane(plane, line); DetailCurve detailcurve = doc.Create.NewDetailCurve(doc.ActiveView, line); return(detailcurve); }
/// <summary> /// Draw point marker with detail circles. /// Optional colors are "red" "blue" "orange" /// </summary> public static void DrawDetailMarkers(Document doc, List <XYZ> pts, int weight = 2, string color = "red", string pattern = "") { GetListOfLinestyles(doc); View view = doc.ActiveView; Color palette = new Color(0, 0, 0); switch (color) { case "red": palette = new Color(200, 50, 80); break; case "blue": palette = new Color(100, 149, 237); break; case "orange": palette = new Color(255, 140, 0); break; } FilteredElementCollector fec = new FilteredElementCollector(doc) .OfClass(typeof(LinePatternElement)); LinePatternElement linePatternElem = null; if (pattern != "") { try { linePatternElem = fec .Cast <LinePatternElement>() .First <LinePatternElement>(linePattern => linePattern.Name == pattern); } catch { Debug.Print("There's no matching pattern in the document"); } } XYZ xAxis = new XYZ(1, 0, 0); XYZ yAxis = new XYZ(0, 1, 0); using (Transaction tx = new Transaction(doc)) { tx.Start("Create Detail Markers"); foreach (XYZ pt in pts) { double radius = 0.3; Arc marker = Arc.Create(pt, radius, 0, 2 * Math.PI, xAxis, yAxis); DetailCurve detailCrv = doc.Create.NewDetailCurve(view, marker); GraphicsStyle gs = detailCrv.LineStyle as GraphicsStyle; gs.GraphicsStyleCategory.LineColor = palette; gs.GraphicsStyleCategory.SetLineWeight(weight, gs.GraphicsStyleType); if (linePatternElem != null) { gs.GraphicsStyleCategory.SetLinePatternId(linePatternElem.Id, GraphicsStyleType.Projection); } } tx.Commit(); } }
/// <summary> /// Draw detail curves based on List<Curve> /// </summary> public static void DrawDetailLines(Document doc, List <Curve> crvs, int weight = 2, string color = "red", string pattern = "") { GetListOfLinestyles(doc); View view = doc.ActiveView; Color palette = new Color(0, 0, 0); switch (color) { case "red": palette = new Color(200, 50, 80); break; case "blue": palette = new Color(100, 149, 237); break; case "orange": palette = new Color(255, 140, 0); break; } FilteredElementCollector fec = new FilteredElementCollector(doc) .OfClass(typeof(LinePatternElement)); LinePatternElement linePatternElem = null; if (pattern != "") { try { linePatternElem = fec .Cast <LinePatternElement>() .First <LinePatternElement>(linePattern => linePattern.Name == pattern); } catch { Debug.Print("There's no matching pattern in the document"); } } using (Transaction tx = new Transaction(doc)) { tx.Start("Create Detail Curves"); foreach (Curve crv in crvs) { // Should do style setting here or...? DetailCurve detailCrv = doc.Create.NewDetailCurve(view, crv); GraphicsStyle gs = detailCrv.LineStyle as GraphicsStyle; gs.GraphicsStyleCategory.LineColor = palette; gs.GraphicsStyleCategory.SetLineWeight(weight, gs.GraphicsStyleType); if (linePatternElem != null) { gs.GraphicsStyleCategory.SetLinePatternId(linePatternElem.Id, GraphicsStyleType.Projection); } } tx.Commit(); } }
//设置线样式 private void SetLineStyle(Category cate, DetailCurve line) { ElementId Id = new ElementId(cate.Id.IntegerValue + 1); foreach (Parameter p in line.Parameters) { if (p.Definition.Name == "线样式") { p.Set(Id); break; } } }
public bool AllowElement(Element elem) { if (elem is DetailCurve) { DetailCurve cv = elem as DetailCurve; if (cv.CurveElementType == CurveElementType.Insulation) { return(true); } } return(false); }
/// <summary> /// 获取详图区域的详图线 /// </summary> public static List <DetailCurve> DetailCurves(this FilledRegion filledRegion, Document doc) { ElementClassFilter elementClassFilter = new ElementClassFilter(typeof(CurveElement)); List <ElementId> detailLineIds = filledRegion.GetDependentElements(elementClassFilter).ToList(); List <DetailCurve> detailCurves = new List <DetailCurve>(); foreach (ElementId elementId in detailLineIds) { DetailCurve detailCurve = doc.GetElement(elementId) as DetailCurve; detailCurves.Add(detailCurve); } return(detailCurves); }
public void ByCurve_ValidArgs() { var line = Line.ByStartPointEndPoint(Point.ByCoordinates(0, 0, 0), Point.ByCoordinates(100, 0, 0)); Assert.NotNull(line); var detailCurve = DetailCurve.ByCurve(Revit.Application.Document.Current.ActiveView, line); Assert.NotNull(detailCurve); var curveRef = detailCurve.ElementCurveReference; Assert.NotNull(curveRef); var curve = detailCurve.Curve; curve.Length.ShouldBeApproximately(100); }
public void ByCurve_Curve_AcceptsStraightDegree3NurbsCurve() { var points = Enumerable.Range(0, 10) .Select(x => Autodesk.DesignScript.Geometry.Point.ByCoordinates(x, 0)); var nurbsCurve = NurbsCurve.ByPoints(points, 3); Assert.NotNull(nurbsCurve); var detailCurve = DetailCurve.ByCurve(Revit.Application.Document.Current.ActiveView, nurbsCurve); Assert.NotNull(detailCurve); detailCurve.Curve.Length.ShouldBeApproximately(9); detailCurve.Curve.StartPoint.ShouldBeApproximately(Point.Origin()); detailCurve.Curve.EndPoint.ShouldBeApproximately(Point.ByCoordinates(9, 0, 0)); }
/// <summary> /// 获取所有线性类别 方法一:通过创建实体线事务,通过事务回滚方式,获取 /// </summary> /// <param name="doc"></param> /// <returns></returns> public static ICollection <ElementId> GetAllLineStyleIdsFromTransaction(Document doc) { ICollection <ElementId> styles = new List <ElementId>(); Transaction transaction = new Transaction(doc); transaction.Start("Create detail line"); try { View view = doc.ActiveView; DetailCurve detailCurve = doc.Create.NewDetailCurve(view, Line.CreateBound(new XYZ(0, 0, 0), new XYZ(10, 0, 0))); styles = detailCurve.GetLineStyleIds(); transaction.RollBack(); } catch (Exception ex) { transaction.RollBack(); } return(styles); }
public void AddDottedLine(XYZ start, XYZ end, Document doc, ViewDrafting vd) { Element style = null; ICollection <Element> elements = new FilteredElementCollector(doc).OfClass(typeof(GraphicsStyle)).ToElements(); foreach (Element element in elements) { if (element.Name == "<Снесено>") { style = element; } } using (Transaction t = new Transaction(doc)) { t.Start("Преобразование линий"); DetailCurve l = doc.Create.NewDetailCurve(vd, Line.CreateBound(start, end)); l.LineStyle = style; t.Commit(); } }
public static void TotalLineLengths(ExternalCommandData commandData) { var app = commandData.Application; var uiDoc = app.ActiveUIDocument; var doc = uiDoc.Document; var selection = uiDoc.Selection.GetElementIds(); var elements = new HashSet <Element>(from ElementId id in selection select doc.GetElement(id)); double totalLength = 0; foreach (Element el in elements) { if (el == null) { ut.ErrorMsg("One of the selected elements is null."); break; } if (el is DetailCurve) { DetailCurve dc = el as DetailCurve; totalLength += dc.GeometryCurve.Length; } else if (el is ModelCurve) { ModelCurve mc = el as ModelCurve; totalLength += mc.GeometryCurve.Length; } else { ut.ErrorMsg(el.Name.ToString() + " is not implemented!"); } } ut.InfoMsg(totalLength.FtToMillimeters().Round4().ToString()); }
public static void ListLineStyles(UIDocument uiDoc) { Document currentDoc = uiDoc.Document; Selection sel = uiDoc.Selection; XYZ BasePt = sel.PickPoint(); FilteredElementCollector LineCollector = new FilteredElementCollector(currentDoc); List <ElementId> Lines = LineCollector.OfCategory(BuiltInCategory.OST_Lines).ToElementIds().ToList(); FilteredElementCollector txtCollector = new FilteredElementCollector(currentDoc); ElementId txtnoteTypeId = txtCollector.OfCategory(BuiltInCategory.OST_TextNotes).FirstElement().GetTypeId(); int adjustment = 10; Dictionary <string, CurveElement> LineStyles = new Dictionary <string, CurveElement>(); for (int i = 0; i < Lines.Count(); i++) { CurveElement l = currentDoc.GetElement(Lines[i]) as CurveElement; if (!LineStyles.Keys.Contains(l.LineStyle.Name)) { LineStyles.Add(l.LineStyle.Name, l); } } List <string> StyleName = LineStyles.Keys.ToList(); StyleName.Sort(); for (int i = 0; i < StyleName.Count(); i++) { XYZ startpoint = new XYZ(BasePt.X, (BasePt.Y - (adjustment * i)), 0); XYZ endpoint = new XYZ((BasePt.X + (adjustment * 3)), (BasePt.Y - (adjustment * i)), 0); XYZ TextPoint = new XYZ(BasePt.X + (adjustment * 4), (BasePt.Y - (adjustment * i)), 0); Curve baseCurve = Line.CreateBound(startpoint, endpoint) as Curve; DetailCurve addedLine = currentDoc.Create.NewDetailCurve(uiDoc.ActiveView, baseCurve); TextNote txNote = TextNote.Create(currentDoc, uiDoc.ActiveView.Id, TextPoint, StyleName[i], txtnoteTypeId); addedLine.LineStyle = LineStyles[StyleName[i]].LineStyle; } }
private IList <Curve> GetCurves(UIDocument uidoc) { IList <Curve> c = new List <Curve>(); IList <Reference> rList = uidoc.Selection.PickObjects(ObjectType.Element); foreach (Reference reference in rList) { Element r = uidoc.Document.GetElement(reference); if (r is ModelCurve) { ModelCurve m = r as ModelCurve; Curve curve = m.GeometryCurve; c.Add(curve); } else if (r is DetailCurve) { DetailCurve m = r as DetailCurve; Curve curve = m.GeometryCurve; c.Add(curve); }//只能拾取单体线段 } return(c); }
/// <summary> /// 提取 详图线 或者 模型线 的 lines /// </summary> /// <param name="_Eles"></param> /// <returns></returns> public static List <Line> ConvetDocLinesTolines(List <Element> _Eles) { List <Line> _Lines = new List <Line>(); foreach (Element _ele in _Eles) { if (_ele is DetailLine) { DetailLine _DetailLine = _ele as DetailLine; Curve _Curve = _DetailLine.GeometryCurve; Line _Line = _Curve as Line; _Lines.Add(_Line); } else if (_ele is ModelLine) { ModelLine _ModelLine = _ele as ModelLine; Curve _Curve = _ModelLine.GeometryCurve; Line _Line = _Curve as Line; _Lines.Add(_Line); } else if (_ele is DetailCurve)//将圆弧转化为多段线,取列表并集 { DetailCurve _DetaillArc = _ele as DetailCurve; Curve _Curve = _DetaillArc.GeometryCurve; List <Line> __Lines = GetunClosedLinesFromArc(_Curve);//将圆弧划分成一定段数的线段相连 _Lines.AddRange(__Lines); } else if (_ele is ModelCurve)//将圆弧转化为多段线,取列表并集 { ModelCurve _ModelArc = _ele as ModelCurve; Curve _Curve = _ModelArc.GeometryCurve; List <Line> __Lines = GetunClosedLinesFromArc(_Curve);//将圆弧划分成一定段数的线段相连 _Lines.AddRange(__Lines); } } return(_Lines); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = commandData.Application.ActiveUIDocument.Document; //window Window1 window = new Window1(); window.ShowDialog(); window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; TaskDialog.Show("GOA", "选择需要添加符号线的轴网点击左上角完成."); //get line length & offset double length = Convert.ToInt32(window.tb_length.Text) / 304.8; //get activeview View activeview = uidoc.ActiveView; //get grids IList <Reference> selection = uidoc.Selection.PickObjects(ObjectType.Element, "选择需要添加符号线的轴网"); // creat a list for group //List<DetailCurve> detaillines = new List<DetailCurve>(); //get linestyle FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(GraphicsStyle)); IEnumerable <GraphicsStyle> tmpgraphicsstyles = null; tmpgraphicsstyles = from tmp in collector let gs = tmp as GraphicsStyle where gs.Name == "G-GRID-IDEN" select gs; if (tmpgraphicsstyles.Count() == 0) { TaskDialog.Show("wrong", "未找到名为G-GRID-IDEN的轴网"); return(Result.Failed); } GraphicsStyle graphicsstyle = tmpgraphicsstyles.ToList().First(); //creat lines using (Transaction transaction = new Transaction(doc)) { transaction.Start("批量添加轴号线"); foreach (Reference refe in selection) { Grid grid = doc.GetElement(refe.ElementId) as Grid; if (grid == null) { continue; } //exclude curve if (grid.IsCurved) { TaskDialog.Show("wrong", "目前暂不支持曲线轴网"); return(Result.Failed); } Line gridline = grid.GetCurvesInView(DatumExtentType.ViewSpecific, activeview).First() as Line; XYZ direction = gridline.Direction; XYZ backdirection = direction.Multiply(-1); XYZ origin = gridline.GetEndPoint(0); XYZ origin2 = gridline.GetEndPoint(1); XYZ linepoint1 = origin + (direction * length); XYZ linepoint2 = origin2 + (backdirection * length); Line line1 = Line.CreateBound(origin, linepoint1); Line line2 = Line.CreateBound(origin2, linepoint2); //creat line by IsBubbleVisibleInView if (grid.IsBubbleVisibleInView(DatumEnds.End0, activeview)) { DetailCurve detailline1 = doc.Create.NewDetailCurve(activeview, line1); detailline1.LineStyle = graphicsstyle; //detaillines.Add(detailline1); } if (grid.IsBubbleVisibleInView(DatumEnds.End1, activeview)) { DetailCurve detailline2 = doc.Create.NewDetailCurve(activeview, line2); detailline2.LineStyle = graphicsstyle; //detaillines.Add(detailline2); } } transaction.Commit(); } return(Result.Succeeded); }
private void WriteElementGeometry( int elementId ) { FilteredElementCollector viewCollector = new FilteredElementCollector( m_doc ); viewCollector.OfClass( typeof( ViewPlan ) ); Func<ViewPlan, bool> isLevel1FloorPlan = v => !v.IsTemplate && v.Name == "Level 1" && v.ViewType == ViewType.FloorPlan; m_targetView = viewCollector.Cast<ViewPlan>().First<ViewPlan>( isLevel1FloorPlan ); Transaction createCurve = new Transaction( m_doc, "Create reference curves" ); createCurve.Start(); const double xReferenceLocation = 30; Line vLine = Line.CreateBound( new XYZ( xReferenceLocation, 0, 0 ), new XYZ( xReferenceLocation, 20, 0 ) ); m_vLine = m_doc.Create.NewDetailCurve( m_targetView, vLine ); const double yReferenceLocation = -10; Line hLine = Line.CreateBound( new XYZ( 0, yReferenceLocation, 0 ), new XYZ( 20, yReferenceLocation, 0 ) ); m_hLine = m_doc.Create.NewDetailCurve( m_targetView, hLine ); createCurve.Commit(); Element e = m_doc.GetElement( new ElementId( elementId ) ); Options options = new Options(); options.ComputeReferences = true; options.IncludeNonVisibleObjects = true; options.View = m_targetView; GeometryElement geomElem = e.get_Geometry( options ); foreach( GeometryObject geomObj in geomElem ) { if( geomObj is Solid ) { WriteSolid( (Solid) geomObj ); } else if( geomObj is GeometryInstance ) { TraverseGeometryInstance( (GeometryInstance) geomObj ); } else { m_writer.WriteLine( "Something else - " + geomObj.GetType().Name ); } } foreach( Curve curve in m_referencePlaneReferences ) { // Try to get the geometry object from reference Reference curveReference = curve.Reference; GeometryObject geomObj = e.GetGeometryObjectFromReference( curveReference ); if( geomObj != null ) { m_writer.WriteLine( "Curve reference leads to: " + geomObj.GetType().Name ); } } // Dimension to reference curves foreach( Curve curve in m_referencePlaneReferences ) { DetailCurve targetLine = m_vLine; Line line = (Line) curve; XYZ lineStartPoint = line.GetEndPoint( 0 ); XYZ lineEndPoint = line.GetEndPoint( 1 ); XYZ direction = lineEndPoint - lineStartPoint; Line dimensionLine = null; if( Math.Abs( direction.Y ) < 0.0001 ) { targetLine = m_hLine; XYZ dimensionLineStart = new XYZ( lineStartPoint.X + 5, lineStartPoint.Y, 0 ); XYZ dimensionLineEnd = new XYZ( dimensionLineStart.X, dimensionLineStart.Y + 10, 0 ); dimensionLine = Line.CreateBound( dimensionLineStart, dimensionLineEnd ); } else { targetLine = m_vLine; XYZ dimensionLineStart = new XYZ( lineStartPoint.X, lineStartPoint.Y + 5, 0 ); XYZ dimensionLineEnd = new XYZ( dimensionLineStart.X + 10, dimensionLineStart.Y, 0 ); dimensionLine = Line.CreateBound( dimensionLineStart, dimensionLineEnd ); } ReferenceArray references = new ReferenceArray(); references.Append( curve.Reference ); references.Append( targetLine.GeometryCurve.Reference ); Transaction t = new Transaction( m_doc, "Create dimension" ); t.Start(); m_doc.Create.NewDimension( m_targetView, dimensionLine, references ); t.Commit(); } }
private int ConvertDWG(Document doc, ImportInstance currentDWG) { string docType; if (doc.IsFamilyDocument == true) { docType = "family"; } else { docType = "project"; } string lineStyleToUse; int counter = 0; List <GeometryObject> curGeometryList = GetLinkedDWGCurves(currentDWG); //Check and set linestyletouse if (doesLinestyleExist(doc, "*Solid (02-Thin)") == true) { lineStyleToUse = "*Solid (02-Thin)"; } else { lineStyleToUse = "Thin Lines"; } using (Transaction tx = new Transaction(doc)) { tx.Start("Convert DWG to Lines"); if (curGeometryList.Count != 0) { //create detail lines for elements in geometry list foreach (GeometryObject curGeom in curGeometryList) { if (curGeom.GetType().FullName == "Autodesk.Revit.DB.PolyLine") { //Since Revit can't handle polylines PolyLine curPolyLine = curGeom as PolyLine; IList <XYZ> ptsList = curPolyLine.GetCoordinates(); for (int i = 0; i <= ptsList.Count - 2; i++) { try { if (docType == "project") { //project file DetailCurve newLine = doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); newLine.LineStyle = getLinestyleByName(doc, lineStyleToUse) as Element; } else { //family file try { DetailCurve newLine = doc.FamilyCreate.NewDetailCurve(doc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); newLine.LineStyle = getLinestyleByName(doc, lineStyleToUse) as Element; } catch { TaskDialog.Show("Error", " Cannot create detail line in this type of family."); return(0); } } } catch { //Debug.Print("Could not create polyline"); } counter = counter + 1; } } else { //create a line in the current view try { if (docType == "project") { DetailCurve newLine = doc.Create.NewDetailCurve(doc.ActiveView, curGeom as Curve); newLine.LineStyle = getLinestyleByName(doc, lineStyleToUse) as Element; } else { try { DetailCurve newLine = doc.FamilyCreate.NewDetailCurve(doc.ActiveView, curGeom as Curve); newLine.LineStyle = getLinestyleByName(doc, lineStyleToUse) as Element; } catch { TaskDialog.Show("Error", " Cannot create detail line in this type of family."); return(0); } } counter = counter + 1; } catch { //Debug.Print("Could not create polyline"); } } } } tx.Commit(); } return(counter); }
/// <summary> /// 根据 地库外墙线线圈 找到 圈内的 障碍物区域 主次车道中心线 /// </summary> public CurveArray RegionConditionGrab(Document doc, List <Element> selEles, out CurveArray roadCurves) { var obstacleLineStyleId = _Methods.GetTarGraphicsStyleId(doc, "地库_障碍物边界线"); CurveArray mianRoadCurves = new CurveArray(); List <CurveLoop> ObstacleLoops = new List <CurveLoop>(); roadCurves = new CurveArray(); List <ElementId> fixedParkingFS = new List <ElementId>(); List <ElementId> unfixedParkingFS = new List <ElementId>(); List <ElementId> othersObstals = new List <ElementId>(); List <ElementId> directShapes = new List <ElementId>(); List <ElementId> filledRegions = new List <ElementId>(); List <ElementId> filledRegions_singleParkignPlace = new List <ElementId>(); List <Curve> allCurves = new List <Curve>(); #region 找到地库_地库外墙线的填充区域Id //ElementId baseWallFilledRegionId = new ElementId(-1); //foreach (Element _ele in selEles) //{ // if (_ele is Group) // { // Group _group = _ele as Group; // if (_group.Name.Contains("地库外墙线")) // { // List<ElementId> elementIds = _group.GetMemberIds().ToList(); // List<Element> elements = _Methods.EleIdsToEles(doc, elementIds); // elements.ForEach(p => // { // if (p is FilledRegion) baseWallFilledRegionId = p.Id ; // }); // } // } //} #endregion foreach (Element _ele in selEles) { if (_ele is DetailCurve) { DetailCurve detailCurve = _ele as DetailCurve; Curve _c = detailCurve.GeometryCurve; GraphicsStyle graphicsStyle = detailCurve.LineStyle as GraphicsStyle; if (graphicsStyle.Name == "地库_主车道中心线") { _c.SetGraphicsStyleId(graphicsStyle.Id); mianRoadCurves.Append(_c); } else if (graphicsStyle.Name == "地库_次车道中心线") { _c.SetGraphicsStyleId(graphicsStyle.Id); roadCurves.Append(_c); } } else if (_ele is FilledRegion) { string filledRegionTypeName = doc.GetElement(_ele.GetTypeId()).Name; if (filledRegionTypeName == "地库_单个停车区域") { filledRegions_singleParkignPlace.Add(_ele.Id); } else if (filledRegionTypeName.Contains("结构轮廓")) { FilledRegion filledRegion = _ele as FilledRegion; filledRegions.Add(_ele.Id); ObstacleLoops.AddRange(filledRegion.GetBoundaries()); } } else if (_ele is FamilyInstance) { if (_ele.Name == "停车位_详图线") { if (_ele.get_Parameter(CMD.parkingFixedGid).AsValueString() == "是") { fixedParkingFS.Add(_ele.Id); } else if (_ele.get_Parameter(CMD.parkingFixedGid).AsValueString() == "否") { unfixedParkingFS.Add(_ele.Id); } } else if (_ele.Name.Contains("坡道-直线")) { othersObstals.Add(_ele.Id); double wight = Methods.MilliMeterToFeet(6000) / 2; double height = Methods.MilliMeterToFeet(12000); Transform transform = (_ele as FamilyInstance).GetTransform(); XYZ leftDownPoint = new XYZ(0, -wight, 0); XYZ leftUpPoint = new XYZ(0, wight, 0); XYZ rightUpPoint = new XYZ(height, wight, 0); XYZ rightDownPoint = new XYZ(height, -wight, 0); XYZ _leftDownPoint = transform.OfPoint(leftDownPoint); XYZ _leftUpPoint = transform.OfPoint(leftUpPoint); XYZ _rightUpPoint = transform.OfPoint(rightUpPoint); XYZ _rightDownPoint = transform.OfPoint(rightDownPoint); Curve curve = Line.CreateBound(_leftDownPoint, _leftUpPoint) as Curve; Curve curve1 = Line.CreateBound(_leftUpPoint, _rightUpPoint) as Curve; Curve curve2 = Line.CreateBound(_rightUpPoint, _rightDownPoint) as Curve; Curve curve3 = Line.CreateBound(_rightDownPoint, _leftDownPoint) as Curve; curve.SetGraphicsStyleId(obstacleLineStyleId); curve1.SetGraphicsStyleId(obstacleLineStyleId); curve2.SetGraphicsStyleId(obstacleLineStyleId); curve3.SetGraphicsStyleId(obstacleLineStyleId); allCurves.Add(curve); allCurves.Add(curve); allCurves.Add(curve); allCurves.Add(curve); } } else if (_ele is DirectShape) { directShapes.Add(_ele.Id); } } #region 抓取属性线 将数据反馈给类字段 foreach (Curve item in mianRoadCurves) { allCurves.Add(item); } foreach (Curve item in roadCurves) { allCurves.Add(item); } this.fixedParkingFS = fixedParkingFS; this.unfixedParkingFS = unfixedParkingFS; this.filledRegions = filledRegions; this.filledRegions_singleParkignPlace = filledRegions_singleParkignPlace; this.othersObstals = othersObstals; this.directShapes = directShapes; #endregion #region 设置obstal curve的属性 foreach (CurveLoop curveLoop in ObstacleLoops) { foreach (Curve curve in curveLoop) { curve.SetGraphicsStyleId(obstacleLineStyleId); allCurves.Add(curve); } } this.allCurves = allCurves; #endregion return(mianRoadCurves); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { XYZ origin = uidoc.Selection.PickPoint("Select insertion point"); double width = 0.2; //feet Category c = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); CategoryNameMap subcats = c.SubCategories; double offset = 0; TextNoteOptions options = new TextNoteOptions(); options.HorizontalAlignment = HorizontalTextAlignment.Left; options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType); var dict = new SortedDictionary <string, GraphicsStyle>(); foreach (Category lineStyle in subcats) { GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection); dict.Add(gs.Name, gs); } var output = dict.OrderBy(e => e.Key).Select(e => new { graphicStyle = e.Value, linestyleName = e.Key }).ToList(); using (Transaction t = new Transaction(doc, "Place Lines")) { t.Start(); //foreach( Line item in ordered) { foreach (var item in output) { // GraphicsStyle gs = lineStyle.GetGraphicsStyle(GraphicsStyleType.Projection); XYZ newOrigin = new XYZ(origin.X, origin.Y + offset, 0); XYZ offsetPoint = new XYZ(origin.X + width, origin.Y + offset, 0); Line L1 = Line.CreateBound(newOrigin, offsetPoint); try { TextNote note = TextNote.Create(doc, doc.ActiveView.Id, new XYZ(origin.X - 0.2, origin.Y + offset + 0.01, 0), 0.2, item.linestyleName, options); DetailCurve e = doc.Create.NewDetailCurve(doc.ActiveView, L1); Parameter p = e.LookupParameter("Line Style"); p.Set(item.graphicStyle.Id); } catch { } offset -= 0.03; } t.Commit(); } return(Result.Succeeded); } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); return(Result.Failed); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiApp = commandData.Application; UIDocument uidoc = uiApp.ActiveUIDocument; Document doc = uidoc.Document; if (IsExistLineStyle(doc, "房间边界线")) { } else { ////生成线样式 using (Transaction ts = new Transaction(doc, "LineStyle")) { ts.Start(); Category lineCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); Category newCategory = doc.Settings.Categories.NewSubcategory(lineCategory, "房间边界线"); Color newColor = new Color(255, 0, 0); newCategory.LineColor = newColor; newCategory.SetLineWeight(1, GraphicsStyleType.Projection); ts.Commit(); } } Transaction ts2 = new Transaction(doc, "BIM"); ts2.Start(); Reference refer = uidoc.Selection.PickObject(ObjectType.Element, ""); Room room = doc.GetElement(refer) as Room; SpatialElementBoundaryOptions opt = new SpatialElementBoundaryOptions(); opt.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish; CurveArray array = new CurveArray(); IList <IList <BoundarySegment> > loops = room.GetBoundarySegments(opt); foreach (var loop in loops) { foreach (BoundarySegment seg in loop) { Curve curve = seg.GetCurve(); DetailCurve dc = doc.Create.NewDetailCurve(uidoc.ActiveView, curve); if (BackLineStyle(doc) != null) { SetLineStyle(BackLineStyle(doc), dc); } array.Append(dc.GeometryCurve); } break; } //foreach(Curve a in array) //{ // Debug.Write($"{a.GetEndPoint(0).X.ToString()}\n"); // Debug.Write($"{a.GetEndPoint(1).X.ToString()}\n"); //} //foreach (Curve a in array) //{ // Debug.Write($"{a.GetEndPoint(0).Y.ToString()}\n"); // Debug.Write($"{a.GetEndPoint(1).Y.ToString()}\n"); //} CreateFloor(doc, array); ts2.Commit(); return(Result.Succeeded); }
private void WriteElementGeometry(int elementId) { FilteredElementCollector viewCollector = new FilteredElementCollector(m_doc); viewCollector.OfClass(typeof(ViewPlan)); Func <ViewPlan, bool> isLevel1FloorPlan = v => !v.IsTemplate && v.Name == "Level 1" && v.ViewType == ViewType.FloorPlan; m_targetView = viewCollector.Cast <ViewPlan>().First <ViewPlan>(isLevel1FloorPlan); Transaction createCurve = new Transaction(m_doc, "Create reference curves"); createCurve.Start(); const double xReferenceLocation = 30; Line vLine = Line.CreateBound(new XYZ(xReferenceLocation, 0, 0), new XYZ(xReferenceLocation, 20, 0)); m_vLine = m_doc.Create.NewDetailCurve(m_targetView, vLine); const double yReferenceLocation = -10; Line hLine = Line.CreateBound(new XYZ(0, yReferenceLocation, 0), new XYZ(20, yReferenceLocation, 0)); m_hLine = m_doc.Create.NewDetailCurve(m_targetView, hLine); createCurve.Commit(); Element e = m_doc.GetElement(new ElementId(elementId)); Options options = new Options(); options.ComputeReferences = true; options.IncludeNonVisibleObjects = true; options.View = m_targetView; GeometryElement geomElem = e.get_Geometry(options); foreach (GeometryObject geomObj in geomElem) { if (geomObj is Solid) { WriteSolid((Solid)geomObj); } else if (geomObj is GeometryInstance) { TraverseGeometryInstance((GeometryInstance)geomObj); } else { m_writer.WriteLine("Something else - " + geomObj.GetType().Name); } } foreach (Curve curve in m_referencePlaneReferences) { // Try to get the geometry object from reference Reference curveReference = curve.Reference; GeometryObject geomObj = e.GetGeometryObjectFromReference(curveReference); if (geomObj != null) { m_writer.WriteLine("Curve reference leads to: " + geomObj.GetType().Name); } } // Dimension to reference curves foreach (Curve curve in m_referencePlaneReferences) { DetailCurve targetLine = m_vLine; Line line = (Line)curve; XYZ lineStartPoint = line.GetEndPoint(0); XYZ lineEndPoint = line.GetEndPoint(1); XYZ direction = lineEndPoint - lineStartPoint; Line dimensionLine = null; if (Math.Abs(direction.Y) < 0.0001) { targetLine = m_hLine; XYZ dimensionLineStart = new XYZ(lineStartPoint.X + 5, lineStartPoint.Y, 0); XYZ dimensionLineEnd = new XYZ(dimensionLineStart.X, dimensionLineStart.Y + 10, 0); dimensionLine = Line.CreateBound(dimensionLineStart, dimensionLineEnd); } else { targetLine = m_vLine; XYZ dimensionLineStart = new XYZ(lineStartPoint.X, lineStartPoint.Y + 5, 0); XYZ dimensionLineEnd = new XYZ(dimensionLineStart.X + 10, dimensionLineStart.Y, 0); dimensionLine = Line.CreateBound(dimensionLineStart, dimensionLineEnd); } ReferenceArray references = new ReferenceArray(); references.Append(curve.Reference); references.Append(targetLine.GeometryCurve.Reference); Transaction t = new Transaction(m_doc, "Create dimension"); t.Start(); m_doc.Create.NewDimension(m_targetView, dimensionLine, references); t.Commit(); } }
public MaterialsAMLPaletteRequest(UIApplication uiApp, String text) { RVTDocument doc = uiApp.ActiveUIDocument.Document; MaterialsAMLPalette materialsPalette = BARevitTools.Application.thisApp.newMainUi.materialsAMLPalette; //Get the versioned symbol family FamilySymbol familySymbol = null; string versionedFamily = RVTOperations.GetVersionedFamilyFilePath(uiApp, Properties.Settings.Default.RevitIDAccentMatTag); //Try loading the family symbol Transaction loadSymbolTransaction = new Transaction(doc, "LoadFamilySymbol"); loadSymbolTransaction.Start(); try { try { IFamilyLoadOptions loadOptions = new RVTFamilyLoadOptions(); doc.LoadFamilySymbol(versionedFamily, "Legend Tag (Fake)", loadOptions, out FamilySymbol symb); familySymbol = symb; } catch { MessageBox.Show(String.Format("Could not get the 'Legend Tag (Fake)' type from {0}", versionedFamily), "Family Symbol Load Error"); } loadSymbolTransaction.Commit(); } catch (Exception transactionException) { loadSymbolTransaction.RollBack(); MessageBox.Show(transactionException.ToString()); } //Get the line style to use, or create the default Element lineStyle = null; if (materialsPalette.paletteMaterialComboBox.Text == "Default") { try { lineStyle = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines).SubCategories.get_Item("6 BA ID ACCENT").GetGraphicsStyle(GraphicsStyleType.Projection); } catch { try { Category linesCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); Category newLineStyleCategory = doc.Settings.Categories.NewSubcategory(linesCategory, "6 BA ID ACCENT"); newLineStyleCategory.LineColor = new Color(0, 0, 0); newLineStyleCategory.SetLineWeight(6, GraphicsStyleType.Projection); newLineStyleCategory.SetLinePatternId(LinePatternElement.GetSolidPatternId(), GraphicsStyleType.Projection); doc.Regenerate(); lineStyle = newLineStyleCategory.GetGraphicsStyle(GraphicsStyleType.Projection); } catch (Exception e) { MessageBox.Show(e.ToString()); } } } else { lineStyle = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines).SubCategories.get_Item("ID " + materialsPalette.paletteMaterialComboBox.Text).GetGraphicsStyle(GraphicsStyleType.Projection); } //Assure the view being used is a floor plan if (doc.ActiveView.ViewType != ViewType.FloorPlan) { MessageBox.Show("This tool should be used ina a Floor Plan or Area Plan view"); } else { //Create a loop for picking points. Change the palette background color based on the number of points picked List <XYZ> pickedPoints = new List <XYZ>(); bool breakLoop = false; int pickCount = 0; while (breakLoop == false) { try { //Have the user begin picking points. The number of clicks to start the UI color change is 1 because the first click is usually to activate the window. XYZ point = uiApp.ActiveUIDocument.Selection.PickPoint(Autodesk.Revit.UI.Selection.ObjectSnapTypes.Endpoints, "Click points for the line to follow. Then click once to the side where the lines should be drawn. Hit ESC to finish"); pickedPoints.Add(point); if (pickCount == 1) { materialsPalette.BackColor = System.Drawing.Color.Firebrick; } else if (pickCount == 2) { materialsPalette.BackColor = System.Drawing.Color.Orange; } else if (pickCount > 2) { //After three clicks in the window, the user has made the minimum point selection to generate the lines from the start, end, and positive side points. materialsPalette.BackColor = System.Drawing.Color.GreenYellow; } else { ; } pickCount++; } catch { materialsPalette.BackColor = MaterialsAMLPalette.DefaultBackColor; breakLoop = true; } } //Get rid of the first point from clicking into the Revit view. This point is not needed. pickedPoints.RemoveAt(0); if (pickedPoints.Count > 2) { Transaction createLinesTransaction = new Transaction(doc, "CreateAccentLines"); createLinesTransaction.Start(); try { //These points will be used in determining the start, end, and room points XYZ firstPoint = pickedPoints[0]; XYZ roomPoint = pickedPoints[pickedPoints.Count - 1]; XYZ lastPoint = pickedPoints[pickedPoints.Count - 2]; //Create a list of points for the polyline that excludes the room point List <XYZ> polyLinePoints = new List <XYZ>(); for (int i = 0; i < pickedPoints.Count - 1; i++) { polyLinePoints.Add(pickedPoints[i]); } //Create a polyline from the list of picked points and then get make lines from the points on the poly line PolyLine guidePolyLine = PolyLine.Create(polyLinePoints); IList <XYZ> polyPoints = guidePolyLine.GetCoordinates(); List <Line> guideLines = new List <Line>(); for (int i = 0; i < polyLinePoints.Count - 1; i++) { guideLines.Add(Line.CreateBound(polyLinePoints[i], polyLinePoints[i + 1])); } //Get the direction of the line offset by measuring the first offset for positive and negative values and comparing their distances with the room point bool positiveZ = false; List <Line> offsetLines = new List <Line>(); Line positiveOffsetLine = guideLines.Last().CreateOffset(0.6666666667d, XYZ.BasisZ) as Line; Line negativeOffsetLine = guideLines.Last().CreateOffset(-0.6666666667d, XYZ.BasisZ) as Line; XYZ positiveOffsetMidPoint = positiveOffsetLine.Evaluate(0.5d, true); XYZ negativeOffsetMidPoint = negativeOffsetLine.Evaluate(0.5d, true); Double positiveOffsetDistance = positiveOffsetMidPoint.DistanceTo(roomPoint); Double negativeOffsetDistance = negativeOffsetMidPoint.DistanceTo(roomPoint); //If the positive offset side resulted in a shorter distance to the point inside the room, then the offset should have a positive Z normal. if (positiveOffsetDistance < negativeOffsetDistance) { positiveZ = true; } //Knowing whether or not to use a positive or negative offset, begin creating offset lines for each guide line foreach (Line guideLine in guideLines) { if (positiveZ) { offsetLines.Add(guideLine.CreateOffset(0.6666666667d, XYZ.BasisZ) as Line); } else { offsetLines.Add(guideLine.CreateOffset(-0.6666666667d, XYZ.BasisZ) as Line); } } //Determine if the number of line segments is 1 or more Line firstLine = offsetLines.First(); Line lastLine = null; if (offsetLines.Count > 1) { lastLine = offsetLines.Last(); } //If there is only one line segment, both end operations must be performed on it if (lastLine == null) { double lineLength = firstLine.Length; double fractionOfLength = 0.6666666667d / lineLength; //Checking fractions to ensure they are not greater than 1 for the normalization if (fractionOfLength > 1) { fractionOfLength = 0.25d; } //Re-evaluating where to place the start and end point of the line XYZ shiftedStartPoint = firstLine.Evaluate(fractionOfLength, true); XYZ shiftedEndPoint = firstLine.Evaluate(1 - fractionOfLength, true); firstLine = Line.CreateBound(shiftedStartPoint, shiftedEndPoint); //Creating the angled corner lines Line firstCornerLine = Line.CreateBound(firstPoint, firstLine.GetEndPoint(0)); Line lastCornerLine = Line.CreateBound(lastPoint, firstLine.GetEndPoint(1)); //Create the detail lines from the lines DetailCurve newAccentLine1 = doc.Create.NewDetailCurve(doc.ActiveView, firstCornerLine); DetailCurve newAccentLine2 = doc.Create.NewDetailCurve(doc.ActiveView, firstLine); DetailCurve newAccentLine3 = doc.Create.NewDetailCurve(doc.ActiveView, lastCornerLine); //Assign a line style to the newly created detail lines newAccentLine1.LineStyle = lineStyle; newAccentLine2.LineStyle = lineStyle; newAccentLine3.LineStyle = lineStyle; XYZ tagPlacementPoint = firstLine.Evaluate(0.5d, true); XYZ direction = firstLine.Direction; Line axisLine = Line.CreateUnbound(tagPlacementPoint, XYZ.BasisZ); double rotationAngle = direction.AngleTo(XYZ.BasisX); //Get the midpoint of the line, its direction, and create the rotation and axis if (familySymbol != null) { //Create the tag instance FamilyInstance newTag = doc.Create.NewFamilyInstance(tagPlacementPoint, familySymbol, doc.ActiveView); //Rotate the new tag instance ElementTransformUtils.RotateElement(doc, newTag.Id, axisLine, rotationAngle); } createLinesTransaction.Commit(); } //If there is more than one line segment, an operation must be performed on the start and end of the start and end lines, respectively else { List <Line> linesToDraw = new List <Line>(); // Get the normalized value for 8" relative to the lengths of the start and end lines double firstLineLength = firstLine.Length; double fractionOfFirstLine = 0.6666666667 / firstLineLength; double lastLineLength = lastLine.Length; double fractionOfLastLine = 0.666666667 / lastLineLength; //Checking fractions to ensure they are not greater than 1 for the normalization if (fractionOfFirstLine > 1) { fractionOfFirstLine = 0.25d; } if (fractionOfLastLine > 1) { fractionOfLastLine = 0.25d; } //Shift the ends of the start and end lines by finding the point along the line relative to the normalized 8" value XYZ shiftedStartPoint = firstLine.Evaluate(fractionOfFirstLine, true); XYZ shiftedEndPoint = lastLine.Evaluate(1 - fractionOfLastLine, true); //Reset the start and end lines with the new shifted points firstLine = Line.CreateBound(shiftedStartPoint, firstLine.GetEndPoint(1)); lastLine = Line.CreateBound(lastLine.GetEndPoint(0), shiftedEndPoint); linesToDraw.Add(firstLine); //If there are only 3 offset lines, there will be just one middle segment if (offsetLines.Count == 3) { linesToDraw.Add(offsetLines[1]); } //If there are more than three offset lines, there will be more than one middle line segment else { List <Line> middleLines = offsetLines.GetRange(1, offsetLines.Count - 2); foreach (Line middleLine in middleLines) { linesToDraw.Add(middleLine); } } linesToDraw.Add(lastLine); //For the lines to draw, intersect them with the next line in the list and reset their start and end points to be the intersection for (int i = 0; i < linesToDraw.Count - 1; i++) { Line line1 = linesToDraw[i]; Line scaledLine1 = Line.CreateUnbound(line1.GetEndPoint(1), line1.Direction); Line line2 = linesToDraw[i + 1]; Line scaledLine2 = Line.CreateUnbound(line2.GetEndPoint(0), line2.Direction.Negate()); SetComparisonResult intersectionResult = scaledLine1.Intersect(scaledLine2, out IntersectionResultArray results); if (intersectionResult == SetComparisonResult.Overlap) { IntersectionResult result = results.get_Item(0); Line newLine1 = Line.CreateBound(line1.GetEndPoint(0), result.XYZPoint); Line newLine2 = Line.CreateBound(result.XYZPoint, line2.GetEndPoint(1)); linesToDraw[i] = newLine1; linesToDraw[i + 1] = newLine2; } } //Create the angled corner lines at the start and end of the line chain Line firstCornerLine = Line.CreateBound(firstPoint, firstLine.GetEndPoint(0)); Line lastCornerLine = Line.CreateBound(lastPoint, lastLine.GetEndPoint(1)); linesToDraw.Add(firstCornerLine); linesToDraw.Add(lastCornerLine); //Create each line as a detail line foreach (Line apiLine in linesToDraw) { DetailCurve newAccentLine = doc.Create.NewDetailCurve(doc.ActiveView, apiLine); newAccentLine.LineStyle = lineStyle; } //Declare some stuff for use in the symbol placement Line firstMiddleLine = linesToDraw[0]; Line lastMiddleLine = linesToDraw[linesToDraw.Count - 3]; XYZ firstTagPoint = firstMiddleLine.Evaluate(0.5d, true); XYZ lastTagPoint = lastMiddleLine.Evaluate(0.5d, true); XYZ firstDirection = firstMiddleLine.Direction; XYZ lastDirection = lastMiddleLine.Direction; Line firstAxisLine = Line.CreateUnbound(firstTagPoint, XYZ.BasisZ); Line lastAxisLine = Line.CreateUnbound(lastTagPoint, XYZ.BasisZ); double firstRotation = firstDirection.AngleTo(XYZ.BasisX); double lastRotation = lastDirection.AngleTo(XYZ.BasisX); if (familySymbol != null) { //Create tag at the beginning of the middle lines FamilyInstance firstTag = doc.Create.NewFamilyInstance(firstTagPoint, familySymbol, doc.ActiveView); ElementTransformUtils.RotateElement(doc, firstTag.Id, firstAxisLine, firstRotation); //Create a tag at the end of the middle lines if there are more than 2 middle lines if (linesToDraw.Count > 4) { FamilyInstance lastTag = doc.Create.NewFamilyInstance(lastTagPoint, familySymbol, doc.ActiveView); ElementTransformUtils.RotateElement(doc, lastTag.Id, lastAxisLine, lastRotation); } } createLinesTransaction.Commit(); } } catch (Exception e) { //Suppose the user closed the palette too soon. This will remind them to keep it open. if (BARevitTools.Application.thisApp.newMainUi.materialsAMLPalette == null) { MessageBox.Show("AML Picker was closed prematurely. Please keep the picker open until the lines are drawn."); } else { //Otherwise, if some other error occurred, show the exception MessageBox.Show(e.ToString()); } createLinesTransaction.RollBack(); } } else { ; } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uiDoc = commandData.Application.ActiveUIDocument; Document doc = uiDoc.Document; View activeview = uiDoc.ActiveView; double radius = 12000 / 304.8; double offset = 2000 / 304.8; FilteredElementCollector collector_temp = new FilteredElementCollector(doc); collector_temp.OfCategory(BuiltInCategory.OST_Lines).WhereElementIsNotElementType(); DetailLine dl_temp = null; foreach (Element elem in collector_temp) { if (elem is DetailLine) { dl_temp = elem as DetailLine; } } if (dl_temp == null) { TaskDialog.Show("goa", "请用符号线绘制路中线"); return(Result.Failed); } ICollection <ElementId> collection_id_linestyle = dl_temp.GetLineStyleIds(); List <GraphicsStyle> list_linestyle = new List <GraphicsStyle>(); foreach (ElementId id in collection_id_linestyle) { list_linestyle.Add(doc.GetElement(id) as GraphicsStyle); } UI ui = new UI(); ui.combobox.ItemsSource = list_linestyle; int l = -1; foreach (GraphicsStyle gs in list_linestyle) { l++; if (gs.Name == "C-FIRE-FLOW") { break; } } ui.combobox.SelectedIndex = l; ui.ShowDialog(); GraphicsStyle graphicsstyle = ui.combobox.SelectedItem as GraphicsStyle; radius = Convert.ToDouble(ui.textbox_radius.Text) / 304.8; offset = Convert.ToDouble(ui.textbox_offset.Text) / 2 / 304.8; //选择所有线 IList <Element> list_DetailLines = uiDoc.Selection.PickElementsByRectangle(new SelectionFilter_DetailLine(), "选择符号线"); List <Line> list_line = new List <Line>(); foreach (Element elem in list_DetailLines) { DetailLine dl = elem as DetailLine; Line line = dl.GeometryCurve as Line; list_line.Add(line); } // List<Line> list_line_split = new List<Line>(); //先打散所有线段. for (int i = 0; i < list_line.Count; i++) { for (int j = i + 1; j < list_line.Count; j++) { if (list_line[i].Intersect(list_line[j]) == SetComparisonResult.Overlap) { List <Line> temps = SplitLine(list_line[i], list_line[j]); if (temps == null) { continue; } list_line.RemoveAt(j); list_line.RemoveAt(i); list_line.AddRange(temps); i--; break; } } } List <Arc> list_arc = new List <Arc>(); //单线模式下,将两根线的转折点做倒角(排除3根及以上线汇到一个点的情况) for (int i = 0; i < list_line.Count; i++) { for (int c = 0; c < 2; c++) { int temp = i; List <int> list_int = new List <int>(); //收集与 i 线段 一个端点重合的 线段的索引值 XYZ point_i = list_line[i].GetEndPoint(c); //第一根线的第一个端点 for (int j = 0; j < list_line.Count; j++) //判断 i 线段与 j 线段的关系 { if (j == i) { continue; } XYZ point_start_j = list_line[j].GetEndPoint(0); //拿出 j 线段的两个端点 XYZ point_end_j = list_line[j].GetEndPoint(1); if (point_i.IsAlmostEqualTo(point_start_j) || point_i.IsAlmostEqualTo(point_end_j)) //如果 i 线段与 j 线段 端点重合 { list_int.Add(j); //如果重合,则把j索引值拿到列表中 } } if (list_int.Count == 1)//基于条件 判断是否倒角 如果收集的重合线段索引值只有1个,则开展倒角 { int j = list_int[0]; Line newline1; Line newline2; Arc arc = Chamfer(list_line[i], list_line[j], radius, out newline1, out newline2);//进行倒角 list_arc.Add(arc); list_line[i] = newline1; list_line[j] = newline2; i--; continue; } if (temp != i) { break; } } } //偏移,从单线变为双线. List <Arc> list_temp = new List <Arc>(); foreach (Arc arc in list_arc) { list_temp.Add(arc.CreateOffset(offset, new XYZ(0, 0, -1)) as Arc); list_temp.Add(arc.CreateOffset(offset, new XYZ(0, 0, 1)) as Arc); } list_arc = list_temp; List <Line> list_temp2 = new List <Line>(); foreach (Line line in list_line) { list_temp2.Add(line.CreateOffset(offset, new XYZ(0, 0, -1)) as Line); list_temp2.Add(line.CreateOffset(offset, new XYZ(0, 0, 1)) as Line); } list_line = list_temp2; //将偏移后的线,倒角. List <Arc> list_arc_nooffset = new List <Arc>(); for (int i = 0; i < list_line.Count; i++) { for (int j = 0; j < list_line.Count; j++) { if (i == j) { continue; } //排除没有交点的线 IntersectionResultArray intersectionResultArray; XYZ intersection; if (list_line[i].Intersect(list_line[j], out intersectionResultArray) == SetComparisonResult.Overlap) { intersection = intersectionResultArray.get_Item(0).XYZPoint; } else { continue; } //排除首尾相接的线.(因为之前单线打断了以后才偏移,存在很多首尾相接的线) XYZ point_start_temp = list_line[i].GetEndPoint(0); XYZ point_end_temp = list_line[i].GetEndPoint(1); XYZ point_start_temp2 = list_line[j].GetEndPoint(0); XYZ point_end_temp2 = list_line[j].GetEndPoint(1); if (point_start_temp.IsAlmostEqualTo(point_start_temp2) || point_start_temp.IsAlmostEqualTo(point_end_temp2) || point_end_temp.IsAlmostEqualTo(point_start_temp2) || point_end_temp.IsAlmostEqualTo(point_end_temp2)) { continue; } Line newline1; Line newline2; Arc arc = Chamfer(list_line[i], list_line[j], radius, out newline1, out newline2); if (arc == null) { continue; } list_arc_nooffset.Add(arc); list_line[i] = newline1; list_line[j] = newline2; } } using (Transaction offset_line = new Transaction(doc)) { offset_line.Start("start"); foreach (Arc arc in list_arc_nooffset) { DetailCurve dc1 = doc.Create.NewDetailCurve(activeview, arc); DetailCurve dc2 = doc.Create.NewDetailCurve(activeview, arc); dc1.LineStyle = graphicsstyle; dc2.LineStyle = graphicsstyle; } foreach (Arc arc in list_arc) { DetailCurve dc1 = doc.Create.NewDetailCurve(activeview, arc); DetailCurve dc2 = doc.Create.NewDetailCurve(activeview, arc); dc1.LineStyle = graphicsstyle; dc2.LineStyle = graphicsstyle; } foreach (Line line in list_line) { DetailCurve dc1 = doc.Create.NewDetailCurve(activeview, line); DetailCurve dc2 = doc.Create.NewDetailCurve(activeview, line); dc1.LineStyle = graphicsstyle; dc2.LineStyle = graphicsstyle; } offset_line.Commit(); } return(Result.Succeeded); }
private void Stream( ArrayList data, DetailCurve detCurve ) { data.Add( new Snoop.Data.ClassSeparator( typeof( DetailCurve ) ) ); data.Add( new Snoop.Data.Object( "Geometry curve", detCurve.GeometryCurve ) ); data.Add( new Snoop.Data.Object( "Sketch plane", detCurve.SketchPlane ) ); data.Add( new Snoop.Data.ElementId( "Line style", detCurve.LineStyle.Id, m_app.ActiveUIDocument.Document ) ); data.Add( new Snoop.Data.Enumerable( "Line styles", detCurve.GetLineStyleIds(), m_app.ActiveUIDocument.Document ) ); DetailArc detArc = detCurve as DetailArc; if( detArc != null ) { Stream( data, detArc ); return; } DetailEllipse detEllipse = detCurve as DetailEllipse; if( detEllipse != null ) { Stream( data, detEllipse ); return; } DetailLine detLine = detCurve as DetailLine; if( detLine != null ) { Stream( data, detLine ); return; } DetailNurbSpline detSpline = detCurve as DetailNurbSpline; if( detSpline != null ) { Stream( data, detSpline ); return; } }
public Result Execute(ExternalCommandData commandData, ref string messages, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Selection sel = uidoc.Selection; Transaction trans = new Transaction(doc, "ExComm"); trans.Start(); DWGExportOptions options = new DWGExportOptions(); //SUPPORT.PARAMETER.PARAMETER Para = new SUPPORT.PARAMETER.PARAMETER(); View view = doc.ActiveView; ElementId eleid = view.Id; ICollection <ElementId> views = new List <ElementId>(); FilteredElementCollector filter = new FilteredElementCollector(doc); FilteredElementCollector Filter = filter.OfCategory(BuiltInCategory.OST_Views).WhereElementIsNotElementType(); IList <Element> list = Filter.ToElements(); IList <Element> lishname = new List <Element>(); ViewDrafting drafting = null; ElementId newlegend = null; string currentview = doc.ActiveView.ViewName; string test = "Zz_" + currentview + "##"; ElementId id = null; View viewlegend = null; foreach (var ele1 in list) { Parameter parameter = ele1.get_Parameter(BuiltInParameter.VIEW_NAME); string viewname = parameter.AsString(); ViewFamilyType vd = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>() .FirstOrDefault(q => q.ViewFamily == ViewFamily.Drafting); views.Add(doc.ActiveView.Id); doc.Export(@"C:\Autodesk", "exportdwg.dwg", views, options); drafting = ViewDrafting.Create(doc, vd.Id); doc.Regenerate(); DWGImportOptions importOptions = new DWGImportOptions(); importOptions.ColorMode = ImportColorMode.BlackAndWhite; doc.Import(@"C:\Autodesk\\exportdwg.dwg", importOptions, drafting, out id); try { drafting.Name = test; trans.Commit(); commandData.Application.ActiveUIDocument.ActiveView = drafting; } catch { TaskDialog.Show("ERROR", "SECTION NÀY ĐÃ ĐƯỢC TẠO FROZEN"); trans.RollBack(); break; } break; } using (Transaction tx = new Transaction(doc)) { tx.Start("Transaction Name"); Element curElem = doc.GetElement(id); ImportInstance curLink = (ImportInstance)curElem; List <GeometryObject> curveobject = GetLinkedDWGCurves(curLink, doc); foreach (GeometryObject curGeom in curveobject) { if (curGeom.GetType() == typeof(PolyLine)) { // create polyline in current view PolyLine curPolyline = (PolyLine)curGeom; // get polyline coordinate points IList <XYZ> ptsList = curPolyline.GetCoordinates(); for (var i = 0; i <= ptsList.Count - 2; i++) { // create detail curve from polyline coordinates try { DetailCurve newDetailLine = doc.Create.NewDetailCurve(doc.ActiveView, Line.CreateBound(ptsList[i], ptsList[i + 1])); } catch { } } } else { try { DetailCurve newDetailLine = doc.Create.NewDetailCurve(doc.ActiveView, (Curve)curGeom); } catch { } } } FilteredElementCollector legCollector = new FilteredElementCollector(doc).OfClass(typeof(View)).WhereElementIsNotElementType(); List <View> alllegends = new List <View>(); foreach (ElementId eid in legCollector.ToElementIds()) { View v = doc.GetElement(eid) as View; if (v.ViewType == ViewType.Legend) { alllegends.Add(v); } } newlegend = alllegends.Last().Duplicate(ViewDuplicateOption.WithDetailing); viewlegend = doc.GetElement(newlegend) as View; tx.Commit(); } using (Form_FrozenSection form = new Form_FrozenSection(doc, uiapp)) { form.ShowDialog(); if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return(Result.Cancelled); } if (form.DialogResult == System.Windows.Forms.DialogResult.OK) { using (Transaction tx1 = new Transaction(doc)) { tx1.Start("Transaction Name"); tx1.Commit(); uiapp.ActiveUIDocument.ActiveView = form.vsheet(); } } using (Transaction tx2 = new Transaction(doc)) { tx2.Start("Transaction Name"); XYZ pos = uidoc.Selection.PickPoint(ObjectSnapTypes.None, "Chon diem dat legend"); Viewport.Create(doc, form.vsheet().Id, newlegend, pos); FilteredElementCollector allElementsInView = new FilteredElementCollector(doc, viewlegend.Id).WhereElementIsNotElementType(); ICollection <ElementId> elementsInView = allElementsInView.WhereElementIsNotElementType().Where(x => x.Category != null).Select(x => x.Id).ToList(); doc.Delete(elementsInView); FilteredElementCollector detailine = new FilteredElementCollector(doc, drafting.Id); IList <ElementId> listdetailine = detailine.OfCategory(BuiltInCategory.OST_Lines).WhereElementIsNotElementType().ToElementIds().ToList(); Transform tranform = ElementTransformUtils.GetTransformFromViewToView(viewlegend, doc.ActiveView); ElementTransformUtils.CopyElements(drafting, listdetailine, viewlegend, tranform, new CopyPasteOptions()); viewlegend.Scale = 16; Parameter viewname = viewlegend.LookupParameter("View Name"); string name = form.Viewname(); viewname.Set(name); doc.Delete(drafting.Id); tx2.Commit(); } } return(Result.Succeeded); }
public static double[] CollectBounds(this Document doc, UIDocument uidoc) { List <double> room = new List <double>(); List <double> bounds = new List <double>(); Selection sel = uidoc.Selection; bool RoomFound = false; var selIds = uidoc.Selection.GetElementIds(); foreach (ElementId eid in selIds) { Element e = doc.GetElement(eid); DetailCurve dc = e as DetailCurve; if (dc != null) { if (!RoomFound) { XYZ mid = dc.GeometryCurve.Evaluate(0.5, true); var r = doc.GetRoomAtPoint(mid); if (r != null) { RoomFound = true; IList <IList <BoundarySegment> > segments = r.GetBoundarySegments(new SpatialElementBoundaryOptions()); if (null != segments) { foreach (IList <BoundarySegment> SegmentList in segments) { for (int i = 0; i < SegmentList.Count; i++) { XYZ bp = SegmentList[i].GetCurve().GetEndPoint(0); room.Add(bp.X); room.Add(bp.Y); } } } } } XYZ start = dc.GeometryCurve.GetEndPoint(0); XYZ end = dc.GeometryCurve.GetEndPoint(1); bounds.Add(start.X); bounds.Add(start.Y); bounds.Add(end.X); bounds.Add(end.Y); } } int roomcount = room.Count(); for (int i = 0; i < 201; i++) { if (i > roomcount) { room.Add(0); } } for (int i = 0; i < 51; i++) { if (i > bounds.Count()) { bounds.Add(0); } } room.AddRange(bounds); double max = Math.Abs(room.Max()); double min = Math.Abs(room.Min()); if (min > max) { max = min; } for (int i = 0; i < room.Count(); i++) { room[i] /= max; } return(room.ToArray()); }
//private void Application_DialogBoxShowing(object sender, Autodesk.Revit.UI.Events.DialogBoxShowingEventArgs e) //{ // // TaskDialog.Show("Information", e.HelpId.ToString()); // // Console.WriteLine("Information", e.HelpId.ToString()); // TaskDialogShowingEventArgs e2 = e as TaskDialogShowingEventArgs; // string s = string.Empty; // if (null != e2) // { // s = string.Format( // ", dialog id {0}, message '{1}'", // e2.DialogId, e2.Message); // bool isConfirm = e2.DialogId.Equals( // "TaskDialog_Save_File"); // if (isConfirm) // { // //e2.OverrideResult( // // (int)WinForms.DialogResult.Yes); // s += ", auto-confirmed."; // } // } //} public void PatTry(ExternalCommandData revit) { Document doc = doc = revit.Application.ActiveUIDocument.Document; Selection s = revit.Application.ActiveUIDocument.Selection; List <Reference> ref_elem = s.PickObjects(ObjectType.Element, "Select Element").Cast <Reference>().ToList(); PickedBox boundary = s.PickBox(PickBoxStyle.Crossing, "Select boundary"); if (ref_elem.Count == 0 || boundary == null) { return; } double tile_width = Line.CreateBound(boundary.Min, new XYZ(boundary.Max.X, boundary.Min.Y, boundary.Min.Z)).Length; double tile_height = Line.CreateBound(boundary.Min, new XYZ(boundary.Min.X, boundary.Max.Y, boundary.Min.Z)).Length; ref_elem.ToList().ForEach((Refr) => { Element deltail_line = doc.GetElement(Refr); if ((deltail_line as DetailCurve) == null) { return; } DetailCurve elem_curve = (deltail_line as DetailCurve); XYZ origin = elem_curve.GeometryCurve.GetEndPoint(0); XYZ dir = (elem_curve.GeometryCurve as Line).Direction; double ang = dir.AngleTo(new XYZ(1, 0, 0)); if (ang > 1.5708) //> 90 deg { ang = 3.14159 - 1.5708; //180-90 } List <Curve> curve_list = new List <Curve>(); CurveArray cr = new CurveArray(); for (int x = 1; x <= 100; x++) { XYZ base_grid_pt = new XYZ(origin.X + tile_width * x, origin.Y, origin.Z); for (int y = 1; y <= 100; y++) { XYZ grid_pt = new XYZ(origin.X + tile_width * x, origin.Y + tile_height * y, origin.Z); cr.Append(Line.CreateBound(base_grid_pt, grid_pt) as Curve); } } using (Transaction t = new Transaction(doc, "Draw Grid")) { try { t.Start(); doc.Create.NewDetailCurveArray(doc.ActiveView, cr); t.Commit(); } catch (Exception) { t.RollBack(); } } }); TaskDialog.Show("Instruction", "Process Complete........#############"); TaskDialog.Show("Instruction", "Process Complete........#############"); }