Exemplo n.º 1
0
        public static bool IsLongestLine(Point3d pt1, Point3d pt2, Point3dCollection pts)
        {
            if (pts.Contains(pt1) && pts.Contains(pt2))
            {
                pts.Remove(pt2);
                pts.Remove(pt1);
            }
            Point3d pt3 = pts[0];
            Point3d pt4 = pts[1];

            if (pt1.DistanceTo(pt2) > pt3.DistanceTo(pt4) &&
                pt1.DistanceTo(pt2) > pt4.DistanceTo(pt1) &&
                pt1.DistanceTo(pt2) > pt2.DistanceTo(pt3) &&
                pt1.DistanceTo(pt2) > pt2.DistanceTo(pt4) &&
                pt1.DistanceTo(pt2) > pt3.DistanceTo(pt1)
                )
            {
                Line l12 = new Line(pt1, pt2);
                Line l34 = new Line(pt3, pt4);
                Point3dCollection lispoint = new Point3dCollection();
                l12.IntersectWith(l34, Intersect.OnBothOperands, lispoint, IntPtr.Zero, IntPtr.Zero);
                if (lispoint.Count == 0)
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 2
0
        //This function gets the 5 points on the passed arc and adds those points
        //to passed point array (pointList)
        static public void BreakArc(ref Arc arc, ref Point3dCollection pointList)
        {
            CircularArc3d arcseg = new CircularArc3d(arc.Center, arc.Normal, arc.Normal.GetPerpendicularVector(),
                                                     arc.Radius, arc.StartAngle, arc.EndAngle);

            var pointArray = arcseg.GetSamplePoints(5);

            bool bReverse = false;

            //Whether to bReverse the reading of points from line, this case is valid
            //only if this function is called for line segment of polyline.
            if (pointList.Count > 0)
            {
                Point3d currentPoint = pointList[pointList.Count - 1];

                if (currentPoint != pointArray[0].Point)
                {
                    bReverse = true;
                }
            }
            int nLength = pointArray.Length;
            int nIndex  = 0;

            if (bReverse == false)
            {
                while (nIndex < nLength)
                {
                    if (pointList.Contains(pointArray[nIndex].Point) == false)
                    {
                        pointList.Add(pointArray[nIndex].Point);

                        DBPoint point = new DBPoint(pointArray[nIndex].Point);
                        point.ColorIndex = 1;
                        point.SetDatabaseDefaults();
                        TGpoints.Add(point);
                    }
                    nIndex++;
                }
            }
            else
            {
                nIndex = nLength;
                while (nIndex > 0)
                {
                    nIndex = nIndex - 1;
                    if (pointList.Contains(pointArray[nIndex].Point) == false)
                    {
                        pointList.Add(pointArray[nIndex].Point);

                        DBPoint point = new DBPoint(pointArray[nIndex].Point);
                        point.ColorIndex = 1;
                        point.SetDatabaseDefaults();
                        TGpoints.Add(point);
                    }
                }
            }
        }
Exemplo n.º 3
0
        //This function gets the 5 points on the passed line and adds those points
        //to passed point array (pointList)
        static public void BreakLine(ref Line line, ref Point3dCollection pointList)
        {
            LineSegment3d lineseg    = new LineSegment3d(line.StartPoint, line.EndPoint);
            var           pointArray = lineseg.GetSamplePoints(5);

            bool bReverse = false;

            //Whether to bReverse the reading of points from line, this case is valid
            //only if this function is called for line segment of polyline.
            if (pointList.Count > 0)
            {
                Point3d currentPoint = pointList[pointList.Count - 1];

                if (currentPoint != line.StartPoint)
                {
                    bReverse = true;
                }
            }
            int nLength = pointArray.Length;
            int nIndex  = 0;

            if (bReverse == false)
            {
                while (nIndex < nLength)
                {
                    if (pointList.Contains(pointArray[nIndex].Point) == false)
                    {
                        pointList.Add(pointArray[nIndex].Point);

                        DBPoint point = new DBPoint(pointArray[nIndex].Point);
                        point.ColorIndex = 1;
                        point.SetDatabaseDefaults();
                        TGpoints.Add(point);
                    }
                    nIndex++;
                }
            }
            else
            {
                nIndex = nLength;
                while (nIndex > 0)
                {
                    nIndex = nIndex - 1;
                    if (pointList.Contains(pointArray[nIndex].Point) == false)
                    {
                        pointList.Add(pointArray[nIndex].Point);

                        DBPoint point = new DBPoint(pointArray[nIndex].Point);
                        point.ColorIndex = 1;
                        point.SetDatabaseDefaults();
                        TGpoints.Add(point);
                    }
                }
            }
        }
Exemplo n.º 4
0
        public void BuildLp(Point3dCollection points, Dictionary <Point3d, Point3dCollection> scanlines)
        {
            if (points.Count == 0)
            {
                return;
            }

            var part = _properties.Parts.SelectedLp;

            foreach (var scanline in scanlines)
            {
                foreach (Point3d p in scanline.Value)
                {
                    if (points.Contains(p))
                    {
                        points.Remove(p);
                    }
                }
            }

            do
            {
                points = PlaceMultipleParts(points, part);
            }while (points.Count > 0 && (part = _partRepository.GetNextSmaller(part, part.UsageType)) != null);
        }
Exemplo n.º 5
0
        private Point3dCollection ConvertViewportContourPointsToModelSpacePoints(Point3dCollection viewPortPoints)
        {
            var points = new Point3dCollection();

            // Преобразование точки из PS в MS
            var rbPSDCS  = new ResultBuffer(new TypedValue(5003, 3));
            var rbDCS    = new ResultBuffer(new TypedValue(5003, 2));
            var rbWCS    = new ResultBuffer(new TypedValue(5003, 0));
            var retPoint = new double[] { 0, 0, 0 };

            foreach (Point3d pnt in viewPortPoints)
            {
                // преобразуем из DCS пространства Листа (PSDCS) RTSHORT=3
                // в DCS пространства Модели текущего Видового Экрана RTSHORT=2
                acedTrans(pnt.ToArray(), rbPSDCS.UnmanagedObject, rbDCS.UnmanagedObject, 0,
                          retPoint);

                // Преобразуем из DCS пространства Модели текущего Видового Экрана RTSHORT=2
                // в WCS RTSHORT=0
                acedTrans(retPoint, rbDCS.UnmanagedObject, rbWCS.UnmanagedObject, 0, retPoint);

                // Добавляем точку в коллекцию
                var newPt = new Point3d(retPoint);
                if (!points.Contains(newPt))
                {
                    points.Add(newPt);
                }
            }

            return(points);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Calculates a normal vector of the curve at the given point
        /// on the given plane. The normal is always in the plane of the curve
        /// and points to the outside of the curve.
        /// </summary>
        public static Vector3d GetNormalVector(this Curve curve, double param, Plane plane)
        {
            Vector3d deriv  = curve.GetFirstDerivative(param);
            Vector3d normal = deriv.CrossProduct(plane.Normal);

            normal /= normal.Length;
            Point3d pt = curve.GetPointAtParameter(param);

            // Check if the normal points to inside the curve (ray-casting)
            Ray ray = new Ray();

            ray.BasePoint   = pt;
            ray.SecondPoint = pt + normal;
            Point3dCollection pts = new Point3dCollection();

            ray.IntersectWith(curve, Intersect.OnBothOperands, plane, pts, IntPtr.Zero, IntPtr.Zero);

            // Remove duplicate points
            Point3dCollection toRemove = new Point3dCollection();

            for (int i = 0; i < pts.Count; i++)
            {
                for (int j = 0; j < pts.Count; j++)
                {
                    if (i != j)
                    {
                        if (pts[i] == pts[j] && !toRemove.Contains(pts[i]))
                        {
                            toRemove.Add(pts[i]);
                        }
                    }
                }
            }
            foreach (Point3d p in toRemove)
            {
                pts.Remove(p);
            }

            // Flip if required
            if (pts.Count % 2 == 0)
            {
                normal = normal.RotateBy(Math.PI, plane.Normal);
            }

            return(normal);
        }
Exemplo n.º 7
0
        protected override bool CanPlace(BlockReference blkRef)
        {
            if (_ldsPoints.Contains(CurrentPoint))
            {
                return(false);
            }

            if (IsCollidingOutline(blkRef))
            {
                return(false);
            }

            if (IsCollidingAnyObstacle(blkRef))
            {
                return(false);
            }

            if (IsInsideAnyEmpty())
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 8
0
        internal static List <MeshData> SolidInfoForCollection(Document doc, Point3d camPos, ObjectIdCollection ids)
        {
            var sols = new List <MeshData>();

            using (var tr = doc.TransactionManager.StartOpenCloseTransaction())
            {
                foreach (ObjectId id in ids)
                {
                    Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity;

                    // Entity handle to name the Three.js objects
                    String hand = ent.Handle.ToString();
                    Autodesk.AutoCAD.Colors.EntityColor clr = ent.EntityColor;

                    // Entity color to use for the Three.js objects
                    long b, g, r;
                    if (ent.ColorIndex < 256)
                    {
                        System.Byte byt = System.Convert.ToByte(ent.ColorIndex);
                        int         rgb = Autodesk.AutoCAD.Colors.EntityColor.LookUpRgb(byt);
                        b = (rgb & 0xffL);
                        g = (rgb & 0xff00L) >> 8;
                        r = rgb >> 16;
                    }
                    else
                    {
                        b = 127;
                        g = 127;
                        r = 127;
                    }
                    String entColor = "0x" + String.Format("{0:X2}{1:X2}{2:X2}", r, g, b);

                    // Entity extents
                    Extents3d ext  = ent.GeometricExtents;
                    var       tmp  = ext.MinPoint + 0.5 * (ext.MaxPoint - ext.MinPoint);
                    Vector3d  dir  = ext.MaxPoint - ext.MinPoint;
                    var       mid  = new Point3d(ext.MinPoint.X, tmp.Y, tmp.Z);
                    var       dist = camPos.DistanceTo(mid);

                    if (id.ObjectClass.Name.Equals("AcDbSubDMesh"))
                    {
                        // Already a Mesh. Get the face info and clean it up
                        // a bit to export it as a THREE.Face3 which only has three vertices

                        var mesh = ent as SubDMesh;

                        Point3dCollection threeVertices = new Point3dCollection();
                        Autodesk.AutoCAD.Geometry.Int32Collection threeFaceInfo = new Autodesk.AutoCAD.Geometry.Int32Collection();

                        Point3dCollection vertices = mesh.Vertices;

                        int[] faceArr = mesh.FaceArray.ToArray();
                        int[] edgeArr = mesh.EdgeArray.ToArray();

                        Autodesk.AutoCAD.Geometry.Int32Collection faceVertices = new Autodesk.AutoCAD.Geometry.Int32Collection();

                        int verticesInFace = 0;
                        int facecnt        = 0;
                        for (int x = 0; x < faceArr.Length; facecnt++, x = x + verticesInFace + 1)
                        {
                            faceVertices.Clear();

                            verticesInFace = faceArr[x];
                            for (int y = x + 1; y <= x + verticesInFace; y++)
                            {
                                faceVertices.Add(faceArr[y]);
                            }

                            // Merging of mesh faces can result in faces with multiple vertices
                            // A simple collinearity check can help remove those redundant vertices
                            bool continueCollinearCheck = false;
                            do
                            {
                                continueCollinearCheck = false;
                                for (int index = 0; index < faceVertices.Count; index++)
                                {
                                    int v1 = index;
                                    int v2 = (index + 1) >= faceVertices.Count ? (index + 1) - faceVertices.Count : index + 1;
                                    int v3 = (index + 2) >= faceVertices.Count ? (index + 2) - faceVertices.Count : index + 2;

                                    // Check collinear
                                    Point3d p1 = vertices[faceVertices[v1]];
                                    Point3d p2 = vertices[faceVertices[v2]];
                                    Point3d p3 = vertices[faceVertices[v3]];

                                    Vector3d vec1 = p1 - p2;
                                    Vector3d vec2 = p2 - p3;
                                    if (vec1.IsCodirectionalTo(vec2))
                                    {
                                        faceVertices.RemoveAt(v2);
                                        continueCollinearCheck = true;
                                        break;
                                    }
                                }
                            } while (continueCollinearCheck);

                            if (faceVertices.Count == 3)
                            {
                                Point3d p1 = vertices[faceVertices[0]];
                                Point3d p2 = vertices[faceVertices[1]];
                                Point3d p3 = vertices[faceVertices[2]];

                                if (!threeVertices.Contains(p1))
                                {
                                    threeVertices.Add(p1);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p1));

                                if (!threeVertices.Contains(p2))
                                {
                                    threeVertices.Add(p2);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p2));

                                if (!threeVertices.Contains(p3))
                                {
                                    threeVertices.Add(p3);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p3));
                            }
                            else if (faceVertices.Count == 4)
                            { // A face with 4 vertices, lets split it to
                                // make it easier later to create a THREE.Face3
                                Point3d p1 = vertices[faceVertices[0]];
                                Point3d p2 = vertices[faceVertices[1]];
                                Point3d p3 = vertices[faceVertices[2]];

                                if (!threeVertices.Contains(p1))
                                {
                                    threeVertices.Add(p1);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p1));

                                if (!threeVertices.Contains(p2))
                                {
                                    threeVertices.Add(p2);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p2));

                                if (!threeVertices.Contains(p3))
                                {
                                    threeVertices.Add(p3);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p3));

                                p1 = vertices[faceVertices[2]];
                                p2 = vertices[faceVertices[3]];
                                p3 = vertices[faceVertices[0]];

                                if (!threeVertices.Contains(p1))
                                {
                                    threeVertices.Add(p1);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p1));

                                if (!threeVertices.Contains(p2))
                                {
                                    threeVertices.Add(p2);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p2));

                                if (!threeVertices.Contains(p3))
                                {
                                    threeVertices.Add(p3);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p3));
                            }
                            else
                            {
                                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Face with more than 4 vertices will need triangulation to import in Three.js ");
                            }
                        }

                        sols.Add(new MeshData(dist, hand, ext, threeVertices, threeFaceInfo, entColor));
                    }
                    else if (id.ObjectClass.Name.Equals("AcDb3dSolid"))
                    {
                        // Mesh the solid to export to Three.js
                        Autodesk.AutoCAD.DatabaseServices.Solid3d sld = tr.GetObject(id, OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.Solid3d;

                        MeshFaceterData mfd = new MeshFaceterData();
                        // Only triangles
                        mfd.FaceterMeshType = 2;

                        // May need change based on how granular we want the mesh to be.
                        mfd.FaceterMaxEdgeLength = dir.Length * 0.025;

                        MeshDataCollection md = SubDMesh.GetObjectMesh(sld, mfd);

                        Point3dCollection threeVertices = new Point3dCollection();
                        Autodesk.AutoCAD.Geometry.Int32Collection threeFaceInfo = new Autodesk.AutoCAD.Geometry.Int32Collection();

                        Point3dCollection vertices = md.VertexArray;

                        int[] faceArr = md.FaceArray.ToArray();

                        Autodesk.AutoCAD.Geometry.Int32Collection faceVertices = new Autodesk.AutoCAD.Geometry.Int32Collection();

                        int verticesInFace = 0;
                        int facecnt        = 0;
                        for (int x = 0; x < faceArr.Length; facecnt++, x = x + verticesInFace + 1)
                        {
                            faceVertices.Clear();

                            verticesInFace = faceArr[x];
                            for (int y = x + 1; y <= x + verticesInFace; y++)
                            {
                                faceVertices.Add(faceArr[y]);
                            }

                            if (faceVertices.Count == 3)
                            {
                                Point3d p1 = vertices[faceVertices[0]];
                                Point3d p2 = vertices[faceVertices[1]];
                                Point3d p3 = vertices[faceVertices[2]];

                                if (!threeVertices.Contains(p1))
                                {
                                    threeVertices.Add(p1);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p1));

                                if (!threeVertices.Contains(p2))
                                {
                                    threeVertices.Add(p2);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p2));

                                if (!threeVertices.Contains(p3))
                                {
                                    threeVertices.Add(p3);
                                }
                                threeFaceInfo.Add(threeVertices.IndexOf(p3));
                            }
                        }

                        sols.Add(new MeshData(dist, hand, ext, threeVertices, threeFaceInfo, entColor));

                        tr.Commit();
                    }
                }
            }
            return(sols);
        }
Exemplo n.º 9
0
        //[CommandMethod("gi")]
        public static void GetIntersections()
        {
            var db = HostApplicationServices.WorkingDatabase;

            var doc = Application.DocumentManager.MdiActiveDocument;

            var ed = doc.Editor;

            using (var docLock = doc.LockDocument())
            {
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        var btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                        var 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;
                        }

                        var ent = tr.GetObject(res.ObjectId, OpenMode.ForRead);

                        if (ent == null)
                        {
                            return;
                        }

                        //Polyline poly = (Polyline)ent as Polyline;
                        var curv = ent as Curve;

                        var pcurves = new DBObjectCollection();

                        curv.Explode(pcurves);
                        TypedValue[] values =
                        {
                            new TypedValue(0, "lwpolyline")
                            //might be added layer name to select curve:
                            //, new TypedValue(8, "mylayer")
                        };
                        var filter = new SelectionFilter(values);

                        var fence = new Point3dCollection();

                        var leng = curv.GetDistanceAtParameter(curv.EndParam) -
                                   curv.GetDistanceAtParameter(curv.StartParam);
                        // number of divisions along polyline to create fence selection
                        var step = leng / 256; // set number of steps to your suit

                        var num = Convert.ToInt32(leng / step);

                        var i = 0;

                        for (i = 0; i < num; i++)
                        {
                            var pp = curv.GetPointAtDist(step * i);

                            fence.Add(curv.GetClosestPointTo(pp, false));
                        }

                        var selres = ed.SelectFence(fence, filter);

                        if (selres.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        var intpts = new Point3dCollection();

                        var qcurves = new DBObjectCollection();

                        foreach (SelectedObject selobj in selres.Value)
                        {
                            var obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false);
                            if (selobj.ObjectId != curv.ObjectId)
                            {
                                var icurves = new DBObjectCollection();
                                var 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);


                        var j       = 0;
                        var polypts = new Point3dCollection();

                        for (i = 0; i < pcurves.Count; ++i)
                        {
                            for (j = 0; j < qcurves.Count; ++j)
                            {
                                var curve1 = pcurves[i] as Curve;

                                var curve2 = qcurves[j] as Curve;

                                var 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);
                                    }
                                }
                            }
                        }

                        Application.SetSystemVariable("osmode", 0); // optional
                        // for debug only
                        Application.ShowAlertDialog(string.Format("\nNumber of Intersections: {0}", polypts.Count));
                        // test for visulization only
                        foreach (Point3d inspt in polypts)
                        {
                            var circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                            circ.ColorIndex = 1;
                            btr.AppendEntity(circ);
                            tr.AddNewlyCreatedDBObject(circ, true);
                        }
                        tr.Commit();
                    }
                    catch (Exception ex)
                    {
                        ed.WriteMessage("\n{0}\n{1}", ex.Message, ex.StackTrace);
                    }
                }
            }
        }
 /// <summary>
 /// Gets a value indicating whether the specified point belongs to the collection.
 /// </summary>
 /// <param name="source">The instance to which the method applies.</param>
 /// <param name="pt">The point to search.</param>
 /// <returns>true if the point is found; otherwise, false.</returns>
 public static bool Contains(this Point3dCollection source, Point3d pt)
 {
     return(source.Contains(pt, Tolerance.Global));
 }
        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.");
                }
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Gets a value indicating whether the specified point belongs to the collection.
 /// </summary>
 /// <param name="pts">The instance to which the method applies.</param>
 /// <param name="pt">The point to search.</param>
 /// <returns>true if the point is found; otherwise, false.</returns>
 public static bool Contains([NotNull] this Point3dCollection pts, Point3d pt)
 {
     return(pts.Contains(pt, Tolerance.Global));
 }
Exemplo n.º 13
0
        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;
        }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 15
0
        public void AddPolylineVertex()
        {
            var db  = HostApplicationServices.WorkingDatabase;
            var ed  = db.GetEditor();
            var doc = db.GetDocument();

            try
            {
                var ent_res = ed.GetEntity("请选择一条多段线:\n");
                if (ent_res.Status != PromptStatus.OK)
                {
                    return;
                }

                var pt_res = ed.GetPoint("请选择一个点:\n");
                if (pt_res.Status != PromptStatus.OK)
                {
                    return;
                }

                var new_pt   = pt_res.Value;            // 新增的端点
                var pl_Index = 0;                       // 记录插入第几段
                var pts      = new Point3dCollection(); //多段线的顶点集合
                var ptAtpl   = Point3d.Origin;          // 选择点与多段线的最近点
                var width    = 0.0;
                using (doc.LockDocument())
                    using (var tr = db.TransactionManager.StartTransaction())
                    {
                        var ent = tr.GetObject(ent_res.ObjectId, OpenMode.ForWrite) as Entity;
                        var pl  = ent as Polyline;
                        if (pl != null)
                        {
                            if (pl.Closed)
                            {
                                PublicMethod.Instance.ShowMessage("面设备不能增加顶点。");
                                return;
                            }
                            ptAtpl = pl.GetClosestPointTo(new_pt, false);
                            width  = pl.GetStartWidthAt(0);
                            for (var index = 0; index < pl.NumberOfVertices; index++)
                            {
                                pts.Add(pl.GetPoint3dAt(index));
                            }
                        }
                        tr.Commit();
                    }

                if (pts.Count >= 2)
                {
                    var isPlPt = pts.Contains(ptAtpl); //如果是多段线顶点
                    if (isPlPt)
                    {
                        pl_Index = pts.IndexOf(ptAtpl);
                        ed.WriteMessageWithReturn(string.Format("最近点多段线顶点重合 {0}", pts.IndexOf(ptAtpl)));
                    }
                    else
                    {
                        for (int i = 0; i < pts.Count - 1; i++)
                        {
                            var line     = new Line(pts[i], pts[i + 1]);
                            var ptAtline = line.GetClosestPointTo(ptAtpl, false);
                            if (ptAtpl.IsEqualTo(ptAtline))
                            {
                                pl_Index = i;
                                ed.WriteMessageWithReturn(string.Format("最近点在第 {0} 段线上", i));
                            }
                            line.Dispose();
                        }
                    }

                    // 插入顶点
                    using (var tr = db.TransactionManager.StartTransaction())
                    {
                        var ent = tr.GetObject(ent_res.ObjectId, OpenMode.ForWrite) as Entity;
                        var pl  = ent as Polyline;
                        if (pl != null)
                        {
                            pl.AddVertexAt(pl_Index + 1, new Point2d(new_pt.X, new_pt.Y), 0, width, width);
                            // 设置线宽度
                        }
                        tr.Commit();
                    }
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessageWithReturn(ex);
            }
        }
Exemplo n.º 16
0
        private Point3dCollection GetViewportContourPoints(Viewport viewport, Transaction tr)
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;

            // Коллекция для точек видового экрана
            var points = new Point3dCollection();

            // Если видовой экран стандартный прямоугольный
            if (!viewport.NonRectClipOn)
            {
                // Получаем его точки
                viewport.GetGripPoints(points, new IntegerCollection(), new IntegerCollection());

                for (var i = points.Count - 1; i >= 0; i--)
                {
                    if (i >= 4)
                    {
                        points.RemoveAt(i);
                    }
                    else
                    {
                        break;
                    }
                }

                // Выстраиваем точки в правильном порядке, по умолчанию они крест-накрест
                var tmp = points[2];
                points[2] = points[1];
                points[1] = tmp;
            }

            // Если видовой экран подрезанный - получаем примитив, по которому он подрезан
            else
            {
                using (var ent = tr.GetObject(viewport.NonRectClipEntityId, OpenMode.ForRead) as Entity)
                {
                    // Если это полилиния - извлекаем ее точки
                    if (ent is Polyline polyline)
                    {
                        for (var i = 0; i < polyline.NumberOfVertices; i++)
                        {
                            points.Add(polyline.GetPoint3dAt(i));
                        }
                    }
                    else if (ent is Polyline2d polyline2d)
                    {
                        foreach (ObjectId vertexId in polyline2d)
                        {
                            using (var vertex2d = tr.GetObject(vertexId, OpenMode.ForRead) as Vertex2d)
                            {
                                if (!points.Contains(vertex2d.Position))
                                {
                                    points.Add(vertex2d.Position);
                                }
                            }
                        }
                    }
                    else if (ent is Curve curve)
                    {
                        double
                            startParam = curve.StartParam,
                            endParam   = curve.EndParam,
                            delParam   = (endParam - startParam) / 100;

                        for (var curParam = startParam; curParam < endParam; curParam += delParam)
                        {
                            var curPt = curve.GetPointAtParameter(curParam);
                            points.Add(curPt);
                            curParam += delParam;
                        }
                    }
                    else
                    {
                        MessageBox.Show(
                            $"{Language.GetItem(LangItem, "msg5")}\n{Language.GetItem(LangItem, "msg6")}{viewport.Number}, {Language.GetItem(LangItem, "msg7")}{ent}\n");
                    }
                }
            }

            return(points);
        }