Author Topic: .NET GEOMETRY Routines  (Read 12760 times)

0 Members and 1 Guest are viewing this topic.

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #15 on: April 19, 2011, 01:16:01 pm »
Thanks, Oleg. You're very welcome.
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #16 on: April 25, 2011, 01:55:10 pm »
A new C# implementation of the ConvexHull using Ling (.NET Framework 3 or upper)

Code: [Select]
using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using AcAp = Autodesk.AutoCAD.ApplicationServices.Application;

namespace LinqConvexHull
{
    public class Commands
    {
        private Point2d _p0;

        private bool Clockwise(Point2d p1, Point2d p2, Point2d p3)
        {
            return ((p2.X - p1.X) * (p3.Y - p1.Y) - (p2.Y - p1.Y) * (p3.X - p1.X)) < 1e-9;
        }

        private double Cosine(Point2d pt)
        {
            double d = _p0.GetDistanceTo(pt);
            return d == 0.0 ? 1.0 : Math.Round((pt.X - _p0.X) / d, 9);
        }

        private List<Point2d> ConvexHull(List<Point2d> pts)
        {
            _p0 = pts.OrderBy(p => p.Y).ThenBy(p => p.X).First();
            pts = pts.OrderByDescending(p => Cosine(p)).ThenBy(p => _p0.GetDistanceTo(p)).ToList();
            for (int i = 1; i < pts.Count - 1; i++)
            {
                while (i > 0 && Clockwise(pts[i - 1], pts[i], pts[i + 1]))
                {
                    pts.RemoveAt(i);
                    i--;
                }
            }
            return pts;
        }

        [CommandMethod("Test")]
        public void Test()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            TypedValue[] filter = new TypedValue[1] { new TypedValue(0, "POINT") };
            PromptSelectionResult psr = ed.GetSelection(new SelectionFilter(filter));
            if (psr.Status != PromptStatus.OK) return;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            using (Polyline pline = new Polyline())
            {
                List<Point2d> pts = new List<Point2d>();
                foreach (SelectedObject so in psr.Value)
                {
                    DBPoint dbPt = (DBPoint)tr.GetObject(so.ObjectId, OpenMode.ForRead);
                    pts.Add(new Point2d(dbPt.Position.X, dbPt.Position.Y));
                }
                pts = ConvexHull(pts);
                for (int i = 0; i < pts.Count; i++)
                {
                    pline.AddVertexAt(i, pts[i], 0.0, 0.0, 0.0);
                }
                pline.Closed = true;
                pline.SetDatabaseDefaults();
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(pline);
                tr.AddNewlyCreatedDBObject(pline, true);
                tr.Commit();
            }
        }
    }
}
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #17 on: July 10, 2011, 10:41:46 am »
Hi,

I made a minor update in GeometryExtensions and I added comments to create a documentation file using Sandcastle Help File Builder.

The GeomExtDoc.chm is downloadable from the reply #2.

Speaking English as a French Frog

qjchen

  • Bull Frog
  • Posts: 274
  • Best wishes to all
Re: .NET GEOMETRY Routines
« Reply #18 on: July 13, 2011, 09:41:50 am »
Gile, Thank you your great library, I will learn a lot from it~

And this code about convex hull which using Linq is so concise, very cool~
« Last Edit: July 13, 2011, 10:11:29 am by qjchen »
http://qjchen.mjtd.com
My blog http://chenqj.blogspot.com (Chinese, can be translate into English)

kaefer

  • Swamp Rat
  • Posts: 562
Re: .NET GEOMETRY Routines
« Reply #19 on: July 13, 2011, 10:39:07 am »
Gile, Thank you your great library, I will learn a lot from it~

I can only second that. Merci beaucoup!

Alas, there was a minor snag in appropriating your intellectual property: The paper space transformations are extension methods to Editor, whereas I needed them for Viewport to replicate the CHSPACE command. Any chance to make them more generic?

Code: [Select]
type Viewport with
    member vp.DCS2PSDCS =
        Matrix3d.Scaling(vp.CustomScale, vp.CenterPoint) *
        Matrix3d.Displacement(vp.CenterPoint - Point3d.Origin) *
        Matrix3d.Displacement(Point3d.Origin - vp.ViewCenter.To3d)
    member vp.PSDCS2DCS = vp.DCS2PSDCS.Inverse()

    member vp.DCS2WCS =
        Matrix3d.Rotation(-vp.TwistAngle, vp.ViewDirection, vp.ViewTarget) *
        Matrix3d.Displacement(vp.ViewTarget - Point3d.Origin) *
        Matrix3d.PlaneToWorld vp.ViewDirection
    member vp.WCS2DCS = vp.DCS2WCS.Inverse()

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #20 on: July 13, 2011, 01:39:14 pm »
Thank you both.

Quote
there was a minor snag in appropriating your intellectual property
I do not really care about "intellectual property" with the code I post on TheSwamp or elsewhere. I learn a lot from you and others and most of the code I write is "hacked" from what I read.
If I can bring my "two cents" sometimes, it makes me happy when other find it usefull.

Anyway, you're right, the Viewport extensions methods may be useful as the actual methods only work with the current (or last activated) one (I wanted to mimic the AutoLISP trans function with the Point3d.Trans() method).

If you don't mind it's an "appropriation of your intellectual proprety" ;-) , I'd add them to the library.
Speaking English as a French Frog

jgr = &jgr

  • Newt
  • Posts: 194
Re: .NET GEOMETRY Routines
« Reply #21 on: July 15, 2011, 07:49:05 pm »

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #22 on: August 29, 2011, 04:16:38 am »
Hi,

Here's a method to write the Brep (Boundary Representation) geométric informations of Solid3d, Region, Surface to an Xml file.
Requires A2009 or upper.

Method parameters:
- id: A Solid3d, Region or Surface ObjectId
- filename: The Xml file complete path
- append: If the file exists and this parameter is True, the new data is append to the file, else, the file is overwritten

Code: [Select]
        public void WriteBrepToXml(ObjectId id, string filename, bool append)
        {
            XmlDocument xmlDoc = new XmlDocument();
            if (System.IO.File.Exists(filename) && append)
            {
                xmlDoc.Load(filename);
            }
            else
            {
                string s = @"<?xml version='1.0' ?>
                <Brep>
                </Brep>";
                xmlDoc.LoadXml(s);
            }
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                string solidType;
                if (ent is Solid3d) solidType = "Solide";
                else if (ent is Region) solidType = "Region";
                else if (ent is AcDb.Surface) solidType = "Surface";
                else return;
                using (Brep brp = new Brep(ent))
                {
                    XmlElement entNode = xmlDoc.CreateElement(solidType);
                    entNode.SetAttribute("Handle", ent.Handle.ToString());
                    xmlDoc.DocumentElement.AppendChild(entNode);
                    foreach (Complex cplx in brp.Complexes)
                    {
                        XmlElement cplxNode = xmlDoc.CreateElement("Complex");
                        entNode.AppendChild(cplxNode);
                        foreach (Shell shl in cplx.Shells)
                        {
                            XmlElement shlNode = xmlDoc.CreateElement("Shell");
                            shlNode.SetAttribute("Type", shl.ShellType.ToString());
                            cplxNode.AppendChild(shlNode);
                            foreach (AcBr.Face face in shl.Faces)
                            {
                                XmlElement faceNode = xmlDoc.CreateElement("Face");
                                shlNode.AppendChild(faceNode);
                                try
                                {
                                    foreach (BoundaryLoop loop in face.Loops)
                                    {
                                        XmlElement loopNode = xmlDoc.CreateElement("Loop");
                                        loopNode.SetAttribute("Type", loop.LoopType.ToString());
                                        faceNode.AppendChild(loopNode);
                                        foreach (Edge edge in loop.Edges)
                                        {
                                            ExternalCurve3d curve = (ExternalCurve3d)edge.Curve;
                                            switch (curve.NativeCurve.GetType().Name)
                                            {
                                                case "LineSegment3d":
                                                    LineSegment3d ls = (LineSegment3d)curve.NativeCurve;
                                                    XmlElement lsNode = xmlDoc.CreateElement("LineSegment3d");
                                                    lsNode.SetAttribute("StartPoint", ls.StartPoint.ToString());
                                                    lsNode.SetAttribute("EndPoint", ls.EndPoint.ToString());
                                                    lsNode.SetAttribute("Direction", ls.Direction.ToString());
                                                    loopNode.AppendChild(lsNode);
                                                    break;
                                                case "CircularArc3d":
                                                    CircularArc3d ca = (CircularArc3d)curve.NativeCurve;
                                                    double angle = Vector3d.XAxis
                                                         .TransformBy(Matrix3d.PlaneToWorld(ca.Normal))
                                                         .GetAngleTo(ca.ReferenceVector, ca.Normal);
                                                    XmlElement caNode = xmlDoc.CreateElement("CircularArc3d");
                                                    caNode.SetAttribute("StartPoint", ca.StartPoint.ToString());
                                                    caNode.SetAttribute("EndPoint", ca.EndPoint.ToString());
                                                    caNode.SetAttribute("Center", ca.Center.ToString());
                                                    caNode.SetAttribute("Radius", ca.Radius.ToString());
                                                    caNode.SetAttribute("StartAngle", (ca.StartAngle + angle).ToString());
                                                    caNode.SetAttribute("EndAngle", (ca.EndAngle + angle).ToString());
                                                    caNode.SetAttribute("Normal", ca.Normal.ToString());
                                                    loopNode.AppendChild(caNode);
                                                    break;
                                                case "EllipticalArc3d":
                                                    EllipticalArc3d ea = (EllipticalArc3d)curve.NativeCurve;
                                                    XmlElement eaNode = xmlDoc.CreateElement("EllipticalArc3d");
                                                    eaNode.SetAttribute("StartPoint", ea.StartPoint.ToString());
                                                    eaNode.SetAttribute("EndPoint", ea.EndPoint.ToString());
                                                    eaNode.SetAttribute("Center", ea.Center.ToString());
                                                    eaNode.SetAttribute("StartAngle", ea.StartAngle.ToString());
                                                    eaNode.SetAttribute("EndAngle", ea.EndAngle.ToString());
                                                    eaNode.SetAttribute("MajorAxis", ea.MajorAxis.ToString());
                                                    eaNode.SetAttribute("MinorAxis", ea.MinorAxis.ToString());
                                                    eaNode.SetAttribute("MajorRadius", ea.MajorRadius.ToString());
                                                    eaNode.SetAttribute("MinorRadius", ea.MinorRadius.ToString());
                                                    eaNode.SetAttribute("Normal", ea.Normal.ToString());
                                                    loopNode.AppendChild(eaNode);
                                                    break;
                                                case "NurbCurve3d":
                                                    XmlElement ncNode = xmlDoc.CreateElement("NurbCurve3d");
                                                    NurbCurve3d nc = (NurbCurve3d)curve.NativeCurve;
                                                    NurbCurve3dData data = nc.DefinitionData;
                                                    ncNode.SetAttribute("StartPoint", nc.StartPoint.ToString());
                                                    ncNode.SetAttribute("EndPoint", nc.EndPoint.ToString());
                                                    ncNode.SetAttribute("Degree", data.Degree.ToString());
                                                    ncNode.SetAttribute("Periodic", data.Periodic.ToString());
                                                    ncNode.SetAttribute("Rational", data.Rational.ToString());
                                                    for (int i = 0; i < data.Knots.Count; i++)
                                                    {
                                                        ncNode.SetAttribute(string.Format("Knot_{0}", i + 1), data.Knots[i].ToString());
                                                    }
                                                    for (int i = 0; i < data.Weights.Count; i++)
                                                    {
                                                        ncNode.SetAttribute(string.Format("Weight_{0}", i + 1), data.Weights[i].ToString());
                                                    }
                                                    for (int i = 0; i < data.ControlPoints.Count; i++)
                                                    {
                                                        ncNode.SetAttribute(string.Format("ControlPoint_{0}", i + 1), data.ControlPoints[i].ToString());
                                                    }
                                                    loopNode.AppendChild(ncNode);
                                                    break;
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                    XmlElement loopNode = xmlDoc.CreateElement("LoopUnbounded");
                                    faceNode.AppendChild(loopNode);
                                }
                            }
                        }
                    }
                    xmlDoc.Save(filename);
                }
                tr.Commit();
            }
        }

Heres a little example of the returned file content for a region made of a rectangle from 0,0 to 80,50 with a circular hole which center is at 20,30 and a 10 radius:
Code: [Select]
<?xml version="1.0"?>
<Brep>
  <Region Handle="2747">
    <Complex>
      <Shell Type="ShellExterior">
        <Face>
          <Loop Type="LoopInterior">
            <CircularArc3d StartPoint="(30,30,0)" EndPoint="(30,30,0)" Center="(20,30,0)" Radius="10" StartAngle="3.14159265358979" EndAngle="9.42477796076938" Normal="(0,0,-1)" />
          </Loop>
          <Loop Type="LoopExterior">
            <LineSegment3d StartPoint="(0,0,0)" EndPoint="(80,0,0)" Direction="(1,0,0)" />
            <LineSegment3d StartPoint="(80,0,0)" EndPoint="(80,50,0)" Direction="(0,1,0)" />
            <LineSegment3d StartPoint="(80,50,0)" EndPoint="(0,50,0)" Direction="(-1,0,0)" />
            <LineSegment3d StartPoint="(0,50,0)" EndPoint="(0,0,0)" Direction="(0,-1,0)" />
          </Loop>
        </Face>
      </Shell>
    </Complex>
  </Region>
</Brep>
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #23 on: September 11, 2011, 08:36:50 am »
Hi,

I expanded a little the GeometryExtensions library.
There're two more classes: PolylineSegment and PolylineSegmentCollection (which inherits from List<PolylineSegment>) and a new extension method: Ellipse.ToPolyline().
I hope these classes make easier some work with polylines or to create polylines from other entities.

Here's a quick and dirty example (will give unexpected result with entities which don't lies on the WCS XY plane).
The MJOIN command joins the selected entities: line, arc, polyline, ellipse and spline (A2010 or later for spline) into one or more polyline(s).

Code: [Select]
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using GeometryExtensions;
using AcAp = Autodesk.AutoCAD.ApplicationServices.Application;

namespace GeometryExtensionsTestCommands
{
    public class MjoinCommand
    {
        [CommandMethod("mjoin")]
        public void PolyJoin()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            TypedValue[] filter = {   
                new TypedValue(-4,"<OR"),
                new TypedValue(0, "ARC,ELLIPSE,LINE,LWPOLYLINE"),
                new TypedValue(-4, "<AND"),
                new TypedValue(0, "SPLINE"),
                new TypedValue(-4, "&"),
                new TypedValue(70, 8),
                new TypedValue(-4, "AND>"),
                new TypedValue(-4, "OR>")};
            PromptSelectionResult psr = ed.GetSelection(new SelectionFilter(filter));
            if (psr.Status != PromptStatus.OK) return;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord btr =
                    (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                PolylineSegmentCollection psc = new PolylineSegmentCollection();
                Plane plane = new Plane(Point3d.Origin, Vector3d.ZAxis);
                foreach (ObjectId id in psr.Value.GetObjectIds())
                {
                    Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                    switch (ent.GetType().Name)
                    {
                        case "Arc":
                            Arc arc = (Arc)ent;
                            psc.Add(new PolylineSegment(
                                new CircularArc2d(
                                    arc.Center.Convert2d(plane),
                                    arc.Radius,
                                    arc.StartAngle,
                                    arc.EndAngle,
                                    Vector2d.XAxis,
                                    false)));
                            break;
                        case "Ellipse":
                            Ellipse el = (Ellipse)ent;
                            psc.AddRange(new PolylineSegmentCollection(el));
                            break;
                        case "Line":
                            Line l = (Line)ent;
                            psc.Add(new PolylineSegment(
                                new LineSegment2d(
                                    l.StartPoint.Convert2d(plane),
                                    l.EndPoint.Convert2d(plane))));
                            break;
                        case "Polyline":
                            Polyline pl = (Polyline)ent;
                            psc.AddRange(new PolylineSegmentCollection(pl));
                            break;
                        case "Spline":
                            try
                            {
                                Spline spl = (Spline)ent;
                                psc.AddRange(new PolylineSegmentCollection((Polyline)spl.ToPolyline()));
                            }
                            catch { }
                            break;
                        default:
                            break;
                    }
                }
                foreach (PolylineSegmentCollection segs in psc.Join())
                {
                    Polyline pline = segs.ToPolyline();
                    btr.AppendEntity(pline);
                    tr.AddNewlyCreatedDBObject(pline, true);
                }
                tr.Commit();
            }
        }
    }
}
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #24 on: October 16, 2011, 11:02:36 am »
Hi,

The GeometryExtension librairy keeps on growing.

The main new things are Polyline, Polyline2d and Polyline3d extensions methods : GetProjectedPolyline and GetOrthoProjectedPolyline.

These methods create a new Polyline object and may replace the GetProjectedCurve and GetOrthoProjectedCurve methods which do not give expected results with Polyline and Polyline2d entities.
The elliptical arcs resulting of the polyline arcs projection are approximated using the PolylineSegmentCollection(Ellipse ellipse) constructor. This constructor uses the same geometric method as the 'old' AutoCAD native approximation of ellipses (i.e. PELLIPSE = 1).
« Last Edit: October 16, 2011, 11:16:30 am by gile »
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #25 on: November 14, 2011, 03:13:32 pm »
New version of GeometryExtensions (1.3).
Download updated in the first message.
Corrected some bugs with the GetProjectedPolyline and GetOrthoProjectedPolyline methods.
Speaking English as a French Frog

fixo

  • Swamp Rat
  • Posts: 856
  • My location is not in the Hitleropa
Re: .NET GEOMETRY Routines
« Reply #26 on: May 05, 2012, 04:56:14 am »
Draw bisector berween 2 lines
Code: [Select]
        [CommandMethod("bisect", CommandFlags.Modal | CommandFlags.Redraw)]
        public static void TestForBiLine()
        {
            // Get the current document and database
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            // Select lines
            PromptEntityOptions opt = new PromptEntityOptions("\nSelect a first line:");
            opt.SetRejectMessage("\nMust be selected the line only!");
            opt.AddAllowedClass(typeof(Line),false);

            PromptEntityResult res1 = ed.GetEntity(opt);
            // Set 'black hole' to exit if something wrong
            if (res1.Status != PromptStatus.OK)return;
         opt=   new PromptEntityOptions("\nSelect a second line:");

            PromptEntityResult res2 = ed.GetEntity(opt);
            // Set 'black hole' to exit if something wrong
            if (res2.Status != PromptStatus.OK) return;
            // Open transaction
             Transaction tr = db.TransactionManager.StartTransaction();
             using (tr)
             {
             
                 DBObject obj1 = tr.GetObject(res1.ObjectId, OpenMode.ForWrite);
                 Line ln1 = obj1 as Line;
                 // Set 'black hole' to exit if something wrong
                 if (ln1 == null) return;
               

                 DBObject obj2 = tr.GetObject(res2.ObjectId, OpenMode.ForWrite);
                 Line ln2 = obj2 as Line;
                 // Set 'black hole' to exit if something wrong
                 if (ln2 == null) return;

         
                 Point3d ps1 = ln1.StartPoint;
                 Point3d pe1 = ln1.EndPoint;
                 Point3d ps2 = ln2.StartPoint;
                 Point3d pe2 = ln2.EndPoint;

                 Point3dCollection pts = new Point3dCollection();
                 ln1.IntersectWith(ln2, Intersect.ExtendBoth, pts, 0, 0);
                 // Set 'black hole' to exit if no intersection
                 if (pts.Count != 1)
                 {
                     acadApp.ShowAlertDialog("Lines are colinear or does not intersects each another");

                     return;
                 }
                 // Calculate nearest point to the first line
                 Point3d pk1 = res1.PickedPoint;
                 pk1 = ln1.GetClosestPointTo(pk1, true);
                 // Calculate nearest point to the first line
                 Point3d pk2 = res2.PickedPoint;
                 pk2 = ln2.GetClosestPointTo(pk2, true);
                 // Swap start and end points if lines has different direction
                 if (ps1.DistanceTo(ps2) + pe1.DistanceTo(pe2) > (ps1.DistanceTo(pe2) + pe1.DistanceTo(ps2)))
                 {
                     Point3d tp = new Point3d(ps1.X, ps1.Y, ps1.Z);
                     ps1 = pe1;
                     pe1 = tp;

                 }
                 // create the first temporary Line3d object
                 Line3d tl1 = new Line3d(ps1, ps2);
                 // Calculate midpoint of this line
                 Point3d tp1 = tl1.EvaluatePoint(0.5);
                 // create the second temporary Line3d object
                 Line3d tl2 = new Line3d(pe1, pe2);
                 // Calculate midpoint of this line
                 Point3d tp2 = tl2.EvaluatePoint(0.5);
                 // Create bisector line
                 Line ln = new Line(tp1, tp2);
                 ln.SetDatabaseDefaults();
                 BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                 // Append line to the current space and transaction
                 btr.AppendEntity(ln);
                 tr.AddNewlyCreatedDBObject(ln, true);
                 // Commit transaction
                 tr.Commit();
             }
        }

Regards,

~'J'~
« Last Edit: May 05, 2012, 03:21:03 pm by fixo »
\\\"Always drink upstream from the herd."\\\ - Will Rogers, was died in 1935 plane crash

--> Donate to TheSwamp <--

gile

  • Water Moccasin
  • Posts: 1743
  • Marseille, France
Re: .NET GEOMETRY Routines
« Reply #27 on: May 05, 2012, 03:13:26 pm »
Hi Oleg,

Here's another way using vectors

Code - C#: [Select]
  1.        [CommandMethod("Bisect")]
  2.        public void Bisector()
  3.        {
  4.            Document doc = AcAp.DocumentManager.MdiActiveDocument;
  5.            Database db = doc.Database;
  6.            Editor ed = doc.Editor;
  7.            PromptEntityOptions peo = new PromptEntityOptions("\nSelect the first line: ");
  8.            peo.SetRejectMessage("Selected object is not a line !");
  9.            peo.AddAllowedClass(typeof(Line), true);
  10.            PromptEntityResult per = ed.GetEntity(peo);
  11.            if (per.Status != PromptStatus.OK) return;
  12.            Point3d p1 = per.PickedPoint.TransformBy(ed.CurrentUserCoordinateSystem);
  13.            ObjectId id1 = per.ObjectId;
  14.            peo.Message = "\nSelect the second line: ";
  15.            per = ed.GetEntity(peo);
  16.            if (per.Status != PromptStatus.OK) return;
  17.            Point3d p2 = per.PickedPoint.TransformBy(ed.CurrentUserCoordinateSystem);
  18.            ObjectId id2 = per.ObjectId;
  19.            using (Transaction tr = db.TransactionManager.StartTransaction())
  20.            {
  21.                Line l1 = (Line)tr.GetObject(id1, OpenMode.ForRead);
  22.                Line l2 = (Line)tr.GetObject(id2, OpenMode.ForRead);
  23.  
  24.                // Checks if lines intersect
  25.                Plane plane;
  26.                Line3d line1 = new Line3d(l1.StartPoint, l1.EndPoint);
  27.                Line3d line2 = new Line3d(l2.StartPoint, l2.EndPoint);
  28.                if (!line1.IsCoplanarWith(line2, out plane) || line1.IsParallelTo(line2))
  29.                    return;
  30.  
  31.                // Calculates the bisector
  32.                Point3d inters = line1.IntersectWith(line2)[0];
  33.                Vector3d vec1 = line1.Direction;
  34.                Vector3d vec2 = line2.Direction;
  35.                // Corrects the vectors direction according to picked points
  36.                if (vec1.DotProduct(inters.GetVectorTo(p1)) < 0)
  37.                    vec1 = vec1.Negate();
  38.                if (vec2.DotProduct(inters.GetVectorTo(p2)) < 0)
  39.                    vec2 = vec2.Negate();
  40.                Vector3d bisectDir = (vec1 + vec2) / 2.0;
  41.  
  42.                // Draws the bisector (XLine)
  43.                Xline xline = new Xline();
  44.                xline.UnitDir = bisectDir.GetNormal();
  45.                xline.BasePoint = inters;
  46.                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  47.                btr.AppendEntity(xline);
  48.                tr.AddNewlyCreatedDBObject(xline, true);
  49.                tr.Commit();
  50.            }
  51.        }

Note: AFAIK, there's no need to call Dispose() on Line3d objects (as for Vector3d, Point3d, ...).
Speaking English as a French Frog

fixo

  • Swamp Rat
  • Posts: 856
  • My location is not in the Hitleropa
Re: .NET GEOMETRY Routines
« Reply #28 on: May 05, 2012, 03:22:47 pm »
Thanks, Gilles, I removed these lines from code
Regards,
Oleg
\\\"Always drink upstream from the herd."\\\ - Will Rogers, was died in 1935 plane crash

--> Donate to TheSwamp <--

fixo

  • Swamp Rat
  • Posts: 856
  • My location is not in the Hitleropa
Re: .NET GEOMETRY Routines
« Reply #29 on: May 06, 2012, 02:27:34 am »
Circle by 3 points
Code: [Select]

        [CommandMethod("circ3p")]// This method can have any name
        public static void TestFor3PointCircle()
        {
            // Get the document and database
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            // If we have a valid point selection, get all 3 points
           PromptPointOptions ppo =   new PromptPointOptions("\nPick a point : ");
            ppo.AllowNone = true;
            PromptPointResult ppr;
                ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
            Point3d p1= ppr.Value;
            ppo =   new PromptPointOptions("\nPick a second point : ");
                 ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
            Point3d p2= ppr.Value;
                        ppo =   new PromptPointOptions("\nPick a third point : ");
                 ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
            Point3d p3= ppr.Value;
            // To pass center point by reference
            Point3d pc = new Point3d();
            // Get result
            bool result = CircleCenter(p1, p2, p3, out pc);
            if (result)
                ed.WriteMessage("\nCenter point calculated:\t{0:f3},{1:f3},{2:f3}", pc.X, pc.Y, pc.Z);
            else return;
            // Calculate radius
            double rad = pc.DistanceTo(p1);
            // Open transaction and add circle to the current space
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Circle circ = new Circle(pc, Vector3d.ZAxis, rad);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(circ);
                tr.AddNewlyCreatedDBObject(circ, true);
                // Commit transaction
                tr.Commit();
               
            }
         
        }

        public static bool CircleCenter(Point3d p0, Point3d pm, Point3d p1, out Point3d pc)
        {
            Vector3d v1 = p0 - pm;

            Vector3d v2 = p1 - pm;

            if (v1.IsParallelTo(v2))
            {
                pc = new Point3d();

                return false;
            }

            CircularArc3d crc = new CircularArc3d(p0, pm, p1);

            pc = crc.Center;

            return true;
        }

    }

Regards,

~'J'~
\\\"Always drink upstream from the herd."\\\ - Will Rogers, was died in 1935 plane crash

--> Donate to TheSwamp <--