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;
                            }
                        }
                    }
                }
            }
        }
Example #2
0
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            JigPromptPointOptions prPntOpts = new JigPromptPointOptions("\nPick Corner 2: ");

            prPntOpts.UseBasePoint = false;

            PromptPointResult prResult = prompts.AcquirePoint(prPntOpts);

            if (prResult.Status == PromptStatus.Cancel || prResult.Status == PromptStatus.Error)
            {
                return(SamplerStatus.Cancel);
            }

            Point3d pnt3dTmp = prResult.Value;

            pnt3dTmp = Db.wcsToUcs(pnt3dTmp);
            //.TransformBy(UCS.Inverse());
            //Point3d pnt3dTmp = prResult.Value;
            if (!pnt3dRes.IsEqualTo(pnt3dTmp, new Tolerance(1E-09, 1E-09)))
            {
                pnt3dRes = pnt3dTmp;
                return(SamplerStatus.OK);
            }
            else
            {
                return(SamplerStatus.NoChange);
            }
        }
Example #3
0
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            var pnt_input = prompts.AcquirePoint();

            if (PromptStatus.Cancel == pnt_input.Status)
            {
                return(SamplerStatus.Cancel);
            }

            DBText text = Entity as DBText;

            if (null == text)
            {
                return(SamplerStatus.NoChange);
            }

            Point3d pnt = pnt_input.Value;

            position = pnt;

            if (position.IsEqualTo(text.Position))
            {
                return(SamplerStatus.NoChange);
            }

            return(SamplerStatus.OK);
        }
Example #4
0
        void locateGripsAtInt(int x, int y, ref ExGripDataCollection aRes, ExGripDataCollection coll, Point3d ptFirst, Tolerance tol)
        {
            foreach (ExGripData exgrData in coll)
            {
                Point3d ptCurrent = exgrData.Point;
                if (aRes.Count == 0)
                {
                    // First grip is obtained by comparing
                    // grip point device position with cursor position.
                    using (Teigha.GraphicsSystem.View pView = m_pDevice.ActiveView)
                    {
                        Point3d ptDC = ptCurrent.TransformBy(pView.WorldToDeviceMatrix);

                        double dDeltaX = Math.Abs(x - ptDC.X);
                        double dDeltaY = Math.Abs(y - ptDC.Y);
                        bool   bOk     = (dDeltaX <= m_GRIPSIZE) && (dDeltaY <= m_GRIPSIZE);
                        if (bOk)
                        {
                            ptFirst = ptCurrent;
                            aRes.Add(exgrData);
                        }
                    }
                }
                else
                {
                    if (ptCurrent.IsEqualTo(ptFirst, tol))
                    {
                        aRes.Add(exgrData);
                    }
                }
            }
        }
Example #5
0
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            JigPromptPointOptions jppo = new JigPromptPointOptions("\nУкажите точку: ");

            jppo.UseBasePoint = true;
            jppo.BasePoint    = _position;

            _jigPoint = prompts.AcquirePoint(jppo).Value;
            if (_jigPoint.IsEqualTo(_jigBasePoint))
            {
                return(SamplerStatus.NoChange);
            }
            else
            {
                //Matrix3d mat = Matrix3d.Displacement(_jigBasePoint.GetVectorTo(_jigPoint));
                //Entity.TransformBy(mat);
                _transformProcessor(_jigPoint);

                _br.Position = _jigPoint;
                _br.RecordGraphicsModified(true);

                _jigBasePoint = _jigPoint;

                return(SamplerStatus.OK);
            }
        }
Example #6
0
        public static bool isSegmentsProjectionOverlapped(LineSegment3d lineseg1, LineSegment3d lineseg2)
        {
            Point3d projectPt1 = lineseg1.GetClosestPointTo(lineseg2.StartPoint).Point;
            Point3d projectPt2 = lineseg1.GetClosestPointTo(lineseg2.EndPoint).Point;

            // after the projection, the two line segments(p1->p2 & p3->p4) may be same
            if ((projectPt1.IsEqualTo(lineseg1.StartPoint) && projectPt2.IsEqualTo(lineseg1.EndPoint)) ||
                (projectPt1.IsEqualTo(lineseg1.EndPoint) && projectPt2.IsEqualTo(lineseg1.StartPoint)))
            {
                return(true);
            }

            // [Daniel] retrun null if no overlap???
            LineSegment3d  projectSeg2 = new LineSegment3d(projectPt1, projectPt2);
            LinearEntity3d overlap     = lineseg1.Overlap(projectSeg2);

            return(overlap != null);
        }
 /// <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>
 /// <param name="tol">The tolerance to use in comparisons.</param>
 /// <returns>true if the point is found; otherwise, false.</returns>
 public static bool Contains(this Point3dCollection pts, Point3d pt, Tolerance tol)
 {
     for (int i = 0; i < pts.Count; i++)
     {
         if (pt.IsEqualTo(pts[i], tol))
             return true;
     }
     return false;
 }
 /// <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>
 /// <param name="tol">The tolerance to use in comparisons.</param>
 /// <returns>true if the point is found; otherwise, false.</returns>
 public static bool Contains(this Point3dCollection pts, Point3d pt, Tolerance tol)
 {
     for (int i = 0; i < pts.Count; i++)
     {
         if (pt.IsEqualTo(pts[i], tol))
         {
             return(true);
         }
     }
     return(false);
 }
Example #9
0
        /// <summary>
        /// Попадает ли точка внутрь полилинии.
        /// Предполагается, что полилиния имеет замкнутый контур.
        /// Подходит для полилиний с дуговыми сегментами.
        /// Работает медленнее чем IsPointInsidePolygon(), примерно в 10 раз.
        /// </summary>
        /// <param name="pt"></param>
        /// <param name="onIsInside">Если исходная точка лежит на полилинии, то считать, что она внутри или нет: True - внутри, False - снаружи.</param>
        /// <param name="pl"></param>
        /// <exception cref="Exceptions.ErrorException">Не удалось определить за несколько попыток.</exception>
        public static bool IsPointInsidePolyline([NotNull] this Polyline pl, Point3d pt, bool onIsInside = false)
        {
            using (var ray = new Ray())
            {
                ray.BasePoint = pt;
                var vec = new Vector3d(0, 1, pt.Z);
                ray.SecondPoint = pt + vec;
                using (var ptsIntersects = new Point3dCollection())
                {
                    bool isContinue;
                    var  isPtOnPolyline = false;
                    var  countWhile     = 0;
                    do
                    {
                        using (var plane = new Plane())
                        {
                            pl.IntersectWith(ray, Intersect.OnBothOperands, plane, ptsIntersects, IntPtr.Zero, IntPtr.Zero);
                        }

                        isContinue = ptsIntersects.Cast <Point3d>().Any(p =>
                        {
                            if (pt.IsEqualTo(p))
                            {
                                isPtOnPolyline = true;
                                return(true);
                            }
                            var param = pl.GetParameterAtPointTry(p);
                            return(Math.Abs(param % 1) < 0.0001);
                        });

                        if (isPtOnPolyline)
                        {
                            return(onIsInside);
                        }

                        if (isContinue)
                        {
                            vec             = vec.RotateBy(0.01, Vector3d.ZAxis);
                            ray.SecondPoint = pt + vec;
                            ptsIntersects.Clear();
                            countWhile++;
                            if (countWhile > 3)
                            {
                                throw new ErrorException(new Errors.Error(
                                                             "Не определено попадает ли точка внутрь полилинии.",
                                                             pt.GetRectangleFromCenter(3), Matrix3d.Identity,
                                                             System.Drawing.SystemIcons.Error));
                            }
                        }
                    } while (isContinue);
                    return(NetLib.MathExt.IsOdd(ptsIntersects.Count));
                }
            }
        }
Example #10
0
        public int GetColumnNumber(Point3d point)
        {
            if (point.IsEqualTo(_insertPoint, Tolerance.Global))
            {
                return(0);
            }

            Vector3d vector = point - _insertPoint;
            double   xval   = HorizontalVector.GetCos2d(vector) * vector.Length;

            return((int)(xval / _horizontalStep));
        }
Example #11
0
        public int GetRowNumber(Point3d point)
        {
            if (point.IsEqualTo(_insertPoint, Tolerance.Global))
            {
                return(0);
            }

            Vector3d vector = point - _insertPoint;
            double   yval   = VerticalVector.GetCos2d(vector) * vector.Length;

            return((int)(yval / _verticalStep));
        }
 /// <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>
 /// <param name="tol">The tolerance to use in comparisons.</param>
 /// <returns>true if the point is found; otherwise, false.</returns>
 public static bool Contains(this Point3dCollection source, Point3d pt, Tolerance tol)
 {
     if (source == null)
     {
         throw new ArgumentNullException("source");
     }
     for (int i = 0; i < source.Count; i++)
     {
         if (pt.IsEqualTo(source[i], tol))
         {
             return(true);
         }
     }
     return(false);
 }
Example #13
0
 /// <summary>
 /// This func gets arc center point, arc radius and side point,
 /// measures if the side point is on the inside or outside of the arc
 /// and returns a value indicating where the SidePoint lies - outside or inside the arc perimeter.
 /// Circle is an Arc with start angle of 0 and end angle of 360, so you can use the same func for both.
 /// </summary>
 /// <param name="aArcCenterPt"></param>
 /// <param name="aArcRadius"></param>
 /// <param name="aSidePoint"></param>
 /// <returns>enum ArcSide</returns>
 public static ArcSide SideOfPointToArc(Point3d aArcCenterPt, double aArcRadius, Point3d aSidePoint)
 {
     if (!aSidePoint.IsEqualTo(new Point3d(0, 0, 0)))
     {
         var proportion = aArcCenterPt.DistanceTo(aSidePoint) / aArcRadius;
         if (proportion > 1)
         {
             return(ArcSide.ArcSideOutside);
         }
         else
         {
             return(ArcSide.ArcSideInside);
         }
     }
     else
     {
         return(ArcSide.ArcSideMiddle);
     }
 }
Example #14
0
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            JigPromptPointOptions jppo = new JigPromptPointOptions("\nУкажите точку: ");

            jppo.UseBasePoint = true;
            jppo.BasePoint    = _jigBasePoint;

            _jigPoint = prompts.AcquirePoint(jppo).Value;
            if (_jigPoint.IsEqualTo(_jigBasePoint))
            {
                return(SamplerStatus.NoChange);
            }
            else
            {
                Matrix3d mat = Matrix3d.Displacement(_jigBasePoint.GetVectorTo(_jigPoint));
                Entity.TransformBy(mat);

                _jigBasePoint = _jigPoint;

                return(SamplerStatus.OK);
            }
        }
Example #15
0
        /// <summary>
        /// point1과 point2가 tolerance 오차 내에서 같은지 반환합니다.
        /// </summary>
        /// <param name="point1">비교할 점1 입니다.</param>
        /// <param name="point2">비교할 점2 입니다.</param>
        /// <param name="tolerance">같다고 볼 오차범위 입니다.</param>
        /// <returns></returns>
        public static bool IsEqualPoint(Point3d point1, Point3d point2, double tolerance)
        {
            Tolerance oTol = new Tolerance(Tolerance.Global.EqualVector, tolerance);

            return(point1.IsEqualTo(point2, oTol));
        }
Example #16
0
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            if (_jppo == null)
            {
                _jppo = new JigPromptPointOptions("\nУкажите точку: ");
                _jppo.UseBasePoint       = true;
                _jppo.UserInputControls |= UserInputControls.Accept3dCoordinates;
                foreach (Keyword key in _keywords)
                {
                    _jppo.Keywords.Add(key.GlobalName, key.LocalName, key.DisplayName, key.Visible, key.Enabled);
                }
            }


            if (_jigPoint.IsEqualTo(_jigBasePoint))
            {
                _jppo.BasePoint = _baseCurve.StartPoint;
            }
            else
            {
                _jppo.BasePoint = _jigBasePoint;
            }

            _jppr = prompts.AcquirePoint(_jppo);
            if (_jppr.Status != PromptStatus.OK)
            {
                return(SamplerStatus.Cancel);
            }
            if (_jppr.Value.IsEqualTo(_jigPoint))
            {
                return(SamplerStatus.NoChange);
            }

            /*
             * if (_baseCurve is Polyline)
             * {
             *  Polyline pline = (Polyline)_baseCurve;
             *  Line line = pline.GetOrthoNormalLine(_jppr.Value);
             *  if (line != null)
             *  {
             *      _jigBasePoint = line.StartPoint;
             *      _jigPoint = line.EndPoint;
             *      return SamplerStatus.OK;
             *  }
             *  else
             *      return SamplerStatus.NoChange;
             * }
             * else if (_baseCurve is Arc)
             * {
             *  Arc arc = (Arc)_baseCurve;
             *  Line normal = arc.GetOrthoNormalLine(_jppr.Value, false);
             *  if (normal != null)
             *  {
             *      _jigBasePoint = normal.StartPoint;
             *      _jigPoint = normal.EndPoint;
             *      return SamplerStatus.OK;
             *  }
             *  else
             *      return SamplerStatus.NoChange;
             * }
             * else if (_baseCurve is Line)
             * {
             *  Line line = (Line)_baseCurve;
             *  Line normal = line.GetOrthoNormalLine(_jppr.Value, null, false);
             *  if (normal != null)
             *  {
             *      _jigBasePoint = normal.StartPoint;
             *      _jigPoint = normal.EndPoint;
             *      return SamplerStatus.OK;
             *  }
             *  else
             *      return SamplerStatus.NoChange;
             * }*/


            /*Polyline pline = _baseCurve.ConvertToPolyline();
             * Line line = pline.GetOrthoNormalLine(_jppr.Value);
             * if (line != null)
             * {
             *  _jigBasePoint = line.StartPoint;
             *  _jigPoint = line.EndPoint;
             *  return SamplerStatus.OK;
             * }
             * else
             *  return SamplerStatus.NoChange;*/

            return(SamplerStatus.OK);
        }
Example #17
0
        public void Avx()
        {
            int  ver          = AcAp.Version.Major;
            bool segHighlight = ver >= 18;
            bool loop         = true;

            PromptEntityOptions peo = new PromptEntityOptions(
                "\nSelet asegment where to add a vertex: ");

            peo.SetRejectMessage("\nPolyline only: ");
            peo.AllowNone = false;
            peo.AllowObjectOnLockedLayer = false;
            peo.AddAllowedClass(typeof(Polyline), false);
            while (loop)
            {
                PromptEntityResult per = ed.GetEntity(peo);
                if (per.Status != PromptStatus.OK)
                {
                    loop = false;
                    continue;
                }
                Matrix3d UCS   = ed.CurrentUserCoordinateSystem;
                ObjectId objId = per.ObjectId;
                try
                {
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        Polyline pline  = (Polyline)trans.GetObject(objId, OpenMode.ForRead, false);
                        Point3d  pickPt = pline.GetClosestPointTo(
                            per.PickedPoint.TransformBy(UCS),
                            ed.GetCurrentView().ViewDirection,
                            false);
                        double param = pline.GetParameterAtPoint(pickPt);
                        int    index = (int)param;

                        Matrix3d OCS     = Matrix3d.PlaneToWorld(pline.Normal);
                        Point3d  transPt = pickPt.TransformBy(OCS);

                        if (!OCS.CoordinateSystem3d.Zaxis.IsEqualTo(UCS.CoordinateSystem3d.Zaxis))
                        {
                            ed.CurrentUserCoordinateSystem = PlineUCS(pline, index);
                        }

                        var       aperture   = (Int16)AcAp.GetSystemVariable("APERTURE");
                        double    viewSize   = (double)AcAp.GetSystemVariable("VIEWSIZE");
                        Point2d   screenSize = (Point2d)AcAp.GetSystemVariable("SCREENSIZE");
                        double    tol        = 2 * aperture * viewSize / screenSize.Y;
                        Tolerance tolerance  = new Tolerance(tol, tol);

                        int endParam = pline.Closed ?
                                       pline.NumberOfVertices :
                                       pline.NumberOfVertices - 1;
                        Vector3d vec;
                        using (Polyline ghost = new Polyline())
                        {
                            ghost.ColorIndex = 1;

                            if (!pline.Closed && pickPt.IsEqualTo(pline.GetPoint3dAt(0), tolerance))
                            {
                                vec = pline.GetFirstDerivative(0);
                                double  bulge = pline.GetBulgeAt(0);
                                double  width = pline.GetStartWidthAt(0);
                                Point2d p0    = transPt.GetPoint2d();
                                Point2d p1    = pline.GetPoint2dAt(0);

                                ghost.AddVertexAt(0, p0, bulge, width, width);
                                ghost.AddVertexAt(1, p1, bulge, width, width);
                                ghost.Normal    = pline.Normal;
                                ghost.Elevation = pline.Elevation;
                                VertexJig jig = new VertexJig(ghost, pickPt, 0, vec, bulge,
                                                              width, width);
                                PromptResult res = ed.Drag(jig);
                                if (res.Status == PromptStatus.OK)
                                {
                                    pline.UpgradeOpen();
                                    pline.AddVertexAt(index, ghost.GetPoint2dAt(0),
                                                      ghost.GetBulgeAt(0), width, width);
                                }
                            }
                            else if (!pline.Closed && pickPt.IsEqualTo(pline.GetPoint3dAt(endParam),
                                                                       tolerance))
                            {
                                vec = pline.GetFirstDerivative(endParam);
                                double  bulge = pline.GetBulgeAt(index);
                                double  width = pline.GetEndWidthAt(endParam);
                                Point2d p0    = pline.GetPoint2dAt(endParam);
                                Point2d p1    = new Point2d(transPt.X, transPt.Y);

                                ghost.AddVertexAt(0, p0, bulge, width, width);
                                ghost.AddVertexAt(1, p1, bulge, width, width);
                                ghost.Normal    = pline.Normal;
                                ghost.Elevation = pline.Elevation;
                                VertexJig jig = new VertexJig(ghost, pickPt, 1, vec,
                                                              bulge, width, width);

                                PromptResult res = ed.Drag(jig);
                                if (res.Status == PromptStatus.OK)
                                {
                                    pline.UpgradeOpen();
                                    pline.AddVertexAt(endParam + 1, ghost.GetPoint2dAt(1),
                                                      ghost.GetBulgeAt(0), width, width);
                                    pline.SetBulgeAt(endParam, ghost.GetBulgeAt(0));
                                }
                            }
                            else
                            {
                                vec = pline.GetFirstDerivative(index);
                                double  bulge  = pline.GetBulgeAt(index);
                                double  sWidth = pline.GetStartWidthAt(index);
                                double  eWidth = pline.GetEndWidthAt(index);
                                Point2d p0     = pline.GetPoint2dAt(index);
                                Point2d p1     = transPt.GetPoint2d();
                                Point2d p2;
                                if (!pline.Closed)
                                {
                                    p2 = pline.GetPoint2dAt(index + 1);
                                }
                                else
                                {
                                    try { p2 = pline.GetPoint2dAt(index + 1); }
                                    catch { p2 = pline.GetPoint2dAt(0); }
                                }

                                FullSubentityPath subId = new FullSubentityPath(
                                    new ObjectId[] { pline.ObjectId },
                                    new SubentityId(SubentityType.Edge,
                                                    new IntPtr((long)index + 1)));
                                pline.Highlight(subId, false);
                                ghost.AddVertexAt(0, p0, bulge, sWidth, 0.0);
                                ghost.AddVertexAt(1, p1, bulge, 0, eWidth);
                                ghost.AddVertexAt(2, p2, 0.0, 0.0, 0.0);
                                ghost.Normal    = pline.Normal;
                                ghost.Elevation = pline.Elevation;
                                VertexJig jig = new VertexJig(ghost, pickPt, 1, vec,
                                                              bulge, sWidth, eWidth);
                                PromptResult res = ed.Drag(jig);
                                if (res.Status == PromptStatus.OK)
                                {
                                    pline.UpgradeOpen();
                                    pline.SetStartWidthAt(index, ghost.GetStartWidthAt(1));
                                    pline.AddVertexAt(
                                        index + 1,
                                        ghost.GetPoint2dAt(1),
                                        ghost.GetBulgeAt(1),
                                        ghost.GetStartWidthAt(1),
                                        eWidth);
                                    pline.SetBulgeAt(index, ghost.GetBulgeAt(0));
                                }
                                pline.Unhighlight(subId, false);
                            }
                        }
                        trans.Commit();
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("\nError: " + ex.Message + ex.StackTrace);
                }
                finally
                {
                    ed.CurrentUserCoordinateSystem = UCS;
                }
            }
        }
        ///////////the below has proven obsolete
        //////public static BlockReference GetBlockReference(ObjectId BRid)
        //////{
        //////    Document doc = Application.DocumentManager.MdiActiveDocument;
        //////    Editor ed = doc.Editor;
        //////    Database db = doc.Database;
        //////    BlockReference br;
        //////    // check the current value of the br and see if it is null - it should not be
        //////    using (Transaction tr = doc.TransactionManager.StartTransaction())
        //////    {
        //////        br = BRid.GetObject(OpenMode.ForRead) as BlockReference;
        //////        if (br != null)
        //////        {
        //////            return br;
        //////        }
        //////        // throws an exception if the point does not have any value
        //////        else
        //////        {
        //////            throw new Autodesk.AutoCAD.Runtime.Exception(ErrorStatus.NullObjectId, "The block reference returned is null - probably because the objectID you passed into the GetBlockReference method was not a blockReference.");
        //////        }
        //////    }
        //////    return br;
        //////}
        public static Point3d GetInsertionPointOfBlockReference(ObjectId BRid)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            Point3d insertionPoint = new Point3d();

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                BlockReference br = BRid.GetObject(OpenMode.ForRead) as BlockReference;

                if (br != null)
                {
                    insertionPoint = br.Position;
                }
            }

            // throws an exception if the point does not have any value
            if (insertionPoint.IsEqualTo(new Point3d()))
            {
                throw new Autodesk.AutoCAD.Runtime.Exception(ErrorStatus.InvalidDxf3dPoint, "The block reference does not have an insertion point. Probably the objectID you passed into the GetInsertionPointOfBlockReference method is not in fact a blockReference id.");
            }

            return insertionPoint;
        }
Example #19
0
        public static bool IsPointOnPolyline([NotNull] this Polyline pl, Point3d pt, Tolerance tolerance)
        {
            var ptPl = pl.GetClosestPointTo(pt, Vector3d.ZAxis, false);

            return(pt.IsEqualTo(ptPl, tolerance));
        }
Example #20
0
        public void makeCylinder()
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            string  getPointMessage = "Pick the center point: ";
            Point3d ptCenter        = getPointWith(getPointMessage, ed);

            if (ptCenter.IsEqualTo(new Point3d(-1, -1, -1)))
            {
                return;
            }

            // Get the radius of the cylinder.
            string radiusMessage = "Pick the radius of cylinder: ";
            int    radius        = getValueWith(radiusMessage, ed);

            if (radius == -1)
            {
                return;
            }

            // Get the height of the cylinder.
            string heightMessage = "Pick the height of the cylinder: ";
            int    height        = getValueWith(heightMessage, ed);

            if (height == -1)
            {
                return;
            }

            Database dwg = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;

            using (Transaction trans = dwg.TransactionManager.StartTransaction())
            {
                try
                {
                    BlockTable blk = trans.GetObject(dwg.BlockTableId, OpenMode.ForWrite) as BlockTable;
                    if (blk == null)
                    {
                        return;
                    }

                    Circle circle = new Circle(ptCenter, Vector3d.ZAxis, radius);

                    // make region.
                    DBObjectCollection dbObjCollec = new DBObjectCollection();
                    dbObjCollec.Add(circle);

                    DBObjectCollection regionObjCollec = Region.CreateFromCurves(dbObjCollec);

                    Solid3d solid3d = new Solid3d();
                    solid3d.Extrude((Region)regionObjCollec[0], height, 0.0);

                    // append elements into database.
                    BlockTableRecord blkRecord = trans.GetObject(blk[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    blkRecord.AppendEntity(solid3d);

                    trans.AddNewlyCreatedDBObject(solid3d, true);

                    trans.Commit();
                }
                catch (System.Exception)
                {
                    trans.Abort();
                    throw;
                }
            }
        }
Example #21
0
        private DBObjectCollection BuildWeldingArcsOverPts(Point3dCollection aWeldingLinePts, Point3d aSidePt, double aArcsLenght, double aArcsDistance, double aArcsOffset)
        {
            // We should think that Point[i] and Point[i + 1] form a line
            double  lenght, ang1, ang2, ang3, pAng3, c, d, radius, distP1Px = 0.0;
            Point3d px, pc, p1, p2, p3, p4 = new Point3d(0, 0, 0);

            p3 = aSidePt;

            var size   = aArcsLenght;
            var space  = aArcsDistance;
            var offset = aArcsOffset;

            var weldingArcs = new DBObjectCollection();

            for (var i = 0; i < aWeldingLinePts.Count - 1; i++)
            {
                p1     = aWeldingLinePts[i];
                p2     = aWeldingLinePts[i + 1];
                lenght = p1.DistanceTo(p2);

                if (aSidePt.IsEqualTo(new Point3d(0, 0, 0))) // Draw in the middle of the line
                {
                    ang1 = GeometryUtility.GetAngleFromXAxis(p1, p2);
                    ang2 = ang1 - GeometryUtility.DoubleToRadians(90);
                    ang3 = ang1 + GeometryUtility.DoubleToRadians(90);

                    d        = aArcsOffset;
                    px       = GeometryUtility.GetPlanePolarPoint(p1, ang1, d);
                    radius   = size * 0.625;
                    c        = size * 0.375;
                    distP1Px = p1.DistanceTo(px);

                    while (distP1Px < lenght)
                    {
                        pc = GeometryUtility.GetPlanePolarPoint(px, ang1, c);
                        p2 = GeometryUtility.GetPlanePolarPoint(pc, ang2, size / 2);
                        p4 = GeometryUtility.GetPlanePolarPoint(pc, ang3, size / 2);
                        var arc = new Arc(pc,
                                          radius,
                                          GeometryUtility.GetAngleFromXAxis(pc, p4),
                                          GeometryUtility.GetAngleFromXAxis(pc, p2));
                        // BricsCAD hack
                        arc.Center = pc;
                        weldingArcs.Add(arc);
                        d        = d + space;
                        px       = GeometryUtility.GetPlanePolarPoint(p1, ang1, d);
                        distP1Px = p1.DistanceTo(px);
                    }
                }
                else // Side point selected
                {
                    ang1 = GeometryUtility.GetAngleFromXAxis(p1, p2);
                    ang2 = GeometryUtility.GetAngleFromXAxis(p1, p3);

                    var tempLine  = new Line(p1, p2);
                    var direction = GeometryUtility.OffsetDirection(tempLine, p3);
                    if (direction == 1)
                    {
                        ang3 = ang1 - GeometryUtility.DoubleToRadians(90.0);
                    }
                    else
                    {
                        ang3 = ang1 + GeometryUtility.DoubleToRadians(90.0);
                    }
                    d        = offset;
                    px       = GeometryUtility.GetPlanePolarPoint(p1, ang1, d);
                    radius   = size * 0.625;
                    c        = size * 0.375;
                    distP1Px = p1.DistanceTo(px);
                    while (distP1Px < lenght)
                    {
                        pAng3 = ang3 + GeometryUtility.DoubleToRadians(90);
                        p3    = GeometryUtility.GetPlanePolarPoint(px, ang3, size);
                        p2    = GeometryUtility.GetPlanePolarPoint(px, ang3, size / 2);
                        pc    = GeometryUtility.GetPlanePolarPoint(p2, pAng3, c);
                        var arc = new Arc(pc,
                                          radius,
                                          GeometryUtility.GetAngleFromXAxis(pc, px),
                                          GeometryUtility.GetAngleFromXAxis(pc, p3));
                        // BricsCAD hack
                        arc.Center = pc;

                        weldingArcs.Add(arc);
                        d        = d + space;
                        px       = GeometryUtility.GetPlanePolarPoint(p1, ang1, d);
                        distP1Px = p1.DistanceTo(px);
                    }
                }
            }
            return(weldingArcs);
        }
Example #22
0
        /// <summary>
        /// Returns the contour polylines at the given elevation.
        /// </summary>
        /// <param name="surface">The type of surface being operated on</param>
        /// <param name="z">Elevation</param>
        public IEnumerable <Polyline> ContourAt(SurfaceType surface, double z)
        {
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

            Point3d  planePoint  = new Point3d(0, 0, z);
            Vector3d planeNormal = Vector3d.ZAxis;

            // List of segments
            Queue <Tuple <Point3d, Point3d> > segments = new Queue <Tuple <Point3d, Point3d> >();

            foreach (TriangleNet.Data.Triangle tri in ((surface == SurfaceType.Original) ? originalSurface : proposedSurface).Triangles)
            {
                TriangleNet.Data.Vertex v1 = tri.GetVertex(0);
                TriangleNet.Data.Vertex v2 = tri.GetVertex(1);
                TriangleNet.Data.Vertex v3 = tri.GetVertex(2);
                Point3d p1 = new Point3d(v1.X, v1.Y, v1.Attributes[0]);
                Point3d p2 = new Point3d(v2.X, v2.Y, v2.Attributes[0]);
                Point3d p3 = new Point3d(v3.X, v3.Y, v3.Attributes[0]);

                if (PlaneTriangleIntersection(planePoint, planeNormal, p1, p2, p3, out Point3d ptOut1, out Point3d ptOut2))
                {
                    segments.Enqueue(new Tuple <Point3d, Point3d>(ptOut1, ptOut2));
                }
            }

            // Create curves from segments
            double          epsilon  = 0.000001;
            Tolerance       tol      = new Tolerance(epsilon, epsilon);
            List <Polyline> contours = new List <Polyline>();

            while (segments.Count > 0)
            {
                LinkedList <Point3d>     curvePoints  = new LinkedList <Point3d>();
                Tuple <Point3d, Point3d> firstSegment = segments.Dequeue();
                curvePoints.AddFirst(firstSegment.Item1);
                curvePoints.AddLast(firstSegment.Item2);
                bool added = false;
                do
                {
                    int n = segments.Count;
                    added = false;
                    for (int i = 0; i < n; i++)
                    {
                        Tuple <Point3d, Point3d> segment = segments.Dequeue();
                        Point3d p1         = segment.Item1;
                        Point3d p2         = segment.Item2;
                        Point3d startPoint = curvePoints.First.Value;
                        Point3d endPoint   = curvePoints.Last.Value;
                        if (startPoint.IsEqualTo(p1, tol))
                        {
                            curvePoints.AddFirst(p2);
                            added = true;
                        }
                        else if (startPoint.IsEqualTo(p2, tol))
                        {
                            curvePoints.AddFirst(p1);
                            added = true;
                        }
                        else if (endPoint.IsEqualTo(p1, tol))
                        {
                            curvePoints.AddLast(p2);
                            added = true;
                        }
                        else if (endPoint.IsEqualTo(p2, tol))
                        {
                            curvePoints.AddLast(p1);
                            added = true;
                        }
                        else
                        {
                            segments.Enqueue(segment);
                        }
                    }
                } while (added);
                Polyline pline = AcadEntity.CreatePolyLine(db, curvePoints.First().IsEqualTo(curvePoints.Last(), tol), curvePoints.ToArray());
                pline.ColorIndex = 31;
                pline.Elevation  = z;
                contours.Add(pline);
            }

            return(contours);
        }
Example #23
0
        void updateInvisibleGrips()
        {
            ExGripDataCollection aOverall = new ExGripDataCollection();

            foreach (KeyValuePair <ObjectId, ExGripDataExt> grDataDc in m_gripDataDict)
            {
                foreach (ExGripData grData in grDataDc.Value.DataArray)
                {
                    aOverall.Add(grData);
                }
                foreach (ExGripDataSubent grDataSub in grDataDc.Value.DataSub)
                {
                    foreach (ExGripData grData in grDataSub.SubData)
                    {
                        aOverall.Add(grData);
                    }
                }
            }

            int iSize = aOverall.Count;

            for (int i = 0; i < iSize; i++)
            {
                ExGripData grData = aOverall[i];
                grData.Invisible = false;
                grData.Shared    = false;

                IntegerCollection aEq = new IntegerCollection();
                aEq.Add(i);

                Point3d ptIni = grData.Point;

                int       iNext = i + 1;
                Tolerance tc    = new Tolerance(1E-6, 1E-6);
                while (iNext < iSize)
                {
                    Point3d ptCur = aOverall[iNext].Point;
                    if (ptIni.IsEqualTo(ptCur, tc))
                    {
                        aEq.Add(iNext);
                        iNext++;
                    }
                    else
                    {
                        break;
                    }
                }

                if (aEq.Count >= 2)
                {
                    int iVisible = 0;
                    int jSize    = aEq.Count;
                    for (int j = 0; j < iSize; j++)
                    {
                        ExGripData pGrip = aOverall[aEq[j]];

                        bool bOk = true;
                        if (pGrip.Data != null)
                        {
                            if (pGrip.Data.SkipWhenShared)
                            {
                                bOk = false;
                            }
                        }

                        if (bOk)
                        {
                            iVisible = j;
                            break;
                        }
                    }

                    for (int j = 0; j < iSize; j++)
                    {
                        ExGripData pGrip = aOverall[aEq[j]];
                        pGrip.Shared    = true;
                        pGrip.Invisible = (j != iVisible);
                    }
                }
            }
        }
Example #24
0
        public static Point3d?GetOrthoNormalPoint(this Polyline pline, Point3d point, Plane plane, bool nullForOutOfRange = true)
        {
            point = point.OrthoProject(pline.GetPlane());

            List <Point3d> res      = new List <Point3d>();
            var            segments = pline.GetSegments();
            int            i        = 0;

            foreach (var s in segments)
            {
                if (point.IsEqualTo(s.StartPoint, Tolerance.Global))
                {
                    return(point);
                }

                Vector3d vector     = point - s.StartPoint;
                Vector3d segmVector = s.EndPoint - s.StartPoint;
                double   cos        = segmVector.GetCos2d(vector);

                double length = s.GetLength(s.GetParameterOf(s.StartPoint),
                                            s.GetParameterOf(s.EndPoint), Tolerance.Global.EqualPoint);

                ///////////////////////////////////////////////
                if (!nullForOutOfRange)
                {
                    if (i == 0 && cos < 0d)
                    {
                        return(s.StartPoint);
                    }
                    if (i == segments.Count() - 1 && cos > 0 && cos * vector.Length > segmVector.Length)
                    {
                        return(s.EndPoint);
                    }
                    i++;
                }
                ///////////////////////////////////////////////

                if (cos >= 0d && cos * vector.Length <= segmVector.Length)
                {
                    if (s is CircularArc3d)
                    {
                        CircularArc3d arc3d       = (CircularArc3d)s;
                        Arc           arc         = arc3d.ConvertToArc();
                        Point3d?      normalPoint = arc.GetOrthoNormalPoint(point, nullForOutOfRange);
                        if (normalPoint.HasValue)
                        {
                            res.Add(normalPoint.Value);
                        }
                    }
                    else if (s is LineSegment3d)
                    {
                        LineSegment3d line3d      = (LineSegment3d)s;
                        Line          line        = line3d.ConvertToLine();
                        Point3d?      normalPoint = line.GetOrthoNormalPoint(point, plane, nullForOutOfRange);
                        if (normalPoint.HasValue)
                        {
                            res.Add(normalPoint.Value);
                        }
                    }
                }
            }
            if (res.Count == 0)
            {
                return(null);
            }
            else
            {
                res.Sort((p1, p2) => Comparer <double> .Default.Compare((point - p1).Length, (point - p2).Length));
                return(res[0]);
            }
        }
Example #25
0
        /// <summary>
        /// Breaks the polyline at specified point.
        /// </summary>
        /// <param name="pline">The polyline this method applies to.</param>
        /// <param name="brkPt">The point where to break the polyline.</param>
        /// <returns>An array of the two resullting polylines.</returns>
        public static Polyline[] BreakAtPoint(this Polyline pline, Point3d brkPt)
        {
            brkPt = pline.GetClosestPointTo(brkPt, false);

            // le point spécifié est sur le point de départ de la polyligne
            if (brkPt.IsEqualTo(pline.StartPoint))
                return new Polyline[2] { null, (Polyline)pline.Clone() };

            // le point spécifié est sur le point de fin de la polyligne
            if (brkPt.IsEqualTo(pline.EndPoint))
                return new Polyline[2] { (Polyline)pline.Clone(), null };

            double param = pline.GetParameterAtPoint(brkPt);
            int index = (int)param;
            int num = pline.NumberOfVertices;
            Polyline pl1 = (Polyline)pline.Clone();
            if (pline.Closed)
            {
                pl1.AddVertexAt(
                    pline.NumberOfVertices,
                    pline.GetPoint2dAt(0),
                    pline.GetStartWidthAt(num - 1),
                    pline.GetEndWidthAt(num - 1),
                    pline.GetBulgeAt(num - 1));
                pl1.Closed = false;
            }
            Polyline pl2 = (Polyline)pl1.Clone();

            // le point spécifié est sur un sommet de la polyligne
            if (Math.Round(param, 6) == index)
            {
                for (int i = pl1.NumberOfVertices - 1; i > index; i--)
                {
                    pl1.RemoveVertexAt(i);
                }
                for (int i = 0; i < index; i++)
                {
                    pl2.RemoveVertexAt(0);
                }
                return new Polyline[2] { pl1, pl2 };
            }

            // le point spécifié est sur un segment
            Point2d pt = brkPt.Convert2d(new Plane(Point3d.Origin, pline.Normal));
            for (int i = pl1.NumberOfVertices - 1; i > index + 1; i--)
            {
                pl1.RemoveVertexAt(i);
            }
            pl1.SetPointAt(index + 1, pt);
            for (int i = 0; i < index; i++)
            {
                pl2.RemoveVertexAt(0);
            }
            pl2.SetPointAt(0, pt);
            if (pline.GetBulgeAt(index) != 0.0)
            {
                double bulge = pline.GetBulgeAt(index);
                pl1.SetBulgeAt(index, MultiplyBulge(bulge, param - index));
                pl2.SetBulgeAt(0, MultiplyBulge(bulge, index + 1 - param));
            }
            return new Polyline[2] { pl1, pl2 };
        }
Example #26
0
        public static void ZoomExtents(Point3d P1, Point3d P2, double dFactor)
        {
            #region 포인트 지정 [P1, P2, P3]
            //var P1 = new Point3d();
            //var P2 = new Point3d();
            var P3 = GetCenterPoint3d(P1, P2);

            int nCurVport = System.Convert.ToInt32(Application.GetSystemVariable("CVPORT"));

            /// 포인트가 없을 경우 따로 포인트 범위를 지정해줘야한다.
            if (DB.TileMode == true)
            {
                if (P1.IsEqualTo(new Point3d()) && P2.IsEqualTo(new Point3d()))
                {
                    P1 = DB.Extmin; // Extents Space
                    P2 = DB.Extmax;
                }
            }
            else
            {
                if (nCurVport == 1)
                {
                    if (P1.IsEqualTo(new Point3d()) && P2.IsEqualTo(new Point3d()))
                    {
                        P1 = DB.Pextmin;    // Paper Space
                        P2 = DB.Pextmax;
                    }
                }
                else
                {
                    if (P1.IsEqualTo(new Point3d()) && P2.IsEqualTo(new Point3d()))
                    {
                        P1 = DB.Extmin;
                        P2 = DB.Extmax;
                    }
                }
            }
            #endregion

            using (Transaction T = DB.TransactionManager.StartTransaction())
            {
                using (ViewTableRecord VTR = Doc.Editor.GetCurrentView())
                {
                    Extents3d extents;

                    // Translate WCS coordinates to DCS
                    Matrix3d matrix;
                    matrix = Matrix3d.PlaneToWorld(VTR.ViewDirection);
                    matrix = Matrix3d.Displacement(VTR.Target - Point3d.Origin) * matrix;
                    matrix = Matrix3d.Rotation(-VTR.ViewTwist, VTR.ViewDirection, VTR.Target) * matrix;

                    if (P3.IsEqualTo(Point3d.Origin))
                    {
                        P1 = new Point3d(P3.X - (VTR.Width / 2), P3.Y - (VTR.Height / 2), 0);
                        P2 = new Point3d((VTR.Width) / 2 * P3.X, (VTR.Height / 2) + P3.Y, 0);
                    }

                    using (var L = new Line(P1, P2))
                    {
                        extents = new Extents3d(L.Bounds.Value.MinPoint, L.Bounds.Value.MaxPoint);
                    }

                    double V_Ratio = VTR.Width / VTR.Height;

                    matrix = matrix.Inverse();
                    extents.TransformBy(matrix);

                    double  W;
                    double  H;
                    Point2d NewCenP;

                    if (!P3.IsEqualTo(Point3d.Origin))
                    {
                        W = VTR.Width;
                        H = VTR.Height;

                        if (dFactor == 0)
                        {
                            P3 = P3.TransformBy(matrix);
                        }

                        NewCenP = new Point2d(P3.X, P3.Y);
                    }
                    else
                    {
                        W = extents.MaxPoint.X - extents.MinPoint.X;
                        H = extents.MaxPoint.Y - extents.MinPoint.Y;

                        NewCenP = new Point2d((extents.MaxPoint.X + extents.MinPoint.X) * 0.5, (extents.MaxPoint.Y + extents.MinPoint.Y) * 0.5);
                    }

                    if (W > (H * V_Ratio))
                    {
                        H = H / V_Ratio;
                    }
                    if (dFactor != 0)
                    {
                        VTR.Height = H * dFactor;
                        VTR.Width  = W * dFactor;
                    }

                    VTR.CenterPoint = NewCenP;

                    ED.SetCurrentView(VTR);
                }

                T.Commit();
            }
        }
Example #27
0
 public static bool IsSame(Point3d P1, Point3d P2, double d1 = 1, double d2 = 1)
 {
     return(P1.IsEqualTo(P2, new Tolerance(d1, d2)));
 }
Example #28
0
 /// <summary>
 /// Поиск узла по координатам точки
 /// </summary>
 /// <param name="point">Точка, в которой должен находится узел</param>
 /// <returns>Узел, удовлетворяющий условию поиска, либо null, если не найден</returns>
 Node FindNode(Point3d point)
 {
     return Nodes.FirstOrDefault(n => point.IsEqualTo(n.Point));
 }
Example #29
0
        public static Polyline[] BreakAtPoint([NotNull] this Polyline pline, Point3d brkPt)
        {
            brkPt = pline.GetClosestPointTo(brkPt, false);

            // le point spécifié est sur le point de départ de la polyligne
            if (brkPt.IsEqualTo(pline.StartPoint))
            {
                return new[] { null, (Polyline)pline.Clone() }
            }
            ;

            // le point spécifié est sur le point de fin de la polyligne
            if (brkPt.IsEqualTo(pline.EndPoint))
            {
                return new[] { (Polyline)pline.Clone(), null }
            }
            ;

            var param = pline.GetParameterAtPoint(brkPt);
            var index = (int)param;
            var num   = pline.NumberOfVertices;
            var pl1   = (Polyline)pline.Clone();

            if (pline.Closed)
            {
                pl1.AddVertexAt(
                    pline.NumberOfVertices,
                    pline.GetPoint2dAt(0),
                    pline.GetStartWidthAt(num - 1),
                    pline.GetEndWidthAt(num - 1),
                    pline.GetBulgeAt(num - 1));

                pl1.Closed = false;
            }

            var pl2 = (Polyline)pl1.Clone();

            // le point spécifié est sur un sommet de la polyligne
            if (Math.Abs(NetLib.DoubleExt.Round(param, 6) - index) < 0.0001)
            {
                for (var i = pl1.NumberOfVertices - 1; i > index; i--)
                {
                    pl1.RemoveVertexAt(i);
                }

                for (var i = 0; i < index; i++)
                {
                    pl2.RemoveVertexAt(0);
                }

                return(new[] { pl1, pl2 });
            }

            // le point spécifié est sur un segment
            var pt = brkPt.Convert2d(new Plane(Point3d.Origin, pline.Normal));

            for (var i = pl1.NumberOfVertices - 1; i > index + 1; i--)
            {
                pl1.RemoveVertexAt(i);
            }

            pl1.SetPointAt(index + 1, pt);
            for (var i = 0; i < index; i++)
            {
                pl2.RemoveVertexAt(0);
            }

            pl2.SetPointAt(0, pt);
            if (Math.Abs(pline.GetBulgeAt(index)) > 0.0001)
            {
                var bulge = pline.GetBulgeAt(index);
                pl1.SetBulgeAt(index, MultiplyBulge(bulge, param - index));
                pl2.SetBulgeAt(0, MultiplyBulge(bulge, index + 1 - param));
            }

            return(new[] { pl1, pl2 });
        }