000

Index Labels

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.






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 เขียนแบบ