using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
namespace AcadTest
{
public class CurveTest
{
[CommandMethod("TestClosestPoint")]
public void ClosestPoint()
{
SupportMethods.InitializeVars
(out Document adoc, out Editor ed, out Database db);
ObjectId id = SupportMethods.SelectEntity(ed, "\nSelect curve:");
if (!id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Curve))))
{
ed.WriteMessage("\nIt's not curve!");
return;
}
Point3d? pt = SupportMethods.GetPoint(ed);
if (!pt.HasValue)
{
ed.WriteMessage("\nNo point!");
return;
}
Point3d? closPt = null;
using (Curve curve = id.Open(OpenMode.ForRead) as Curve)
{
if (curve != null)
{
if (curve is Spline spline)
{
using (Curve plCurve = spline.ToPolylineWithPrecision(5))
{
closPt = plCurve.GetClosestPointTo(pt.Value, false);
}
}
else
{
closPt = curve.GetClosestPointTo(pt.Value, false);
}
}
}
if (closPt.HasValue)
{
using (Circle circle = new Circle())
{
circle.Center = closPt.Value;
circle.Radius = 0.1 * closPt.Value.DistanceTo(pt.Value);
circle.ColorIndex = 1;
using (BlockTableRecord cSpace
= id.Database.CurrentSpaceId.Open(OpenMode.ForWrite) as BlockTableRecord)
{
if (cSpace != null)
cSpace.AppendEntity(circle);
}
}
}
}
internal static class SupportMethods
{
public static void InitializeVars(out Document adoc, out Editor ed, out Database db)
{
adoc = Application.DocumentManager.MdiActiveDocument;
ed = adoc.Editor;
db = adoc.Database;
}
public static ObjectId SelectEntity(Editor ed, string msg = "\nSelect entity: ")
{
PromptEntityResult entRes = ed.GetEntity(msg);
return entRes.Status == PromptStatus.OK ? entRes.ObjectId : ObjectId.Null;
}
public static string GetString(Editor ed, string msg = "\nInput string value: ")
{
PromptResult stringRes = ed.GetString(msg);
return stringRes.Status == PromptStatus.OK ? stringRes.StringResult : null;
}
public static Point3d? GetPoint(Editor ed, string msg = "\nSelect point: ")
{
PromptPointResult ptRes = ed.GetPoint(msg);
return ptRes.Status == PromptStatus.OK ? (Point3d?)ptRes.Value : null;
}
}
}
}