000

Index Labels

Customizing Object Snap: Take One - Using OsnapOverrule

.
AutoCAD provides 2 commands that are used under similar situation: Measure and Divide. With these 2 commands, user can insert blocks along a curve (Line, Polyline, Arc, Circle...) in equal distance. The difference of the 2 commands is that for "Divide", user specifies the number of segments the curve will be divided into, while for "Measure", user specifies the length of segment the curve will be measured segment by segment.

I came across an interesting request from a user, who wants some thing like the 2 commands. But after selecting the curve to be measured/divided, the user want to able to see the points as the result of measuring/dividing, or the mouse cursor can snap to these points when hovering the curve, then the user can decide what to do at the point the cursor is snapped to.

So, I decided to write some code to provide the convenience to AutoCAD users. Upon a little bit study and try-out coding, I came to 2 solutions that can do the same thing:
  • Using OsnapOverrule
  • Using CustomObjectSnapMode in conjunction with Glyth
So, I decided to post 2 articles on each solution. This is the first one.

Here is the code that derives from Autodesk.AutoCAD.DatabaseServices.OsnapOverrule:

    1 using System;
    2 using Autodesk.AutoCAD.DatabaseServices;
    3 using Autodesk.AutoCAD.Geometry;
    4 using Autodesk.AutoCAD.Runtime;
    5 
    6 namespace MeasureOsnap
    7 {
    8     public class MeasureOsnapOverrule : OsnapOverrule
    9     {
   10         private enum MeasureOsnapType
   11         {
   12             Measure = 0,
   13             Divide = 1,
   14         }
   15 
   16         private static MeasureOsnapOverrule _instance = null;
   17         private bool _overruling;
   18         private bool _started = false;
   19         private int _segmentNumber = 1;
   20         private double _segmentLength = 0.0;
   21         private MeasureOsnapType _snapType = MeasureOsnapType.Measure;
   22 
   23         private ObjectId _entId = ObjectId.Null;
   24 
   25         public MeasureOsnapOverrule()
   26         {
   27             _overruling = Overrule.Overruling;
   28         }
   29 
   30         public static MeasureOsnapOverrule Instance
   31         {
   32             get
   33             {
   34                 if (_instance == null)
   35                 {
   36                     _instance = new MeasureOsnapOverrule();
   37                 }
   38                 return _instance;
   39             }
   40         }
   41 
   42         public void StartDivideSnap(ObjectId entId,
   43             int segmentNumber)
   44         {
   45             if (_started) return;
   46 
   47             _segmentNumber = segmentNumber;
   48             _snapType = MeasureOsnapType.Divide;
   49 
   50             StartSnap(entId);
   51         }
   52 
   53         public void StartMeasureSnap(ObjectId entId,
   54             double segmentLength)
   55         {
   56             if (_started) return;
   57 
   58             _segmentLength = segmentLength;
   59             _snapType = MeasureOsnapType.Measure;
   60 
   61             StartSnap(entId);
   62         }
   63 
   64         public void StopSnap()
   65         {
   66             if (!_started) return;
   67 
   68             Type t = GetEntityType();
   69             Overrule.RemoveOverrule(RXClass.GetClass(t), this);
   70             Overrule.Overruling = _overruling;
   71 
   72             _started = false;
   73             _entId = ObjectId.Null;
   74         }
   75 
   76         #region Override base class mathods
   77 
   78         public override void GetObjectSnapPoints(
   79             Entity entity, ObjectSnapModes snapMode, IntPtr gsSelectionMark,
   80             Point3d pickPoint, Point3d lastPoint, Matrix3d viewTransform,
   81             Point3dCollection snapPoints, IntegerCollection geometryIds)
   82         {
   83             Curve curve = entity as Curve;
   84 
   85             snapPoints.Clear();
   86             snapMode = ObjectSnapModes.ModeNear;
   87 
   88             //Add snap point at start point
   89             snapPoints.Add(curve.StartPoint);
   90 
   91             if (_snapType == MeasureOsnapType.Measure)
   92             {
   93                 if (_segmentLength<=0.0) return;
   94             }
   95 
   96             if (_snapType == MeasureOsnapType.Divide)
   97             {
   98                 if (_segmentNumber < 2) return;
   99             }
  100 
  101             double length = curve.GetDistanceAtParameter(curve.EndParam);
  102 
  103             //get each segment length
  104             double segLength = _snapType == MeasureOsnapType.Measure ?
  105                 _segmentLength : length / _segmentNumber;
  106 
  107             //Add snap points. If the curve is closed. Obviously
  108             //the snap points at start point and end point will
  109             //be overlapped in the case of Divide-Snap
  110             double l = segLength;
  111             while (l <= length)
  112             {
  113                 Point3d pt = curve.GetPointAtDist(l);
  114                 snapPoints.Add(pt);
  115 
  116                 l += segLength;
  117             }
  118         }
  119 
  120         public override bool IsContentSnappable(Entity entity)
  121         {
  122             return false;
  123         }
  124 
  125         #endregion
  126 
  127         #region private methods
  128 
  129         private void StartSnap(ObjectId entId)
  130         {
  131             _entId = entId;
  132 
  133             Type t = GetEntityType();
  134 
  135             Overrule.AddOverrule(RXClass.GetClass(t), this, false);
  136 
  137             Overrule.Overruling = true;
  138             _started = true;
  139 
  140             this.SetIdFilter(new ObjectId[] { _entId });
  141         }
  142 
  143         private Type GetEntityType()
  144         {
  145                 Type t;
  146                 switch (_entId.ObjectClass.DxfName.ToUpper())
  147                 {
  148                     case "CIRCLE":
  149                         t = typeof(Circle);
  150                         break;
  151                     case "ARC":
  152                         t = typeof(Arc);
  153                         break;
  154                     case "LINE":
  155                         t = typeof(Line);
  156                         break;
  157                     default:
  158                         t = typeof(Polyline);
  159                         break;
  160                 }
  161 
  162             return t;
  163         }
  164 
  165         #endregion
  166     }
  167 }

The code is pretty simple and straightforward: simply overriding GetObjectSnapPoints() method to generate a set points where you want the snap points to be placed.

Here is the code to use the MeasureOSnapOverrule class:

    1 using Autodesk.AutoCAD.ApplicationServices;
    2 using Autodesk.AutoCAD.DatabaseServices;
    3 using Autodesk.AutoCAD.EditorInput;
    4 using Autodesk.AutoCAD.Runtime;
    5 
    6 [assembly: CommandClass(typeof(MeasureOsnap.MyCommands))]
    7 
    8 namespace MeasureOsnap
    9 {
   10     public class MyCommands
   11     {
   12         private static string _snapType = "Measure";
   13 
   14         [CommandMethod("MyOverruledSnap")]
   15         public static void RunMyOverruledSnap()
   16         {
   17             Document dwg = Application.DocumentManager.MdiActiveDocument;
   18             Editor ed = dwg.Editor;
   19 
   20             //Pick entity to show snap for measuring or dividing
   21             ObjectId selectedId = GetSanpEntity(ed);
   22 
   23             if (selectedId == ObjectId.Null)
   24             {
   25                 OnCommandCancelled();
   26                 return;
   27             }
   28 
   29             if (_snapType == "Measure")
   30             {
   31                 //Get segment length
   32                 PromptDoubleOptions dop = new PromptDoubleOptions(
   33                     "\nEnter segment length: ");
   34                 dop.AllowNegative = false;
   35                 dop.AllowNone = false;
   36                 dop.AllowZero = false;
   37 
   38                 PromptDoubleResult dres = ed.GetDouble(dop);
   39                 if (dres.Status != PromptStatus.OK)
   40                 {
   41                     OnCommandCancelled();
   42                     return;
   43                 }
   44 
   45                 //Start Measure-Snap
   46                 MeasureOsnapOverrule.Instance.StartMeasureSnap(
   47                     selectedId, dres.Value);
   48             }
   49             else
   50             {
   51                 //Get segment count
   52                 PromptIntegerOptions iop = new PromptIntegerOptions(
   53                     "\nEnter segment count: ");
   54                 iop.AllowNegative = false;
   55                 iop.AllowNone = false;
   56                 iop.AllowZero = false;
   57 
   58                 PromptIntegerResult ires = ed.GetInteger(iop);
   59                 if (ires.Status != PromptStatus.OK)
   60                 {
   61                     OnCommandCancelled();
   62                     return;
   63                 }
   64 
   65                 //Start Divide-Snap
   66                 MeasureOsnapOverrule.Instance.StartDivideSnap(
   67                     selectedId, ires.Value);
   68             }
   69 
   70             //Obtain point when taking advantage of
   71             //Measure or Divide-Snap
   72             PromptPointOptions pOp = new PromptPointOptions(
   73                 "\nPick point: ");
   74             PromptPointResult pres = ed.GetPoint(pOp);
   75             if (pres.Status == PromptStatus.OK)
   76             {
   77                 ed.WriteMessage("\nPoint: X={0}, Y={1}",
   78                     pres.Value.X, pres.Value.Y);
   79             }
   80             else
   81             {
   82                 ed.WriteMessage("\n*Cancel*");
   83             }
   84 
   85             //Stop the overrule
   86             MeasureOsnapOverrule.Instance.StopSnap();
   87 
   88             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
   89         }
   90 
   91         private static ObjectId GetSanpEntity(Editor ed)
   92         {
   93             ObjectId entId = ObjectId.Null;
   94 
   95             while (true)
   96             {
   97                 string keyword =
   98                     _snapType == "Measure" ? "Divide" : "Measure";
   99 
  100                 PromptEntityOptions opt = new PromptEntityOptions(
  101                     "\nPick a line/polyline/arc/circle to show " +
  102                     _snapType + "-Snap:");
  103                 opt.SetRejectMessage(
  104                     "\nInvalid pick: must be a line/polyline/arc/circle.");
  105                 opt.AddAllowedClass(typeof(Line), true);
  106                 opt.AddAllowedClass(typeof(Polyline), true);
  107                 opt.AddAllowedClass(typeof(Arc), true);
  108                 opt.AddAllowedClass(typeof(Circle), true);
  109                 opt.AllowNone = true;
  110                 opt.Keywords.Add(keyword);
  111                 opt.Keywords.Default = keyword;
  112                 opt.AppendKeywordsToMessage = true;
  113 
  114                 PromptEntityResult res = ed.GetEntity(opt);
  115 
  116                 if (res.Status == PromptStatus.OK)
  117                 {
  118                     entId = res.ObjectId;
  119                     break;
  120                 }
  121                 else if (res.Status == PromptStatus.Keyword)
  122                 {
  123                     _snapType = res.StringResult;
  124                 }
  125                 else
  126                 {
  127                     break;
  128                 }
  129             }
  130 
  131             return entId;
  132         }
  133 
  134         private static void OnCommandCancelled()
  135         {
  136             Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
  137             ed.WriteMessage("\n*Cancel*");
  138             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
  139         }
  140     }
  141 }

See this video clip for the code in action.

Stay tuned for the article on another solution for the same task.

Blog Archive

Labels

.NET Programming 2D Drafting 3D Animation 3D Art 3D Artist 3D design 3D effects 3D Engineering 3D Materials 3D Modeling 3D models 3D presentation 3D Printing 3D rendering 3D scanning 3D scene 3D simulation 3D Sketch Inventor 3D Texturing 3D visualization 3D Web App 3ds Max 4D Simulation ACC Adaptive Clearing adaptive components Add-in Development Additive Manufacturing Advanced CAD features Advanced Modeling AEC Technology AEC Tools affordable Autodesk tools AI AI animation AI Assistance AI collaboration AI Design AI Design Tools AI Experts AI for Revit AI Guide AI in CAD AI in CNC AI in design AI in Manufacturing AI in Revit AI insights AI lighting AI rigging AI Tips AI Tools AI troubleshooting AI workflow AI-assisted AI-assisted rendering AI-enhanced Animation animation pipeline animation tips Animation workflow annotation AR architectural design architectural modeling architectural preservation architectural visualization Architecture architecture design Architecture Engineering Architecture Firm Architecture Productivity architecture software architecture technology Architecture Workflow Arnold Renderer Arnold Shader Artificial Intelligence As-Built Model Asset Management augmented reality AutoCAD AutoCAD advice AutoCAD API AutoCAD Basics AutoCAD Beginner AutoCAD Beginners AutoCAD Civil 3D AutoCAD Civil3D AutoCAD commands AutoCAD efficiency AutoCAD Expert Advice AutoCAD features AutoCAD File Management AutoCAD Layer AutoCAD Layers AutoCAD learning AutoCAD print settings AutoCAD productivity AutoCAD Teaching AutoCAD Techniques AutoCAD tips AutoCAD tools AutoCAD training. AutoCAD tricks AutoCAD Tutorial AutoCAD workflow AutoCAD Xref Autodesk Autodesk 2025 Autodesk 2026 Autodesk 3ds Max Autodesk AI Autodesk AI Tools Autodesk Alias Autodesk AutoCAD Autodesk BIM Autodesk BIM 360 Autodesk Certification Autodesk Civil 3D Autodesk Cloud Autodesk community forums Autodesk Construction Cloud Autodesk Docs Autodesk Dynamo Autodesk features Autodesk for Education Autodesk Forge Autodesk FormIt Autodesk Fusion Autodesk Fusion 360 Autodesk help Autodesk InfraWorks Autodesk Inventor Autodesk Inventor Frame Generator Autodesk Inventor iLogic Autodesk Knowledge Network Autodesk License Autodesk Maya Autodesk mistakes Autodesk Navisworks Autodesk news Autodesk plugins Autodesk productivity Autodesk Recap Autodesk resources Autodesk Revit Autodesk Software Autodesk support ecosystem Autodesk Takeoff Autodesk Tips Autodesk training Autodesk tutorials Autodesk update Autodesk Upgrade Autodesk Vault Autodesk Video Autodesk Viewer Automated Design Automation Automation Tutorial automotive design automotive visualization Backup Basic Commands Basics Batch Plot Beginner Beginner Tips beginner tutorial beginners guide Big Data BIM BIM 360 BIM Challenges BIM collaboration BIM Compliance BIM Coordination BIM Data BIM Design BIM Efficiency BIM for Infrastructure BIM Implementation BIM Library BIM Management BIM modeling BIM software BIM Standards BIM technology BIM tools BIM Trends BIM workflow Block Editor Block Management Block Organization Building Design Software Building Maintenance building modeling Building Systems Building Technology ByLayer CAD CAD API CAD assembly CAD Automation CAD Blocks CAD CAM CAD commands CAD comparison CAD Customization CAD Data Management CAD Design CAD errors CAD Evolution CAD File Size Reduction CAD Integration CAD Learning CAD line thickness CAD management CAD Migration CAD mistakes CAD modeling CAD Optimization CAD plugins CAD Productivity CAD Rendering CAD Security CAD Skills CAD software CAD software 2026 CAD software training CAD standards CAD technology CAD Tips CAD Tools CAD tricks CAD Tutorial CAD workflow CAM car design software Case Study CEO Guide CGI design Character Rig cinematic lighting Civil 3D Civil 3D hidden gems Civil 3D productivity Civil 3D tips civil design software civil engineering Civil engineering software Clash Detection Class-A surfacing clean CAD file cleaning command client engagement Cloud CAD Cloud Collaboration Cloud design platform Cloud Engineering Cloud Management Cloud Storage Cloud-First CNC CNC machining collaboration command abbreviations Complex Renovation concept car conceptual workflow Connected Design construction Construction Analytics Construction Automation Construction BIM Construction Cloud Construction Planning Construction Scheduling Construction Technology contractor tools Contractor Workflow Contraints corridor design Cost Effective Design cost estimation Create resizable blocks Creative Teams CTB STB Custom visual styles Cutting Parameters Cybersecurity Data Backup data management Data Protection Data Reference Data Security Data Shortcut Design Automation Design Career Design Collaboration Design Comparison Design Coordination design efficiency Design Engineering Design Hacks Design Innovation design optimization Design Options design productivity design review Design Rules design software design software tips Design Technology design tips Design Tools Design Workflow design-to-construction Designer Designer Tools Digital Art Digital Assets Digital Construction Digital Construction Technology Digital Content Digital Design Digital engineering digital fabrication Digital Manufacturing digital marketing digital takeoff Digital Thread Digital Tools Digital Transformation Digital Twin Digital Twins digital workflow dimension dimensioning Disaster Recovery drafting Drafting Efficiency Drafting Shortcuts Drafting Standards Drafting Tips Drawing Drawing Automation drawing tips Dref Dynamic Block Dynamic Block AutoCAD Dynamic Blocks Dynamic doors Dynamic windows Dynamo Dynamo automation early stage design eco design editing commands Electrical Systems Emerging Features Energy Analysis energy efficiency Engineering Engineering Automation engineering data Engineering Design Engineering Innovation Engineering Productivity Engineering Skills engineering software Engineering Technology engineering tools Engineering Tools 2025 Engineering Workflow Excel Export Workflow Express Tools External Reference facial animation Facial Rigging Facility Management Families Fast Structural Design Field Documentation File Optimization File Recovery Flame flange tips flat pattern Forge Development Forge Viewer FreeCAD Fusion 360 Fusion 360 API Fusion 360 tutorial Future of Design Future Skills Game Development Gamification Generative Design Geospatial Data GIS Global design teams global illumination grading optimization green building Green Technology Grips Handoff HDRI health check Healthcare Facilities heavy CAD file Heavy CAD Files heritage building conservation hidden commands Hospital Design HVAC HVAC Design Tools HVAC Engineering Hydraulic Modeling IK/FK iLogic Import Workflow Industry 4.0 Infrastructure infrastructure design Infrastructure Monitoring Infrastructure Planning Infrastructure Technology InfraWorks innovation Insight intelligent modeling Interactive Design interactive presentation Interior Design Inventor Inventor API Inventor Drawing Template Inventor Frame Generator Inventor Graphics Issues Inventor IDW Inventor Tips Inventor Tutorial IoT ISO 19650 joints Keyboard Shortcuts keyframe animation Keyframe generation Landscape Design Large Projects Laser Scan Layer Management Layer Organization Learn AutoCAD Legacy CAD Licensing light techniques Lighting and shading Lighting Techniques Linked Models Machine Learning Machine Learning in CAD Machine Optimization Machining Efficiency maintenance command Management manufacturing Manufacturing Innovation Manufacturing Technology Mapping Technology marketing visuals Material Creation Maya Maya character animation Maya lighting Maya Shader Maya Tips Maya tutorial measurement Mechanical Design Mechanical Engineering Media & Entertainment MEP Modeling Mesh-to-BIM Metal Structure modal analysis Model Management Model Optimization Modeling Secrets Modular Housing Motion capture motion graphics motion simulation MotionBuilder Multi Office Workflow Multi-User Environment multileader Navisworks Navisworks Best Practices Net Zero Design ObjectARX .NET API Open Source CAD Organization OVERKILL OVERKILL AutoCAD Page Setup Palette Parametric Components parametric design parametric family Parametric Modeling particle effects particle systems PDF PDM system Personal Brand Phasing PlanGrid Plot Settings Plot Style Plot Style AutoCAD Plotting Plugin Tutorial Plumbing Design point cloud Portfolio Post Construction Post-Processing Practice Drawing preconstruction workflow predictive analysis predictive animation Predictive Maintenance Predictive rigging Prefabrication Presentation-ready visuals Printing Printing Quality Procedural animation procedural motion Procedural Rig Procedural Textures Product Design Product Development product lifecycle product rendering Productivity productivity tools Professional 3D design Professional CAD Professional Drawings professional printing Professional Tips Project Documentation project efficiency project management Project Management Tools Project Visualization PTC Creo PURGE PURGE AutoCAD Rail Transit Rapid Prototyping realistic rendering ReCap Redshift Shader reduce CAD file size Render Render Passes Render Quality Render Settings Rendering rendering engine Rendering Engines Rendering Optimization rendering software Rendering Tips Rendering Workflow RenderMan Renewable Energy Renovation Project Renovation Workflow Reports Resizable Block restoration workflow Revit Revit add-ins Revit API Revit automation Revit Best Practices Revit Collaboration Revit Documentation Revit Family Revit integration Revit MEP Revit Performance Revit Phasing Revit Plugins Revit Scripting Revit skills Revit Standards Revit Template Revit Tips Revit tutorial Revit Workflow Ribbon Rigging robotics ROI Scale Autodesk Schedules screen Sculpting Secure Collaboration Sensor Data Shader Networks Sheet Metal Design Sheet Metal Tricks Sheet Set Manager shortcut keys Shortcuts Siemens NX Simulation simulation tools Sketch Sketching Tricks Small Firms Smart Architecture Smart Block Smart Building Design Smart City Smart Design Smart Engineering Smart Factory Smart Infrastructur Software Compliance software ecosystem Software Management Software Trends software troubleshooting Software Update Solar Energy Solar Panels SolidWorks Startup Design static stress Steel Structure Design Structural Optimization subscription model Subscription Value Surface Modeling sustainability sustainable design Sustainable Manufacturing system performance T-Spline team training guide Technical Drawing technical support Template Setup text style Texture Mapping Texturing thermal analysis Time Management time saving tools Title Blocks toolbar Toolpath Optimization Toolpaths Topography Troubleshooting Tutorial Tutorials urban planning User Interface (UI) UV Mapping UV Unwrap V-Ray Vault Best Practices Vault Lifecycle Vault Mistakes Vector Plotting vehicle modeling VFX Viewport configuration Virtual Environments virtual reality visual effects visualization workflow VR VR Tools VRED Water Infrastructure Water Management Weight Painting What’s New in Autodesk Wind Energy Wind Turbines Workbook workflow Workflow Automation workflow efficiency Workflow Optimization Workflow Tips Worksets Worksharing Workspace XLS Xref Xrefs เขียนแบบ