public void CreateContour(BlockTableRecord btr) { if (panelBtr.ExtentsByTile.Diagonal() < endOffset) { return; } // из всех плиток отделить торцевые плитки???? // дерево границ плиток TreeTiles = new RTree<Tuple<ObjectId, Extents3d>>(); panelBtr.Tiles.ForEach(t => { try { var r = new Rectangle(t.Item2.MinPoint.X, t.Item2.MinPoint.Y, t.Item2.MaxPoint.X, t.Item2.MaxPoint.Y, 0, 0); TreeTiles.Add(r, t); } catch { } }); // Первый угол панели - левый нижний var pt1 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MinPoint, EnumCorner.LeftLower); var pt2 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MinPoint.X, panelBtr.ExtentsByTile.MaxPoint.Y, 0), EnumCorner.LeftTop); var pt3 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MaxPoint, EnumCorner.RightTop); var pt4 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MaxPoint.X, panelBtr.ExtentsByTile.MinPoint.Y, 0), EnumCorner.RightLower); Extents3d extNoEnd = new Extents3d(pt1, pt2); extNoEnd.AddPoint(pt3); extNoEnd.AddPoint(pt4); panelBtr.ExtentsNoEnd = extNoEnd; Point3dCollection pts = new Point3dCollection(); pts.Add(pt1); pts.Add(pt2); pts.Add(pt3); pts.Add(pt4); using (Polyline3d poly = new Polyline3d(Poly3dType.SimplePoly, pts, true)) { poly.LayerId = panelBtr.CPS.IdLayerContour; btr.AppendEntity(poly); btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(poly, true); } }
public static void Draw(Point3dCollection points, int deep, ref List<Entity> ents) { if (deep == 0) { DrawPolygon(points, ref ents); return; } else { Point3dCollection middlePoints = CalculateMiddlePoints(points); Point3dCollection aux = new Point3dCollection(); aux.Add( points[0] ); aux.Add( middlePoints[0] ); aux.Add( middlePoints[2] ); Draw(aux, deep-1, ref ents); // aux.Clear(); aux = new Point3dCollection(); aux.Add( middlePoints[0] ); aux.Add( points[1] ); aux.Add( middlePoints[1]); Draw(aux, deep - 1, ref ents); // aux.Clear(); aux = new Point3dCollection(); aux.Add( middlePoints[2]); aux.Add( middlePoints[1] ); aux.Add( points[2]); Draw(aux, deep - 1, ref ents); } }
public static Point3dCollection CalculateMiddlePoints(Point3dCollection basePoints) { Point3dCollection auxC= new Point3dCollection(); auxC.Add( PointBetweenPoints(basePoints[0], basePoints[1]) ); auxC.Add( PointBetweenPoints(basePoints[1], basePoints[2]) ); auxC.Add( PointBetweenPoints(basePoints[2], basePoints[0]) ); return auxC; }
public Sierpinski(Point3d center, float rad) { this.center = center; this.rad = rad; points = new Point3dCollection(); ents = new List<Entity>(); points.Add( new Point3d(center.X + (rad * Math.Cos(90 * deg2rad)), center.Y + (rad * Math.Sin(90 * deg2rad)), center.Z)); points.Add( new Point3d(center.X + (rad * Math.Cos(210 * deg2rad)), center.Y + (rad * Math.Sin(210 * deg2rad)), center.Z)); points.Add( new Point3d(center.X + (rad * Math.Cos(330 * deg2rad)), center.Y + (rad * Math.Sin(330 * deg2rad)), center.Z)); }
public Cuadrado(int Depth, Point3d pt0, Point3d pt1, Point3d pt2, Point3d pt3) { this.Depth = Depth; pts = new Point3dCollection(); pts.Add(pt0); pts.Add(pt1); pts.Add(pt2); pts.Add(pt3); Lab3.DBMan.DrawGeometry(pts, true); }
public Pixel(Color c, Point3d center, Double size = 10) { this.center = center; this.c = c; this.size = size; points = new Point3dCollection(); points.Add(new Point3d(this.center.X - this.size / 2, this.center.Y - this.size / 2, this.center.Z)); points.Add(new Point3d(this.center.X + this.size / 2, this.center.Y - this.size / 2, this.center.Z)); points.Add(new Point3d(this.center.X + this.size / 2, this.center.Y + this.size / 2, this.center.Z)); points.Add(new Point3d(this.center.X - this.size / 2, this.center.Y + this.size / 2, this.center.Z)); this.face = new Face( points[0], points[1], points[2], points[3], true, true, true, true); this.face.Color = this.c; }
/// <summary> /// Gets the vertices of a polyline. /// </summary> /// <param name="polyline">Polyline, Polyline2d, or Polyline3d from which to obtain the vertices</param> public static Point3dCollection GetVertices(Curve polyline) { Point3dCollection vertices = new Point3dCollection(); if (polyline is Polyline) { Polyline pline = (Polyline)polyline; for (int i = 0; i < pline.NumberOfVertices; i++) { vertices.Add(pline.GetPoint3dAt(i)); } } else { Database database = HostApplicationServices.WorkingDatabase; Transaction transaction = database.TransactionManager.StartTransaction(); if (polyline is Polyline2d) { Polyline2d pline2d = (Polyline2d)polyline; foreach (Object vertex in pline2d) { if (vertex is Vertex2d) { vertices.Add(((Vertex2d)vertex).Position); } else if (vertex is ObjectId) { vertices.Add(((Vertex2d)transaction.GetObject((ObjectId)vertex, OpenMode.ForRead)).Position); } } } else if (polyline is Polyline3d) { Polyline3d pline3d = (Polyline3d)polyline; foreach (ObjectId vertexId in pline3d) { PolylineVertex3d vertex = (PolylineVertex3d)transaction.GetObject(vertexId, OpenMode.ForRead); vertices.Add(vertex.Position); } } transaction.Dispose(); } return vertices; }
public static void TestRhinoInside() { // RhinoCommon code var plane = Rhino.Geometry.Plane.WorldXY; var sphere = new Rhino.Geometry.Sphere(plane, 5.0); //var mesh = Rhino.Geometry.Mesh.CreateIcoSphere(sphere, 3); var mesh = Rhino.Geometry.Mesh.CreateQuadSphere(sphere, 3); // Get the current document and database, and start a transaction var document = Application.DocumentManager.MdiActiveDocument; var database = document.Database; using (var transaction = database.TransactionManager.StartTransaction()) { // Open the Block table record for read var block_table = transaction.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write var block_table_record = transaction.GetObject(block_table[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Create a polyface mesh using (var poly_face_mesh = new PolyFaceMesh()) { // Add the new object to the block table record and the transaction block_table_record.AppendEntity(poly_face_mesh); transaction.AddNewlyCreatedDBObject(poly_face_mesh, true); // Before adding vertexes, the polyline must be in the drawing var points_collection = new Point3dCollection(); foreach (var v in mesh.Vertices) { points_collection.Add(new Point3d(v.X, v.Y, v.Z)); } // Add mesh vertices foreach (Point3d point in points_collection) { var mesh_vertex = new PolyFaceMeshVertex(point); poly_face_mesh.AppendVertex(mesh_vertex); transaction.AddNewlyCreatedDBObject(mesh_vertex, true); } // Add mesh faces. Note, AutoCAD face vertex indices start at 1, not 0. foreach (var f in mesh.Faces) { using (var face_record = new FaceRecord((short)(f.A + 1), (short)(f.B + 1), (short)(f.C + 1), (short)(f.D + 1))) { poly_face_mesh.AppendFaceRecord(face_record); transaction.AddNewlyCreatedDBObject(face_record, true); } } } document.Editor.UpdateTiledViewportsFromDatabase(); transaction.Commit(); } }
protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw) { pts = new Point3dCollection(); pts.Add(startPt + new Vector3d(-3, 0, 0)); pts.Add(startPt + new Vector3d(3, 0, 0)); pts.Add(startPt + new Vector3d(3, 0, 6)); pts.Add(startPt + new Vector3d(2.5, 0, 6)); pts.Add(startPt + new Vector3d(2.5, 0, 1)); pts.Add(startPt + new Vector3d(-2.5, 0, 1)); pts.Add(startPt + new Vector3d(-2.5, 0, 6)); pts.Add(startPt + new Vector3d(-3, 0, 6)); pts.Add(startPt + new Vector3d(-3, 0, 0)); return(draw.Geometry.Polygon(pts)); }
public void CreateContour(BlockTableRecord btr) { if (panelBtr.ExtentsByTile.Diagonal() < endOffset) { return; } // из всех плиток отделить торцевые плитки???? // дерево границ плиток TreeTiles = new RTree <Tuple <ObjectId, Extents3d> >(); panelBtr.Tiles.ForEach(t => { try { var r = new Rectangle(t.Item2.MinPoint.X, t.Item2.MinPoint.Y, t.Item2.MaxPoint.X, t.Item2.MaxPoint.Y, 0, 0); TreeTiles.Add(r, t); } catch { } }); // Первый угол панели - левый нижний var pt1 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MinPoint, EnumCorner.LeftLower); var pt2 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MinPoint.X, panelBtr.ExtentsByTile.MaxPoint.Y, 0), EnumCorner.LeftTop); var pt3 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MaxPoint, EnumCorner.RightTop); var pt4 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MaxPoint.X, panelBtr.ExtentsByTile.MinPoint.Y, 0), EnumCorner.RightLower); Extents3d extNoEnd = new Extents3d(pt1, pt2); extNoEnd.AddPoint(pt3); extNoEnd.AddPoint(pt4); panelBtr.ExtentsNoEnd = extNoEnd; Point3dCollection pts = new Point3dCollection(); pts.Add(pt1); pts.Add(pt2); pts.Add(pt3); pts.Add(pt4); using (Polyline3d poly = new Polyline3d(Poly3dType.SimplePoly, pts, true)) { poly.LayerId = panelBtr.CPS.IdLayerContour; btr.AppendEntity(poly); btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(poly, true); } }
drawLdr(Point3d pnt3d, double txtSize, string nameLayer, short color) { ObjectId idLdr = ObjectId.Null; bool Stop = false; bool escape = false; PromptStatus ps; ObjectIdCollection ids = new ObjectIdCollection(); Point3dCollection pnts3d = new Point3dCollection(); pnts3d.Add(pnt3d); int k = 0; do { k = pnts3d.Count; pnt3d = UserInput.getPoint("\nPick Next Vertex: ", pnts3d[k - 1], out escape, out ps, osMode: 0); if (ps == PromptStatus.Cancel) { ids.delete(); return(ObjectId.Null); } if (ps == PromptStatus.None) { switch (ids.Count) { case 0: return(ObjectId.Null); default: Stop = true; idLdr = Draw.addLdr(pnts3d, false, nameLayer: "ARROW"); ids.delete(); break; } } else { ids.Add(Draw.addLine(pnts3d[k - 1], pnt3d)); pnts3d.Add(pnt3d); } }while (!Stop); return(idLdr); }
public static List <T> IntersectedObjs <T>(Point3d P1, Point3d P2) { var PoColl = new Point3dCollection(); PoColl.Add(P1); PoColl.Add(P2); PoColl.Add(point.Move(P2, 0, 1)); PoColl.Add(point.Move(P1, 0, 1)); var PSR = AC.Editor.SelectCrossingPolygon(PoColl); if (PSR.Status != PromptStatus.OK) { return(null); } return(Get.Objects <T>(PSR.Value.GetObjectIds().ToList())); }
Point3dCollection ArcToVectors(CircularArc3d arc, int numSegments) { Interval interval = arc.GetInterval(); double increment = interval.Length / (double)numSegments; double controller = interval.LowerBound; Point3dCollection points = new Point3dCollection(); for (int i = 0; i < numSegments; ++i) { points.Add(arc.EvaluatePoint(controller)); controller += increment; } points.Add(arc.EvaluatePoint(controller)); return(points); }
public BB_Jig(Point3d pnt3dFirst, ObjectIdCollection idsIn) : base(null) { _mPts = new Point3dCollection(); _mPts.Add(pnt3dFirst); ids = idsIn; _mIsJigStarted = false; }
public void addVertex() { Leader leader = Entity as Leader; leader.AppendVertex(_mTempPoint); // Add the latest point to our history _mPts.Add(_mTempPoint); }
public void FenceSelectAndLinetype_Method() { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; try { Point3dCollection pts = new Point3dCollection(); PromptPointOptions prPntOpt = new PromptPointOptions("\nFence point: (Enter to finish)"); prPntOpt.AllowArbitraryInput = true; prPntOpt.AllowNone = true; prPntOpt.UseBasePoint = false; prPntOpt.UseDashedLine = true; Point3d prePnt = new Point3d(double.NegativeInfinity, 0, 0); while (true) { if (!double.IsNegativeInfinity(prePnt.X)) { prPntOpt.UseBasePoint = true; prPntOpt.BasePoint = prePnt; } PromptPointResult prPntRes = ed.GetPoint(prPntOpt); if (prPntRes.Status == PromptStatus.OK) { pts.Add(prPntRes.Value); prePnt = prPntRes.Value; } else { break; } } PromptSelectionResult prSelRes = ed.SelectFence(pts); if (prSelRes.Status == PromptStatus.OK) { SelectionSet ss = prSelRes.Value; if (ss != null) { ed.WriteMessage("\nThe SS is good and has {0} entities.", ss.Count); } else { ed.WriteMessage("\nThe SS is bad!"); } } else { ed.WriteMessage("\nFence selection failed!"); } } catch (System.Exception ex) { ed.WriteMessage(Environment.NewLine + ex.ToString()); } }
public static bool BuildPolylineFrom3Point(Point3d pt1, Point3d pt2, Point3d pt3) { Vector3d v12 = (pt2 - pt1).GetNormal(); Vector3d v13 = (pt3 - pt1).GetNormal(); Vector3d v23 = (pt3 - pt2).GetNormal(); if (v12.IsPerpendicularTo(v13, ArxHelper.Tol)) { Point3dCollection verx = new Point3dCollection(); verx.Add(pt3 + (pt2 - pt1).GetNormal() * 3); verx.Add(pt3); verx.Add(pt1); verx.Add(pt2); verx.Add(pt2 + (pt3 - pt1).GetNormal() * 3); Polyline3d pl = new Polyline3d(Poly3dType.SimplePoly, verx, false); AppendEntity(pl); return(true); } else if (v13.IsPerpendicularTo(v23, ArxHelper.Tol)) { Point3dCollection verx = new Point3dCollection(); verx.Add(pt1 + (pt2 - pt3).GetNormal() * 3); verx.Add(pt1); verx.Add(pt3); verx.Add(pt2); verx.Add(pt2 + (pt1 - pt3).GetNormal() * 3); Polyline3d pl = new Polyline3d(Poly3dType.SimplePoly, verx, false); AppendEntity(pl); return(true); } else if (v12.IsPerpendicularTo(v23, ArxHelper.Tol)) { Point3dCollection verx = new Point3dCollection(); verx.Add(pt3 + (pt1 - pt2).GetNormal() * 3); verx.Add(pt3); verx.Add(pt2); verx.Add(pt1); verx.Add(pt1 + (pt3 - pt2).GetNormal() * 3); Polyline3d pl = new Polyline3d(Poly3dType.SimplePoly, verx, false); AppendEntity(pl); return(true); } return(false); }
/// <summary> /// 根据两条样条曲线创建出位于其中间的一条新样条曲线 /// </summary> /// <param name="cur1"></param> /// <param name="cur2"></param> /// <returns></returns> private static NurbCurve3d MiddleCurve(NurbCurve3d cur1, NurbCurve3d cur2) { // Return a NurbCurve3d that's halfway between those passed in // Start by getting the period of both curves double per1, per2; var ip1 = cur1.IsPeriodic(out per1); var ip2 = cur2.IsPeriodic(out per2); // Make the sure the curves have the same degree, period, // number of control points, knots and weights if ( cur1.Degree != cur2.Degree || ip1 != ip2 || per1 != per2 || cur1.NumberOfControlPoints != cur2.NumberOfControlPoints || cur1.NumberOfKnots != cur2.NumberOfKnots || cur1.NumWeights != cur2.NumWeights ) { return(null); } var degree = cur1.Degree; var period = ip1; // Get the set of averaged control points var numPoints = cur1.NumberOfControlPoints; var pts = new Point3dCollection(); for (var i = 0; i < numPoints; i++) { var pt1 = cur1.ControlPointAt(i); var pt2 = cur2.ControlPointAt(i); pts.Add(pt1 + (pt2 - pt1) / 2); } // Get the set of averaged knots var numKnots = cur1.NumberOfKnots; var knots = new KnotCollection(); for (var i = 0; i < numKnots; i++) { knots.Add((cur1.KnotAt(i) + cur2.KnotAt(i)) / 2); } // Get the set of averaged weights var numWeights = cur1.NumWeights; var weights = new DoubleCollection(); for (var i = 0; i < numWeights; i++) { knots.Add((cur1.GetWeightAt(i) + cur2.GetWeightAt(i)) / 2); } // Create our new Ge curve based on all this data return(new NurbCurve3d(degree, knots, pts, weights, period)); }
private void GenerateNodes(List <FoundationNode> nodes, ICollection <FoundationCentreLine> centrelines) { bool complete = false; while (!complete) { nodes.Clear(); complete = true; foreach (FoundationCentreLine fcl in centrelines) { fcl.AttachNodes(nodes); } Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Transaction acTrans = acCurDb.TransactionManager.TopTransaction; // TODO: This section needs checking //Iterate over full collection, identifying any nodes that intersect part way through the lines and adjusting to suit BlockTableRecord modelSpace = HostDocument.Database.GetModelSpace(true); foreach (FoundationNode foundationNode in nodes) { for (int i = 0; i < centrelines.Count; i++) { Curve toBeChecked = acTrans.GetObject(centrelines.ElementAt(i).BaseObject, OpenMode.ForRead) as Curve; Point3d closest = toBeChecked.GetClosestPointTo(foundationNode.Location, false); if (!closest.IsEqualTo(toBeChecked.StartPoint) && !closest.IsEqualTo(toBeChecked.EndPoint)) { //TODO: Will global tolerance work?? if ((foundationNode.Location - closest).Length <= 0.0001) //Tolerance.Global.EqualPoint) { Point3dCollection splitPoint = new Point3dCollection(); splitPoint.Add(closest); //Node is one line DBObjectCollection splitSegments = toBeChecked.GetSplitCurves(splitPoint); foreach (DBObject splitSegment in splitSegments) { FoundationCentreLine fcl = new FoundationCentreLine(acDoc, _soilProperties, _foundationLayerName); fcl.BaseObject = modelSpace.AppendEntity(splitSegment as Entity); acTrans.AddNewlyCreatedDBObject(splitSegment, true); centrelines.Add(fcl); } toBeChecked.Erase(); //centrelines.RemoveAt(i); centrelines.Remove(centrelines.ElementAt(i)); complete = false; break; } } } } } }
/// <summary> /// Creates the new polyliness. /// </summary> /// <param name="_sourcedb">The _sourcedb.</param> /// <param name="_collection">The _collection.</param> public static void CreateNewPolyliness(Autodesk.AutoCAD.DatabaseServices.Database _sourcedb, Point2dCollection _collection) { // Get the current document and database Document acDoc = Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.Database acCurDb = acDoc.Database; Editor ed = acDoc.Editor; // Lock the current document PlanarEntity plane; CoordinateSystem3d ucs = ed.CurrentUserCoordinateSystem.CoordinateSystem3d; plane = new Plane(ucs.Origin, ucs.Xaxis); using (DocumentLock acLckDocCur = acDoc.LockDocument()) { // Start a transaction using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { #region MyRegion // Open the Block table record for read BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; DoubleCollection bulges = new DoubleCollection(); double[] bulgelist = new double[] {}; Point3dCollection p3DCollection = new Point3dCollection(); foreach (var point in _collection) { Point3d p3D = new Point3d(point.X, point.Y, 0.0); p3DCollection.Add(p3D); bulges.Add(0); } Polyline2d polyline2D = new Polyline2d(Poly2dType.SimplePoly, p3DCollection, 0, true, 0, 0, bulges); polyline2D.Color = Color.FromColorIndex(ColorMethod.ByAci, 1); acBlkTblRec.AppendEntity(polyline2D); acTrans.AddNewlyCreatedDBObject(polyline2D, true); #endregion acTrans.Commit(); } // // Unlock the document } }
protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw) { Entities.Clear(); Entities.Add(CreateCircle(new Point3d(CenterPoint.X + 10, CenterPoint.Y, CenterPoint.Z), 20, 90)); Entities.Add(CreateCircle(new Point3d(CenterPoint.X - 10, CenterPoint.Y, CenterPoint.Z), 20, 210)); Entities.Add(CreateLine(new Point3d(CenterPoint.X + 30, CenterPoint.Y, CenterPoint.Z), new Point3d(CenterPoint.X + 40, CenterPoint.Y, CenterPoint.Z), (int)Atend.Control.Enum.ProductType.Transformer, 0, 10)); Entities.Add(CreateLine(new Point3d(CenterPoint.X - 30, CenterPoint.Y, CenterPoint.Z), new Point3d(CenterPoint.X - 40, CenterPoint.Y, CenterPoint.Z), (int)Atend.Control.Enum.ProductType.Transformer, 0, 10)); Entities.Add(DrawKablsho(new Point3d(CenterPoint.X + 40, CenterPoint.Y, CenterPoint.Z))); //header cabel Point3dCollection Points = new Point3dCollection(); Points.Add(new Point3d(CenterPoint.X - 45, CenterPoint.Y, CenterPoint.Z)); Points.Add(new Point3d(CenterPoint.X - 40, CenterPoint.Y - 5, CenterPoint.Z)); Points.Add(new Point3d(CenterPoint.X - 40, CenterPoint.Y + 5, CenterPoint.Z)); Points.Add(new Point3d(CenterPoint.X - 45, CenterPoint.Y, CenterPoint.Z)); Entities.Add(CreateHeaderCable(Points)); //~~~~~~~~ SCALE ~~~~~~~~~~ Matrix3d trans1 = Matrix3d.Scaling(MyScale, new Point3d(CenterPoint.X, CenterPoint.Y, 0)); foreach (Entity en in Entities) { en.TransformBy(trans1); } //~~~~~~~~~~~~~~~~~~~~~~~~~ foreach (Entity ent in Entities) { draw.Geometry.Draw(ent); } return(true); }
public static void RemoveDuplicate([NotNull] this Point3dCollection pts, Tolerance tol) { var ptsClean = RemoveDuplicate(pts.Cast <Point3d>().ToList(), tol); pts.Clear(); foreach (var pt in ptsClean) { pts.Add(pt); } }
public static Point3dCollection GenerateRandomPoints(int count, int xMax, int yMax, int zMax) { Point3dCollection points = new Point3dCollection(); for (int i = 0; i < count; i++) { points.Add(GenerateRandomPoint(xMax, yMax, zMax)); } return(points); }
public Polyline3d PolylineToNativeDB(Polyline polyline) // AC polyline3d can only have linear segments { var vertices = new Point3dCollection(); for (int i = 0; i < polyline.points.Count; i++) { vertices.Add(PointToNative(polyline.points[i])); } return(new Polyline3d(Poly3dType.SimplePoly, vertices, polyline.closed)); }
public override bool ViewportDraw(ViewportDraw worldDraw, ObjectId entityId, DrawType type, Point3d?imageGripPoint, int gripSizeInPixels) { CoordinateSystem3d eCS = GetECS(entityId); Point2d numPixelsInUnitSquare = worldDraw.Viewport.GetNumPixelsInUnitSquare(GripPoint); double num = (double)gripSizeInPixels / numPixelsInUnitSquare.X; Point3dCollection point3dCollections = new Point3dCollection(); point3dCollections.Add((GripPoint - (num * eCS.Xaxis)) - (num * eCS.Yaxis)); point3dCollections.Add((GripPoint - (num * eCS.Xaxis)) + (num * eCS.Yaxis)); point3dCollections.Add((GripPoint + (num * eCS.Xaxis)) + (num * eCS.Yaxis)); point3dCollections.Add((GripPoint + (num * eCS.Xaxis)) - (num * eCS.Yaxis)); worldDraw.SubEntityTraits.FillType = FillType.FillAlways; worldDraw.Geometry.Polygon(point3dCollections); worldDraw.SubEntityTraits.FillType = FillType.FillNever; worldDraw.SubEntityTraits.TrueColor = new EntityColor(0, 0, 0); worldDraw.Geometry.Polygon(point3dCollections); return(true); }
public static Point3dCollection GetAllPoints(this Polyline pline) { Point3dCollection p3dc = new Point3dCollection(); for (int i = 0; i < pline.NumberOfVertices; i++) { p3dc.Add(pline.GetPoint3dAt(i)); } return(p3dc); }
private void AddLinesForSkeleton( List <Line> lines, Skeleton sd, int idx ) { // Hard-code lists of connections between joints int[][] links = new int[][] { // Head to left toe new int[] { 3, 2, 1, 0, 12, 13, 14, 15 }, // Hips to right toe new int[] { 0, 16, 17, 18, 19 }, // Left hand to right hand new int[] { 7, 6, 5, 4, 2, 8, 9, 10, 11 } }; // Populate an array of joints Point3dCollection joints = new Point3dCollection(); for (int i = 0; i < 20; i++) { joints.Add( PointFromVector(sd.Joints[(JointType)i].Position, false) ); } // For each path of joints, create a sequence of lines foreach (int[] link in links) { for (int i = 0; i < link.Length - 1; i++) { // Line from this vertex to the next Line ln = new Line(joints[link[i]], joints[link[i + 1]]); // Set the color to distinguish between skeletons ln.ColorIndex = idx; // Make tracked skeletons bolder ln.LineWeight = (sd.TrackingState == SkeletonTrackingState.Tracked ? LineWeight.LineWeight050 : LineWeight.LineWeight000 ); lines.Add(ln); } } }
private static IList <Point3dCollection> IncludeIntersectingNeighbor(Point3dCollection p3D, ACADDB.ObjectIdCollection originalCollection) { IList <Point3dCollection> outCollection = new List <Point3dCollection>(); Point3dCollection temPoint3DCollection = null; foreach (ACADDB.ObjectId polyoid in originalCollection) { var index = originalCollection.IndexOf(polyoid); Point2dCollection polypoints = PGA.AcadUtilities.AcadUtilities.GetPointsFromPolyline(polyoid); Point2d nearPoint = new Point2d(); Point2d outPoint = new Point2d(); var pointindex = 0; temPoint3DCollection = new Point3dCollection(); Point2dCollection p2d = PGA.AcadUtilities.AcadUtilities.ConvertTo2d(p3D); foreach (var point in polypoints) { if (PGA.AcadUtilities.PolygonFunctions.IsPointInsidePolygon(point, p2d.ToArray(), true)) { double maxdist = 100000; double mindist = 0; var matchingIndex = -1; //Points on Poly are not Lidar Points Must add manually for (int i = 0; i < p2d.Count - 1; i++) { mindist = PGA.AcadUtilities.PolygonFunctions.DistanceToSegment(point, p2d[i], p2d[i + 1], ref nearPoint); if (mindist < maxdist) { maxdist = mindist; outPoint = nearPoint; pointindex = i; } } //for (int i = 0; i < p3D.Count; i++) //{ // if (Equals(p3D[i], outPoint)) // temPoint3DCollection.Add(p3D[i]); //} if (maxdist < 5.0) { temPoint3DCollection.Add(new Point3d(point.X, point.Y, p3D[pointindex].Z)); } // temPoint3DCollection.Add(p3D[pointindex]); //var matchingIndex = p2d.IndexOf(outPoint); //if (matchingIndex != -1) // temPoint3DCollection.Add(p3D[index][matchingIndex]); } } if (temPoint3DCollection != null) { outCollection.Add(temPoint3DCollection); } } return(outCollection); }
static public void selectMsFromPs() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; // pick a PS Viewport PromptEntityOptions opts = new PromptEntityOptions("Pick PS Viewport"); opts.SetRejectMessage("Must select PS Viewport objects only"); opts.AddAllowedClass(typeof(Autodesk.AutoCAD.DatabaseServices.Viewport), false); PromptEntityResult res = ed.GetEntity(opts); if (res.Status == PromptStatus.OK) { int vpNumber = 0; // extract the viewport points Point3dCollection psVpPnts = new Point3dCollection(); using (Autodesk.AutoCAD.DatabaseServices.Viewport psVp = res.ObjectId.Open(OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.Viewport) { // get the vp number vpNumber = psVp.Number; // now extract the viewport geometry psVp.GetGripPoints(psVpPnts, new IntegerCollection(), new IntegerCollection()); } // let's assume a rectangular vport for now, make the cross-direction grips square Point3d tmp = psVpPnts[2]; psVpPnts[2] = psVpPnts[1]; psVpPnts[1] = tmp; // Transform the PS points to MS points ResultBuffer rbFrom = new ResultBuffer(new TypedValue(5003, 3)); ResultBuffer rbTo = new ResultBuffer(new TypedValue(5003, 2)); double[] retPoint = new double[] { 0, 0, 0 }; // loop the ps points Point3dCollection msVpPnts = new Point3dCollection(); foreach (Point3d pnt in psVpPnts) { // translate from from the DCS of Paper Space (PSDCS) RTSHORT=3 and // the DCS of the current model space viewport RTSHORT=2 acedTrans(pnt.ToArray(), rbFrom.UnmanagedObject, rbTo.UnmanagedObject, 0, retPoint); // add the resulting point to the ms pnt array msVpPnts.Add(new Point3d(retPoint)); ed.WriteMessage("\n" + new Point3d(retPoint).ToString()); } // now switch to MS ed.SwitchToModelSpace(); // set the CVPort Application.SetSystemVariable("CVPORT", vpNumber); // once switched, we can use the normal selection mode to select PromptSelectionResult selectionresult = ed.SelectCrossingPolygon(msVpPnts); // now switch back to PS ed.SwitchToPaperSpace(); } }
public string getWindowText(Point3d pt1, Point3d pt2) { Editor editor = Application.DocumentManager.MdiActiveDocument.Editor; TypedValue[] array = new TypedValue[] { new TypedValue(0, "TEXT") }; SelectionFilter selectionFilter = new SelectionFilter(array); Point3dCollection point3dCollection = new Point3dCollection(); Point3d point3d = new Point3d(pt2.X, pt1.Y, 0.0); Point3d point3d2 = new Point3d(pt1.X, pt2.Y, 0.0); point3dCollection.Add(pt1); point3dCollection.Add(point3d2); point3dCollection.Add(pt2); point3dCollection.Add(point3d); Polyline3d polyline3d = this.CreatePolye(point3dCollection); double area = polyline3d.Area; Point3dCollection point3dCollection2 = new Point3dCollection(); polyline3d.GetStretchPoints(point3dCollection2); PromptSelectionResult ents = editor.SelectCrossingPolygon(point3dCollection2); DBObjectCollection entityCollection = this.GetEntityCollection(ents); string text = ""; foreach (Entity entity in entityCollection) { if (entity is DBText) { DBText dBText = entity as DBText; if (dBText != null) { if (!dBText.TextString.Equals("")) { } text += dBText.TextString; } } } return(text); }
public static Point3dCollection PointCollection(Polyline acPoly) { var PoColl = new Point3dCollection(); var A = new List <Point3d>(); for (int i = 0; i < acPoly.NumberOfVertices; i++) { try { var a = acPoly.GetPoint3dAt(i); var x = Math.Round(a.X, 2); var y = Math.Round(a.Y, 2); var z = Math.Round(a.Z, 2); A.Add(new Point3d(x, y, z)); } catch { } } var B = A.Distinct(new Point3dComparer()).ToList(); if (!B.First().Equals(B.Last())) { B.Add(B.First()); } for (int i = 0; i < B.Count - 1; i++) { if (B[i].DistanceTo(B[i + 1]) == 0) { continue; } PoColl.Add(B[i]); } PoColl.Add(B.Last()); return(PoColl); }
//convert parts to splines (works for line and arcs*Not arcs yet) static private Spline convertSpline(DBObject dbo) { if (dbo is Spline) { return(dbo as Spline); } if (dbo is Arc) { Arc arcDat = dbo as Arc; Spline seg = new Spline(); //whatever that is return(seg); } else if (dbo is Line) { Line lDat = dbo as Line; Point3dCollection vertices = new Point3dCollection(); vertices.Add(lDat.StartPoint); vertices.Add(lDat.EndPoint); Polyline3d tempPline = new Polyline3d(); //polyine 3D has to be in btr before adding vertices Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTableRecord btr = (BlockTableRecord)(trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)); btr.AppendEntity(tempPline); foreach (Point3d pnt in vertices) { using (PolylineVertex3d poly3dVert = new PolylineVertex3d(pnt)) { tempPline.AppendVertex(poly3dVert); } } trans.Commit(); } Spline seg = tempPline.Spline; tempPline.Erase(true); return(seg); } return(null); }
public static Point3dCollection TransformPaperSpacePointToModelSpace(Point3dCollection paperSpacePoints, Matrix3d mt) { Point3dCollection points = new Point3dCollection(); foreach (Point3d p in paperSpacePoints) { points.Add(p.TransformBy(mt)); } return(points); }
public static Point3dCollection GetPoints(this Curve curve) { Point3dCollection points = new Point3dCollection(); int count = curve.GetNumberOfVertices(); for (int i = 0; i < count; i++) { points.Add(curve.GetPointAtParameter(i)); } return(points); }
public static Point3dCollection P2M(this Viewport vp, Point3dCollection paperPoints) { var pts = new Point3dCollection(); var xForm = vp.P2M(); foreach (Point3d pt in paperPoints) { pts.Add(pt.TransformBy(xForm)); } return(pts); }
public static Point3dCollection GetPoints(this Polyline pline) { Point3dCollection points = new Point3dCollection(); int count = pline.NumberOfVertices; for (int i = 0; i < count; i++) { points.Add(pline.GetPointAtParameter(i)); } return(points); }
public static Point3dCollection M2P(this Viewport vp, Point3dCollection modelPoints) { var pts = new Point3dCollection(); var xForm = vp.M2P(); foreach (Point3d pt in modelPoints) { pts.Add(pt.TransformBy(xForm)); } return(pts); }
public void CreateGeometry() { Geometry = new Point3dCollection(); Double delta = Math.PI * 2 / Sides; Double x, y; for (int i = 0; i < Sides; i++) { x = this.Center.X + this.Apotema * Math.Cos(delta * i); y = this.Center.Y + this.Apotema * Math.Sin(delta * i); Geometry.Add(new Point3d(x, y, 0)); } }
/** * @brief Metodo que descompone una curva en un conjunto de segmentos de línea que aproximan o recubren la curva original. * * @param cur Entidad curva que debe ser linealizada. * @param numSeg Número de líneas en las que tiene que ser partida la curva. * @param acBlkTbl Tabla de bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados. * @param acBlkTblRec Tabla de registros de los bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados. * @param t Transaccion abierta para manipular la tabla de bloques de AutoCAD. * @param LayerId Parámetro del tipo ObjectId que identifica la capa a la que tendrán que asociarse las nuevas líneas generadas por el proceso * de descomposición de la curva. * @param dwfg Parámetro del tipo dwgFile donde se almacenaran las nuevas líneas creadas a partir del proceso de descomposición de la curva. * * @return Devuelve una colección de entidades tipo linea bajo la clase DBObjectCollection. **/ public static DBObjectCollection curvaAlineas(Curve cur, int numSeg, BlockTable acBlkTbl, BlockTableRecord acBlkTblRec,Transaction t, ObjectId LayerId, dwgFile dwfg) { DBObjectCollection ret = new DBObjectCollection(); // Collect points along our curve Point3dCollection pts = new Point3dCollection(); // Split the curve's parameter space into // equal parts double startParam = cur.StartParam; double segLen = (cur.EndParam - startParam) / numSeg; // Loop along it, getting points each time for (int i = 0; i < numSeg + 1; i++) { Point3d pt = cur.GetPointAtParameter(startParam + segLen * i); pts.Add(pt); } if (pts != null && pts.Count > 0) { if (pts.Count == 1) { // Retornamos un punto. } else if (pts.Count >= 2) { // Retornamos una secuencia de lineas for (int i = 0; i < pts.Count - 1; i++) { Line ln = new Line(); ln.StartPoint = pts[i]; ln.EndPoint = pts[i + 1]; ln.LayerId = LayerId; acBlkTblRec.AppendEntity(ln); t.AddNewlyCreatedDBObject(ln, true); dwfg.objetosArtificiales.Add(ln.ObjectId); ret.Add(ln); } } } return ret; }
public static void book01() { Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction(); BlockTable bt = (BlockTable)tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); Point3d[] pts = new Point3d[]{ new Point3d(15.0, 12.0, 0.0), new Point3d(30.0, 44.0, 0.0), new Point3d(60.0, 10.0, 0.0), new Point3d(25.0, 30.0, 0.0) }; Point3dCollection points = new Point3dCollection(); for (int i = 0; i < 4; i++) { points.Add(pts[i]); } Spline spline = new Spline(points, 4, 0.0); btr.AppendEntity(spline); tr.AddNewlyCreatedDBObject(spline, true); tr.Commit(); tr.Dispose(); }
private Point3dCollection GetContourVertex(Point3d p1, Point3d p2) { // Возвращает массив точек контура полилинии плитки. Point3dCollection pts = new Point3dCollection(); var vec = p2 - p1; var vecSingle = vec.GetNormal(); var vecSinglePerpend = vecSingle.GetPerpendicularVector(); double len = vec.Length;//длина участка double curLen = len - Options.LenTile; if (curLen >= 0) { // Первый сегент - первая плитка pts.Add(p1); _lastVertex = p1 + vecSingle * Options.LenTile; pts.Add(_lastVertex); // Второй и последующие сегменты do { curLen = GetTileSection(pts, vecSingle, vecSinglePerpend, curLen); } while (curLen > 0); } return pts; }
protected override bool WorldDraw(WorldDraw draw) { WorldGeometry geo = draw.Geometry; if (geo != null) { geo.PushModelTransform(UCS); // Не очень понятно, что это. if (_allVertex.Count != 0) { // Копирование точек полилинии во временную колекцию Point3dCollection tempAllVertex = new Point3dCollection(); foreach (Point3d pt in _allVertex) tempAllVertex.Add(pt); // Последняя вершина полилинии. Point3d pt1 = _allVertex[_allVertex.Count - 1]; // Точка отрогональная по длинной стороне к текущей указанной. Point3d ptNew = GetPointOrhto(pt1, _lastVertex); // Получение вершин для полилинии текущего участка. Point3dCollection _tempNewSectionPts = GetContourVertex(pt1, ptNew); // Добавление вершин последнего участка к остальным. if (_tempNewSectionPts.Count > 0) { foreach (Point3d pt in _tempNewSectionPts) tempAllVertex.Add(pt); } // Отрисовка полилинии. geo.Polyline(tempAllVertex, Vector3d.ZAxis, IntPtr.Zero); } geo.PopModelTransform(); // Что это? } return true; }
private Point3dCollection GetAllButLast( Point3dCollection pts, int n ) { Point3dCollection res = new Point3dCollection(); for (int i = 0; i < pts.Count - n; i++) { res.Add(pts[i]); } return res; }
public static void Create(Grevit.Types.Spline s) { Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database; Transaction tr = db.TransactionManager.StartTransaction(); Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); try { Point3dCollection points = new Point3dCollection(); foreach (Grevit.Types.Point p in s.controlPoints) points.Add(GrevitPtoPoint3d(p)); DoubleCollection dc = new DoubleCollection(); foreach (double dbl in s.weights) dc.Add(dbl); DoubleCollection dcc = new DoubleCollection(); foreach (double dbl in s.knots) dcc.Add(dbl); Spline sp = new Spline(s.degree, s.isRational, s.isClosed, s.isPeriodic, points, dcc, dc, 0, 0); sp.SetDatabaseDefaults(db); BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); AddXData(s, sp); if (lt.Has(s.TypeOrLayer)) sp.LayerId = lt[s.TypeOrLayer]; ms.AppendEntity(sp); tr.AddNewlyCreatedDBObject(sp, true); writeProperties(sp, s.parameters, tr); storeID(s, sp.Id); tr.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception e) { ed.WriteMessage(e.Message); tr.Abort(); } finally { tr.Dispose(); } }
public override void MoveGripPointsAt(Entity entity, IntegerCollection indices, Vector3d offset) { base.MoveGripPointsAt(entity, indices, offset); if (Gripindex != null || GripIndexs[0] != null && GripIndexs[1] != null) { Polyline pLine = tr.openObject(DimInc_pLine, OpenMode.ForWrite) as Polyline; if (pLine != null) { Point3dCollection points = new Point3dCollection(); for (int i = 0; i < pLine.NumberOfVertices; i++) { if (i == Gripindex) { points.Add(CurrPoint); continue; } else if (i == GripIndexs[0] || i == GripIndexs[1]) { points.Add(acMath.getPointAtVector(pLine.GetPoint3dAt(i),offset)); continue; } else { points.Add(pLine.GetPoint3dAt(i)); } } tr.closeObject(); Group Texts = tr.openGroup(DimInc_texts, OpenMode.ForWrite); ObjectId[] ids = Texts.GetAllEntityIds(); tr.closeGroup(); int index = 0; foreach (ObjectId id in ids) { DBText txt = tr.openObject(id, OpenMode.ForWrite) as DBText; if (index != points.Count - 1) { txt.TextString = acMath.totalDistance(points, DIMset.DimUnit_Precision, index).ToString(); txt.Rotation = acMath.RetriveRot(points[index], points[index + 1]); txt.AlignmentPoint = acMath.pointOffset(points[index],points[index + 1],DIMset.Dimtxt_Offset)[1]; } else { txt.TextString = acMath.totalDistance(points, DIMset.DimUnit_Precision, index).ToString(); txt.Rotation = acMath.RetriveRot(points[index], points[0]); txt.AlignmentPoint = acMath.pointOffset(points[index], points[0], DIMset.Dimtxt_Offset)[1]; } tr.closeObject(); index++; } needRefresh = true; } } }
public static Point3dCollection To3dPointCollection(this Grevit.Types.Component curve) { Point3dCollection points = new Point3dCollection(); if (curve.GetType() == typeof(Grevit.Types.Line)) { Grevit.Types.Line baseline = (Grevit.Types.Line)curve; Point3d p1 = baseline.from.ToPoint3d(); Point3d p2 = baseline.to.ToPoint3d(); if (!points.Contains(p1)) points.Add(p1); if (!points.Contains(p2)) points.Add(p2); } else if (curve.GetType() == typeof(Grevit.Types.Arc)) { } else if (curve.GetType() == typeof(Grevit.Types.Curve3Points)) { Grevit.Types.Curve3Points baseline = (Grevit.Types.Curve3Points)curve; Point3d p1 = baseline.a.ToPoint3d(); Point3d p2 = baseline.b.ToPoint3d(); Point3d p3 = baseline.c.ToPoint3d(); if (!points.Contains(p1)) points.Add(p1); if (!points.Contains(p2)) points.Add(p2); if (!points.Contains(p3)) points.Add(p3); } else if (curve.GetType() == typeof(Grevit.Types.PLine)) { Grevit.Types.PLine baseline = (Grevit.Types.PLine)curve; for (int i = 0; i < baseline.points.Count; i++) { Point3d p1 = baseline.points[i].ToPoint3d(); if (!points.Contains(p1)) points.Add(p1); } } else if (curve.GetType() == typeof(Grevit.Types.Spline)) { Grevit.Types.Spline s = (Grevit.Types.Spline)curve; foreach (Grevit.Types.Point p in s.controlPoints) { Point3d p1 = p.ToPoint3d(); if (!points.Contains(p1)) points.Add(p1); } } return points; }
private void Create_symbol1() { string blockName = "symbol1"; DBObjectCollection entityCollection = new DBObjectCollection(); Line ent1 = new Line(new Point3d(0, 0.12, 0), new Point3d(0, -0.12, 0)); ent1.Layer = "0"; entityCollection.Add(ent1); Point3dCollection verties = new Point3dCollection(); verties.Add(new Point3d(0, 0, 0)); verties.Add(new Point3d(0.077, 0.064, 0)); verties.Add(new Point3d(0.077, -0.064, 0)); verties.Add(new Point3d(0, 0, 0)); Polyline2d ent2 = new Polyline2d(Poly2dType.SimplePoly, verties, 0, false, 0, 0, new DoubleCollection(new double[] { 0, 0, 0, 0 })); ent2.Layer = "0"; entityCollection.Add(ent2); TryInsertBlockRecord(blockName, entityCollection); }
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."); } } }
private void AddLinesForSkeleton( List<Line> lines, Skeleton sd, int idx ) { // Hard-code lists of connections between joints int[][] links = new int[][] { // Head to left toe new int[] { 3, 2, 1, 0, 12, 13, 14, 15 }, // Hips to right toe new int[] { 0, 16, 17, 18, 19 }, // Left hand to right hand new int[] { 7, 6, 5, 4, 2, 8, 9, 10, 11 } }; // Populate an array of joints Point3dCollection joints = new Point3dCollection(); for (int i = 0; i < 20; i++) { joints.Add( PointFromVector(sd.Joints[(JointType)i].Position, false) ); } // For each path of joints, create a sequence of lines foreach (int[] link in links) { for (int i = 0; i < link.Length - 1; i++) { // Line from this vertex to the next Line ln = new Line(joints[link[i]], joints[link[i + 1]]); // Set the color to distinguish between skeletons ln.ColorIndex = idx; // Make tracked skeletons bolder ln.LineWeight = (sd.TrackingState == SkeletonTrackingState.Tracked ? LineWeight.LineWeight050 : LineWeight.LineWeight000 ); lines.Add(ln); } } }
/// <summary> /// Sorts a Point3dCollection so that the order of its points corresponds /// to their position along the axis parameter. /// </summary> /// <param name="points">Points that will be sorted.</param> /// <param name="axis">Axis along which the points will be sorted.</param> public static Point3dCollection SortPoints(Point3dCollection points, Axis axis) { Point3d[] pointsArray = new Point3d[points.Count]; double[] positions = new double[points.Count]; for (int i = 0; i < points.Count; i++) { pointsArray[i] = points[i]; switch (axis) { case Axis.X: positions[i] = points[i].X; break; case Axis.Y: positions[i] = points[i].Y; break; case Axis.Z: positions[i] = points[i].Z; break; } } Array.Sort(positions, pointsArray); Point3dCollection sortedPoints = new Point3dCollection(); for (int i = 0; i < pointsArray.Length; i++) { sortedPoints.Add(pointsArray[i]); } return sortedPoints; }
public static DBObject Create(this Grevit.Types.Spline s, Transaction tr) { LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); try { Point3dCollection points = new Point3dCollection(); foreach (Grevit.Types.Point p in s.controlPoints) points.Add(p.ToPoint3d()); DoubleCollection dc = new DoubleCollection(); foreach (double dbl in s.weights) dc.Add(dbl); DoubleCollection dcc = new DoubleCollection(); foreach (double dbl in s.knots) dcc.Add(dbl); Spline sp = new Spline(s.degree, s.isRational, s.isClosed, s.isPeriodic, points, dcc, dc, 0, 0); sp.SetDatabaseDefaults(Command.Database); BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); if (lt.Has(s.TypeOrLayer)) sp.LayerId = lt[s.TypeOrLayer]; ms.AppendEntity(sp); tr.AddNewlyCreatedDBObject(sp, true); ms.Dispose(); return sp; } catch (Autodesk.AutoCAD.Runtime.Exception e) { } return null; }
public static void Create(Grevit.Types.PLine a) { Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database; Transaction tr = db.TransactionManager.StartTransaction(); Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; try { LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); Point3dCollection pc = new Point3dCollection(); foreach (Grevit.Types.Point p in a.points) pc.Add(GrevitPtoPoint3d(p)); Polyline3d pp = new Polyline3d(Poly3dType.SimplePoly, pc, a.closed); pp.SetDatabaseDefaults(db); if (lt.Has(a.TypeOrLayer)) pp.LayerId = lt[a.TypeOrLayer]; BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); ms.AppendEntity(pp); tr.AddNewlyCreatedDBObject(pp, true); writeProperties(pp, a.parameters, tr); storeID(a, pp.Id); tr.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception e) { ed.WriteMessage(e.Message); tr.Abort(); } finally { tr.Dispose(); } }
public static Curve3dCollection To3dCurve(this Grevit.Types.Component curve) { Curve3dCollection curveArray = new Curve3dCollection(); if (curve.GetType() == typeof(Grevit.Types.Line)) { Grevit.Types.Line baseline = (Grevit.Types.Line)curve; curveArray.Add(new Line3d(baseline.from.ToPoint3d(), baseline.to.ToPoint3d())); } else if (curve.GetType() == typeof(Grevit.Types.Arc)) { Grevit.Types.Arc baseline = (Grevit.Types.Arc)curve; curveArray.Add(new Arc(baseline.center.ToPoint3d(), baseline.radius, baseline.start, baseline.end).GetGeCurve()); } else if (curve.GetType() == typeof(Grevit.Types.Curve3Points)) { Grevit.Types.Curve3Points baseline = (Grevit.Types.Curve3Points)curve; curveArray.Add(new CircularArc3d(baseline.a.ToPoint3d(), baseline.c.ToPoint3d(), baseline.b.ToPoint3d())); } else if (curve.GetType() == typeof(Grevit.Types.PLine)) { Grevit.Types.PLine baseline = (Grevit.Types.PLine)curve; for (int i = 0; i < baseline.points.Count - 1; i++) { curveArray.Add(new Line3d(baseline.points[i].ToPoint3d(), baseline.points[i + 1].ToPoint3d())); } } else if (curve.GetType() == typeof(Grevit.Types.Spline)) { Grevit.Types.Spline s = (Grevit.Types.Spline)curve; Point3dCollection points = new Point3dCollection(); foreach (Grevit.Types.Point p in s.controlPoints) points.Add(p.ToPoint3d()); DoubleCollection dc = new DoubleCollection(); foreach (double dbl in s.weights) dc.Add(dbl); Spline sp = new Spline(s.degree, s.isRational, s.isClosed, s.isPeriodic, points, new DoubleCollection(), dc, 0, 0); curveArray.Add(sp.GetGeCurve()); } return curveArray; }
private double GetTileSection(Point3dCollection pts, Vector3d vecSingle, Vector3d vecSinglePerpend, double curLen) { curLen = curLen - (Options.LenTile + Options.LenSeam); if (curLen >= 0) { // Первая точка шва _lastVertex = GetPoint(_lastVertex, vecSinglePerpend,Options.LenSeam); pts.Add(_lastVertex); // Вторая точка шва _lastVertex = GetPoint(_lastVertex, vecSingle, Options.LenSeam); pts.Add(_lastVertex); // Первая точка плитки _lastVertex = GetPoint(_lastVertex, vecSinglePerpend, -Options.LenSeam); pts.Add(_lastVertex); // Вторая точка плитки _lastVertex = GetPoint(_lastVertex, vecSingle, Options.LenTile); pts.Add(_lastVertex); } return curLen; }
public static DBObject Create(this Grevit.Types.PLine a, Transaction tr) { try { LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead); Point3dCollection pc = new Point3dCollection(); foreach (Grevit.Types.Point p in a.points) pc.Add(p.ToPoint3d()); Polyline3d pp = new Polyline3d(Poly3dType.SimplePoly, pc, a.closed); pp.SetDatabaseDefaults(Command.Database); if (lt.Has(a.TypeOrLayer)) pp.LayerId = lt[a.TypeOrLayer]; BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); ms.AppendEntity(pp); tr.AddNewlyCreatedDBObject(pp, true); return pp; } catch (Autodesk.AutoCAD.Runtime.Exception e) { } return null; }