public void BeginTriangulate() { buildTriangulations buildT = new buildTriangulations(); AC_Transactions tr = new AC_Transactions(); PromptEntityOptions options = new PromptEntityOptions("Pick a Line to Triangulate"); options.SetRejectMessage("not valid Object \n"); options.AddAllowedClass(typeof(Line), true); PromptEntityResult sel = tr.AC_Doc.Editor.GetEntity(options); if (sel.Status == PromptStatus.OK) { tr.AC_Doc.Editor.WriteMessage("Line " + sel.ObjectId.ToString() + " Selected \n"); buildT.Create((AC_Line)tr.openObjectErased(sel.ObjectId)); } }
public void TestWEdding() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; var selOpt = new PromptEntityOptions("\nВыбери полилинию для прополки"); selOpt.SetRejectMessage("\nТолько полилинию"); selOpt.AddAllowedClass(typeof(Polyline), true); var selRes = ed.GetEntity(selOpt); if (selRes.Status != PromptStatus.OK) return; using (var t = db.TransactionManager.StartTransaction()) { var pl = selRes.ObjectId.GetObject(OpenMode.ForWrite) as Polyline; pl.TestDrawVertexNumbers(Color.FromColor(System.Drawing.Color.Green)); pl.Wedding(new Autodesk.AutoCAD.Geometry.Tolerance (0.02,0.1)); pl.TestDrawVertexNumbers(Color.FromColor(System.Drawing.Color.Red)); t.Commit(); } }
public void Cmd_DimExtend() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; var prEntOpt = new PromptEntityOptions("\nSelect a dimension system to extend: "); prEntOpt.SetRejectMessage("\nOnly linear dimensions may be selected."); prEntOpt.AllowNone = false; prEntOpt.AddAllowedClass(typeof(RotatedDimension), false); var prEntRes = acCurEd.GetEntity(prEntOpt); if (prEntRes.Status != PromptStatus.OK) { return; } var objId = prEntRes.ObjectId; var matrix3d = acCurEd.GetAlignedMatrix(); var eqPoint = CalcTol.ReturnCurrentTolerance(); using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var acEnt = acTrans.GetObject(objId, OpenMode.ForWrite) as Entity; if (acEnt != null) { acEnt.Unhighlight(); var acRotDim = acEnt as RotatedDimension; if (acRotDim != null) { var dimSys = DimSystem.GetSystem(acRotDim, eqPoint, eqPoint); dimSys.Highlight(); var promptPointOption2 = new PromptPointOptions( "\nSelect a dimension line to extend or press CTRL to start crossing line:"); while (true) { if (dimSys.Count == 0) { break; } dimSys.Highlight(); var nArray = DimSystem.GetActiveViewCount(); var ctManager = TransientManager.CurrentTransientManager; var acCirc = new Circle(); var acLine = new Line(new Point3d(0, 0, 0), new Point3d(0, 0, 0)); acCirc.Color = SettingsUser.DynPreviewColor; acCirc.Normal = acRotDim.Normal; acLine.Color = SettingsUser.DynPreviewColor; var intCol = new IntegerCollection(nArray); ctManager.AddTransient(acCirc, TransientDrawingMode.Highlight, 128, intCol); ctManager.AddTransient(acLine, TransientDrawingMode.Highlight, 128, intCol); var sysPts = dimSys.GetSystemPoints(eqPoint); void Handler(object sender, PointMonitorEventArgs e) { var cPt = dimSys.GetNearest(e.Context.ComputedPoint, eqPoint); var sysPt = sysPts[cPt]; var dlPt = sysPt.DimLinePoint; var scrSize = ScreenReader.GetSreenSize(); acCirc.Radius = scrSize / 200; var point3d = sysPt.Dim1PointIndex != 1 ? sysPt.Dim1.XLine2Point : sysPt.Dim1.XLine1Point; if (Math.Abs(point3d.DistanceTo(dlPt)) <= eqPoint) { acCirc.Center = dlPt; acLine.StartPoint = dlPt; acLine.EndPoint = dlPt; ctManager.UpdateTransient(acCirc, intCol); ctManager.UpdateTransient(acLine, intCol); return; } var point = new Line3d(dlPt, point3d).GetClosestPointTo(e.Context.ComputedPoint).Point; acLine.StartPoint = dlPt; acLine.EndPoint = point; acCirc.Center = point; ctManager.UpdateTransient(acCirc, intCol); ctManager.UpdateTransient(acLine, intCol); } acCurEd.PointMonitor += Handler; PromptPointResult ptRes; try { ptRes = acCurDoc.Editor.GetPoint(promptPointOption2); } finally { acCurEd.PointMonitor -= Handler; ctManager.EraseTransient(acCirc, intCol); ctManager.EraseTransient(acLine, intCol); acCirc.Dispose(); acLine.Dispose(); } var cntrlPressed = (Control.ModifierKeys & Keys.Control) > Keys.None; PromptPointResult ctrlRes = null; if (cntrlPressed) { var promptPointOption3 = new PromptPointOptions("\nSelect second point of crossing line:") { UseBasePoint = true, UseDashedLine = true, BasePoint = ptRes.Value }; ctrlRes = acCurDoc.Editor.GetPoint(promptPointOption3); if (ctrlRes.Status != PromptStatus.OK) { break; } } if (ptRes.Status != PromptStatus.OK) { break; } if (cntrlPressed) { var point3d6 = ptRes.Value.TransformBy(matrix3d); var point3d7 = ctrlRes.Value.TransformBy(matrix3d); var nums = dimSys.GetSystemByLine(point3d6, point3d7, eqPoint); if (nums.Count <= 0) { continue; } var sysPoints2 = dimSys.GetSystemPoints(eqPoint); foreach (var num3 in nums) { var point3d8 = DimSystem.GetCrossing(dimSys, sysPoints2, num3, point3d6, point3d7, eqPoint); if (point3d8.X != -99999 || point3d8.Y != -99999 || point3d8.Z != -99999) { dimSys.Extend(num3, 0, point3d8, eqPoint); } else { acCurEd.WriteMessage("\nCannot extend lines with zero length."); } } acTrans.TransactionManager.QueueForGraphicsFlush(); } else { var point3d9 = ptRes.Value.TransformBy(matrix3d); var num4 = dimSys.GetNearest(point3d9, eqPoint); var sysPoint = dimSys.GetSystemPoints(eqPoint)[num4]; var point3d10 = sysPoint.DimLinePoint; var point3d11 = sysPoint.Dim1PointIndex != 1 ? sysPoint.Dim1.XLine2Point : sysPoint.Dim1.XLine1Point; if (Math.Abs(point3d10.DistanceTo(point3d11)) >= eqPoint) { dimSys.Extend(num4, 0, point3d9, eqPoint); acTrans.TransactionManager.QueueForGraphicsFlush(); } else { acCurEd.WriteMessage("\nCannot extend lines with zero length."); } } } dimSys.Unhighlight(); acTrans.Commit(); } } } }
public void DrawingAmounts() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; int drwStyle = 0;//张拉方式,0为两端张拉,-1为左端张拉,1为右端张拉 //钢束总体参数 double kii = TendonGeneralParameters.Kii; double miu = TendonGeneralParameters.Miu; double Ep = TendonGeneralParameters.Ep; double ctrlStress = TendonGeneralParameters.CtrlStress; using (Transaction trans = db.TransactionManager.StartTransaction())//开始事务处理 { //1.选择钢束线 PromptEntityOptions tdLineOpt = new PromptEntityOptions("\n选择钢束或[张拉方式(D)/管道偏差系数(K)/摩阻系数(U)/张拉控制应力(C)]"); tdLineOpt.SetRejectMessage("\n钢束应为多段线"); tdLineOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线 tdLineOpt.Keywords.Add("D"); tdLineOpt.Keywords.Add("K"); tdLineOpt.Keywords.Add("U"); tdLineOpt.Keywords.Add("C"); tdLineOpt.AppendKeywordsToMessage = false; //提示信息中不显示关键字 for (;;) //无限循环,直到选中钢束线为止 { PromptEntityResult tdLineRes = ed.GetEntity(tdLineOpt); //2.各关键字下分别设置钢束张拉参数 if (tdLineRes.Status == PromptStatus.Keyword) { switch (tdLineRes.StringResult) { case "D": PromptIntegerOptions drwOpt = new PromptIntegerOptions($"\n输入张拉方式[两端张拉(0)/左端张拉(-1)/右端张拉(1)<{drwStyle}>"); drwOpt.AllowNone = true; PromptIntegerResult drwRes = ed.GetInteger(drwOpt); if (drwRes.Value == 0) { drwStyle = 0; } else if (drwRes.Value == -1) { drwStyle = -1; } else if (drwRes.Value == 1) { drwStyle = 1; } break; case "K": PromptDoubleOptions kiiOpt = new PromptDoubleOptions($"\n设置管道偏差系数(1/m)<{kii}>"); kiiOpt.AllowNone = true; kiiOpt.AllowNegative = false; kiiOpt.AllowZero = false; PromptDoubleResult kiiRes = ed.GetDouble(kiiOpt); if (kiiRes.Status == PromptStatus.OK) { kii = kiiRes.Value; } break; case "U": PromptDoubleOptions miuOpt = new PromptDoubleOptions($"\n设置摩阻系数<{miu}>"); miuOpt.AllowNone = true; miuOpt.AllowNegative = false; miuOpt.AllowZero = false; PromptDoubleResult miuRes = ed.GetDouble(miuOpt); if (miuRes.Status == PromptStatus.OK) { miu = miuRes.Value; } break; case "C": PromptDoubleOptions ctrOpt = new PromptDoubleOptions($"\n设置张拉控制应力(MPa)<{ctrlStress}>"); ctrOpt.AllowNone = true; PromptDoubleResult ctrRes = ed.GetDouble(ctrOpt); if (ctrRes.Status == PromptStatus.OK) { ctrlStress = ctrRes.Value; } break; } } //3.输出引伸量 else if (tdLineRes.Status == PromptStatus.OK) { ObjectId tdLineId = tdLineRes.ObjectId; Polyline tdLine = trans.GetObject(tdLineId, OpenMode.ForRead) as Polyline; if (drwStyle == 0)//两端张拉 { double[] drawAmounts = tdLine.BothDrawAmount(ctrlStress, kii, miu, Ep); ed.WriteMessage("\n左侧引伸量:" + drawAmounts[0].ToString("F0") + "; " + "右侧引伸量:" + drawAmounts[1].ToString("F0") + "。"); } else if (drwStyle == -1)//左侧张拉 { double drawAmount = tdLine.SingleDrawAmount(ctrlStress, kii, miu, -1, Ep); ed.WriteMessage("\n左侧引伸量:" + drawAmount.ToString("F0") + "。"); } else if (drwStyle == 1)//右侧张拉 { double drawAmount = tdLine.SingleDrawAmount(ctrlStress, kii, miu, 1, Ep); ed.WriteMessage("\n右侧引伸量:" + drawAmount.ToString("F0") + "。"); } break; } else { ed.WriteMessage("输入有误!"); return; } } trans.Commit();//执行事务处理 } }
public void ProfileOnCurve() { if (!CheckLicense.Check()) { return; } Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Topography.SurfaceType surface = Topography.PickSurface(); if (surface == Topography.SurfaceType.None) { return; } if (!Topography.EnsureSurfaceNotEmpty(surface)) { return; } // Pick alignment bool flag = true; ObjectId curveId = ObjectId.Null; while (flag) { PromptEntityOptions entityOpts = new PromptEntityOptions("\nEksen [Seçenekler]: ", "Settings"); entityOpts.SetRejectMessage("\nSelect a curve."); entityOpts.AddAllowedClass(typeof(Curve), false); PromptEntityResult entityRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(entityOpts); if (entityRes.Status == PromptStatus.Keyword) { ShowSettings(); } else if (entityRes.Status == PromptStatus.OK) { curveId = entityRes.ObjectId; break; } else if (entityRes.Status == PromptStatus.Cancel) { return; } } using (Transaction tr = db.TransactionManager.StartTransaction()) using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)) { Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs; ObjectId textStyleId = ObjectId.Null; using (TextStyleTable tt = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead)) { if (tt.Has(TextStyleName)) { textStyleId = tt[TextStyleName]; } } // Project curve onto surface Topography topo = Topography.Instance; Curve curve = tr.GetObject(curveId, OpenMode.ForRead) as Curve; Point2dCollection points = topo.ProfileOnCurve(curve, surface); // Base point for profile drawing PromptPointResult pointRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint("\nProfil başlangıcı: "); if (pointRes.Status != PromptStatus.OK) { return; } Point3d basePt = pointRes.Value; if (points.Count > 0) { // Limits Extents2d ex = AcadUtility.AcadGeometry.Limits(points); // Base level for profile drawing PromptDoubleOptions levelOpts = new PromptDoubleOptions("\nProfil baz kotu: "); levelOpts.DefaultValue = Math.Floor(ex.MinPoint.Y / ProfileGridV) * ProfileGridV; levelOpts.UseDefaultValue = true; PromptDoubleResult levelRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(levelOpts); if (pointRes.Status != PromptStatus.OK) { return; } double startLevel = levelRes.Value; double endLevel = Math.Ceiling(ex.MaxPoint.Y / ProfileGridV + 1) * ProfileGridV; // Base chainage for profile drawing double startCh = 0; flag = true; while (flag) { PromptStringOptions chOpts = new PromptStringOptions("\nProfil baz KM: "); chOpts.DefaultValue = AcadUtility.AcadText.ChainageToString(0, Precision); chOpts.UseDefaultValue = true; PromptResult chRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetString(chOpts); if (chRes.Status != PromptStatus.OK) { return; } if (AcadUtility.AcadText.TryChainageFromString(chRes.StringResult, out startCh)) { break; } } double endCh = Math.Ceiling((startCh + ex.MaxPoint.X) / ProfileGridH) * ProfileGridH; // Draw grid IEnumerable <Entity> entities = DrawProfileFrame(db, basePt, startCh, startLevel, endCh, endLevel, ProfileGridH, ProfileGridV, ProfileVScale, TextHeight, Precision, textStyleId); foreach (Entity ent in entities) { ent.TransformBy(ucs2wcs); btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } // Draw profile ObjectId profileLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, "Profil_Eksen", Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByAci, 5)); Point2dCollection trPoints = new Point2dCollection(points.Count); foreach (Point2d pt in points) { trPoints.Add(new Point2d(basePt.X + pt.X, basePt.Y + (pt.Y - startLevel) * ProfileVScale)); } Polyline pline = AcadUtility.AcadEntity.CreatePolyLine(db, false, trPoints); pline.TransformBy(ucs2wcs); pline.LayerId = profileLayerId; btr.AppendEntity(pline); tr.AddNewlyCreatedDBObject(pline, true); } tr.Commit(); } }
public void GetPointsAtEqualDists() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; //初始化各标注图元 Vector3d drvt = new Vector3d(); //标注点切线 double len = 10 * scale_GPAD; //标注点长度,为10单位 Point3d pt1 = new Point3d(); //标准线起点 Point3d pt2 = new Point3d(); //标准线终点 Line line = new Line(); //标注线 using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理 { //1.选择多段线 PromptEntityOptions plineOpt = new PromptEntityOptions("\n选择多段线"); plineOpt.SetRejectMessage("\n并非多段线!"); plineOpt.AddAllowedClass(typeof(Polyline), true); PromptEntityResult plineRes = ed.GetEntity(plineOpt); if (plineRes.Status != PromptStatus.OK) { return; } Polyline pline = plineRes.ObjectId.GetObject(OpenMode.ForRead) as Polyline; //2.选择绘图比例 PromptDoubleOptions scaleOpt = new PromptDoubleOptions($"\n设置绘图比例<{scale_GPAD}>"); scaleOpt.AllowNone = true; //允许回车,则采用默认比例 scaleOpt.AllowNegative = false; //不允许负值 scaleOpt.AllowZero = false; //不允许零值 PromptDoubleResult scaleRes = ed.GetDouble(scaleOpt); //获取比例 if (scaleRes.Status == PromptStatus.OK) { scale_GPAD = scaleRes.Value; //获取绘图比例 len = 10 * scale_GPAD; //重设标注线长度 } //3.选择起点 PromptPointOptions startPtOpt = new PromptPointOptions("\n选择曲线上的点作为起点"); PromptPointResult startPtRes = ed.GetPoint(startPtOpt); if (startPtRes.Status != PromptStatus.OK) { return; } Point3d startPt = pline.GetClosestPointTo(startPtRes.Value, false);//选择点到多段线的最近点 //4.选择终点 PromptPointOptions endPtOpt = new PromptPointOptions("\n选择曲线上的点作为终点"); PromptPointResult endPtRes = ed.GetPoint(endPtOpt); if (endPtRes.Status != PromptStatus.OK) { return; } Point3d endPt = pline.GetClosestPointTo(endPtRes.Value, false);//选择点到多段线的最近点 //5.是否标注距离 PromptKeywordOptions kwOpt = new PromptKeywordOptions($"\n是否标注沿曲线长度[Y/N]<{isDistDenote}>"); kwOpt.Keywords.Add("Y"); kwOpt.Keywords.Add("N"); kwOpt.AllowNone = true; //可回车 kwOpt.AllowArbitraryInput = false; //不可随意输入 kwOpt.AppendKeywordsToMessage = false; //提示信息中不显示关键字 PromptResult kwRes = ed.GetKeywords(kwOpt); if (kwRes.Status == PromptStatus.OK) { isDistDenote = kwRes.StringResult; } //6.输入分段数量 PromptIntegerOptions intOpt = new PromptIntegerOptions("\n输入分段数"); intOpt.AllowNegative = false; //不予许负值 intOpt.AllowZero = false; //不允许0 PromptIntegerResult intRes = ed.GetInteger(intOpt); if (intRes.Status == PromptStatus.OK) //输入成功 { int nSegs = intRes.Value; Double distOfStPt = pline.GetDistanceToStartPt(startPt); //获取起点距曲线起点的距离 //绘制起点线 drvt = pline.GetFirstDerivative(startPt); //获取切线 pt1 = startPt + len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis); pt2 = startPt - len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis); line = new Line(pt1, pt2); db.AddToModelSpace(line); double distOfEdPt = pline.GetDistanceToStartPt(endPt); //获取终点距曲线起点的距离 //绘制终点线 drvt = pline.GetFirstDerivative(endPt); //获取切线 pt1 = endPt + len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis); pt2 = endPt - len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis); line = new Line(pt1, pt2); db.AddToModelSpace(line); List <double> dists = new List <double>(); for (int i = 1; i <= nSegs; i++) { dists.Add((distOfEdPt - distOfStPt) / nSegs); } CreateSpanLines(pline, startPt, dists, isDistDenote, scale_GPAD); //绘制分跨线 } trans.Commit(); //执行事务处理 } }
public void LineSegs3d() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; using (Transaction trans = db.TransactionManager.StartTransaction())//开始事务处理 { //1.选择空间轴线的平面视图多段线 PromptEntityOptions plxyOpt = new PromptEntityOptions("\n选择空间轴线的平面视图多段线"); plxyOpt.SetRejectMessage("\n并非多段线!"); plxyOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线 PromptEntityResult plxyRes = ed.GetEntity(plxyOpt); if (plxyRes.Status != PromptStatus.OK) { return; } ObjectId plxyId = plxyRes.ObjectId; Polyline plxy = trans.GetObject(plxyId, OpenMode.ForWrite) as Polyline; //2.选择空间轴线的立面视图多段线 PromptEntityOptions plxzOpt = new PromptEntityOptions("\n选择空间轴线的立面视图多段线"); plxzOpt.SetRejectMessage("\n并非多段线!"); plxzOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线 PromptEntityResult plxzRes = ed.GetEntity(plxzOpt); if (plxzRes.Status != PromptStatus.OK) { return; } ObjectId plxzId = plxzRes.ObjectId; Polyline plxz = trans.GetObject(plxzId, OpenMode.ForWrite) as Polyline; //3.判断平面视图和立面视图中的长度是否一致 double lenXY = plxy.Length; double lenXZ = Math.Abs(plxz.StartPoint.X - plxz.EndPoint.X); if (Math.Abs(lenXY - lenXZ) > 10) { ed.WriteMessage("\n轴线平面长度与立面长度不一致,请检查!"); return; } double totalLen = lenXY;//记录轴线总长 //4.输入拟合直线段的长度 PromptDoubleOptions slOpt = new PromptDoubleOptions("\n输入拟合直线段的长度<1000>"); slOpt.AllowNegative = false; //不允许负值 slOpt.AllowZero = false; //不允许零值 slOpt.DefaultValue = 1000; //默认值为1000 PromptDoubleResult slRes = ed.GetDouble(slOpt); if (slRes.Status != PromptStatus.OK) { return; } double segLen = slRes.Value; //或得拟合线段长度 if (segLen > (totalLen - 10)) //节段过长(仅比总长小1cm或更长) { ed.WriteMessage("\n节段长度过长!"); return; } //5.获取每个节段点的坐标 //节段需要包括所有平面曲线节点、立面曲线节点和节段长度端点 List <Point3d> verts = new List <Point3d>();//初始化节段点List //5.1 添加平面曲线节点 for (int i = 0; i < plxy.NumberOfVertices; i++) { Point3d vertInPlxy = plxy.GetPoint3dAt(i); //平面图节点 double prmt = plxy.GetParameterAtPoint(vertInPlxy); //该节点参数 double distance = plxy.GetDistanceAtParameter(prmt); //该节点到起点距离,即为立面图上到起点的横坐标差 Point3d xlBase = plxz.StartPoint + new Vector3d(distance, 0, 0); //立面图起点偏移distance后,作为Xline基点 Xline xl = new Xline(); //新建xline xl.BasePoint = xlBase; //基点如前所述 xl.UnitDir = new Vector3d(0, 1, 0); //竖直方向 Point3dCollection ptIntersects = new Point3dCollection(); //建立交点组 plxz.IntersectWith(xl, Intersect.OnBothOperands, ptIntersects, IntPtr.Zero, IntPtr.Zero); //与立面轴线相交 Point3d vertInPlxz = ptIntersects[0]; //获得交点 //将节点添加至节点列表,X,Y坐标由平面图确定,Z坐标由立面图确定 Point3d vert = new Point3d(vertInPlxy.X, vertInPlxy.Y, vertInPlxz.Y - plxz.StartPoint.Y); verts.Add(vert); xl.Dispose(); } //5.2 添加立面曲线节点 for (int i = 1; i < plxz.NumberOfVertices - 1; i++) { Point3d vertInPlxz = plxz.GetPoint3dAt(i); //立面图节点 double distance = vertInPlxz.X - plxz.StartPoint.X; //该节点到起点距离,即为立面图上到起点的横坐标差 Point3d vertInPlxy = plxy.GetPointAtDist(distance); //获取该点在平面图上的对应点 //将节点添加至节点列表,X,Y坐标由平面图确定,Z坐标由立面图确定 Point3d vert = new Point3d(vertInPlxy.X, vertInPlxy.Y, vertInPlxz.Y - plxz.StartPoint.Y); if (!IsPtInList(vert, verts, 10))//如果该点尚不在点群中 { verts.Add(vert); } } //5.3 节段端点 double dist = segLen; do { Point3d vertInPlxy = plxy.GetPointAtDist(dist); //平面图节点 //立面图节点 Point3d xlBase = plxz.StartPoint + new Vector3d(dist, 0, 0); //立面图起点偏移dist后,作为Xline基点 Xline xl = new Xline(); //新建xline xl.BasePoint = xlBase; //基点如前所述 xl.UnitDir = new Vector3d(0, 1, 0); //竖直方向 Point3dCollection ptIntersects = new Point3dCollection(); //建立交点组 plxz.IntersectWith(xl, Intersect.OnBothOperands, ptIntersects, IntPtr.Zero, IntPtr.Zero); //与立面轴线相交 Point3d vertInPlxz = ptIntersects[0]; //获得交点 //将节点添加至节点列表,X,Y坐标由平面图确定,Z坐标由立面图确定 Point3d vert = new Point3d(vertInPlxy.X, vertInPlxy.Y, vertInPlxz.Y - plxz.StartPoint.Y); if (!IsPtInList(vert, verts, 10))//如果该点尚不在点群中 { verts.Add(vert); } dist += segLen; }while (dist < totalLen - 10);//前进长度小于总长度 //6.对所有节点进行排序 var sortedPts = (from pt in verts let p = plxy.GetParameterAtPoint(pt) let d = plxy.GetDistanceAtParameter(p) orderby d select pt).ToList(); //7.指定插入点 Point3d insertPt = new Point3d(); for (;;) { PromptPointOptions ptOpt = new PromptPointOptions("\n指定空间拟合段插入点"); PromptPointResult ptRes = ed.GetPoint(ptOpt); if (ptRes.Status == PromptStatus.OK) { insertPt = ptRes.Value; break; } } Vector3d vect = insertPt - plxy.StartPoint; //建立平移向量,从曲线平面图起点至选择的插入点 Matrix3d mt = Matrix3d.Displacement(vect); //建立对应的变换矩阵 //7.依次建立线段 for (int i = 0; i < sortedPts.Count - 1; i++) { Line line = new Line(sortedPts[i], sortedPts[i + 1]); line.TransformBy(mt); //平移到位 db.AddToModelSpace(line); //添加至模型空间 } trans.Commit();//执行事务处理 } }
public static String PromptSelectTINSurface(String sufraceStatus) { String surfName = ""; try { using (var tr = AcadApp.StartTransaction()) { var opt = new PromptEntityOptions("\nВыберите " + sufraceStatus + " поверхность TIN: "); opt.SetRejectMessage("\nОбъект должен быть поверхностью TIN.\n"); opt.AddAllowedClass(typeof(TinSurface), false); var ent = AcadApp.AcaEd.GetEntity(opt); if (ent.Status == PromptStatus.OK) { var tinsurfId = ent.ObjectId; if (tinsurfId == ObjectId.Null) { return ""; } var tinsurf = tinsurfId.GetObject(OpenMode.ForRead) as TinSurface; surfName = tinsurf.Name; return surfName; // All OK. Return surface name } // If PromptStatus.OK } // using } catch (Autodesk.AutoCAD.Runtime.Exception ex) { AcadApp.AcaEd.WriteMessage("ERROR: CivApp.PromptSelectTINSurface()\n" + ex + "\n"); } return ""; //There have been some errors }
public static void AddCurveCommand() { double GetAngle(Point2d a, Point2d b) { double xDiff = b.X - a.X; double yDiff = b.Y - a.Y; return(Math.Atan2(yDiff, xDiff) * 180.0d / Math.PI); } try { var options = new PromptEntityOptions("\nSelect a point on a polyline: "); options.SetRejectMessage("Invalid Object."); options.AddAllowedClass(typeof(Polyline), true); options.AddAllowedClass(typeof(Polyline2d), true); options.AddAllowedClass(typeof(Polyline3d), true); var result = Quick.Editor.GetEntity(options); if (result.Status != PromptStatus.OK) { return; } var lineId = result.ObjectId; var pickpoint = result.PickedPoint.ToPoint2D(); var qtarget = Quick.Editor.GetPoint(new PromptPointOptions("Pick the strech point.") { AllowNone = false, BasePoint = pickpoint.ToPoint3D(), UseBasePoint = true, UseDashedLine = true }); if (qtarget.Status != PromptStatus.OK) { return; } var target = qtarget.Value.ToPoint2D(); using (var tr = new QuickTransaction()) { try { var poly = (Curve)tr.GetObject(lineId, OpenMode.ForWrite); if (poly is Polyline2d) { poly = poly.ConvertToPolyline(tr); } if (poly is Polyline3d) { throw new InvalidCastException("Can't be applied on polyline of type Polyline3d."); } var distance = target.GetDistanceTo(pickpoint); var pointRight = poly.OffsetToEnd(result.PickedPoint, distance); var pointLeft = poly.OffsetToStart(result.PickedPoint, distance); if (!pointRight.Item2 || !pointLeft.Item2) { return; } var rightcut = poly.BreakOnPoint(pointRight.Item1, tr, false); poly = (Polyline)rightcut[0]; //right poly var rightpoly = (Polyline)rightcut[1]; var leftcut = poly.BreakOnPoint(pointLeft.Item1, tr, false); var leftpoly = (Polyline)leftcut[0]; leftcut[1].UpgradeOpen(); leftcut[1].Erase(); var buldge = Math.Tan((90d * 0.85 * Deg2Rad) / 4); leftpoly.AddVertexAt(leftpoly.NumberOfVertices, target, 0, leftpoly.GetStartWidthAt(leftpoly.NumberOfVertices - 1), leftpoly.GetEndWidthAt(leftpoly.NumberOfVertices - 1)); leftpoly.SetBulgeAt(leftpoly.NumberOfVertices - 2, buldge); rightpoly.AddVertexAt(0, target, buldge, leftpoly.GetStartWidthAt(0), leftpoly.GetEndWidthAt(0)); void setdir(bool right) { if (right) { leftpoly.SetBulgeAt(leftpoly.NumberOfVertices - 2, buldge); rightpoly.SetBulgeAt(0, buldge); } else { leftpoly.SetBulgeAt(leftpoly.NumberOfVertices - 2, -buldge); rightpoly.SetBulgeAt(0, -buldge); } } setdir(Settings.addcurve_direction as bool? ?? true); tr.Transaction.TransactionManager.QueueForGraphicsFlush(); // ReSharper disable once AssignmentInConditionalExpression var ask = (bool?)Quick.AskQuestion("Reverse Direction?", false) ?? false; if (ask) { Settings.addcurve_direction = !(Settings.addcurve_direction as bool? ?? false); setdir(Settings.addcurve_direction); } tr.Transaction.TransactionManager.QueueForGraphicsFlush(); // ReSharper disable once AssignmentInConditionalExpression if (Settings["addcurve_join"] = Quick.AskQuestion("Join Polylines?", (Settings["addcurve_join"]) ?? !true)) { new[] { leftpoly.Join(rightpoly, tr) }.SetSelected(); } else { new[] { leftpoly, rightpoly }.SetSelected(); } tr.Commit(); } catch (Exception ex) { Quick.WriteLine(ex.Message + "\n" + ex.StackTrace); } } } catch (Exception ex) { Quick.WriteLine(ex.Message + "\n" + ex.StackTrace); } }
public void Cmd_DimMove() { var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; var prEntOpt = new PromptEntityOptions("\nSelect a dimension system to move: "); prEntOpt.SetRejectMessage("\nOnly linear dimensions may be selected."); prEntOpt.AllowNone = false; prEntOpt.AddAllowedClass(typeof(RotatedDimension), false); var prEntRes = acCurEd.GetEntity(prEntOpt); if (prEntRes.Status != PromptStatus.OK) { return; } var objId = prEntRes.ObjectId; var addMatrix = acCurEd.GetAlignedMatrix(); var eqPoint = CalcTol.ReturnCurrentTolerance(); using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var acEnt = acTrans.GetObject(objId, OpenMode.ForWrite) as Entity; if (acEnt != null) { acEnt.Unhighlight(); var acRotDim = acEnt as RotatedDimension; if (acRotDim != null) { var dimSys = DimSystem.GetSystem(acRotDim, eqPoint, eqPoint); var prPtOpts = new PromptPointOptions("\nSelect new position for dimensions: "); while (true) { dimSys.Highlight(); var nArray = DimSystem.GetActiveViewCount(); var ctManager = TransientManager.CurrentTransientManager; var intCol = new IntegerCollection(nArray); var rotatedDimensions = new List <RotatedDimension>(); foreach (var dim in dimSys.SysList) { var dimClone = (RotatedDimension)dim.Clone(); ctManager.AddTransient(dimClone, TransientDrawingMode.Highlight, 128, intCol); rotatedDimensions.Add(dimClone); } void Handler(object sender, PointMonitorEventArgs e) { foreach (var tDim in rotatedDimensions) { if (!tDim.UsingDefaultTextPosition) { var dimLinePoint = tDim.DimLinePoint; var textPosition = tDim.TextPosition; tDim.DimLinePoint = e.Context.ComputedPoint; ctManager.UpdateTransient(tDim, intCol); tDim.TextPosition = textPosition.Add(dimLinePoint.GetVectorTo(tDim.DimLinePoint)); } else { tDim.DimLinePoint = e.Context.ComputedPoint; } ctManager.UpdateTransient(tDim, intCol); } } acCurEd.PointMonitor += Handler; PromptPointResult prRes; try { prRes = acCurEd.GetPoint(prPtOpts); } finally { acCurEd.PointMonitor -= Handler; foreach (var acRotRim in rotatedDimensions) { ctManager.EraseTransient(acRotRim, intCol); acRotRim.Dispose(); } } if (prRes.Status != PromptStatus.OK) { break; } dimSys.MoveSystem(prRes.Value.TransformBy(addMatrix), eqPoint); acTrans.TransactionManager.QueueForGraphicsFlush(); } dimSys.Unhighlight(); } } acTrans.Commit(); } }
private void ChangeCase(bool upper) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // Specifically select an MText object var peo = new PromptEntityOptions(string.Format("\nSelect MText to change to {0}case: ", upper ? "upper" : "lower")); peo.SetRejectMessage("\nObject must be MText."); peo.AddAllowedClass(typeof(MText), false); PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { // We only need our MText open for read DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead, false); MText mt = obj as MText; if (mt == null) { return; } // Create a text editor object for the MText TextEditor te = TextEditor.CreateTextEditor(mt); if (te == null) { return; } // Select the entire contents of the MText te.SelectAll(); TextEditorSelection sel = te.Selection; if (sel == null) { return; } // Check whether we can change the selection's // case, and then do so if (sel.CanChangeCase) { if (upper) { sel.ChangeToUppercase(); } else { sel.ChangeToLowercase(); } } // Be sure to save the results from the editor te.Close(TextEditor.ExitStatus.ExitSave); tr.Commit(); } }
public void CutawayViewTest() { Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor; //选择剖切线 var peo = new PromptEntityOptions("\n选择一条剖切线"); peo.SetRejectMessage("选择直线"); peo.AddAllowedClass(typeof(Line), true); var per = ed.GetEntity(peo); if (per.Status == PromptStatus.OK) { Database db = HostApplicationServices.WorkingDatabase; using (var tr = db.TransactionManager.StartTransaction()) { var line = (Line)per.ObjectId.GetObject(OpenMode.ForRead); //选择剖切图形 var pso = new PromptSelectionOptions(); pso.MessageForAdding = "\n选择剖切对象"; var psr = ed.GetSelection(pso); if (psr.Status == PromptStatus.OK) { //投影对象 List <ObjectId> ids = new List <ObjectId>(); foreach (var id in psr.Value.GetObjectIds()) { var ent = (Entity)id.GetObject(OpenMode.ForRead); if (ent is Curve c) { //剖切线转平面 var plane = new Plane(line.StartPoint, line.Delta.RotateBy(Math.PI / 2, Vector3d.ZAxis)); //投影图形 var curveResult = c.GetOrthoProjectedCurve(plane); if (curveResult != null) { //变色(红) curveResult.ColorIndex = 1; ids.Add(db.AddToCurrentSpace(curveResult)); } } } if (ids.Count > 0) { //剖立面插入点 var ppr = ed.GetPoint(new PromptPointOptions("\n指定点")); if (ppr.Status == PromptStatus.OK) { var pt = ppr.Value; //添加原线 ids.Add(line.ObjectId); //复制剖立面内容 var copyIds = db.Copy(line.StartPoint, pt, ids.ToArray()); //旋转矩阵(水平) var mt = Matrix3d.Rotation(-line.Angle, Vector3d.ZAxis, pt); //几何变换 foreach (var cid in copyIds) { var ent = (Entity)cid.Value.GetObject(OpenMode.ForWrite); ent.TransformBy(mt); ent.DowngradeOpen(); } } } } tr.Commit(); } } }
public void Bora() { Editor ed = acDoc.Editor; //Prompt options for running line PromptEntityOptions peo = new PromptEntityOptions("Select Running Line"); peo.SetRejectMessage("Please Select Running Line"); peo.AddAllowedClass(typeof(Polyline), false); PromptEntityResult perRunningLine = ed.GetEntity(peo); if (perRunningLine.Status != PromptStatus.OK) { return; } while (checkForDriveways()) { //get the selection set from the prompt results //SelectionSet acSSetDriveways = psResultDriveways.Value; // Start a transaction using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //open block table record for read BlockTable blkTbl; blkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; //open table record for write BlockTableRecord blkTblRec; blkTblRec = acTrans.GetObject(blkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; _runningLine = acTrans.GetObject(perRunningLine.ObjectId, OpenMode.ForRead) as Polyline; //Polyline drivewayLine = acTrans.GetObject(perDriveways.ObjectId, OpenMode.ForRead) as Polyline; //get all point crossing running line Point3dCollection ptscoll = getIntersectionPoints(); // if the points did not intersect the running line return if (ptscoll == null) { return; } if (_runningLine != null) { // we will assume that line only intersect one time for now!!!!! FIX THIS LATER bool isOn = isPointOnRunningLine(_runningLine, ptscoll); //find the polyline segment using distance at point //getRunningLineSegment() //if they intercept then create the offset line and so forth ed.WriteMessage( "Selected point is {0} on the curve.", isOn ? ptscoll[0].ToString() : "not" ); if (isOn) { createPolyline2(ptscoll); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //foreach (DBObject dbo in createBoreSymbol(ptscoll)) //{ // //////////////////////blkTblRec.AppendEntity(); // acTrans.AddNewlyCreatedDBObject(dbo, true); //} } } // Save the changes and dispose of the transaction acTrans.Commit(); } } return; }
private void GetLengthFromEntity(TextBox txt) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; using (EditorUserInteraction UI = ed.StartUserInteraction(this)) { PromptEntityOptions opts = new PromptEntityOptions("\nSelect entity: "); opts.SetRejectMessage("\nSelect a LINE, ARC, TEXT, MTEXT, POLYLINE or DIMENSION entity."); opts.AddAllowedClass(typeof(Line), false); opts.AddAllowedClass(typeof(Arc), false); opts.AddAllowedClass(typeof(DBText), false); opts.AddAllowedClass(typeof(MText), false); opts.AddAllowedClass(typeof(Dimension), false); opts.AddAllowedClass(typeof(Polyline), false); PromptEntityResult per = ed.GetEntity(opts); if (per.Status == PromptStatus.OK) { ObjectId id = per.ObjectId; Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); if (obj is Line) { Line dobj = obj as Line; txt.Text = dobj.Length.ToString(); } else if (obj is Arc) { Arc dobj = obj as Arc; txt.Text = dobj.Length.ToString(); } else if (obj is DBText) { DBText dobj = obj as DBText; txt.Text = dobj.TextString; } else if (obj is MText) { MText dobj = obj as MText; txt.Text = dobj.Text; } else if (obj is Dimension) { Dimension dobj = obj as Dimension; txt.Text = dobj.Measurement.ToString(); } else if (obj is Polyline) { Polyline dobj = obj as Polyline; txt.Text = dobj.Length.ToString(); } CheckPosLength(txt); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("Error: " + ex.Message, "RebarPos", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } } } }
private void btnAlign_Click(object sender, EventArgs e) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; using (EditorUserInteraction UI = ed.StartUserInteraction(this)) { PromptEntityOptions opts = new PromptEntityOptions("\nSelect entity: "); opts.AllowNone = false; opts.SetRejectMessage("\nSelect a LINE, ARC or POLYLINE entity."); opts.AddAllowedClass(typeof(Curve), false); PromptEntityResult per = ed.GetEntity(opts); if (per.Status == PromptStatus.OK) { Point3d pt = per.PickedPoint; ObjectId id = per.ObjectId; bool posUp = false; Vector3d dir = new Vector3d(), up = new Vector3d(), normal = new Vector3d(); Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { RebarPos pos = (RebarPos)tr.GetObject(m_Pos, OpenMode.ForRead); Curve curve = (Curve)tr.GetObject(id, OpenMode.ForRead); pt = curve.GetClosestPointTo(pt, curve.GetPlane().Normal, false); dir = curve.GetFirstDerivative(pt); dir = dir * pos.DirectionVector.Length / dir.Length; normal = pos.NormalVector; normal = normal * pos.DirectionVector.Length / normal.Length; up = dir.CrossProduct(normal); up = up * pos.DirectionVector.Length / up.Length; posUp = (dir.DotProduct(pos.UpVector) > 0); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("Error: " + ex.Message, "RebarPos", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } double offset = 0.0; double offset1 = -0.75, offset2 = 1.75; if (posUp) { AlignPos(pt + offset1 * up, dir, up, normal); offset = offset2; } else { AlignPos(pt + offset2 * up, dir, up, normal); offset = offset1; } PromptKeywordOptions kopts = new PromptKeywordOptions("\nDiğer tarafa yerleştirilsin mi? [Evet/Hayır] <Hayir>: ", "Yes No"); kopts.AllowNone = true; PromptResult kres = ed.GetKeywords(kopts); if (kres.Status == PromptStatus.None || kres.StringResult == "Yes") { AlignPos(pt + offset * up, dir, up, normal); ed.UpdateScreen(); } } } }
public void Cmd_DimLt() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; var prEntOpt = new PromptEntityOptions("\nSelect an extension line to convert to line-type <" + SettingsUser.RcDimLt + "> : "); prEntOpt.SetRejectMessage("\nOnly dimensions may be selected."); prEntOpt.AllowNone = false; prEntOpt.AddAllowedClass(typeof(AlignedDimension), false); prEntOpt.AddAllowedClass(typeof(RotatedDimension), false); prEntOpt.AddAllowedClass(typeof(ArcDimension), false); var prEntRes = acCurEd.GetEntity(prEntOpt); var prPickPoint = prEntRes.PickedPoint; if (prEntRes.Status != PromptStatus.OK) { return; } using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var acDim = acTrans.GetObject(prEntRes.ObjectId, OpenMode.ForWrite) as Entity; if (acDim != null) { try { // Open the Linetype table for read var acLineTypTbl = acTrans.GetObject(acCurDb.LinetypeTableId, OpenMode.ForRead) as LinetypeTable; if (acLineTypTbl != null) { var sLineTypName = SettingsUser.RcDimLt; if (acLineTypTbl.Has(sLineTypName) == false) { acCurDb.LoadLineTypeFile(sLineTypName, "acad.lin"); } Point3d xPt1; Point3d xPt2; var ltId = acLineTypTbl[sLineTypName]; switch (acDim) { case AlignedDimension alDim: { xPt1 = alDim.XLine1Point; xPt2 = alDim.XLine2Point; if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2)) { alDim.Dimltex1 = ltId; } else { alDim.Dimltex2 = ltId; } break; } case RotatedDimension roDim: { xPt1 = roDim.XLine1Point; xPt2 = roDim.XLine2Point; if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2)) { roDim.Dimltex1 = ltId; } else { roDim.Dimltex2 = ltId; } break; } case ArcDimension arDim: { xPt1 = arDim.XLine1Point; xPt2 = arDim.XLine2Point; if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2)) { arDim.Dimltex1 = ltId; } else { arDim.Dimltex2 = ltId; } break; } } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } } acTrans.Commit(); } }
/// <summary> /// 按点打断 /// </summary> public static void Break() { DCadApi.isModifySymbol = true; DCadApi.isEraseRollback = true; try { var ed = PublicMethod.Instance.Editor; //选择直线 PromptEntityOptions entityOption = new PromptEntityOptions("\n选择对象"); entityOption.SetRejectMessage("\n请选择导线或电缆!"); entityOption.AddAllowedClass(typeof(Polyline), true); var entityObj = ed.GetEntity(entityOption); if (entityObj.Status == PromptStatus.OK) { if (!GetObjectType(entityObj.ObjectId)) { PublicMethod.Instance.AlertDialog("只能选择导线或电缆!"); return; } if (DBEntityFinder.Instance.VerifyLTTID(entityObj.ObjectId)) { var pars = new List <double>(); var point = PublicMethod.Instance.GetPoint("\n选择打断点"); if (point.X == 0) { return; } var oldline = (Polyline)PublicMethod.Instance.GetObject(entityObj.ObjectId, OpenMode.ForRead); if (point.Equals(oldline.StartPoint) || point.Equals(oldline.EndPoint)) { PublicMethod.Instance.AlertDialog("选择打断点错误!不能选择线段的起始点!"); return; } //按点打断线条 var closestPoint = oldline.GetClosestPointTo(new Point3d(point.X, point.Y, point.Z), false); pars.Add(oldline.GetParameterAtPoint(closestPoint)); //打断 var objs = oldline.GetSplitCurves(new DoubleCollection(pars.ToArray())); var index = 0; foreach (Polyline newline in objs) { var newObjId = PublicMethod.Instance.ToModelSpace(newline); //复制数据 CopyDBEntity(entityObj.ObjectId, newObjId, index); index++; } //删除图形 PublicMethod.Instance.EraseObject(entityObj.ObjectId); //删除缓存 DBSymbolFinder.Instance.Remove(entityObj.ObjectId); } else { PublicMethod.Instance.AlertDialog("该设备未锁定,不能编辑!"); } } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { PublicMethod.Instance.ShowMessage(ex.ToString()); } finally { DCadApi.isModifySymbol = false; DCadApi.isEraseRollback = false; } }
/// <summary> /// 两点打断 /// </summary> public static void BreakLine2() { DCadApi.isModifySymbol = true; DCadApi.isEraseRollback = true; Editor ed = PublicMethod.Instance.Editor; try { //选择直线 var entityOption = new PromptEntityOptions("\n选择对象:"); entityOption.SetRejectMessage("\n请选择导线或电缆!"); entityOption.AddAllowedClass(typeof(Polyline), true); var entityObj = ed.GetEntity(entityOption); if (entityObj.Status == PromptStatus.OK) { if (!GetObjectType(entityObj.ObjectId)) { PublicMethod.Instance.AlertDialog("只能选择导线或电缆!"); return; } if (DBEntityFinder.Instance.VerifyLTTID(entityObj.ObjectId)) { //获取原线段的对象 var oldline = (Polyline)PublicMethod.Instance.GetObject(entityObj.ObjectId, OpenMode.ForRead); //选择第二打断点 var ppo1 = new PromptPointOptions("\n选择第一点"); var point1 = ed.GetPoint(ppo1); if (point1.Status != PromptStatus.OK) { return; } if (point1.Value.Equals(oldline.StartPoint) || point1.Value.Equals(oldline.EndPoint)) { PublicMethod.Instance.AlertDialog("选择打断点错误!不能选择线段的起始点!"); return; } //选择第二打断点 var ppo2 = new PromptPointOptions("\n选择第二点"); ppo2.AllowNone = true; var point2 = ed.GetPoint(ppo2); if (point2.Value.Equals(oldline.StartPoint) || point2.Value.Equals(oldline.EndPoint)) { PublicMethod.Instance.AlertDialog("选择打断点错误!不能选择线段的起始点!"); return; } var pars = new List <double>(); var closestPoint = oldline.GetClosestPointTo(point1.Value, false); pars.Add(oldline.GetParameterAtPoint(closestPoint)); if (point2.Status == PromptStatus.OK) { //如果选择了第二点,获取直线上两点的param值,并排序 var point = oldline.GetClosestPointTo(point2.Value, false); pars.Add(oldline.GetParameterAtPoint(point)); pars.Sort(); var index = 0; //按param值打断曲线 var objs = oldline.GetSplitCurves(new DoubleCollection(pars.ToArray())); foreach (Polyline newline in objs) { //如果生成的直线起点或终点不是选择的打断点,把它加入数据库 if ((newline.StartPoint != closestPoint && newline.StartPoint != point) ^ (newline.EndPoint != closestPoint && newline.EndPoint != point)) { var newObjId = PublicMethod.Instance.ToModelSpace(newline); //复制数据 CopyDBEntity(entityObj.ObjectId, newObjId, index); index++; } } //删除图形 PublicMethod.Instance.EraseObject(entityObj.ObjectId); //删除缓存 DBSymbolFinder.Instance.Remove(entityObj.ObjectId); } } else { PublicMethod.Instance.AlertDialog("该设备未锁定,不能编辑!"); } } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { LogManager.Instance.Error(ex); } finally { DCadApi.isModifySymbol = false; DCadApi.isEraseRollback = false; } }
public void getang() { Autodesk.AutoCAD.ApplicationServices.Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; string filepath = "D:\\tdoc.docx"; using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { try { // Add a main document part. MainDocumentPart mainPart = docX.AddMainDocumentPart(); StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>(); Styles styles1 = new Styles(); DocDefaults docDefaults = new DocDefaults( new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" })), new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto })); styles1.AppendChild(docDefaults); styleDefinitionsPart.Styles = styles1; mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body()); ParagraphProperties paragraphProperties1 = new ParagraphProperties( new Justification() { Val = JustificationValues.Center }, new ParagraphMarkRunProperties( new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" } )); Paragraph para = body.AppendChild(new Paragraph()); para.AppendChild(paragraphProperties1); Run run = para.AppendChild(new Run()); RunProperties runProperties1 = new RunProperties( new Bold()); // String msg contains the text, "Hello, Word!" run.AppendChild(runProperties1); run.AppendChild(new Text("ПРИЛОЖЕНИЕ Ф")); run.AppendChild(new Break()); run.AppendChild(new Text("Ведомость углов поворотов")); run.AppendChild(new Break()); var table = new DocumentFormat.OpenXml.Wordprocessing.Table(); // Create a TableProperties object and specify its border information. TableProperties tblProp = new TableProperties( new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa }, new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa }, new TableBorders( new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }), new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" } ); // Append the TableProperties object to the empty table. table.AppendChild<TableProperties>(tblProp); // Add 3 columns to the table. TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn()); table.AppendChild(tg); TableRow tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 430 }), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Обозначение точки")))), //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"}) new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Run(new Text("Координаты точки")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new VerticalMerge() { Val = MergedCellValues.Restart }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Пикетаж")))), new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Угол")))), new TableCell(new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прямая вставка, м")))) ); table.AppendChild(tr1); TableRow tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 419 }), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("Y")))), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("X")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Лево")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Право")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run()))); table.AppendChild(tr2); TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 7 }); while (true) { double dist = 0, paste = 0; table.AppendChild(new TableRow( new TableCell( new TableCellProperties( new GridSpan() { Val = 7 }), new Paragraph( new ParagraphProperties( new ParagraphMarkRunProperties(new Bold()), new Justification() { Val = JustificationValues.Center }), new Run(new RunProperties( new Bold()), new Text("Трасса")))))); PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline: "); peo.SetRejectMessage("Можно только polyline."); peo.AddAllowedClass(typeof(Polyline), true); PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { break; } PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); // Prompt for the start point pPtOpts.Message = "\nВведи начало: "; pPtRes = doc.Editor.GetPoint(pPtOpts); PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): "); PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik); dist = 100 * getpikRes.Value; /* PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: "); pStrOpts.AllowSpaces = true; PromptResult pStrRes = doc.Editor.GetString(pStrOpts); Application.ShowAlertDialog("The name entered was: " + pStrRes.StringResult); */ Point3d curr = pPtRes.Value, next = pPtRes.Value; try { using (Transaction tr = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tr.GetObject(per.ObjectId, OpenMode.ForRead); if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint)) for (int i = 0; i < pline.NumberOfVertices - 2; i++) { TrassaRecord temp = new TrassaRecord(); temp.Name = "ВТ" + (i + 1).ToString(); LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y); next = l1.StartPoint; temp.CoordsX = l1.StartPoint.X.ToString("F"); temp.CoordsY = l1.StartPoint.Y.ToString("F"); } else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y); next = l1.EndPoint; temp.CoordsX = l1.EndPoint.X.ToString("F"); temp.CoordsY = l1.EndPoint.Y.ToString("F"); } angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI; ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60); temp.AngleT = TrassaRecord.Angle.Right; temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’"; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y); next = l1.StartPoint; temp.CoordsX = l1.StartPoint.X.ToString("F"); temp.CoordsY = l1.StartPoint.Y.ToString("F"); } else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y); next = l1.EndPoint; temp.CoordsX = l1.EndPoint.X.ToString("F"); temp.CoordsY = l1.EndPoint.Y.ToString("F"); } angle = angle * 180.0 / Math.PI; ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60); temp.AngleT = TrassaRecord.Angle.Left; temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’"; } paste = curr.DistanceTo(next); dist += paste; curr = next; ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste); temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F"); temp.DirectInsert = paste.ToString("F"); tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert)))) ); table.AppendChild(tr2); tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run(new Text(temp.Name)))), new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))), new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))), new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))), new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))), new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))), new TableCell(new Paragraph(new Run())) ); table.AppendChild(tr1); } else for (int i = pline.NumberOfVertices - 3; i >= 0; i--) { TrassaRecord temp = new TrassaRecord(); temp.Name = "ВУ" + (pline.NumberOfVertices - 2 - i).ToString(); LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y); next = l1.StartPoint; temp.CoordsX = l1.StartPoint.X.ToString("F"); temp.CoordsY = l1.StartPoint.Y.ToString("F"); } else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y); next = l1.EndPoint; temp.CoordsX = l1.EndPoint.X.ToString("F"); temp.CoordsY = l1.EndPoint.Y.ToString("F"); } angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI; ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60); temp.AngleT = TrassaRecord.Angle.Left; temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’"; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y); next = l1.StartPoint; temp.CoordsX = l1.StartPoint.X.ToString("F"); temp.CoordsY = l1.StartPoint.Y.ToString("F"); } else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y); next = l1.EndPoint; temp.CoordsX = l1.EndPoint.X.ToString("F"); temp.CoordsY = l1.EndPoint.Y.ToString("F"); } angle = angle * 180.0 / Math.PI; ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60); temp.AngleT = TrassaRecord.Angle.Right; temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’"; } paste = curr.DistanceTo(next); dist += paste; curr = next; ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste); temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F"); temp.DirectInsert = paste.ToString("F"); tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert)))) ); table.AppendChild(tr2); tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run(new Text(temp.Name)))), new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))), new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))), new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))), new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))), new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))), new TableCell(new Paragraph(new Run())) ); table.AppendChild(tr1); } } } catch { ed.WriteMessage("\nInvalid polyline."); } } body.AppendChild(table); body.AppendChild( new SectionProperties( new PageMargin() { Top = 1134, Right = (UInt32Value)850U, Bottom = 1134, Left = (UInt32Value)1418U, Header = (UInt32Value)708U, Footer = (UInt32Value)708U, Gutter = (UInt32Value)0U })); ed.WriteMessage("\nДокумент сохранен в D:\\tdoc.docx"); } catch { ed.WriteMessage("\nError."); } } }
public void ProfileCreator() { //prompt the user for running line PromptEntityOptions promptEntity = new PromptEntityOptions("\nPlease Select Running Line: "); promptEntity.SetRejectMessage("Line selected is not a polyline!!"); promptEntity.AddAllowedClass(typeof(Polyline), true); PromptEntityResult entityResult = document.Editor.GetEntity(promptEntity); if (entityResult.Status != PromptStatus.OK) { document.Editor.WriteMessage("Error: Please select a Polyline."); return; } Transaction tr = database.TransactionManager.StartTransaction(); //Save the polyline Polyline runningLine = null; using (tr) { runningLine = tr.GetObject(entityResult.ObjectId, OpenMode.ForRead) as Polyline; } //create the grid for the profile Grid grid = null; try { grid = new Grid(4, runningLine.Length); grid.Draw(); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { document.Editor.WriteMessage("error creating grid;" + ex.Message); } if (grid != null) { grid.SaveGrid(); } Point3d gradeLineInsPt = grid.InsertionPoint; //create a vector to generate the starting point for the gradeline..It 80' from -25 to 0 Point3d origin = new Point3d(0, 0, 0); Matrix3d matrix = Matrix3d.Displacement(origin.GetVectorTo(new Point3d(0, 100, 0))); gradeLineInsPt = gradeLineInsPt.TransformBy(matrix); Polyline gradeLine = new Polyline(); Transaction trans = database.TransactionManager.StartTransaction(); using (trans) { BlockTable bt = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; gradeLine.AddVertexAt(0, new Point2d(gradeLineInsPt.X, gradeLineInsPt.Y), 0, 0, 0); gradeLine.AddVertexAt(1, new Point2d((gradeLineInsPt.X + runningLine.Length), gradeLineInsPt.Y), 0, 0, 0); gradeLine.Layer = "PROFILE"; btr.AppendEntity(gradeLine); trans.AddNewlyCreatedDBObject(gradeLine, true); trans.Commit(); } //vertice to create selection fence use runningLine SelectionSet selectionSet = CreateFenceUsingPolyline(runningLine, false); //if any objects selected if (selectionSet != null) { //find objects that intersect with runningLine var objCrossingRunningLine = CrossingRunnngLine(selectionSet, runningLine, gradeLineInsPt); Point3dCollection bocPoints = new Point3dCollection(); //draw profile objects if any if (objCrossingRunningLine != null) { foreach (var obj in objCrossingRunningLine) { //draw profiles objects of Type = boc if (obj.Type == "boc") { bocPoints.Add(obj.Center); } else { DrawProfileObjects(obj); } } } if (bocPoints.Count != 0) { //convert to array to sort Point3d[] point3s = new Point3d[bocPoints.Count]; bocPoints.CopyTo(point3s, 0); Array.Sort(point3s, new sort3dByX()); Point3dCollection bocPtsSorted = new Point3dCollection(point3s); DrawProfileDriveway(bocPtsSorted, gradeLine.Length); } //find boc intersect //var bocCrossingRunningLine = } //bore line Polyline bore = gradeLine.GetOffsetCurves(14)[0] as Polyline; DrawBoreLine(bore); //find intercepting profile objects using fence and filter for only ellipses SelectionSet utilitiesCrossingBore = CreateFenceUsingPolyline(bore, true); //if any profile ellipses selected if (utilitiesCrossingBore != null) { //DrawBoreBelowUtilities(utilitiesCrossingBore, bore.ObjectId); } }
public void LineSegs2d() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Polyline pline = new Polyline(); //初始化钢束线 Point3d startPt = new Point3d(); //初始化起点 using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理 { //1.选择空间多段线 PromptEntityOptions plineOpt = new PromptEntityOptions("\n选择多段线"); plineOpt.SetRejectMessage("\n并非多段线!"); plineOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线 PromptEntityResult plineRes = ed.GetEntity(plineOpt); if (plineRes.Status != PromptStatus.OK) { return; } ObjectId plineId = plineRes.ObjectId; pline = trans.GetObject(plineId, OpenMode.ForWrite) as Polyline; //2.选择起始点 PromptPointOptions startPtOpt = new PromptPointOptions("\n选择曲线上的点作为起点"); PromptPointResult startPtRes = ed.GetPoint(startPtOpt); if (startPtRes.Status != PromptStatus.OK) { return; } startPt = pline.GetClosestPointTo(startPtRes.Value, false); //选择点到多段线的最近点 trans.Commit(); //执行事务处理 } //3.输入分段距离并节线化 Point3d newStartPt = startPt; //初始化每次绘制起点 double distOfStPt = pline.GetDistanceToStartPt(startPt); //获取起点距曲线起点的距离 for (;;) { PromptStringOptions segsOpt = new PromptStringOptions("\n输入分段距离或按ESC退出(各段长度以空格分隔,等间距采用N@d格式)"); segsOpt.AllowSpaces = true; //允许输入空格 PromptResult segsRes = ed.GetString(segsOpt); if (segsRes.Status == PromptStatus.OK) //如果输入正确且不为回车 { string input = segsRes.StringResult; //获得输入字符串 List <double> segLengths = new List <double>(); //初始化节段长List if (ReadSegsInput(ref segLengths, input)) //读入距离数据成功 { distOfStPt += segLengths.Sum(); //计算累计距离 if (distOfStPt > pline.Length) //累计距离已超过多段线长 { ed.WriteMessage("\n输入间距值已超出多段线范围,请重新输入!"); continue; } CreateLineSegs(pline, newStartPt, segLengths);//绘制直线段 newStartPt = pline.GetPointAtDist(distOfStPt); } else//读入距离数据有误 { ed.WriteMessage("\n输入有误,请重新输入!"); continue; } } else { break; //输入回车、ESC等则退出 } } }
public static void ColneToText() { DBText sourText = null; DBText targetText = null; var doc = Application.DocumentManager.MdiActiveDocument; var peo = new PromptEntityOptions("\n" + CommandStringResources.ResourceManager.GetString("SelectSourceText", GLOBAL.CurrentCulture)); peo.SetRejectMessage("\n" + CommandStringResources.ResourceManager.GetString("ObjectTypeIsNotSupported", GLOBAL.CurrentCulture)); peo.AddAllowedClass(typeof(DBText), false); var per = doc.Editor.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } var sId = per.ObjectId; using (var tr = doc.TransactionManager.StartTransaction()) { var t = tr.GetObject(sId, OpenMode.ForRead) as DBText; if (t != null) { sourText = t; } } doc.Editor.WriteMessage("\nSource Text Content: " + sourText.TextString); bool continueSelect = true; while (continueSelect) { var peo2 = new PromptEntityOptions("\nSelect Target Text"); peo2.SetRejectMessage("\n" + CommandStringResources.ResourceManager.GetString("ObjectTypeIsNotSupported", GLOBAL.CurrentCulture)); peo2.AddAllowedClass(typeof(DBText), false); var per2 = doc.Editor.GetEntity(peo2); if (per2.Status == PromptStatus.OK) { var tId = per2.ObjectId; using (var tr = doc.TransactionManager.StartTransaction()) { var t = tr.GetObject(tId, OpenMode.ForWrite) as DBText; if (t != null) { targetText = t; } } using (Transaction tr = doc.TransactionManager.StartTransaction()) { var text = tr.GetObject(targetText.ObjectId, OpenMode.ForWrite) as DBText; if (text != null) { text.TextString = sourText.TextString; } tr.Commit(); } } else { continueSelect = false; } } }
public void GetPointsAtDists() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Polyline pline = new Polyline(); //初始化多段线 Point3d startPt = new Point3d(); //初始化起点 double distOfStPt = 0; //初始化起点距 //初始化各标注图元 Vector3d drvt = new Vector3d(); //标注点切线 double len = 10 * scale_GPAD; //标注点长度,为10单位 Point3d pt1 = new Point3d(); //标准线起点 Point3d pt2 = new Point3d(); //标准线终点 Line line = new Line(); //标注线 using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理 { //1.选择多段线 PromptEntityOptions plineOpt = new PromptEntityOptions("\n选择多段线"); plineOpt.SetRejectMessage("\n并非多段线!"); plineOpt.AddAllowedClass(typeof(Polyline), true); PromptEntityResult plineRes = ed.GetEntity(plineOpt); if (plineRes.Status != PromptStatus.OK) { return; } pline = plineRes.ObjectId.GetObject(OpenMode.ForRead) as Polyline; //2.选择绘图比例 PromptDoubleOptions scaleOpt = new PromptDoubleOptions($"\n设置绘图比例<{scale_GPAD}>"); scaleOpt.AllowNone = true; //允许回车,则采用默认比例 scaleOpt.AllowNegative = false; //不允许负值 scaleOpt.AllowZero = false; //不允许零值 PromptDoubleResult scaleRes = ed.GetDouble(scaleOpt); //获取比例 if (scaleRes.Status == PromptStatus.OK) { scale_GPAD = scaleRes.Value; //获取绘图比例 len = 10 * scale_GPAD; //重设标注线长度 } //3.选择起点 PromptPointOptions startPtOpt = new PromptPointOptions("\n选择曲线上的点作为起点"); PromptPointResult startPtRes = ed.GetPoint(startPtOpt); if (startPtRes.Status != PromptStatus.OK) { return; } startPt = pline.GetClosestPointTo(startPtRes.Value, false); //选择点到多段线的最近点 distOfStPt = pline.GetDistanceToStartPt(startPt); //获取起点距曲线起点的距离 //绘制起点线 drvt = pline.GetFirstDerivative(startPt); //获取切线 pt1 = startPt + len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis); pt2 = startPt - len / 2 * drvt.GetUnitVector().RotateBy(Math.PI / 2, Vector3d.ZAxis); line = new Line(pt1, pt2); db.AddToModelSpace(line); //4.是否标注距离 PromptKeywordOptions kwOpt = new PromptKeywordOptions($"\n是否标注沿曲线长度[Y/N]<{isDistDenote}>"); kwOpt.Keywords.Add("Y"); kwOpt.Keywords.Add("N"); kwOpt.AllowNone = true; //可回车 kwOpt.AllowArbitraryInput = false; //不可随意输入 kwOpt.AppendKeywordsToMessage = false; //提示信息中不显示关键字 PromptResult kwRes = ed.GetKeywords(kwOpt); if (kwRes.Status == PromptStatus.OK) { isDistDenote = kwRes.StringResult; } trans.Commit();//执行事务处理 } //5.输入沿曲线距离 //无限循环 double distCum = distOfStPt; //初始化累计长度 Point3d newStartPt = startPt; //初始化当前前进起始点 for (;;) { using (Transaction trans = db.TransactionManager.StartTransaction())//开始事务处理 { PromptStringOptions distsOpt = new PromptStringOptions("\n输入分段距离或按ESC退出(各段长度以空格分隔,等间距采用N@d格式)"); distsOpt.AllowSpaces = true; //允许输入空格 PromptResult distsRes = ed.GetString(distsOpt); if (distsRes.Status == PromptStatus.OK) //输入正确 { List <double> dists = new List <double>(); if (ReadSegsInput(ref dists, distsRes.StringResult))//读入距离数据成功 { if (distCum + dists.Sum() > pline.Length) { ed.WriteMessage("超出多段线范围,请重新输入!"); trans.Abort(); continue; } CreateSpanLines(pline, newStartPt, dists, isDistDenote, scale_GPAD); distCum += dists.Sum(); //重置前进距离 newStartPt = pline.GetPointAtDist(distCum); //重置当前前进起始点 trans.Commit(); //执行事务处理 } else//读入距离数据有误 { ed.WriteMessage("\n输入有误,请重新输入!"); trans.Abort(); continue; } } else { trans.Abort(); break;//输入回车、ESC等则退出 } } } }
public void RegionDescriptionStart() { var sysUnits = Application.GetSystemVariable("INSUNITS").ToString(); if ((sysUnits != "1") && (sysUnits != "2") && (sysUnits != "4") && (sysUnits != "5") && (sysUnits != "6") && (sysUnits != "14")) { MessageBox.Show("\nUnits to scale inserted content: UNRECOGNIZED ?!", "units E R R O R"); return; } // Prompt the user to select region mode - points or object //var regDescrModeOpts =new PromptKeywordOptions("\nSelect mode [Polylines And Circles/Regions/Block]", "PolylinesAndCircles Regions Block"); var regDescrModeOpts = new PromptKeywordOptions("") { Message = "Select cross section mode:" }; regDescrModeOpts.Keywords.Add("PolylinesAndCircles"); regDescrModeOpts.Keywords.Add("Regions"); regDescrModeOpts.Keywords.Add("Block"); var regDescrModeRslt = Ed.GetKeywords(regDescrModeOpts); // If the user pressed cancel - return with no error if (regDescrModeRslt.Status != PromptStatus.OK) { return; } var myRegionColl = new DBObjectCollection(); var objectsType = typeof(bool); switch (regDescrModeRslt.StringResult) { case "PolylinesAndCircles": #region Contours Selection // Start a transaction using (var tr = Db.TransactionManager.StartTransaction()) { #region contour // Request for objects to be selected in the drawing area \ Ed.WriteMessage("\nSelect object describing outer contour"); //TypeVals.SetValue(new TypedValue((int)DxfCode.Start , "POLYLINE") , 0); //TypeVals.SetValue(new TypedValue((int)DxfCode.Operator , "OR") , 1); //TypeVals.SetValue(new TypedValue((int)DxfCode.Start , "CIRCLE") , 2); // Assign the filter criteria to a SelectionFilter object //SelectionFilter SelFilter = new SelectionFilter(TypeVals); //PromptSelectionResult SSPrompt = Ed.GetSelection(SelFilter); var ssPrompt = Ed.GetSelection(); // If the prompt status is OK, objects were selected if (ssPrompt.Status == PromptStatus.OK) { var acSSet = ssPrompt.Value; // Step through the objects in the selection set var acDbObjColl = new DBObjectCollection(); foreach (SelectedObject acSsObj in acSSet) { // Check to make sure a valid SelectedObject object was returned if (acSsObj == null) { continue; } // Open the selected object for write var acEnt = tr.GetObject(acSsObj.ObjectId, OpenMode.ForWrite) as Entity; if (acEnt != null) { acDbObjColl.Add(acEnt); } else { Ed.WriteMessage("Invalid input."); } } myRegionColl = Region.CreateFromCurves(acDbObjColl); } #endregion tr.Commit(); } // If the user did not select any objects if (myRegionColl.Count == 0) { return; } objectsType = typeof(Polyline); #endregion break; case "Regions": #region Regions Selection // Prompt for Regions var regionsSsOpts = new PromptSelectionOptions { AllowDuplicates = false }; //PromptEntityResult ObjectSelectionRslt = Ed.GetEntity(ObjectSelectionOpts); var regionsSsPrompt = Ed.GetSelection(regionsSsOpts); // If the prompt status is OK, objects were selected if (regionsSsPrompt.Status != PromptStatus.OK) { return; } var regionsacSSet = regionsSsPrompt.Value; // Step through the objects in the selection set using (var tr = Db.TransactionManager.StartTransaction()) { var acDbObjColl = new DBObjectCollection(); foreach (SelectedObject acSsObj in regionsacSSet) { // Check to make sure a valid SelectedObject object was returned if (acSsObj == null) { continue; } // Open the selected object for write var acEnt = tr.GetObject(acSsObj.ObjectId, OpenMode.ForWrite) as Region; if (acEnt != null) { var acDBObjColl_ = new DBObjectCollection(); acEnt.Explode(acDBObjColl_); foreach (Entity acEntt in acDBObjColl_) { acDbObjColl.Add(acEntt); } } } myRegionColl = Region.CreateFromCurves(acDbObjColl); } // Dispatch function here #endregion objectsType = typeof(Region); break; case "Block": #region Block Selection // Ask the user to select a block var peo = new PromptEntityOptions("\nSelect a block:"); peo.AllowNone = false; peo.SetRejectMessage("\nMust select a block."); peo.AddAllowedClass(typeof(BlockReference), false); var per = Ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } using (var tr = Db.TransactionManager.StartTransaction()) { try { var ent = (Entity)tr.GetObject(per.ObjectId, OpenMode.ForRead); var br = ent as BlockReference; if (br != null) { var btr = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForWrite); var acDbObjColl = new DBObjectCollection(); foreach (var id in btr) { var ent2 = (Entity)tr.GetObject(id, OpenMode.ForWrite); var str = ent2.GetType().ToString().Split('.'); var Str = str[str.Length - 1]; if (Str != "Polyline") { if (Str == "Region") { var acEnt = (Region)tr.GetObject(ent2.ObjectId, OpenMode.ForWrite); var acDBObjColl_ = new DBObjectCollection(); acEnt.Explode(acDBObjColl_); foreach (Entity acEntt in acDBObjColl_) { acDbObjColl.Add(acEntt); } } else { acDbObjColl.Add(ent2); } } else { var pl = ent2 as Polyline; if (pl != null) { if (pl.Closed) { acDbObjColl.Add(pl); } else { if ((pl.StartPoint.DistanceTo(pl.EndPoint) < 0.0000001) && (Str == "Polyline")) { acDbObjColl.Add(pl); } else { MessageBox.Show("Not Closed PolyLine !"); } } } else { var crl = ent2 as Circle; if (crl != null) { acDbObjColl.Add(crl); } } } } // myRegionColl = new DBObjectCollection(); myRegionColl = Region.CreateFromCurves(acDbObjColl); var ori = new Point3d(0, 0, 0); var pos = br.Position; foreach (Region reg in myRegionColl) { var Reg = reg; MoveRegionInOrigin(ref Reg, ref ori, ref pos); } tr.Commit(); } } catch (Exception e) { Ed.WriteMessage(e.ToString()); } } #endregion objectsType = typeof(BlockReference); break; } #region Density selection /* PromptDoubleOptions DensityOptions = new PromptDoubleOptions( "Enter density [kg/m3] : " ); * DensityOptions.UseDefaultValue = true; * DensityOptions.DefaultValue = Settings.Default.RegionDescrDensity; * PromptDoubleResult DensityResult = Ed.GetDouble( DensityOptions ); * if ( DensityResult.Status != PromptStatus.OK ) * { * return; * } * else if ( DensityResult.Value == 0.0 ) * { * MessageBox.Show( "Density must be greater than zero!" ); * return; * }*/ Settings.Default.RegionDescrDensity = 1000.0 /*DensityResult.Value*/; Settings.Default.Save(); #endregion #region Insertion Point selection var insPointOptions = new PromptPointOptions("Pick insertion point : "); var insPointResult = Ed.GetPoint(insPointOptions); if (insPointResult.Status != PromptStatus.OK) { return; } #endregion if (objectsType.Name == "Boolean") { MessageBox.Show("Error identifing type."); return; } using (var tr = Db.TransactionManager.StartTransaction()) { var extractedRegion = ExtractRegionFromObjects(ref myRegionColl, tr); //RegMassProps = GetRegionMassProperties(ExtractedRegion); var regMassProps = new RegionMassProperties(extractedRegion, Settings.Default.RegionDescrDensity) { TextInsertionPoint = insPointResult.Value }; var rdForm = new RegionDescriptionForm(regMassProps, Ed.Document); rdForm.ShowDialog(); if (rdForm.DialogResult == DialogResult.OK) { _textId = new ObjectId(); } tr.Commit(); } }
//////////////////////////// //// Display Props //// list all the disp reps for the door for the current view port //////////////////////////// private void DisplayProps() { Database db = Application.DocumentManager.MdiActiveDocument.Database; TransactionManager tm = db.TransactionManager; Transaction trans = db.TransactionManager.StartTransaction(); BlockTable bt = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false); BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false); DictionaryDisplaySet dds = new DictionaryDisplaySet(db, false); try { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptEntityOptions optEnt = new PromptEntityOptions("Select an AEC door entity"); optEnt.SetRejectMessage("Selected entity is NOT an AEC door entity, try again..."); optEnt.AddAllowedClass(typeof(Autodesk.Aec.Arch.DatabaseServices.Door), false); // Geo is the base class of AEC entities. PromptEntityResult resEnt = ed.GetEntity(optEnt); if (resEnt.Status != PromptStatus.OK) { ed.WriteMessage("Selection error - aborting" + "\n"); return; } Autodesk.Aec.Arch.DatabaseServices.Door door = trans.GetObject(resEnt.ObjectId, OpenMode.ForRead) as Door; ed.WriteMessage("You have selected an " + door.GetRXClass().Name + "\n"); // get its style Autodesk.Aec.Arch.DatabaseServices.DoorStyle doorstyle = trans.GetObject(door.StyleId, OpenMode.ForRead) as DoorStyle; ObjectId doorId = door.ObjectId; DisplayRepresentationManager drm = new DisplayRepresentationManager(db); ObjectIdCollection ids = drm.GetDisplayRepresentationIdsFromCurrentViewport(door.GetRXClass()); DisplayRepresentation dr = null; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Get all the Display Representations work with the door for current view port\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("door disp rep count = " + ids.Count + "\n"); foreach (ObjectId id in ids) { dr = trans.GetObject(id, OpenMode.ForRead) as DisplayRepresentation; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Display Representation Name: " + dr.Name + " Display Name: " + dr.DisplayName + "\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Display Representation Name: " + dr.Name + "Display Name" + dr.DisplayName + "\n"); DisplayProperties dps = null; RXClass rcProps = dr.DisplayPropertiesClass; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Display Props Class: " + rcProps.Name + "\n"); // find override at instance level. ObjectId overId = dr.FindDisplayPropertiesOverride(door); if (overId != ObjectId.Null) { dps = trans.GetObject(overId, OpenMode.ForRead) as DisplayProperties; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Element override Display Props Name: " + dps.Name + "Display Name" + dps.DisplayName + "\n"); continue; } ObjectId overstyleId = dr.FindDisplayPropertiesOverride(doorstyle); if (overstyleId != ObjectId.Null) { dps = trans.GetObject(overstyleId, OpenMode.ForRead) as DisplayProperties; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Style override Style Display Props Name: " + dps.Name + "Display Name" + dps.DisplayName + "\n"); continue; } ObjectId defaultDpsId = dr.DefaultDisplayPropertiesId; if (!defaultDpsId.IsNull) { dps = trans.GetObject(defaultDpsId, OpenMode.ForRead) as DisplayProperties; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Default Display Props Name: " + dps.Name + "Display Name" + dps.DisplayName + "\n"); } } trans.Commit(); } catch (System.Exception) { trans.Abort(); } finally { trans.Dispose(); } return; }
private bool GetAlignmentParameters() { var doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; var ed = doc.Editor; Matrix3d ucs2wcs = AcadGraphics.UcsToWcs; Matrix3d wcs2ucs = AcadGraphics.WcsToUcs; // Alignment type Alignment = Bridge.PickAlignment(); if (Alignment == Bridge.AlignmentType.None) { return(false); } // Alignment line PromptEntityOptions entityOpts = new PromptEntityOptions("\nEksen: "); entityOpts.SetRejectMessage("\nSelect a curve."); entityOpts.AddAllowedClass(typeof(Curve), false); PromptEntityResult entityRes = ed.GetEntity(entityOpts); if (entityRes.Status == PromptStatus.OK) { CenterlineId = entityRes.ObjectId; } else { return(false); } // Start point PromptPointResult ptRes = ed.GetPoint("\nBaşlangıç noktası: "); if (ptRes.Status == PromptStatus.OK) { StartPoint = ptRes.Value.TransformBy(ucs2wcs); } else { return(false); } // Start CH AcadEditor.PromptChainageOptions chOpts = new AcadEditor.PromptChainageOptions("\nBaşlangıç kilometresi: "); chOpts.DefaultValue = AcadText.ChainageToString(StartCH, ChPrecision); chOpts.UseDefaultValue = true; AcadEditor.PromptChainageResult chRes = ed.GetChainage(chOpts); if (chRes.Status == PromptStatus.OK) { StartCH = chRes.DoubleResult; } else if (chRes.Status == PromptStatus.None) { // Use default } else if (chRes.Status != PromptStatus.OK) { return(false); } return(true); }
public void TendonAnnotation() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; db.SyncDwgToTdGenParas();//设置默认总体参数,已有总体参数字典项则无动作 using (Transaction trans = db.TransactionManager.StartTransaction()) { #region 1.选择梁顶缘线 PromptEntityOptions tpLineOpt = new PromptEntityOptions("\n选择梁顶缘线"); tpLineOpt.SetRejectMessage("\n顶缘线应为直线、圆弧或多段线"); tpLineOpt.AddAllowedClass(typeof(Line), true); //可以选择直线 tpLineOpt.AddAllowedClass(typeof(Polyline), true); //可以选择多段线 tpLineOpt.AddAllowedClass(typeof(Arc), true); //可以选择圆弧线 PromptEntityResult tpLineRes = ed.GetEntity(tpLineOpt); if (tpLineRes.Status != PromptStatus.OK) { return; } ObjectId tpLineId = tpLineRes.ObjectId; Curve tpLine = trans.GetObject(tpLineId, OpenMode.ForRead) as Curve; #endregion #region 2.选择钢束线 PromptEntityOptions tdLineOpt = new PromptEntityOptions("\n选择钢束"); tdLineOpt.SetRejectMessage("\n钢束应为多段线"); tdLineOpt.AddAllowedClass(typeof(Polyline), true);//仅能选择多段线 PromptEntityResult tdLineRes = ed.GetEntity(tdLineOpt); if (tdLineRes.Status != PromptStatus.OK) { return; } ObjectId tdLineId = tdLineRes.ObjectId; Polyline tdLine = trans.GetObject(tdLineId, OpenMode.ForRead) as Polyline; //判断钢束线是否在顶缘线以内,否则报错返回 if (tdLine.StartPoint.X < tpLine.StartPoint.X || tdLine.EndPoint.X > tpLine.EndPoint.X) { Application.ShowAlertDialog("钢束线超出顶缘线,请检查!"); return; } tdLine.SetDefaultTendonParams();//设置钢束默认参数,如已有Xrecord信息则无动作 #endregion #region 3.设置绘图参数(包括张拉方式和工作长度设置) //3.1 尺寸标注绘图位置及张拉方式和工作长度设置 Point3d pos = new Point3d();//初始化标注点 PromptPointOptions posOpt = new PromptPointOptions("\n设置标注线位置或设置[张拉方式(D)/工作长度(W)]"); posOpt.Keywords.Add("D"); posOpt.Keywords.Add("W"); posOpt.AppendKeywordsToMessage = false; //提示信息中不显示关键字 //获取钢束张拉方式 int tdDrawStyle = 0; //默认为两端张拉 if (!tdLine.ExtensionDictionary.IsNull && tdLine.ObjectId.GetXrecord("DA_Tendons") != null) //如果钢束线有扩展记录则取扩展记录数据 { tdDrawStyle = (Int16)tdLine.ObjectId.GetXrecord("DA_Tendons")[4].Value; } //获取工作长度信息 double workLen = 800; DBDictionary dicts = db.NamedObjectsDictionaryId.GetObject(OpenMode.ForWrite) as DBDictionary; if (dicts.Contains("DA_Tendons"))//如果字典中含DA_Tendons的字典项 { ObjectId tdsDictId = dicts.GetAt("DA_Tendons"); DBDictionary tdsDict = tdsDictId.GetObject(OpenMode.ForRead) as DBDictionary; //获取DA_Tendons字典 ObjectId xrecId = tdsDict.GetAt("workLen"); //获取字典中的工作长度项 Xrecord xrec = xrecId.GetObject(OpenMode.ForRead) as Xrecord; //获取工作长度项中的Xrecird TypedValueList vls = xrec.Data; //获取Xrecord中的TypedValueList数据 workLen = (double)vls[0].Value; //根据TypedValueList数据中的数值更新工作长度workLen } for (;;) { PromptPointResult posRes = ed.GetPoint(posOpt); if (posRes.Status == PromptStatus.Keyword) { switch (posRes.StringResult) { case "D": //选择修改张拉方式 PromptIntegerOptions drwOpt = new PromptIntegerOptions($"\n输入张拉方式[两端张拉(0)/左端张拉[-1]/右端张拉[1]<{tdDrawStyle}>"); drwOpt.AllowNone = true; //允许ESC退出 PromptIntegerResult drwRes = ed.GetInteger(drwOpt); if (drwRes.Value == 0) { tdDrawStyle = 0; } else if (drwRes.Value == -1) { tdDrawStyle = -1; } else if (drwRes.Value == 1) { tdDrawStyle = 1; } TypedValueList values = tdLine.ObjectId.GetXrecord("DA_Tendons"); //根据输入更新钢束线的Xrecord记录 values.RemoveAt(4); values.Add(DxfCode.Int16, tdDrawStyle); break; case "W": //修改工作长度 PromptDoubleOptions wklOpt = new PromptDoubleOptions($"\n输入工作长度<{workLen.ToString("F0")}>"); wklOpt.AllowNone = true; //允许ESC退出 PromptDoubleResult wklRes = ed.GetDouble(wklOpt); if (wklRes.Status == PromptStatus.OK) { workLen = wklRes.Value; ObjectId tdsDictId = dicts.GetAt("DA_Tendons");//更新DA_Tendons字典中的钢束总体参数 DBDictionary tdsDict = tdsDictId.GetObject(OpenMode.ForRead) as DBDictionary; ObjectId xrecId = tdsDict.GetAt("workLen"); Xrecord xrec = xrecId.GetObject(OpenMode.ForWrite) as Xrecord; TypedValueList vls = new TypedValueList(); vls.Add(DxfCode.Real, workLen); xrec.Data = vls; xrec.DowngradeOpen(); } break; } } else if (posRes.Status == PromptStatus.OK) { pos = posRes.Value; break; } } //3.2 绘图比例 PromptDoubleOptions scaleOpt = new PromptDoubleOptions($"\n设置绘图比例<{scale}>"); scaleOpt.AllowNone = true; //允许回车,则采用前次比例 scaleOpt.AllowNegative = false; //不允许负值 scaleOpt.AllowZero = false; //不允许零值 PromptDoubleResult scaleRes = ed.GetDouble(scaleOpt); //获取比例 if (scaleRes.Status != PromptStatus.OK && scaleRes.Status != PromptStatus.None) { return; } else if (scaleRes.Status == PromptStatus.OK) { scale = scaleRes.Value; } #endregion #region 4.建立各类标注 List <Point3d> ptsH = new List <Point3d>(); //创建水平标注点集 List <Dimension> dims = new List <Dimension>(); //创建标注集,存放各类标注 for (int i = 0; i < tdLine.NumberOfVertices - 1; i++) { //4.1 水平点集 ptsH.Add(tdLine.GetPoint3dAt(i)); //4.2 每段钢束线的长度 //4.3 直线标注角度 //4.4 圆弧线标注半径 if (tdLine.GetSegmentType(i) == SegmentType.Line) { LineSegment3d lineSeg = tdLine.GetLineSegmentAt(i); //4.2 每段钢束线的长度 db.LineLengthDim(lineSeg, scale); //4.3 直线标注角度 if (tdLine.StartPoint.X < tdLine.EndPoint.X) { db.LineAngelDim(lineSeg, !(i == tdLine.NumberOfVertices - 2), scale); } else { db.LineAngelDim(lineSeg, (i == tdLine.NumberOfVertices - 2), scale); } } else if (tdLine.GetSegmentType(i) == SegmentType.Arc) { CircularArc3d arcSeg = tdLine.GetArcSegmentAt(i); //4.2 每段钢束线的长度 db.ArcLengthDim(arcSeg, scale); //4.3 圆弧标注半径 db.ArrowRadiusDim(arcSeg, scale); } //4.5 竖直距离标注 Ray vRay = new Ray();//建立竖直射线 vRay.BasePoint = tdLine.GetPoint3dAt(i); vRay.UnitDir = new Vector3d(0, 1, 0); Point3dCollection ptIntersects = new Point3dCollection(); tpLine.IntersectWith(vRay, Intersect.OnBothOperands, ptIntersects, IntPtr.Zero, IntPtr.Zero); Point3d ptIntersect = ptIntersects[0]; RotatedDimension dimV = new RotatedDimension(); dimV.XLine1Point = tdLine.GetPoint3dAt(i); //第一条尺寸边线 dimV.XLine2Point = ptIntersect; //第二条尺寸边线 dimV.DimLinePoint = tdLine.GetPoint3dAt(i); //尺寸线位置 dimV.Rotation = Math.PI / 2; //标注旋转90度 dimV.DimensionStyle = db.Dimstyle; //尺寸样式为当前样式 dimV.Dimscale = scale; //设置尺寸全局比例 dims.Add(dimV); } //4.1 节点间距点集缺钢束最后一个点、梁顶缘线端点 ptsH.Add(tdLine.EndPoint); ptsH.Add(tpLine.StartPoint); ptsH.Add(tpLine.EndPoint); db.ContinuedHorizontalDims(ptsH, pos, scale);//建立水平连续标注 //4.5 竖直距离标注缺最后一个点 Ray vRayLast = new Ray();//建立竖直射线 vRayLast.BasePoint = tdLine.GetPoint3dAt(tdLine.NumberOfVertices - 1); vRayLast.UnitDir = new Vector3d(0, 1, 0); Point3dCollection ptIntersectsLast = new Point3dCollection(); tpLine.IntersectWith(vRayLast, Intersect.OnBothOperands, ptIntersectsLast, IntPtr.Zero, IntPtr.Zero); Point3d ptIntersectLast = ptIntersectsLast[0]; RotatedDimension dimVLast = new RotatedDimension(); dimVLast.XLine1Point = tdLine.GetPoint3dAt(tdLine.NumberOfVertices - 1); //第一条尺寸边线 dimVLast.XLine2Point = ptIntersectLast; //第二条尺寸边线 dimVLast.DimLinePoint = tdLine.GetPoint3dAt(tdLine.NumberOfVertices - 1); //尺寸线位置 dimVLast.Rotation = Math.PI / 2; //标注旋转90度 dimVLast.DimensionStyle = db.Dimstyle; //尺寸样式为当前样式 dimVLast.Dimscale = scale; //设置尺寸全局比例 dims.Add(dimVLast); #endregion #region 5 绘制张拉端 //5.1 获取张拉端几何特征 //获取钢束线真实的起点和终点 Point3d tdStart = (tdLine.StartPoint.X < tdLine.EndPoint.X) ? tdLine.StartPoint : tdLine.EndPoint; Point3d tdEnd = (tdLine.StartPoint.X < tdLine.EndPoint.X) ? tdLine.EndPoint : tdLine.StartPoint; //获取钢束线真实的起终点角度 double iclStart = (tdLine.StartPoint.X < tdLine.EndPoint.X) ? tdLine.GetLineSegmentAt(0).GetAngleOfLineSeg() : tdLine.GetLineSegmentAt(tdLine.NumberOfVertices - 2).GetAngleOfLineSeg(); double iclEnd = (tdLine.StartPoint.X < tdLine.EndPoint.X) ? tdLine.GetLineSegmentAt(tdLine.NumberOfVertices - 2).GetAngleOfLineSeg() : tdLine.GetLineSegmentAt(0).GetAngleOfLineSeg(); //初始化张拉端图元 Polyline leftDraw = new Polyline(); Polyline rightDraw = new Polyline(); MText lengthL = new MText(); MText lengthR = new MText(); //5.2 左侧张拉端 //5.2.1 两侧张拉或左侧张拉时左端绘制工作长度线 if (tdDrawStyle == 0 || tdDrawStyle == -1) { //创建张拉端几何点 Point3d tdDrawL = GeTools.PolarPoint(tdStart, iclStart, -workLen); //创建张拉段 leftDraw = new Polyline(); leftDraw.AddVertexAt(0, tdStart.ToPoint2d(), 0, 0, 0); leftDraw.AddVertexAt(1, tdDrawL.ToPoint2d(), 0, 0, 0); leftDraw.Layer = tdLine.Layer;//张拉段与钢束线应该在同一层 //标注左侧张拉段 lengthL = new MText(); //长度 lengthL.Contents = "工作长度" + workLen.ToString("F0"); //文字高度 lengthL.TextHeight = 3 * scale; //样式为当前样式 lengthL.TextStyleId = db.Textstyle; //旋转角度同直线段倾角 lengthL.Rotation = iclStart; //对齐位置为右上 lengthL.Attachment = AttachmentPoint.TopRight; //位置为中点垂线以下0.5个单位 lengthL.Location = GeTools.PolarPoint(GeTools.MidPoint(leftDraw.StartPoint, leftDraw.EndPoint), iclStart - Math.PI / 2, 0.5 * scale); } //5.2.2 右侧张拉时绘制P锚标识 else { //创建P锚起终点 Point3d tdDrawL1 = GeTools.PolarPoint(tdStart, iclStart + Math.PI / 2, 0.75 * scale); Point3d tdDrawL2 = GeTools.PolarPoint(tdStart, iclStart + Math.PI / 2, -0.75 * scale); //创建P锚标志 leftDraw = new Polyline(); leftDraw.AddVertexAt(0, tdDrawL1.ToPoint2d(), 0, 0.35 * scale, 0.35 * scale); leftDraw.AddVertexAt(1, tdDrawL2.ToPoint2d(), 0, 0.35 * scale, 0.35 * scale); leftDraw.Layer = tdLine.Layer;//张拉段与钢束线应该在同一层 //标注左侧P锚 lengthL = new MText(); //长度 lengthL.Contents = "P锚"; //文字高度 lengthL.TextHeight = 3 * scale; //样式为当前样式 lengthL.TextStyleId = db.Textstyle; //旋转角度同直线段倾角 lengthL.Rotation = iclStart; //对齐位置为右中 lengthL.Attachment = AttachmentPoint.MiddleRight; //位置为P锚标志右侧0.5个单位 lengthL.Location = GeTools.PolarPoint(GeTools.MidPoint(leftDraw.StartPoint, leftDraw.EndPoint), iclStart, -2 * scale); } //5.3 右侧张拉端绘制 //5.3.1 两侧张拉或右侧张拉时右端绘制工作长度线 if (tdDrawStyle == 0 || tdDrawStyle == 1) { //创建张拉端几何点 Point3d tdDrawR = GeTools.PolarPoint(tdEnd, iclEnd, workLen); //创建张拉段 rightDraw = new Polyline(); rightDraw.AddVertexAt(0, tdEnd.ToPoint2d(), 0, 0, 0); rightDraw.AddVertexAt(1, tdDrawR.ToPoint2d(), 0, 0, 0); rightDraw.Layer = tdLine.Layer;//张拉段与钢束线应该在同一层 //标注右侧张拉段 lengthR = new MText(); //长度 lengthR.Contents = "工作长度" + workLen.ToString("F0"); //文字高度 lengthR.TextHeight = 3 * scale; //样式为当前样式 lengthR.TextStyleId = db.Textstyle; //旋转角度同直线段倾角 lengthR.Rotation = iclEnd; //对齐位置为左上 lengthR.Attachment = AttachmentPoint.TopLeft; //位置为中点垂线以下0.5个单位 lengthR.Location = GeTools.PolarPoint(GeTools.MidPoint(rightDraw.StartPoint, rightDraw.EndPoint), iclEnd - Math.PI / 2, 0.5 * scale); } //5.2.2 左侧张拉时绘制P锚标识 else//绘制P锚 { //创建P锚起终点 Point3d tdDrawR1 = GeTools.PolarPoint(tdEnd, iclEnd + Math.PI / 2, 0.75 * scale); Point3d tdDrawR2 = GeTools.PolarPoint(tdEnd, iclEnd + Math.PI / 2, -0.75 * scale); //创建P锚标志 rightDraw = new Polyline(); rightDraw.AddVertexAt(0, tdDrawR1.ToPoint2d(), 0, 0.35 * scale, 0.35 * scale); rightDraw.AddVertexAt(1, tdDrawR2.ToPoint2d(), 0, 0.35 * scale, 0.35 * scale); rightDraw.Layer = tdLine.Layer;//张拉段与钢束线应该在同一层 //标注左侧P锚 lengthR = new MText(); //长度 lengthR.Contents = "P锚"; //文字高度 lengthR.TextHeight = 3 * scale; //样式为当前样式 lengthR.TextStyleId = db.Textstyle; //旋转角度同直线段倾角 lengthR.Rotation = iclEnd; //对齐位置为左中 lengthR.Attachment = AttachmentPoint.MiddleLeft; //位置为P锚标志右侧0.5个单位 lengthR.Location = GeTools.PolarPoint(GeTools.MidPoint(rightDraw.StartPoint, rightDraw.EndPoint), iclEnd, 2 * scale); } #endregion #region 6 在截面顶缘标识“梁顶缘线” Point3d midPt = GeTools.MidPoint(tpLine.StartPoint, tpLine.EndPoint); //顶缘线起终点中点 Point3d midPtInTp = tpLine.GetClosestPointTo(midPt, Vector3d.YAxis, true); //顶缘线上靠近中点的点 MText tpAnno = new MText(); tpAnno.Contents = "梁顶缘线"; //文字高度 tpAnno.TextHeight = 3 * scale; //样式为当前样式 tpAnno.TextStyleId = db.Textstyle; //对齐位置为右上 tpAnno.Attachment = AttachmentPoint.BottomLeft; //位置为中点以上0.5个单位 tpAnno.Location = GeTools.PolarPoint(midPtInTp, Math.PI / 2, 0.5 * scale); #endregion db.AddToModelSpace(dims.ToArray()); //添加各类标注 db.AddToModelSpace(leftDraw, rightDraw, lengthL, lengthR); //添加张拉段线 db.AddToModelSpace(tpAnno); //添加梁顶缘线标识 trans.Commit(); } }
public void Cmd_DimAdd() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; var prEntOpt = new PromptEntityOptions("\nSelect a dimension system to add to: "); prEntOpt.SetRejectMessage("\nOnly linear dimensions may be selected."); prEntOpt.AllowNone = false; prEntOpt.AddAllowedClass(typeof(RotatedDimension), false); var prEntRes = acCurEd.GetEntity(prEntOpt); if (prEntRes.Status != PromptStatus.OK) { return; } var objId = prEntRes.ObjectId; var addMatrix = acCurEd.GetAlignedMatrix(); var eqPoint = CalcTol.ReturnCurrentTolerance(); using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var acEnt = acTrans.GetObject(objId, OpenMode.ForWrite) as Entity; if (acEnt != null) { acEnt.Unhighlight(); var acRotDim = acEnt as RotatedDimension; if (acRotDim != null) { var dimSys = DimSystem.GetSystem(acRotDim, eqPoint, eqPoint); var prPtOpts = new PromptPointOptions("\nSelect point to add: "); while (true) { dimSys.Highlight(); var dPoints = dimSys.GetSystemPoints(eqPoint); var dimLinPt = new Point3d(); var pt = new Point3d(); var bl = false; foreach (var dPt in dPoints) { if (bl) { pt = dPt.DimLinePoint; break; } dimLinPt = dPt.DimLinePoint; bl = true; } var nArray = DimSystem.GetActiveViewCount(); var currentTransientManager = TransientManager.CurrentTransientManager; var acLine = new Line(new Point3d(0, 0, 0), new Point3d(0, 0, 0)); var acPreview = new Line(new Point3d(0, 0, 0), new Point3d(0, 0, 0)); acLine.Color = SettingsUser.DynPreviewColor; acPreview.Color = SettingsUser.DynPreviewColor; var integerCollections = new IntegerCollection(nArray); currentTransientManager.AddTransient(acLine, TransientDrawingMode.Main, 128, integerCollections); currentTransientManager.AddTransient(acPreview, TransientDrawingMode.Main, 128, integerCollections); void PointMonitorEventHandler(object sender, PointMonitorEventArgs e) { var point3dArray = DimSystem.GetSystemPoint(dimLinPt, pt, e.Context.ComputedPoint); acLine.StartPoint = point3dArray[0]; acLine.EndPoint = point3dArray[1]; acPreview.StartPoint = point3dArray[1]; acPreview.EndPoint = e.Context.ComputedPoint; currentTransientManager.UpdateTransient(acLine, integerCollections); currentTransientManager.UpdateTransient(acPreview, integerCollections); } acCurEd.PointMonitor += PointMonitorEventHandler; PromptPointResult ptRes; try { ptRes = acCurEd.GetPoint(prPtOpts); } finally { acCurEd.PointMonitor -= PointMonitorEventHandler; currentTransientManager.EraseTransient(acLine, integerCollections); currentTransientManager.EraseTransient(acPreview, integerCollections); acLine.Dispose(); acPreview.Dispose(); } if (ptRes.Status != PromptStatus.OK) { break; } dimSys.Insert(ptRes.Value.TransformBy(addMatrix)); } dimSys.Unhighlight(); } } acTrans.Commit(); } }
public void CreateSectionFromPolylineCommand() { #if !DEBUG Statistic.SendCommandStarting("mpSectionFromPolyline", ModPlusConnector.Instance.AvailProductExternalVersion); #endif try { // Выберите полилинию: var peo = new PromptEntityOptions($"\n{Language.GetItem(Invariables.LangItem, "msg6")}") { AllowNone = false, AllowObjectOnLockedLayer = true }; peo.SetRejectMessage($"\n{Language.GetItem(Invariables.LangItem, "wrong")}"); peo.AddAllowedClass(typeof(Polyline), true); var per = AcadUtils.Editor.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } /* Регистрация ЕСКД приложения должна запускаться при запуске * функции, т.к. регистрация происходит в текущем документе * При инициализации плагина регистрации нет! */ ExtendedDataUtils.AddRegAppTableRecord(SectionDescriptor.Instance.Name); var style = StyleManager.GetCurrentStyle(typeof(Section)); var sectionLastLetterValue = string.Empty; var sectionLastIntegerValue = string.Empty; FindLastSectionValues(ref sectionLastLetterValue, ref sectionLastIntegerValue); var section = new Section(sectionLastIntegerValue, sectionLastLetterValue); MainFunction.CreateBlock(section); section.ApplyStyle(style, true); var plineId = per.ObjectId; using (AcadUtils.Document.LockDocument(DocumentLockMode.ProtectedAutoWrite, null, null, true)) { using (var tr = AcadUtils.Document.TransactionManager.StartOpenCloseTransaction()) { var dbObj = tr.GetObject(plineId, OpenMode.ForRead); if (dbObj is Polyline pline) { for (int i = 0; i < pline.NumberOfVertices; i++) { if (i == 0) { section.InsertionPoint = pline.GetPoint3dAt(i); } else if (i == pline.NumberOfVertices - 1) { section.EndPoint = pline.GetPoint3dAt(i); } else { section.MiddlePoints.Add(pline.GetPoint3dAt(i)); } } section.UpdateEntities(); section.BlockRecord.UpdateAnonymousBlocks(); var ent = (BlockReference)tr.GetObject(section.BlockId, OpenMode.ForWrite, true, true); ent.Position = pline.GetPoint3dAt(0); ent.XData = section.GetDataForXData(); } tr.Commit(); } AcadUtils.Document.TransactionManager.QueueForGraphicsFlush(); AcadUtils.Document.TransactionManager.FlushGraphics(); // "Удалить исходную полилинию?" if (MessageBox.ShowYesNo(Language.GetItem(Invariables.LangItem, "msg7"), MessageBoxIcon.Question)) { using (var tr = AcadUtils.Document.TransactionManager.StartTransaction()) { var dbObj = tr.GetObject(plineId, OpenMode.ForWrite, true, true); dbObj.Erase(true); tr.Commit(); } } } } catch (System.Exception exception) { ExceptionBox.Show(exception); } }
public void fOPENVISUAL() { Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor; try { Document doc = acApp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Utils.Utils.Init(); Utils.Utils.ChangeViewStyle("X-Ray"); while (true) { PromptEntityOptions peo = new PromptEntityOptions("\nSelect mesh face:"); peo.SetRejectMessage("\nMust be a 3D solid."); peo.AddAllowedClass(typeof(Solid3d), false); PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK || per.Status == PromptStatus.Cancel) { Utils.Utils.End(); break; } Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { Solid3d sol = tr.GetObject(per.ObjectId, OpenMode.ForRead) as Solid3d; if (sol != null) { Brep brp = new Brep(sol); using (brp) { // We're going to check interference between our // solid and a line we're creating between the // picked point and the user (we use the view // direction to decide in which direction to // draw the line) Point3d dir = (Point3d)acApp.GetSystemVariable("VIEWDIR"); Point3d picked = per.PickedPoint, nearerUser = per.PickedPoint - (dir - Point3d.Origin); // Two hits should be enough (in and out) const int numHits = 1; // Create out line Line3d ln = new Line3d(picked, nearerUser); Hit[] hits = brp.GetLineContainment(ln, numHits); ln.Dispose(); if (hits == null || hits.Length < numHits) { Utils.Utils.End(); return; } // Set the shortest distance to something large // and the index to the first item in the list double shortest = (picked - nearerUser).Length; int found = 0; // Loop through and check the distance to the // user (the depth of field). for (int idx = 0; idx < numHits; idx++) { Hit hit = hits[idx]; double dist = (hit.Point - nearerUser).Length; if (dist < shortest) { shortest = dist; found = idx; } } // Once we have the nearest point to the screen, // use that one to get the containing curves //List<Curve3d> curves = new List<Curve3d>(); List <Point3d> faceBoundary = new List <Point3d>(); if (CheckContainment(ed, brp, hits[found].Point, ref faceBoundary)) { Utils.Layers.SetLayer("!FDS_MESH[open]"); if (faceBoundary[0].X == faceBoundary[1].X) { if (faceBoundary[0].X == sol.GeometricExtents.MinPoint.X) { Utils.Utils.CreateExtrudedSurface(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y, faceBoundary[1].Z), "!FDS_MESH[open]", 1, 1); } else if (faceBoundary[0].X == sol.GeometricExtents.MaxPoint.X) { Utils.Utils.CreateExtrudedSurface(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y, faceBoundary[1].Z), "!FDS_MESH[open]", 1, 1); } } else if (faceBoundary[0].Y == faceBoundary[1].Y) { if (faceBoundary[0].Y == sol.GeometricExtents.MinPoint.Y) { Utils.Utils.CreateExtrudedSurface(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y, faceBoundary[1].Z), "!FDS_MESH[open]", 1, 1); } else if (faceBoundary[0].Y == sol.GeometricExtents.MaxPoint.Y) { Utils.Utils.CreateExtrudedSurface(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y, faceBoundary[1].Z), "!FDS_MESH[open]", 1, 1); } } if (faceBoundary[0].Z == faceBoundary[1].Z) { if (faceBoundary[0].Z == sol.GeometricExtents.MinPoint.Z) { Utils.Utils.CreateExtrudedSurface(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y, faceBoundary[1].Z), "!FDS_MESH[open]", 1, 1); } else if (faceBoundary[0].Z == sol.GeometricExtents.MaxPoint.Z) { Utils.Utils.CreateExtrudedSurface(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y, faceBoundary[1].Z), "!FDS_MESH[open]", 1, 1); } } } } } tr.Commit(); } } Utils.Utils.End(); Utils.Utils.ChangeViewStyle("2dWireframe"); return; } catch (System.Exception e) { ed.WriteMessage("Program error: " + e.ToString()); Utils.Utils.End(); return; } }
public static void StartFunction() { #if !DEBUG Statistic.SendCommandStarting(ModPlusConnector.Instance); #endif try { var doc = Application.DocumentManager.MdiActiveDocument; var db = doc.Database; var ed = doc.Editor; var workType = "Tangent"; while (true) { var peo = new PromptEntityOptions($"\n{Language.GetItem(PlinesEditFunction.LangItem, "k16")}:") { AllowNone = false, AllowObjectOnLockedLayer = true }; peo.SetRejectMessage($"\n{Language.GetItem(PlinesEditFunction.LangItem, "wrong")}"); peo.AddAllowedClass(typeof(Polyline), true); var per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } var polylineId = per.ObjectId; var pickedPt = ModPlus.Helpers.AutocadHelpers.UcsToWcs(per.PickedPoint); using (doc.LockDocument()) { using (var tr = db.TransactionManager.StartTransaction()) { var dbObj = tr.GetObject(polylineId, OpenMode.ForWrite); if (dbObj is Polyline polyline) { var p = polyline.GetClosestPointTo(pickedPt, false); var param = polyline.GetParameterAtPoint(p); var vx = Convert.ToInt32(Math.Truncate(param)); var jig = new LineToArcSegment(); var jigResult = jig.StartJig(polyline, polyline.GetPoint3dAt(vx), vx, workType); if (jigResult.Status != PromptStatus.OK) { return; } workType = jig.WorkType(); } tr.Commit(); } } } } catch (System.Exception exception) { ExceptionBox.Show(exception); } }
public void DimOfCE() { ObjectId dicId = CreateCeDic(); ObjectId IDofL1 = ObjectId.Null; ObjectId IDofL2 = ObjectId.Null; if (dicId != ObjectId.Null) { CurrentConfig(dicId); //开始选择直线 PromptEntityOptions opt = new PromptEntityOptions("\n选择第一条直线或[更改设置(S)]:", "S"); opt.SetRejectMessage("\n只能选择直线哦!"); opt.AddAllowedClass(typeof(Line), true); //必须先使用SetRejectMessage设置提示才能使用这个方法,否则会报错。 opt.AllowObjectOnLockedLayer = true; opt.AllowNone = false; PromptEntityResult result = ed.GetEntity(opt); while (result.Status == PromptStatus.Keyword) { ChangeConfig(dicId); result = ed.GetEntity(opt); } if (result.Status != PromptStatus.OK) { return; } IDofL1 = result.ObjectId; IDofL2 = ChooseAnotherLine(IDofL1); if (IDofL2 == ObjectId.Null) { return; } } //直线选择完毕 //开始获取交点 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { Line L1 = trans.GetObject(IDofL1, OpenMode.ForRead) as Line; Line L2 = trans.GetObject(IDofL2, OpenMode.ForRead) as Line; Point3dCollection intersectionpoints = new Point3dCollection(); L1.IntersectWith ( L2, Intersect.OnBothOperands, intersectionpoints, 0, 0 ); while (intersectionpoints.Count == 0) { ed.WriteMessage("\n两条直线不相交,需要重新选择第二条直线"); IDofL2 = ChooseAnotherLine(IDofL1); L1 = trans.GetObject(IDofL1, OpenMode.ForRead) as Line; L2 = trans.GetObject(IDofL2, OpenMode.ForRead) as Line; intersectionpoints = new Point3dCollection(); L1.IntersectWith ( L2, Intersect.OnBothOperands, intersectionpoints, 0, 0 ); } Point3d node = intersectionpoints[0]; //获取交点结束 //开始获取夹角 double AngleOfL1 = L1.Angle; double AngleOfL2 = L2.Angle; double angle = Math.Abs(AngleOfL1 - AngleOfL2); if (angle < Math.PI / 2) { angle = Math.PI - angle; } else if (angle > Math.PI) { angle = angle - Math.PI; } //获取夹角结束 Table tb = (Table)trans.GetObject(CreatCeTable(dicId, node, angle), OpenMode.ForWrite); jigCE jigger = new jigCE(tb); Line drgline = new Line(jigger.basePT, jigger.basePT); jigger.Leader = drgline; PromptResult jigresult = ed.Drag(jigger); if (jigresult.Status == PromptStatus.OK) { jigger.TransformEnties(); BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); btr.AppendEntity(jigger.Leader); trans.AddNewlyCreatedDBObject(jigger.Leader, true); trans.Commit(); //ed.WriteMessage("\n起点坐标,x={0},y={1}", jigger.basePT.X, jigger.basePT.Y);//测试用 //ed.WriteMessage("\n终点坐标,x={0},y={1}", jigger.dargPT.X, jigger.dargPT.Y);//测试用 } else { trans.Abort(); } } catch (Autodesk.AutoCAD.Runtime.Exception EX) { ed.WriteMessage("\n出错了!" + EX.ToString()); } } }
public void Cmd_DimArrow() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; var prEntOpt = new PromptEntityOptions("\nSelect a dimensions arrow to convert to arrow-type <" + EnumAgent.GetNameOf(SettingsUser.ArwHead) + "> : "); prEntOpt.SetRejectMessage("\nOnly dimensions may be selected."); prEntOpt.AllowNone = false; prEntOpt.AddAllowedClass(typeof(AlignedDimension), false); prEntOpt.AddAllowedClass(typeof(RotatedDimension), false); prEntOpt.AddAllowedClass(typeof(ArcDimension), false); var prEntRes = acCurEd.GetEntity(prEntOpt); var prPickPoint = prEntRes.PickedPoint; if (prEntRes.Status != PromptStatus.OK) { return; } using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var acDim = acTrans.GetObject(prEntRes.ObjectId, OpenMode.ForWrite) as Entity; if (acDim != null) { try { Point3d xPt1; Point3d xPt2; var arwString = EnumAgent.GetNameOf(SettingsUser.ArwHead); var arwId = DimSystem.GetArrowId(arwString); switch (acDim) { case AlignedDimension alDim: { alDim.Dimsah = true; xPt1 = alDim.XLine1Point; xPt2 = alDim.XLine2Point; if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2)) { alDim.Dimblk1 = arwId; } else { alDim.Dimblk2 = arwId; } alDim.RecomputeDimensionBlock(true); break; } case RotatedDimension roDim: { roDim.Dimsah = true; xPt1 = roDim.XLine1Point; xPt2 = roDim.XLine2Point; if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2)) { roDim.Dimblk1 = arwId; } else { roDim.Dimblk2 = arwId; } roDim.RecomputeDimensionBlock(true); break; } case ArcDimension arDim: { arDim.Dimsah = true; xPt1 = arDim.XLine1Point; xPt2 = arDim.XLine2Point; if (prPickPoint.DistanceTo(xPt1) < prPickPoint.DistanceTo(xPt2)) { arDim.Dimblk1 = arwId; } else { arDim.Dimblk2 = arwId; } arDim.RecomputeDimensionBlock(true); break; } } } catch (Exception e) { Console.WriteLine(e); MailAgent.Report(e.Message); } } acTrans.Commit(); } }
public void GetIntersections() { Database db = HostApplicationServices.WorkingDatabase; Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { try { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); PromptEntityOptions peo = new PromptEntityOptions("\nSelect a single polyline >>"); peo.SetRejectMessage("\nSelected object might be of type polyline only >>"); peo.AddAllowedClass(typeof(Polyline), false); PromptEntityResult res; res = ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { return; } DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead); if (ent == null) { return; } //Polyline poly = (Polyline)ent as Polyline; Curve curv = ent as Curve; DBObjectCollection pcurves = new DBObjectCollection(); curv.Explode(pcurves); TypedValue[] values = new TypedValue[] { new TypedValue(0, "lwpolyline") //might be added layer name to select curve: //, new TypedValue(8, "mylayer") }; SelectionFilter filter = new SelectionFilter(values); Point3dCollection fence = new Point3dCollection(); double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam); // number of divisions along polyline to create fence selection double step = leng / 256;// set number of steps to your suit int num = Convert.ToInt32(leng / step); int i = 0; for (i = 0; i < num; i++) { Point3d pp = curv.GetPointAtDist(step * i); fence.Add(curv.GetClosestPointTo(pp, false)); } PromptSelectionResult selres = ed.SelectFence(fence, filter); if (selres.Status != PromptStatus.OK) { return; } Point3dCollection intpts = new Point3dCollection(); DBObjectCollection qcurves = new DBObjectCollection(); foreach (SelectedObject selobj in selres.Value) { DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject; if (selobj.ObjectId != curv.ObjectId) { DBObjectCollection icurves = new DBObjectCollection(); Curve icurv = obj as Curve; icurv.Explode(icurves); foreach (DBObject dbo in icurves) { if (!qcurves.Contains(dbo)) { qcurves.Add(dbo); } } } } ed.WriteMessage("\n{0}", qcurves.Count); int j = 0; Point3dCollection polypts = new Point3dCollection(); for (i = 0; i < pcurves.Count; ++i) { for (j = 0; j < qcurves.Count; ++j) { Curve curve1 = pcurves[i] as Curve; Curve curve2 = qcurves[j] as Curve; Point3dCollection pts = new Point3dCollection(); curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero); foreach (Point3d pt in pts) { if (!polypts.Contains(pt)) { polypts.Add(pt); } } } } Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("osmode", 0);// optional // for debug only Autodesk.AutoCAD.ApplicationServices.Core.Application.ShowAlertDialog(string.Format("\nNumber of Intersections: {0}", polypts.Count)); // test for visulization only foreach (Point3d inspt in polypts) { Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt) { ColorIndex = 1 }; btr.AppendEntity(circ); tr.AddNewlyCreatedDBObject(circ, true); } tr.Commit(); } catch (System.Exception ex) { ed.WriteMessage("\n{0}\n{1}", ex.Message, ex.StackTrace); } } }
public void DrawGroupLeader() { Editor ed = dwg.Editor; PromptEntityOptions prmtEntityOpts = new PromptEntityOptions("Укажите линию"); prmtEntityOpts.AllowNone = false; prmtEntityOpts.SetRejectMessage("Должна быть линия или полилиния!"); prmtEntityOpts.AddAllowedClass(typeof(Line), true); prmtEntityOpts.AddAllowedClass(typeof(Polyline), true); PromptEntityResult entRes = ed.GetEntity(prmtEntityOpts); if (entRes.Status!= PromptStatus.OK) { return; } using (Transaction tr = CurrentDatabase.TransactionManager.StartTransaction()) { GroupsInformation groupEntities = new GroupsInformation(tr, CurrentDatabase); List<string> groupList = groupEntities.GetGroupsOfObject(entRes.ObjectId); if (groupList == null) { ed.WriteMessage("За указанным объектом не значится никаких групп!"); return; } PromptPointOptions pointOpts = new PromptPointOptions("\nУкажите точку вставки блока: "); PromptPointResult pointRes = ed.GetPoint(pointOpts); if (pointRes.Status!= PromptStatus.OK) { return; } BlockTable bt = (BlockTable)CurrentDatabase.BlockTableId.GetObject(OpenMode.ForRead); BlockTableRecord btrSpace = (BlockTableRecord)CurrentDatabase.CurrentSpaceId .GetObject(OpenMode.ForWrite); if (!bt.Has("group_vinoska")) { ed.WriteMessage("\nВ файле не определён блок выноски!!"); return; } BlockTableRecord gleaderBtr = (BlockTableRecord)bt["group_vinoska"].GetObject(OpenMode.ForRead); BlockReference gleader = new BlockReference(pointRes.Value, gleaderBtr.ObjectId); btrSpace.AppendEntity(gleader); tr.AddNewlyCreatedDBObject(gleader, true); //Если блок аннотативный - добавляем в таблицу аннотативных масштабов блока текущий масштаб ObjectContextManager ocm = CurrentDatabase.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (gleaderBtr.Annotative == AnnotativeStates.True) { ObjectContexts.AddContext(gleader, occ.CurrentContext); } gleader.SetDatabaseDefaults(); if (gleaderBtr.HasAttributeDefinitions) { var attDefs = gleaderBtr.Cast<ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)n.GetObject(OpenMode.ForRead)); foreach (AttributeDefinition attdef in attDefs) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(attdef, gleader.BlockTransform); gleader.AttributeCollection.AppendAttribute(attref); tr.AddNewlyCreatedDBObject(attref, true); if (gleaderBtr.Annotative == AnnotativeStates.True) { ObjectContexts.AddContext(attref, occ.CurrentContext); } int attCount = int.Parse(attref.Tag.Remove(0,10)); if (attCount<=groupList.Count) { attref.TextString = groupList[attCount-1]; } } } if (gleaderBtr.IsDynamicBlock) { DynamicBlockReferencePropertyCollection dynBRefColl = gleader.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in dynBRefColl) { if (prop.PropertyName == "Lookup1") { prop.Value = prop.GetAllowedValues()[groupList.Count-1]; } } } tr.Commit(); } }
void wallSpaceDraw() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Database db = Application.DocumentManager.MdiActiveDocument.Database; TransactionManager tm = db.TransactionManager; Transaction trans = tm.StartTransaction(); try { PromptEntityOptions entopts = new PromptEntityOptions("Select a space "); entopts.SetRejectMessage("Must select a space, please!"); entopts.AddAllowedClass(typeof(Space), true); PromptEntityResult ent = null; try { ent = ed.GetEntity(entopts); } catch { ed.WriteMessage("You did not select a valid entity"); return; } if (ent.Status == PromptStatus.OK) { ObjectId entId = ent.ObjectId; Space space = trans.GetObject(entId, OpenMode.ForRead, false) as Space; if (space != null) { Manager mgr = new Manager(db); } else { ed.WriteMessage("\nSomething bad has happened..."); } } trans.Commit(); Point3d centerPt = new Point3d(0.0, 0.0, 0.0); using (Transaction trans1 = tm.StartTransaction()) { BlockTable bt = (BlockTable)(trans1.GetObject(db.BlockTableId, OpenMode.ForWrite)); BlockTableRecord btr = (BlockTableRecord)trans1.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); double distX = 4800; double distY = 2400; Point3d[] pts = new Point3d[5]; pts[0] = centerPt + new Vector3d(-(distX / 2), -(distY / 2), 0); pts[1] = centerPt + new Vector3d((distX / 2), -(distY / 2), 0); pts[2] = centerPt + new Vector3d((distX / 2), (distY / 2), 0); pts[3] = centerPt + new Vector3d(-(distX / 2), (distY / 2), 0); pts[4] = pts[0]; for (int i = 0; i < 4; i++) { Wall wall = new Wall(); wall.SetDatabaseDefaults(db); wall.SetToStandard(db); wall.SetDefaultLayer(); wall.Normal = new Vector3d(0, 0, 1); wall.Set(pts[i], pts[i + 1], Vector3d.ZAxis); btr.AppendEntity(wall); trans1.AddNewlyCreatedDBObject(wall, true); } trans1.Commit(); } } catch (System.Exception e) { trans.Abort(); ed.WriteMessage(e.Message); } finally { trans.Dispose(); } }
public void ModifyTriangulate() { Triangulations triangulation = new Triangulations(); AC_Transactions tr = new AC_Transactions(); PromptEntityOptions options = new PromptEntityOptions("Pick a Line to modify Triangulations"); options.SetRejectMessage("not valid Object \n"); options.AddAllowedClass(typeof(Line), true); PromptEntityResult sel = tr.AC_Doc.Editor.GetEntity(options); if (sel.Status == PromptStatus.OK) { triangulation.Modify((AC_Line)tr.openObjectErased(sel.ObjectId)); } }
void getConnectionsWithSelection() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Database db = Application.DocumentManager.MdiActiveDocument.Database; TransactionManager tm = db.TransactionManager; Transaction trans = tm.StartTransaction(); try { PromptEntityOptions entopts = new PromptEntityOptions("Select a wall "); entopts.SetRejectMessage("Must select a wall, please!"); entopts.AddAllowedClass(typeof(Wall), true); PromptEntityResult ent = null; try { ent = ed.GetEntity(entopts); } catch { ed.WriteMessage("You did not select a valid entity"); return; } if (ent.Status == PromptStatus.OK) { ObjectId entId = ent.ObjectId; Wall wall = trans.GetObject(entId, OpenMode.ForRead, false) as Wall; Manager mgr = new Manager(db); Graph theGraph = mgr.FindGraph(wall); Matrix3d mat = theGraph.WcsToEcsMatrix.Inverse(); for (int i = 0; i < theGraph.WallJointCount; i++) { Joint joint = theGraph.GetWallJoint(i); ConnectionCollection connections = joint.Connections; foreach (Connection connection in connections) { ed.WriteMessage("\nConnection in wall system for wall id: " + connection.Section.WallId.ToString()); ed.WriteMessage("\n Direction from here: " + connection.DirectionFromHere.ToString()); foreach (double elevation in connection.ElevationVariations) { ed.WriteMessage("\n Elevation Variations: " + elevation.ToString()); } ed.WriteMessage("\n Start Elevation: " + connection.StartElevation.ToString()); ed.WriteMessage("\n End Elevation: " + connection.EndElevation.ToString()); ed.WriteMessage("\n Section Starts Here: " + connection.SectionStartsHere.ToString()); } } } trans.Commit(); } catch (System.Exception e) { trans.Abort(); ed.WriteMessage(e.Message); } finally { trans.Dispose(); } }
public void GetIntersectionsRiver() { Database db = HostApplicationServices.WorkingDatabase; Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); #region For Word string filepath = "D:\\intersections_rivers.docx"; using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { try { // Add a main document part. MainDocumentPart mainPart = docX.AddMainDocumentPart(); StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>(); Styles styles1 = new Styles(); DocDefaults docDefaults = new DocDefaults( new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" })), new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto })); styles1.AppendChild(docDefaults); styleDefinitionsPart.Styles = styles1; mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body()); ParagraphProperties paragraphProperties1 = new ParagraphProperties( new Justification() { Val = JustificationValues.Center }, new ParagraphMarkRunProperties( new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" } )); Paragraph para = body.AppendChild(new Paragraph()); para.AppendChild(paragraphProperties1); Run run = para.AppendChild(new Run()); RunProperties runProperties1 = new RunProperties( new Bold()); // String msg contains the text, "Hello, Word!" run.AppendChild(runProperties1); run.AppendChild(new Text("ПРИЛОЖЕНИЕ")); run.AppendChild(new Break()); run.AppendChild(new Text("Ведомость пересечений")); run.AppendChild(new Break()); var table = new DocumentFormat.OpenXml.Wordprocessing.Table(); // Create a TableProperties object and specify its border information. TableProperties tblProp = new TableProperties( new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa }, new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa }, new TableBorders( new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }), new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" } ); // Append the TableProperties object to the empty table. table.AppendChild<TableProperties>(tblProp); // Add 3 columns to the table. TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn()); table.AppendChild(tg); TableRow tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 430 }), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Наимен. водотока")))), //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"}) new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Run(new Text("Пикетное положение пересечения")))), new TableCell( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Run(new Text("Ширина водотока в межень")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new VerticalMerge() { Val = MergedCellValues.Restart }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Глуб. водотока")))), new TableCell( new TableCellProperties( new GridSpan() { Val = 3 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Горизонт воды")))), new TableCell(new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим.")))) ); table.AppendChild(tr1); TableRow tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 419 }), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run()))); table.AppendChild(tr2); TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 }); #endregion while (true) { //using (tr) //{ try { #region Поиск пересечений BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline >>"); peo.SetRejectMessage("\nМожно только polyline >>"); peo.AddAllowedClass(typeof(Polyline), false); PromptEntityResult res; res = ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { break; } DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead); if (ent == null) return; PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); // Prompt for the start point pPtOpts.Message = "\nВведи начало: "; pPtRes = doc.Editor.GetPoint(pPtOpts); PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): "); PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik); //zoom /*PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) return;*/ // Extract its extents Extents3d ext; Transaction trans = db.TransactionManager.StartTransaction(); using (trans) { Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead); ext = enti.GeometricExtents; trans.Commit(); } ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse()); ZoomWin(ed, ext.MinPoint, ext.MaxPoint); // //Polyline poly = (Polyline)ent as Polyline; Curve curv = ent as Curve; DBObjectCollection pcurves = new DBObjectCollection(); curv.Explode(pcurves); TypedValue[] values = new TypedValue[] { new TypedValue(0, "lwpolyline") //might be added layer name to select curve: //, new TypedValue(8, "mylayer") }; SelectionFilter filter = new SelectionFilter(values); Point3dCollection fence = new Point3dCollection(); double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam); // number of divisions along polyline to create fence selection double step = leng / 256;// set number of steps to your suit int num = Convert.ToInt32(leng / step); for (int i = 0; i < num; i++) { Point3d pp = curv.GetPointAtDist(step * i); fence.Add(curv.GetClosestPointTo(pp, false)); } PromptSelectionResult selres = ed.SelectFence(fence, filter); if (selres.Status != PromptStatus.OK) return; Point3dCollection intpts = new Point3dCollection(); DBObjectCollection qcurves = new DBObjectCollection(); //ed.WriteMessage("\nCheck"); foreach (SelectedObject selobj in selres.Value) { DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject; if (selobj.ObjectId != curv.ObjectId) { DBObjectCollection icurves = new DBObjectCollection(); Curve icurv = obj as Curve; icurv.Explode(icurves); foreach (DBObject dbo in icurves) { if (!qcurves.Contains(dbo)) qcurves.Add(dbo); } } } //ed.WriteMessage("\n{0}", qcurves.Count); int j = 0; Point3dCollection polypts = new Point3dCollection(); for (int i = 0; i < pcurves.Count; ++i) { for (j = 0; j < qcurves.Count; ++j) { Curve curve1 = pcurves[i] as Curve; Curve curve2 = qcurves[j] as Curve; Point3dCollection pts = new Point3dCollection(); curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero); foreach (Point3d pt in pts) { if (!polypts.Contains(pt)) polypts.Add(pt); } } } #endregion try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); table.AppendChild(new TableRow( new TableCell( new TableCellProperties( new GridSpan() { Val = 9 }), new Paragraph( new ParagraphProperties( new ParagraphMarkRunProperties(new Bold()), new Justification() { Val = JustificationValues.Center }), new Run(new RunProperties( new Bold()), new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" + ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" + ((100 * getpikRes.Value + pline.Length) % 100).ToString("F"))))))); } } catch { ed.WriteMessage("\nError."); } Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional // for debug only Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count)); if (polypts.Count == 0) { try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); table.AppendChild(new TableRow( new TableCell( new TableCellProperties( new GridSpan() { Val = 9 }), new Paragraph( new ParagraphProperties( new Justification() { Val = JustificationValues.Center }), new Run(new Text("На данном участке трассы пересечения отсутствуют")))))); } } catch { ed.WriteMessage("\nError."); } } else { //List<double> pik = new List<double>(polypts.Count); double[] pik = new double[polypts.Count]; int numInter = 0; foreach (Point3d inspt in polypts) { double dist = 0; dist = 100 * getpikRes.Value; // test for visulization only /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt); circ.ColorIndex = 1; btr.AppendEntity(circ); tr.AddNewlyCreatedDBObject(circ, true);*/ Point3d curr = pPtRes.Value, next = pPtRes.Value; try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint)) for (int i = 0; i < pline.NumberOfVertices - 2; i++) { LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1) { dist += inspt.DistanceTo(curr); ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n"); break; } else dist += curr.DistanceTo(next); curr = next; } else for (int i = pline.NumberOfVertices - 3; i >= 0; i--) { LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1) { dist += inspt.DistanceTo(curr); ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n"); break; } else dist += curr.DistanceTo(next); curr = next; } } } catch { ed.WriteMessage("\nInvalid polyline."); } pik[numInter] = dist; numInter++; //ed.WriteMessage(" {0:0.00}\n", dist); } //pik.Sort(); Array.Sort(pik); for (int i = 0; i < polypts.Count; i++) { tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run())), new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }), new Paragraph( new ParagraphProperties( new Justification() { Val = JustificationValues.Center }), new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())) ); table.AppendChild(tr1); } } } catch { ed.WriteMessage("\nError"); } //} } tr.Commit(); body.AppendChild(table); body.AppendChild( new SectionProperties( new PageMargin() { Top = 1134, Right = (UInt32Value)850U, Bottom = 1134, Left = (UInt32Value)1418U, Header = (UInt32Value)708U, Footer = (UInt32Value)708U, Gutter = (UInt32Value)0U })); ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx"); } catch { ed.WriteMessage("\nError."); } } }
public static String PromptSelectAlignment(String alignmentStatus) { String algnName = ""; try { using (var tr = AcadApp.StartTransaction()) { var opt = new PromptEntityOptions("\nВыберите " + alignmentStatus + " трассу: "); opt.SetRejectMessage("\nОбъект должен быть трассой.\n"); opt.AddAllowedClass(typeof(Alignment), false); var ent = AcadApp.AcaEd.GetEntity(opt); if (ent.Status == PromptStatus.OK) { var alignId = ent.ObjectId; if (alignId == ObjectId.Null) { return ""; } var curAlgn = tr.GetObject(alignId, OpenMode.ForRead) as Alignment; algnName = curAlgn.Name; return algnName; // All OK. Return alignment name } // If PromptStatus.OK } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { AcadApp.AcaEd.WriteMessage("ERROR: CivApp.PromptSelectAlignment()\n" + ex + "\n"); } return ""; //There have been some errors }