Thursday, June 27, 2013

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.

Thursday, June 20, 2013

Drag Something And Drop Into AutoCAD

Windows users are familiar with Windows Drag & Drop operation - clicking on something and holding down the left mouse button, then dragging it to somewhere and releasing the left mouse button. Many applications built for Windows adopt this mechanism, AutoCAD is no exception. For example, user can drag a drawing file (*.dwg) from Windows explorer and drop it into AutoCAD editor. As result, AutoCAD starts block inserting command.

When we do our customizing programming with AutoCAD's .NET API, we can easily create Drag & Drop feature into our custom applications. Imagine this user case: a form presenting some drawing options, such as drawing circles with different radius; user is asked to drag one option into AutoCAD editor to actually have the circle drawn.

Here is an entire set of code to do this.

The form that presents circle drawing options looks like this:


The code behind the form is as following:

    1 using System;
    2 using System.Linq;
    3 using System.Windows.Forms;
    4 
    5 namespace DragDropIntoAcad
    6 {
    7     public partial class dlgCircle : Form
    8     {
    9         public dlgCircle()
   10         {
   11             InitializeComponent();
   12         }
   13 
   14         private void LoadCircleList()
   15         {
   16             string[] circles = new string[]
   17             {
   18                 "Radius=3",
   19                 "Radius=4",
   20                 "Radius=5",
   21                 "Radius=6",
   22                 "Radius=7",
   23                 "Radius=8",
   24                 "Radius=9",
   25                 "Radius=10",
   26                 "Radius=11",
   27                 "Radius=12"
   28             };
   29 
   30             var data = from c in circles
   31                        select new {
   32                            CircleName = c,
   33                            CircleRadius = Int32.Parse(c.Substring(7))
   34                        };
   35 
   36             cboCircle.DisplayMember = "CircleName";
   37             cboCircle.ValueMember = "CircleRadius";
   38             cboCircle.DataSource = data.ToList();
   39         }
   40 
   41         private void dlgCircle_Load(object sender, EventArgs e)
   42         {
   43             LoadCircleList();
   44         }
   45 
   46         private void btnClose_Click(object sender, EventArgs e)
   47         {
   48             this.Visible = false;
   49         }
   50 
   51         private void dlgCircle_FormClosing(
   52             object sender, FormClosingEventArgs e)
   53         {
   54             e.Cancel = true;
   55             this.Visible = false;
   56         }
   57 
   58         private void lblCircle_MouseDown(object sender, MouseEventArgs e)
   59         {
   60             if (e.Button == MouseButtons.Left)
   61             {
   62                 double r = Convert.ToDouble(cboCircle.SelectedValue);
   63 
   64                 CircleDropper.DragDropCircle(lblCircle, r);
   65             }
   66         }
   67     }
   68 }

There are 2 things in the form's code to pay attention.

Firstly, I intend to show the form as modeless form, thus clicking the "Close" button, or clicking the "x" button of the form will only hide the form. In the command method where the form is called to show, the code there make sure only one instance of the form is ever created.

Secondly, the whole trick of doing "Drag & Drop" here lies in lblCircle_MouseDown() event handler. In order to separate AutoCAD functioning code with the UI code (the form code), I create a static class CircleDropper, which hides all the AutoCAD operation (of drawing circle) details away from the UI.

Here is the code for class CircleDropper, which draws the circle when something dragged from the form and dropped into AutoCAD editor:

    1 using System.Windows.Forms;
    2 using Autodesk.AutoCAD.ApplicationServices;
    3 using Autodesk.AutoCAD.DatabaseServices;
    4 using Autodesk.AutoCAD.EditorInput;
    5 using Autodesk.AutoCAD.Geometry;
    6 using Autodesk.AutoCAD.Windows;
    7 
    8 namespace DragDropIntoAcad
    9 {
   10     public static class CircleDropper
   11     {
   12         public static void DragDropCircle(
   13             System.Windows.Forms.Control ctl, double radius)
   14         {
   15             //Complete Drag & Drop operation, which mainly for getting
   16             //a point indicating where the dropping occurs
   17             CircleDropTarget dropTarget = new CircleDropTarget();
   18             Autodesk.AutoCAD.ApplicationServices.Application.
   19                     DoDragDrop(ctl, radius, DragDropEffects.Copy, dropTarget);
   20 
   21             Document dwg=Autodesk.AutoCAD.ApplicationServices.
   22                 Application.DocumentManager.MdiActiveDocument;
   23             Editor ed=dwg.Editor;
   24 
   25             Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView();
   26 
   27             //Create a circle. and then start an EntityJig to give user
   28             //a chance to accurately position the circle, or change
   29             //the circle's radius, or even cancel the operation
   30             using (dwg.LockDocument())
   31             {
   32                 using (Circle c = new Circle())
   33                 {
   34                     c.Radius = radius;
   35 
   36                     //Set circle's centre at location where mouse drag-drops at
   37                     c.Center = dropTarget.DropPoint;
   38 
   39                     CircleJig jig = new CircleJig(ed, c);
   40                     if (jig.Drag())
   41                     {
   42                         //Add the circle into drawing database
   43                         using (Transaction tran =
   44                             dwg.TransactionManager.StartTransaction())
   45                         {
   46                             BlockTableRecord space = (BlockTableRecord)
   47                                 tran.GetObject(dwg.Database.CurrentSpaceId,
   48                                 OpenMode.ForWrite);
   49 
   50                             space.AppendEntity(c);
   51                             tran.AddNewlyCreatedDBObject(c, true);
   52 
   53                             tran.Commit();
   54                         }
   55                     }
   56                 }
   57             }
   58 
   59             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
   60         }
   61     }
   62 
   63     public class CircleDropTarget : DropTarget
   64     {
   65         private Point3d _dropPoint = Point3d.Origin;
   66 
   67         public Point3d DropPoint
   68         {
   69             get { return _dropPoint; }
   70         }
   71 
   72         public override void OnDrop(System.Windows.Forms.DragEventArgs e)
   73         {
   74             //Convert windows location of mouse into AutoCAD editor's
   75             //WCS coordinate (Point3d)
   76             Document dwg = Autodesk.AutoCAD.ApplicationServices.
   77                 Application.DocumentManager.MdiActiveDocument;
   78 
   79             System.Drawing.Point pt = new System.Drawing.Point(e.X, e.Y);
   80             _dropPoint = dwg.Editor.PointToWorld(pt);
   81         }
   82     }
   83 
   84     public class CircleJig : EntityJig
   85     {
   86         private enum DragFor
   87         {
   88             Location=0,
   89             Radius=1,
   90         }
   91 
   92         private Editor _ed;
   93         private DragFor _dragFor = DragFor.Location;
   94         private Point3d _basePoint;
   95 
   96         private Point3d _currCentre;
   97         private double _currRadius;
   98         private Circle _circle;
   99 
  100         public CircleJig(Editor ed, Circle circle):base(circle)
  101         {
  102             _ed = ed;
  103             _circle = (Circle)this.Entity;
  104 
  105             _basePoint = _circle.Center;
  106         }
  107 
  108         public bool Drag()
  109         {
  110             while (true)
  111             {
  112                 _basePoint = _circle.Center;
  113 
  114                 _currCentre = _circle.Center;
  115                 _currRadius = _circle.Radius;
  116 
  117                 PromptResult res = _ed.Drag(this);
  118                 if (res.Status == PromptStatus.OK)
  119                 {
  120                     return true;
  121                 }
  122                 else if (res.Status == PromptStatus.Keyword)
  123                 {
  124                     switch(res.StringResult.ToUpper())
  125                     {
  126                         case "LOCATION":
  127                             _dragFor = DragFor.Location;
  128                             break;
  129                         case "RADIUS":
  130                             _dragFor = DragFor.Radius;
  131                             break;
  132                         default:
  133                             return false;
  134                     }
  135                 }
  136                 else
  137                 {
  138                     return false;
  139                 }
  140             }
  141         }
  142 
  143         protected override bool Update()
  144         {
  145             return true;
  146         }
  147 
  148         protected override SamplerStatus Sampler(JigPrompts prompts)
  149         {
  150             SamplerStatus status;
  151 
  152             switch (_dragFor)
  153             {
  154                 case DragFor.Location:
  155                     status = CircleLocationSampler(prompts);
  156                     break;
  157                 case DragFor.Radius:
  158                     status = CircleRadiusSampler(prompts);
  159                     break;
  160                 default:
  161                     status = SamplerStatus.NoChange;
  162                     break;
  163             }
  164 
  165             return status;
  166         }
  167 
  168         protected SamplerStatus CircleLocationSampler(JigPrompts prompts)
  169         {
  170             SamplerStatus status = SamplerStatus.NoChange;
  171 
  172             JigPromptPointOptions opt = new JigPromptPointOptions(
  173                 "\nPick circle centre point:");
  174             opt.AppendKeywordsToMessage = true;
  175             opt.UseBasePoint = true;
  176             opt.BasePoint = _basePoint;
  177             opt.Cursor = CursorType.RubberBand;
  178             opt.UserInputControls = UserInputControls.NullResponseAccepted;
  179             opt.Keywords.Add("Radius");
  180             opt.Keywords.Add("Cancel");
  181             opt.Keywords.Default = "Cancel";
  182 
  183             PromptPointResult res = prompts.AcquirePoint(opt);
  184             if (res.Status == PromptStatus.OK)
  185             {
  186                 _currCentre = res.Value;
  187                 if (_currCentre != _circle.Center)
  188                 {
  189                     ChangeCircleLocation();
  190                     status = SamplerStatus.OK;
  191                 }
  192             }
  193             else
  194             {
  195                 status = SamplerStatus.Cancel;
  196             }
  197 
  198             return status;
  199         }
  200 
  201         protected SamplerStatus CircleRadiusSampler(JigPrompts prompts)
  202         {
  203             SamplerStatus status = SamplerStatus.NoChange;
  204 
  205             JigPromptDistanceOptions opt = new JigPromptDistanceOptions(
  206                 "\nPick/enter circle radius:");
  207             opt.AppendKeywordsToMessage = true;
  208             opt.UseBasePoint = true;
  209             opt.BasePoint = _basePoint;
  210             opt.Cursor = CursorType.RubberBand;
  211             opt.UserInputControls =
  212                 UserInputControls.NullResponseAccepted |
  213                 UserInputControls.NoZeroResponseAccepted |
  214                 UserInputControls.NoNegativeResponseAccepted;
  215             opt.Keywords.Add("Location");
  216             opt.Keywords.Add("Cancel");
  217             opt.Keywords.Default = "Cancel";
  218 
  219             PromptDoubleResult res = prompts.AcquireDistance(opt);
  220             if (res.Status == PromptStatus.OK)
  221             {
  222                 _currRadius = res.Value;
  223                 if (_currRadius != _circle.Radius)
  224                 {
  225                     ChangeCircleRadius();
  226                     status = SamplerStatus.OK;
  227                 }
  228             }
  229             else
  230             {
  231                 status = SamplerStatus.Cancel;
  232             }
  233 
  234             return status;
  235         }
  236 
  237         private void ChangeCircleLocation()
  238         {
  239             Matrix3d mt = Matrix3d.Displacement(
  240                 _circle.Center.GetVectorTo(_currCentre));
  241             _circle.TransformBy(mt);
  242         }
  243 
  244         private void ChangeCircleRadius()
  245         {
  246             _circle.Radius = _currRadius;
  247         }
  248     }
  249 }

From the code we can see, Autodesk.AutoCAD.ApplicationServices.Application.DoDragDrop() is the key method that gets some information on what and where something is dropped into AutoCAD, which needs an argument of Autodesk.AutoCAD.Windows.DropTarget type. Since DropTarget is an abstract class, we must derive our own custom DropTarget class, hence the CircleDropTarget class here.

In most cases, only OnDrop() method in the DropTarget class is needed to be overridden, and the primary goal of that method is to obtain a point where the dropping occurs. While it is doable that in this method we add code to let AutoCAD actually draw what we want (circle, in my case), it is desired to separate entity generating code from this OnDrop() method, as my code shows.

It is also obvious that when dragging something into AutoCAD, the mouse cursor location is not ideal to accurate drafting/CAD operation. It would be good practice that once the mouse cursor is dragged into AutoCAD and dropped, user is asked to select a point in standard AutoCAD manner, better yet, user is given a sort of Jig to dynamically pick or enter accurate location, and the change for other possible operation options, including cancelling the Drag & Drop operation. All AutoCAD users know when a drawing file is dragged from Windows Explorer and dropped into AutoCAD starts "INSERT" command with a block inserting jig. This the reason of my code using an EntityJig after Drag & Drop.

OK, here is the last piece of code that runs the code:

    1 using Autodesk.AutoCAD.ApplicationServices;
    2 using Autodesk.AutoCAD.EditorInput;
    3 using Autodesk.AutoCAD.Runtime;
    4 
    5 [assembly: CommandClass(typeof(DragDropIntoAcad.MyCommands))]
    6 
    7 namespace DragDropIntoAcad
    8 {
    9     public class MyCommands
   10     {
   11         private static dlgCircle dlg=null;
   12 
   13         [CommandMethod("DragDrop")]
   14         public static void RunMyCommand()
   15         {
   16             Document dwg = Application.DocumentManager.MdiActiveDocument;
   17             Editor ed = dwg.Editor;
   18 
   19             if (dlg == null)
   20             {
   21                 dlg = new dlgCircle();
   22             }
   23 
   24             Application.ShowModelessDialog(dlg);
   25 
   26             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
   27         }
   28     }
   29 }

As usual, this video clip shows how the code works.

Personally, I do not there is much difference between dragging something from a form/tool palette into AutoCAD and clicking a ribbon/menu/toolbar item in terms of creating new entity. But, hey, if you use it properly in your custom application, your user may like it.

Friday, April 12, 2013

How to Get Current View Size

Sometimes one could run into question that you are sure you knew the answer and had dealt with it before, but just could not get it off your head right away.

A few days ago when I update an existing CAD application, I was asked to select certain entities visible in current view, be them in modelspace layout or paperspace layout, or in a active viewport of paperspace layout. I thought, "OK, I can get the size of current view and then select everything in a window that is the size of the current view (or slightly smaller than the view size). Then I went on searching Object Browser in Visual Studio for View, Viewport, ViewTableRecord, ViewportTableRecord... to see how I can easily get the size of current view in AutoCAD.

Well, it turned out that it would be unnecessarily complicated if I tried to use these classes for this task and luckily I recalled in my old VBA code I used AutoCAD system variables for similar work: VIEWSIZE and VIEWCTR.

System variable VIEWCTR provides a Point3d value as current view's centre point, while VIEWSIZE is the height of current view, measured in drawing unit. The problem left is how to know the width of current view? Again, another system variable SCREENSIZE comes to rescue: it provides the current viewport's size, but in PIXELs. Here what the unit of the size from SCREENSIZE is does not matter, we can use the ratio of width-height to calculate the current view's width in drawing unit from its height, like this:

view_width=view_height * (screen_width/screen_height)

The other thing to be careful is that the view's centre from VIEWCTR is in UCS coordinate.

Here is the code to get current view's size and its extents:

    1 using Autodesk.AutoCAD.ApplicationServices;
    2 using Autodesk.AutoCAD.DatabaseServices;
    3 using Autodesk.AutoCAD.Geometry;
    4 
    5 namespace GetViewSize
    6 {
    7     public class ViewUtil
    8     {
    9         private Document _dwg;
   10 
   11         public ViewUtil(Document dwg)
   12         {
   13             _dwg = dwg;
   14         }
   15 
   16         public Point2d GetCurrentViewSize()
   17         {
   18             //Get current view height
   19             double h = (double)Application.GetSystemVariable("VIEWSIZE");
   20 
   21             //Get current view width,
   22             //by calculate current view's width-height ratio
   23             Point2d screen = (Point2d)Application.GetSystemVariable("SCREENSIZE");
   24             double w = h * (screen.X / screen.Y);
   25 
   26             return new Point2d(w, h);
   27         }
   28 
   29         public Extents2d GetCurrentViewBound(
   30             double shrinkScale=1.0, bool drawBoundBox=false)
   31         {
   32             //Get current view size
   33             Point2d vSize = GetCurrentViewSize();
   34 
   35             double w = vSize.X * shrinkScale;
   36             double h = vSize.Y * shrinkScale;
   37 
   38 
   39             //Get current view's centre.
   40             //Note, the centre point from VIEWCTR is in UCS and
   41             //need to be transformed back to World CS
   42             Point3d cent = ((Point3d)Application.GetSystemVariable("VIEWCTR")).
   43                 TransformBy(_dwg.Editor.CurrentUserCoordinateSystem);
   44 
   45             Point2d minPoint = new Point2d(cent.X - w / 2.0, cent.Y - h / 2.0);
   46             Point2d maxPoint = new Point2d(cent.X + w / 2.0, cent.Y + h / 2.0);
   47 
   48             if (drawBoundBox)
   49             {
   50                 DrawBoundBox(minPoint, maxPoint);
   51             }
   52 
   53             return new Extents2d(minPoint, maxPoint);
   54         }
   55 
   56         private void DrawBoundBox(Point2d minPoint, Point2d maxPoint)
   57         {
   58             using (Transaction tran = _dwg.TransactionManager.StartTransaction())
   59             {
   60                 //Get current space
   61                 BlockTableRecord space = (BlockTableRecord)tran.GetObject(
   62                     _dwg.Database.CurrentSpaceId, OpenMode.ForWrite);
   63 
   64                 //Create a polyline as bounding box
   65                 Polyline pl = new Polyline(4);
   66 
   67                 pl.AddVertexAt(0, minPoint, 0.0, 0.0, 0.0);
   68                 pl.AddVertexAt(1, new Point2d(minPoint.X, maxPoint.Y), 0.0, 0.0, 0.0);
   69                 pl.AddVertexAt(2, maxPoint, 0.0, 0.0, 0.0);
   70                 pl.AddVertexAt(3, new Point2d(maxPoint.X, minPoint.Y), 0.0, 0.0, 0.0);
   71                 pl.Closed = true;
   72 
   73                 pl.SetDatabaseDefaults(_dwg.Database);
   74 
   75                 space.AppendEntity(pl);
   76                 tran.AddNewlyCreatedDBObject(pl, true);
   77 
   78                 tran.Commit();
   79             }
   80         }
   81     }
   82 }

In the GetCurrentViewBound() method, the optional argument "shrinkScale" is used for getting a slight smaller bound than the view is (or slightly larger, if it is greater than 1.0). The second optional argument is mostly for debugging purpose: if set to "true", a polyline would be drawn as the bounding box of the current view.

Here is the command class to run the code:

    1 using Autodesk.AutoCAD.ApplicationServices;
    2 using Autodesk.AutoCAD.EditorInput;
    3 using Autodesk.AutoCAD.Geometry;
    4 using Autodesk.AutoCAD.Runtime;
    5 
    6 [assembly: CommandClass(typeof(GetViewSize.MyCommands))]
    7 
    8 namespace GetViewSize
    9 {
   10     public class MyCommands
   11     {
   12         [CommandMethod("GetViewSize")]
   13         public static void RunMyCommand()
   14         {
   15             Document dwg = Application.DocumentManager.MdiActiveDocument;
   16             Editor ed = dwg.Editor;
   17 
   18             ViewUtil util = new ViewUtil(dwg);
   19 
   20             try
   21             {
   22                 //Get current view size
   23                 Point2d vSize = util.GetCurrentViewSize();
   24                 ed.WriteMessage("\nCurrent view size: " +
   25                     "H={0} W={1}", vSize.Y, vSize.X);
   26 
   27                 //Draw a bound box of current view, which
   28                 //is slightly smaller than current view
   29                 util.GetCurrentViewBound(0.95, true);
   30 
   31                 //Draw a bound box of current view, which
   32                 //is exactly the same size as current view
   33                 util.GetCurrentViewBound(1.0, true);
   34             }
   35             catch (System.Exception ex)
   36             {
   37                 ed.WriteMessage("\nError: {0}", ex.ToString());
   38             }
   39 
   40             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
   41         }
   42     }
   43 }
 
 The code can be used to get current view's size. When in tiled multi-viewport modelspace, the view is the view in active viewport. When in paperspace layout, if there is no paperspace viewport active (after command "PS"), the view is the view of paperspace, while if there is a paperspace viewport active (after command "MS"), the view is the modelspace view seeing through the paperspace viewport.

Well, with paperspace viewport, one can use the size of the viewport and transform to size in modelspace in order to get the model view size seeing through the paperspace viewport. If the paperspace viewport has non-rectangular border, then the simple approach to get a rectangular view size shown in this article would be problematic (when the purpose is to selecting all entities visible in the view/viewport.

 

Followers

About Me

My photo
After graduating from university, I worked as civil engineer for more than 10 years. It was AutoCAD use that led me to the path of computer programming. Although I now do more generic business software development, such as enterprise system, timesheet, billing, web services..., AutoCAD related programming is always interesting me and I still get AutoCAD programming tasks assigned to me from time to time. So, AutoCAD goes, I go.