Saturday, July 26, 2014

Open A Viewport From ModelSpace - Take 2

In one of my previous post - Open A Viewport From ModelSpace - I wrote some code to allow user to open a Viewport based on the entities user selected. In that project, user simply focus in ModelSpace to select what he/she want to see in the a Viewport in PaperSpace, and determine the Viewport twist angle and ModelToPaper scale. Then the code will open a minimum Viewport in specified layout.

After posting that article, I thought doing thing from the other way around would also be interesting and, maybe, also quite useful. Imagine this situation: I want to open a Viewport in a layout; because of the limited space in the layout, I can only open the Viewport in the layout with certain size (width and height) and can only place it at where I selected; then I want to easily adjust the model view target, ModelToPaper scale and twist angle; for the scale, I want to choose a scale from a list predefined scales so that the see-able model view in the Viewport would fit the Viewport the best.

Based on these requirements, I decided that the work flow would be:
  • User pick a window in selected layout as desired Viewport
  • The code switch AutoCAD to ModelSpace view
  • Showing a Viewport boundary with TransientGraphic in ModelSpace view
  • User then manipulate the Viewport boundary (moving, rotating and scaling) so that the Viewport boundary would be fit to the ModelSpace drawing content to be shown in the Viewport the best
  • Once the user satisfied with the Viewport boundary, its twist angle, view target center and ModelToPaper scale would be used to update the Viewport in layout.
This time, before see the code of how this being done, I'd like my reader to see this video clip for the project's action.

Firstly, here is a helper class CadHelper with a few static methods defined:

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;
 
namespace OpenViewPort
{
 public class CadHelper
 {
  // Sellect a layout to open the viewport
  public static string SelectViewportLayout(Document dwg)
  {
   string layout = null;
 
   while (true)
   {
    PromptStringOptions opt = new PromptStringOptions(
     "\nEnter the name of a layout " +
     "where the viewport will be open:");
    opt.AllowSpaces = true;
    PromptResult res = dwg.Editor.GetString(opt);
    if (res.Status==PromptStatus.OK)
    {
     if (IsValidLayoutName(dwg, res.StringResult))
     {
      layout = res.StringResult;
      break;
     }
     else
     {
      dwg.Editor.WriteMessage(
       "\nNot a valid layout name!");
     }
    }
    else
    {
     break;
    }
   }
 
   return layout;
  }
 
  // Open a viewport based on a corners selected by user
  // Its view target is set to the center of drawing's extents
  public static ObjectId OpenViewport(
   Document dwg,
   string layoutName, Point3d corner1, Point3d corner2,
   double defaultCustomScale, string defaultCustomScaleString,
   string layerName = null)
  {
   ObjectId vportId = ObjectId.Null;
 
   double width = Math.Abs(corner1.X - corner2.X);
   double height = Math.Abs(corner1.Y - corner2.Y);
   double dist = corner1.DistanceTo(corner2);
   Point3d centre;
   using (Line line = new Line(corner1, corner2))
   {
    centre = line.GetPointAtDist(dist / 2.0);
   }
 
   using (Transaction tran = 
    dwg.TransactionManager.StartTransaction())
   {
    BlockTableRecord layoutBlock =
     GetLayoutBlock(tran, dwg.Database, layoutName);
 
    Viewport vport = new Viewport();
 
    vport.Width = width;
    vport.Height = height;
    vport.CenterPoint = centre;
    if (!string.IsNullOrEmpty(layerName))
    {
     try
     {
      vport.Layer = layerName;
     }
     catch { }
    }
 
    layoutBlock.UpgradeOpen();
    vportId = layoutBlock.AppendEntity(vport);
    tran.AddNewlyCreatedDBObject(vport, true);
 
    vport.On = true;
    vport.ViewDirection = Vector3d.ZAxis;
    vport.ViewCenter = Point2d.Origin;
    vport.ViewTarget = GetModelViewCenterPoint(dwg.Database);
    vport.TwistAngle = 0.0;
    vport.CustomScale = defaultCustomScale;
    vport.Locked = true;
 
    vport.UpdateDisplay();
 
    tran.Commit();
   }
 
   return vportId;
  }
 
  // Create a polyline as drawablw for TransientGraphics
  // respresenting the viewport boundary in ModelSpace
  // user would move/rotate/scale this viewport boundary
  // to best fit the ModelSpace content to be seen in 
  // the viewport
  public static Polyline GetViewportBoundaryInModel(
   ObjectId vportId, double vportCustomScale, int colorIndex = 2)
  {
   Matrix3d paperToModel;
   Point3d centerPoint;
   double width;
   double height;
 
   using (Transaction tran = 
    vportId.Database.TransactionManager.StartTransaction())
   {
    Viewport vport = (Viewport)
     tran.GetObject(vportId, OpenMode.ForRead);
 
    centerPoint = vport.CenterPoint;
    width = vport.Width;
    height = vport.Height;
 
    if (Math.Abs(vport.CustomScale - vportCustomScale) > 
     Tolerance.Global.EqualVector)
    {
     vport.UpgradeOpen();
     vport.CustomScale = vportCustomScale;
    }
 
    paperToModel = CadHelper.PaperToModel(vport);
 
    tran.Commit();
   }
 
   Point3d pt;
 
   Polyline pl = new Polyline(4);
 
   pt = new Point3d(
    centerPoint.X - 0.5 * width,
    centerPoint.Y - 0.5 * height, 0.0).TransformBy(paperToModel);
   pl.AddVertexAt(0, new Point2d(pt.X, pt.Y), 0.0, 0.0, 0.0);
 
   pt = new Point3d(
    centerPoint.X + 0.5 * width,
    centerPoint.Y - 0.5 * height, 0.0).TransformBy(paperToModel);
   pl.AddVertexAt(1, new Point2d(pt.X, pt.Y), 0.0, 0.0, 0.0);
 
   pt = new Point3d(
    centerPoint.X + 0.5 * width,
    centerPoint.Y + 0.5 * height, 0.0).TransformBy(paperToModel);
   pl.AddVertexAt(2, new Point2d(pt.X, pt.Y), 0.0, 0.0, 0.0);
 
   pt = new Point3d(
    centerPoint.X - 0.5 * width,
    centerPoint.Y + 0.5 * height, 0.0).TransformBy(paperToModel);
   pl.AddVertexAt(3, new Point2d(pt.X, pt.Y), 0.0, 0.0, 0.0);
 
   pl.ColorIndex = colorIndex;
   pl.Closed = true;
 
   return pl;
  }
 
  #region private methods
 
  private static string[] GetAllLayouts(Document dwg)
  {
   List<string> names = new List<string>();
 
   using (Transaction tran = 
    dwg.TransactionManager.StartTransaction())
   {
    DBDictionary dic = (DBDictionary)tran.GetObject(
     dwg.Database.LayoutDictionaryId, OpenMode.ForRead);
 
    foreach (DBDictionaryEntry entry in dic)
    {
     Layout l = (Layout)tran.GetObject(
      entry.Value, OpenMode.ForRead);
 
     names.Add(l.LayoutName);
    }
 
    tran.Commit();
   }
 
   return (from n in names orderby n ascending select n).ToArray();
  }
 
  private static bool IsValidLayoutName(Document dwg, string layout)
  {
   string[] names = GetAllLayouts(dwg);
   foreach (var name in names)
   {
    if (name.ToUpper() == layout.ToUpper()) return true;
   }
 
   return false;
  }
 
  private static BlockTableRecord GetLayoutBlock(
   Transaction tran, Database db, string layoutName)
  {
   LayoutManager lmanager = LayoutManager.Current;
   ObjectId layId = lmanager.GetLayoutId(layoutName);
 
   Layout layout = tran.GetObject(layId, OpenMode.ForRead) as Layout;
 
   return tran.GetObject(
    layout.BlockTableRecordId, OpenMode.ForRead)
    as BlockTableRecord;
  }
 
  private static Point3d GetModelViewCenterPoint(Database db)
  {
   Point3d pMax = db.Extmax;
   Point3d pMin = db.Extmin;
   Point3d center;
   using (Line line = new Line(pMin, pMax))
   {
    center = line.GetPointAtDist(pMin.DistanceTo(pMax) / 2.0);
   }
 
   return center;
  }
 
  #endregion
 
  #region code borrowed from www.theswamp.org
  //**********************************************************************
  //Create coordinate transform matrix 
  //between modelspace and paperspace viewport
 
  //The code is borrowed from
  //http://www.theswamp.org/index.php?topic=34590.msg398539#msg398539
  //*********************************************************************
  public static Matrix3d PaperToModel(Viewport vp)
  {
   Matrix3d mx = ModelToPaper(vp);
   return mx.Inverse();
  }
 
  public static Matrix3d ModelToPaper(Viewport vp)
  {
   Vector3d vd = vp.ViewDirection;
   Point3d vc = new Point3d(vp.ViewCenter.X, vp.ViewCenter.Y, 0);
   Point3d vt = vp.ViewTarget;
   Point3d cp = vp.CenterPoint;
   double ta = -vp.TwistAngle;
   double vh = vp.ViewHeight;
   double height = vp.Height;
   double width = vp.Width;
   double scale = vh / height;
   double lensLength = vp.LensLength;
   Vector3d zaxis = vd.GetNormal();
   Vector3d xaxis = Vector3d.ZAxis.CrossProduct(vd);
   Vector3d yaxis;
 
   if (!xaxis.IsZeroLength())
   {
    xaxis = xaxis.GetNormal();
    yaxis = zaxis.CrossProduct(xaxis);
   }
   else if (zaxis.Z < 0)
   {
    xaxis = Vector3d.XAxis * -1;
    yaxis = Vector3d.YAxis;
    zaxis = Vector3d.ZAxis * -1;
   }
   else
   {
    xaxis = Vector3d.XAxis;
    yaxis = Vector3d.YAxis;
    zaxis = Vector3d.ZAxis;
   }
   Matrix3d pcsToDCS = Matrix3d.Displacement(Point3d.Origin - cp);
   pcsToDCS = pcsToDCS * Matrix3d.Scaling(scale, cp);
   Matrix3d dcsToWcs = Matrix3d.Displacement(vc - Point3d.Origin);
   Matrix3d mxCoords = Matrix3d.AlignCoordinateSystem(
    Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis,
    Vector3d.ZAxis, Point3d.Origin,
    xaxis, yaxis, zaxis);
   dcsToWcs = mxCoords * dcsToWcs;
   dcsToWcs = Matrix3d.Displacement(vt - Point3d.Origin) * dcsToWcs;
   dcsToWcs = Matrix3d.Rotation(ta, zaxis, vt) * dcsToWcs;
 
   Matrix3d perspectiveMx = Matrix3d.Identity;
   if (vp.PerspectiveOn)
   {
    double vSize = vh;
    double aspectRatio = width / height;
    double adjustFactor = 1.0 / 42.0;
    double adjstLenLgth = vSize * lensLength *
     Math.Sqrt(1.0 + aspectRatio * aspectRatio) * adjustFactor;
    double iDist = vd.Length;
    double lensDist = iDist - adjstLenLgth;
    double[] dataAry = new double[] 
     {   
      1,0,0,0,0,1,0,0,0,0,
      (adjstLenLgth-lensDist)/adjstLenLgth,
      lensDist*(iDist-adjstLenLgth)/adjstLenLgth,
      0,0,-1.0/adjstLenLgth,iDist/adjstLenLgth
     };
 
    perspectiveMx = new Matrix3d(dataAry);
   }
 
   Matrix3d finalMx =
    pcsToDCS.Inverse() * perspectiveMx * dcsToWcs.Inverse();
 
   return finalMx;
  }
 
  #endregion
 }
 
 public static class MyExtension
 {
  public static Point3d GetCenterPoint(this Polyline pline)
  {
   double x = 0.0;
   double y = 0.0;
   for (int i = 0; i < pline.NumberOfVertices; i++)
   {
    Point2d p = pline.GetPoint2dAt(i);
    x += p.X;
    y += p.Y;
   }
 
   x = x / Convert.ToDouble(pline.NumberOfVertices);
   y = y / Convert.ToDouble(pline.NumberOfVertices);
 
   return new Point3d(x, y, 0.0);
  }
 
  public static void MoveTo(
   this Polyline pline, Point3d newCenterPoint)
  {
   Point3d center = pline.GetCenterPoint();
   Matrix3d mt = Matrix3d.Displacement(
    center.GetVectorTo(newCenterPoint));
   pline.TransformBy(mt);
  }
 }
}

Then comes the main working class ViewportOpener, which does 3 things: opening a Viewport in selected layout; letting user to manipulate a TransientGraphic rectangle in ModelSpace, which representing the Viewport, to best fit the ModelSpace content into the Viewport window; and finally update the Viewport (its ViewTarget, CustomScale and TwistAngle properties) according to user's inputs. Here is the code:

using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
 
namespace OpenViewPort
{
    public class ViewportOpener
    {
        private Document _dwg;
        private Editor _ed;
        private string _layoutName = null;
        private string _layerName = null;
        private const double DEFAULT_SCALE = 0.2;
        private const string DEFAULT_SCALE_STRING = "1/5";
 
        public ViewportOpener()
        {
            
        }
 
        public bool OpenViewport(Document dwg, 
            string layoutName = nullstring layerName=null)
        {
            _dwg = dwg;
            _ed = dwg.Editor;
 
            _layerName = layerName;
 
            //Open Viewport in layout
            if (!GetLayoutName(layoutName)) return false;
            LayoutManager.Current.CurrentLayout = _layoutName;
            ObjectId vportId = CreateViewport();
            
            //Manipulate viewport boundary in ModelSpace
            bool success=true;
            using (ViewportSetter setter=
                new ViewportSetter(_dwg, vportId, 
                    DEFAULT_SCALE, DEFAULT_SCALE_STRING))
            {
                if (setter.SetViewport())
                {
                    //Update viewport in layout
                    UpdateViewport(
                        vportId,
                        setter.ViewTargetPoint, 
                        setter.TwistAngle, 
                        setter.Scale);
                }
                else
                {
                    success = false;
                }
            }
 
            return success;
        }
 
        #region private methods: misc
 
        private bool GetLayoutName(string layoutName)
        {
            _layoutName = null;
            if (string.IsNullOrEmpty(layoutName))
            {
                _layoutName = CadHelper.SelectViewportLayout(_dwg);
            }
            else
            {
                _layoutName = layoutName;
            }
 
            return !string.IsNullOrEmpty(_layoutName);
        }
 
        #endregion
 
        #region private methods: create/update viewport in layout
 
        private ObjectId CreateViewport()
        {
            ObjectId vportId = ObjectId.Null;
 
            Point3d pt1;
            Point3d pt2;
 
            LayoutManager.Current.CurrentLayout = _layoutName;
 
            PromptPointOptions pOpt = new PromptPointOptions(
                "\nSelect a corner point of the new viewport:");
            PromptPointResult pres = _ed.GetPoint(pOpt);
            if (pres.Status==PromptStatus.OK)
            {
                pt1 = pres.Value;
 
                PromptCornerOptions cOpt = new PromptCornerOptions(
                    "\nSelect the opposite corner of the viewport:", pt1);
                pres = _ed.GetCorner(cOpt);
                if (pres.Status==PromptStatus.OK)
                {
                    pt2 = pres.Value;
 
                    vportId = CreateViewport(pt1, pt2);
                }
            }
 
            return vportId;
        }
 
        private ObjectId CreateViewport(
            Point3d corner1, Point3d corner2)
        {
            return CadHelper.OpenViewport(
                _dwg, _layoutName, corner1, corner2, 
                DEFAULT_SCALE, DEFAULT_SCALE_STRING);
        }
 
        private void UpdateViewport(
            ObjectId vportId, Point3d modelTarget, 
            double twistAngle, double customScale)
        {
            LayoutManager.Current.CurrentLayout = _layoutName;
 
            using (Transaction tran=_dwg.TransactionManager.StartTransaction())
            {
                Viewport vport = (Viewport)
                    tran.GetObject(vportId, OpenMode.ForWrite);
 
                vport.Locked = false;
                vport.CustomScale = customScale;
                vport.TwistAngle = Math.PI * 2 - twistAngle;
                vport.ViewTarget = modelTarget;
                vport.Locked = true;
 
                vport.UpdateDisplay();
 
                tran.Commit();
            }
        }
 
        #endregion
    }
}

Because manipulating the TransientGraphic rectangle, representing Viewport boundary in ModelSpace, is where the complexity of this project is, I place this process in its own class ViewportSetter:

using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.GraphicsInterface;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
 
namespace OpenViewPort
{
    public class ViewportSetter : IDisposable 
    {
        private Document _dwg;
        private Editor _ed;
        private TransientManager _tsManager;
        private ObjectId _viewportId;
 
        private Point3d _target;
        private double _twist = 0.0;
        private double _scale;
        private string _scaleString = "";
 
        private Point3d _origTarget;
        private double _origTwist;
        private double _origScale;
 
        private CadDb.Polyline _polyline = null;
        private Drawable _ghost = null;
        private double _curGhostAngle = 0.00;
 
        public ViewportSetter(
            Document dwg, ObjectId viewportId,
            double startScale, string startScaleString)
        {
            _dwg = dwg;
            _ed = dwg.Editor;
            _tsManager = TransientManager.CurrentTransientManager;
            _viewportId = viewportId;
 
            _scale = startScale;
            _scaleString = startScaleString;
        }
 
        public Point3d ViewTargetPoint
        {
            get { return _target; }
        }
 
        public double Scale
        {
            get { return _scale; }
        }
 
        public double TwistAngle
        {
            get { return _twist; }
        }
        public void Dispose()
        {
            CleanUp();
        }
 
        public bool SetViewport()
        {
            LayoutManager.Current.CurrentLayout = "Model";
 
            _origTarget = _target;
            _origTwist = _twist;
            _origScale = _scale;
 
            bool cancelled = false;
            bool done = false;
 
            try
            {
                //Pick vier target center
                if (!PickViewTargetPoint(out _target)) return false;
 
                _polyline = 
                    CadHelper.GetViewportBoundaryInModel(
                    _viewportId, _scale, 2);
 
                _polyline.MoveTo(_target);
 
                //Zoom to the polyline viewport boundary
                ZoomTo(_polyline);
 
                ShowBoundaryPolyline();
 
                string keyword = "Move";
 
                while (true)
                {
                    PromptKeywordOptions kopt = new PromptKeywordOptions(
                        "\nSelect option:");
                    kopt.Keywords.Add("Move");
                    kopt.Keywords.Add("Align");
                    kopt.Keywords.Add("Rotate");
                    kopt.Keywords.Add("Scale");
                    kopt.Keywords.Add("Done");
                    kopt.Keywords.Add("Cancel");
                    kopt.Keywords.Default = keyword;
                    kopt.AppendKeywordsToMessage = true;
                    kopt.AllowArbitraryInput = false;
 
                    PromptResult res = _ed.GetKeywords(kopt);
                    if (res.Status == PromptStatus.OK)
                    {
                        keyword = res.StringResult;
                        switch (res.StringResult)
                        {
                            case "Move":
                                MoveBoundary();
                                break;
                            case "Align":
                                AlignBoundary();
                                break;
                            case "Rotate":
                                RotateBoundary();
                                break;
                            case "Scale":
                                ScaleBoundary();
                                break;
                            case "Cancel":
                                cancelled = true;
                                break;
                            default:
                                done = true;
                                break;
                        }
                    }
                    else
                    {
                        break;
                    }
 
                    if (done || cancelled) break;
                }   
            }
            finally
            {
                if (!done)
                {
                    if (_target!=_origTarget ||
                        _scale!=_origScale ||
                        _twist!=_origTwist)
                    {
 
                    }
                }
            }
 
            return done;
        }
 
        #region private methods: misc
 
        private bool PickViewTargetPoint(out Point3d target)
        {
            target = new Point3d();
 
            PromptPointOptions opt = new PromptPointOptions(
                "\nSelect viewport targeting center point:");
            opt.AllowNone = false;
            PromptPointResult res = _ed.GetPoint(opt);
            if (res.Status == PromptStatus.OK)
            {
                target = res.Value;
                return true;
            }
            else
            {
                return false;
            }
        }
 
        #endregion
 
        #region private methods: show/clear visual
 
        private void ShowBoundaryPolyline()
        {
            if (_polyline!=null)
            {
                _tsManager.EraseTransient(
                    _polyline, new IntegerCollection());
            }
 
            _tsManager.AddTransient(
                _polyline, 
                TransientDrawingMode.DirectTopmost, 
                128, 
                new IntegerCollection());
        }
 
        private void CleanUp()
        {
            if (_polyline!=null)
            {
                if (_polyline != null)
                {
                    _tsManager.EraseTransient(
                        _polyline, new IntegerCollection());
                }
 
                _polyline.Dispose();
            }
 
            _polyline = null;
        }
 
        private void ZoomTo(Entity ent)
        {
            Extents3d ext = ent.GeometricExtents;
 
            double l = 0.0;
            double w = Math.Abs(ext.MaxPoint.X - ext.MinPoint.X);
            double h = Math.Abs(ext.MaxPoint.Y - ext.MinPoint.Y);
            l = w > h ? w : h;
            double d = 0.2 * l;
 
            ext.AddPoint(
                new Point3d(ext.MinPoint.X - d, ext.MinPoint.Y - d, 0.0));
            ext.AddPoint(
                new Point3d(ext.MaxPoint.X + d, ext.MaxPoint.Y + d, 0.0));
 
            double[] pt1 = new double[] { 
                ext.MinPoint.X, ext.MinPoint.Y, ext.MinPoint.Z };
            double[] pt2 = new double[] { 
                ext.MaxPoint.X, ext.MaxPoint.Y, ext.MaxPoint.Z };
 
            dynamic acadApp = Application.AcadApplication;
            acadApp.ZoomWindow(pt1, pt2);
        }
 
        #endregion
 
        #region private methods: manipulate polyline viewport boundary
 
        private Point3d GetPolygonCentre(CadDb.Polyline pl)
        {
            double x = 0.0;
            double y = 0.0;
 
            for (int i=0; i<pl.NumberOfVertices; i++)
            {
                Point2d p = pl.GetPoint2dAt(i);
                x += p.X;
                y += p.Y;
            }
 
            return new Point3d(
                x / (pl.NumberOfVertices * 1.0), 
                y / (pl.NumberOfVertices * 1.0), 
                0.0);
        }
 
        private void MoveBoundary()
        {
            try
            {
                PromptPointOptions opt = new PromptPointOptions(
                    "\nMove viewport target center to:");
                opt.UseBasePoint = true;
                opt.BasePoint = _target;
                opt.UseDashedLine = true;
 
                _ghost = _polyline.Clone() as Drawable;
                _ed.PointMonitor += Move_PointMonitor;
 
                PromptPointResult res = _ed.GetPoint(opt);
                if (res.Status == PromptStatus.OK)
                {
                    _polyline.MoveTo(res.Value);
                    _target = res.Value;
 
                    ShowBoundaryPolyline();
                }
            }
            finally
            {
                if (_ghost!=null)
                {
                    _tsManager.EraseTransient(
                        _ghost, new IntegerCollection());
                    _ghost.Dispose();
                    _ghost = null;
                }
 
                _ed.PointMonitor -= Move_PointMonitor;
            }
        }
 
        private void Move_PointMonitor(object sender, PointMonitorEventArgs e)
        {
            if (_ghost!=null)
            {
                _tsManager.EraseTransient(_ghost, new IntegerCollection());
            }
 
            Point3d newPt = e.Context.RawPoint;
            Point3d oldPt = GetPolygonCentre(_ghost as CadDb.Polyline);
 
            string tip = string.Format(
                "Move to {0},{1}",
                newPt.X, newPt.Y);
 
            e.AppendToolTipText(tip);
 
            if (newPt.DistanceTo(oldPt)>Tolerance.Global.EqualPoint)
            {
                Matrix3d mt=Matrix3d.Displacement(oldPt.GetVectorTo(newPt));
                ((CadDb.Polyline)_ghost).TransformBy(mt);
            }
 
            _tsManager.AddTransient(
                _ghost, 
                TransientDrawingMode.Highlight, 
                128, 
                new IntegerCollection());
        }
        private void AlignBoundary()
        {
            PromptPointOptions opt;
            PromptPointResult res;
            Point3d pt1, pt2;
 
            opt = new PromptPointOptions(
                "\nSelect first point to align viewport twist angle:");
            res = _ed.GetPoint(opt);
            if (res.Status==PromptStatus.OK)
            {
                pt1 = res.Value;
 
                opt = new PromptPointOptions(
                    "\nSelect second point to align viewport twist angle:");
                opt.UseBasePoint = true;
                opt.BasePoint = pt1;
                opt.UseDashedLine = true;
                res = _ed.GetPoint(opt);
                if (res.Status==PromptStatus.OK)
                {
                    pt2 = res.Value;
                    AlignBoundary(pt1, pt2);
                }
            }
        }
 
        private void AlignBoundary(Point3d pt1, Point3d pt2)
        {
            double angle = 0.0;
            using (Line line=new Line(pt1,pt2))
            {
                angle = line.Angle;
            }
 
            DoRotation(angle);
        }
 
        private void RotateBoundary()
        {
            try
            {
                PromptAngleOptions opt = new PromptAngleOptions(
                    "Enter viewport twist angle:");
                opt.AllowNone = false;
                opt.BasePoint = _target;
                opt.UseBasePoint = true;
                opt.DefaultValue = _twist;
 
                _ghost = _polyline.Clone() as Drawable;
                _curGhostAngle = _twist;
                _ed.PointMonitor += Rotate_PointMonitor;
 
                PromptDoubleResult res = _ed.GetAngle(opt);
                if (res.Status == PromptStatus.OK)
                {
                    DoRotation(res.Value);
                }
            }
            finally
            {
                if (_ghost != null)
                {
                    _tsManager.EraseTransient(
                        _ghost, new IntegerCollection());
                    _ghost.Dispose();
                    _ghost = null;
                }
 
                _ed.PointMonitor -= Rotate_PointMonitor;
            }
        }
 
        private void Rotate_PointMonitor(
            object sender, PointMonitorEventArgs e)
        {
            if (_ghost != null)
            {
                _tsManager.EraseTransient(
                    _ghost, new IntegerCollection());
            }
 
            // Get angle
            Point3d newPt = e.Context.RawPoint;
            double angle = 0;
            using (CadDb.Line line=new CadDb.Line(_target,newPt))
            {
                angle = line.Angle;
            }
 
            if (Math.Abs(angle - _curGhostAngle) > 
                Tolerance.Global.EqualVector)
            {
 
                double oldAngle = Math.PI * 2 - _curGhostAngle;
 
                string ang = Converter.AngleToString(
                    angle, AngularUnitFormat.DegreesMinutesSeconds, 2);
                e.AppendToolTipText(ang);
 
                // Rotate back to 0 degree
                Matrix3d mt = Matrix3d.Rotation(
                    oldAngle, Vector3d.ZAxis, _target);
                ((Entity)_ghost).TransformBy(mt);
 
                // Rotate to angle
                mt = Matrix3d.Rotation(angle, Vector3d.ZAxis, _target);
                ((Entity)_ghost).TransformBy(mt);
 
                _curGhostAngle = angle;
            }
            
            _tsManager.AddTransient(
                _ghost, 
                TransientDrawingMode.Highlight, 
                128, 
                new IntegerCollection());
        }
 
        private void DoRotation(double angle)
        {
            // Roate to 0 degree
            Matrix3d mt = Matrix3d.Rotation(
                Math.PI - _twist, Vector3d.ZAxis, _target);
            _polyline.TransformBy(mt);
 
            // Then rotate to selected angle
            mt = Matrix3d.Rotation(angle, Vector3d.ZAxis, _target);
            _polyline.TransformBy(mt);
 
            _twist = angle;
 
            ShowBoundaryPolyline();
        }
 
        private void ScaleBoundary()
        {
            double scale;
            string scaleString;
            if (!GetScaleInput(out scale, out scaleString)) return;
 
            if (scale == _scale) return;
 
            _scale = scale;
            _scaleString = scaleString;
 
            // Remove existing polygon boundary
            if (_polyline!=null)
            {
                CleanUp();
            }
 
            // Recreate polygon boundary
            _polyline = CadHelper.GetViewportBoundaryInModel(
                _viewportId, _scale, 2);
 
            _polyline.MoveTo(_target);
 
            ShowBoundaryPolyline();
        }
 
        private bool GetScaleInput(out double scale, out string scaleString)
        {
            scale = 1.0;
            scaleString = "1/1";
 
            bool oked = false;
            using (dlgScale dlg=new dlgScale(_scaleString))
            {
                System.Windows.Forms.DialogResult res =
                    Application.ShowModalDialog(dlg);
 
                if (res==System.Windows.Forms.DialogResult.OK)
                {
                    scale = dlg.SelectedScale;
                    scaleString = dlg.ScaleString;
                    oked = true;
                }
            }
 
            return oked;
        }
 
        #endregion
    }
}

When scale ModelSpace content shown in a Viewport, while any scale (standard or custom) can be used, in drafting practice only certain scales according to drafting standard being used. So, when it comes to scale, I use a small dialog box to let user to choose a scale from a predefined scale instead of allowing user to enter whatever scale he/she likes. The dialog box looks like this:


The code behind for this dialog box is fairly simple:

using System;
using System.Windows.Forms;
 
namespace OpenViewPort
{
    public partial class dlgScale : Form
    {
        public dlgScale()
        {
            InitializeComponent();
        }
 
        public dlgScale(string scaleString) : this()
        {
            lblCurrentScale.Text = scaleString;
        }
 
        public double SelectedScale
        {
            get { return 1.0 / double.Parse(cboScale.Text); }
        }
 
        public string ScaleString
        {
            get { return "1/" + cboScale.Text; }
        }
 
        private bool ValidateCombo()
        {
            try
            {
                int val = Int32.Parse(cboScale.Text);
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        private void ShowScale()
        {
            lblScale.Text = "";
            try
            {
                double x = double.Parse(cboScale.Text);
                lblScale.Text = (1.0 / x).ToString("#0.0000");
            }
            catch { }
        }
 
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (ValidateCombo())
            {
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                btnOK.Enabled = false;
            }
        }
 
        private void cboScale_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ValidateCombo())
            {
                btnOK.Enabled = true;
                ShowScale();
                btnOK.Focus();
            }
            else
            {
                btnOK.Enabled = false;
            }
        }
 
        private void cboScale_TextChanged(object sender, EventArgs e)
        {
            if (ValidateCombo())
            {
                btnOK.Enabled = true;
                ShowScale();
                btnOK.Focus();
            }
            else
            {
                btnOK.Enabled = false;
            }          
        }
 
        private void dlgScale_Load(object sender, EventArgs e)
        {
            cboScale.SelectedIndex = 4;
            ShowScale();
        }
    }
}

Put all these together into a CommandClassViewportOpenerCmd:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
[assemblyCommandClass(typeof(OpenViewPort.ViewportOpenerCmd))]
 
namespace OpenViewPort
{
    public class ViewportOpenerCmd
    {
        private static ViewportOpener _viewOpener=null;
 
        [CommandMethod("OpenViewport")]
        public void OpenViewportFromModelSpace()
        {
            Document dwg = CadApp.DocumentManager.MdiActiveDocument;
            Editor ed = dwg.Editor;
 
            try
            {
                if (_viewOpener == null) _viewOpener = new ViewportOpener();
 
                if (!_viewOpener.OpenViewport(dwg))
                {
                    ed.WriteMessage("\n*Cancel*");
                }
                else
                {
                    ed.WriteMessage("\nCommand completed.");
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}\n{1}", 
                    ex.Message, ex.StackTrace);
            }
            finally
            {
                Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
            }
        }
    }
}

I am not an AutoCAD drafter who uses AutoCAD day-in and day-out, thus not sure that using the process of opening a Viewport I presented here is better than using AutoCAD built-in commands. This project is mainly meant to explore the programmability with AutoCAD.

Enjoy writing and reading code!

Source code can be downloaded here.






No comments:

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.