示例#1
0
        public static ViewportTableRecord GetViewportTblRec(Transaction trans, Document doc, OpenMode mode = OpenMode.ForRead)
        {
            ViewportTableRecord acVportTblRec = trans.GetObject(doc.Editor.ActiveViewportId,
                                                                mode) as ViewportTableRecord;

            return(acVportTblRec);
        }
        public static void SetViewportToExtents(Database db, ViewportTableRecord viewportTableRec)
        {
            try
            {
                //lets update the database extents first
                //true gives the best fit but will take time
                db.UpdateExt(false); //Does not work corectly

                //get the screen aspect ratio to calculate the height and width
                double scrRatio = (viewportTableRec.Width / viewportTableRec.Height);

                //prepare Matrix for DCS to WCS transformation
                Matrix3d matWCS2DCS = Matrix3d.PlaneToWorld(viewportTableRec.ViewDirection);

                //for DCS target point is the origin
                matWCS2DCS = Matrix3d.Displacement(viewportTableRec.Target - Point3d.Origin) * matWCS2DCS;

                //WCS Xaxis is twisted by twist angle
                matWCS2DCS = Matrix3d.Rotation(-viewportTableRec.ViewTwist,
                                               viewportTableRec.ViewDirection,
                                               viewportTableRec.Target)
                             * matWCS2DCS;

                matWCS2DCS = matWCS2DCS.Inverse();

                //tranform the extents to the DCS defined by the viewdir
                Extents3d extents = new Extents3d(db.Extmin, db.Extmax);
                extents.TransformBy(matWCS2DCS);

                //width of the extents in current view
                double width = (extents.MaxPoint.X - extents.MinPoint.X);

                //height of the extents in current view
                double height = (extents.MaxPoint.Y - extents.MinPoint.Y);

                //get the view center point
                Point2d center = new Point2d((extents.MaxPoint.X + extents.MinPoint.X) * 0.5,
                                             (extents.MaxPoint.Y + extents.MinPoint.Y) * 0.5);

                //check if the width 'fits' in current window
                //if not then get the new height as per the viewports aspect ratio
                if (width > (height * scrRatio))
                {
                    height = width / scrRatio;
                }

                viewportTableRec.Height      = height;
                viewportTableRec.Width       = height * scrRatio;
                viewportTableRec.CenterPoint = center;
            }
            catch (Exception ex)
            {
            }
        }
示例#3
0
        /// <summary>
        /// 获取当前UCS
        /// </summary>
        /// <param name="db">数据库对象</param>
        /// <returns>返回当前UCS的Id</returns>
        public static ObjectId GetCurrentUCS(this Database db)
        {
            var    trans = db.TransactionManager;
            Editor ed    = db.GetEditor();
            //打开UCS表
            UcsTable ut = (UcsTable)trans.GetObject(db.UcsTableId, OpenMode.ForRead);
            //打开当前活动的视口
            ViewportTableRecord vtr = (ViewportTableRecord)trans.GetObject(db.CurrentViewportTableRecordId(), OpenMode.ForRead);

            //返回当前UCS的ObjectId
            return(vtr.UcsName);
        }
示例#4
0
        public ViewportTableRecord getCurrentViewPort(Document document)
        {
            ViewportTableRecord viewport_tablerecord = new ViewportTableRecord();

            using (Transaction tr = document.Database.TransactionManager.StartTransaction())
            {
                ViewportTable viewport_table = tr.GetObject(document.Database.ViewportTableId, OpenMode.ForRead) as ViewportTable;
                viewport_tablerecord = tr.GetObject(viewport_table["*Active"], OpenMode.ForRead) as ViewportTableRecord;
                tr.Commit();
                return(viewport_tablerecord);
            }
        }
示例#5
0
        Stream(ArrayList data, AbstractViewTableRecord rec)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(AbstractViewTableRecord)));

            data.Add(new Snoop.Data.Point2d("Center point", rec.CenterPoint));
            data.Add(new Snoop.Data.Distance("Width", rec.Width));
            data.Add(new Snoop.Data.Distance("Height", rec.Height));
            data.Add(new Snoop.Data.Point3d("Target", rec.Target));
            data.Add(new Snoop.Data.Vector3d("View direction", rec.ViewDirection));
            data.Add(new Snoop.Data.Distance("View twist", rec.ViewTwist));
            data.Add(new Snoop.Data.Double("Lens length", rec.LensLength));
            data.Add(new Snoop.Data.Bool("Front clip at eye", rec.FrontClipAtEye));
            data.Add(new Snoop.Data.Distance("Front clip distance", rec.FrontClipDistance));
            data.Add(new Snoop.Data.Distance("Back clip distance", rec.BackClipDistance));
            data.Add(new Snoop.Data.Bool("Front clip enabled", rec.FrontClipEnabled));
            data.Add(new Snoop.Data.Bool("Back clip enabled", rec.BackClipEnabled));
            data.Add(new Snoop.Data.Distance("Elevation", rec.Elevation));
            data.Add(new Snoop.Data.Bool("Perspective enabled", rec.PerspectiveEnabled));
            // data.Add(new Snoop.Data.String("Render mode", rec.RenderMode.ToString()));
            data.Add(new Snoop.Data.Object("UCS", rec.Ucs));
            data.Add(new Snoop.Data.ObjectId("UCS name", rec.UcsName));
            data.Add(new Snoop.Data.String("UCS orthographic", rec.UcsOrthographic.ToString()));
            data.Add(new Snoop.Data.String("View orthographic", rec.ViewOrthographic.ToString()));

            data.Add(new Snoop.Data.Object("Ambient light color", rec.AmbientLightColor));
            data.Add(new Snoop.Data.ObjectId("Background ID", rec.Background));
            data.Add(new Snoop.Data.Double("Brightness", rec.Brightness));
            data.Add(new Snoop.Data.Double("Contrast", rec.Contrast));
            data.Add(new Snoop.Data.Bool("Default lighting on", rec.DefaultLightingOn));
            data.Add(new Snoop.Data.String("Default lighting type", rec.DefaultLightingType.ToString()));
            data.Add(new Snoop.Data.ObjectId("Sun ID", rec.SunId));
            data.Add(new Snoop.Data.ObjectId("Visual style ID", rec.VisualStyleId));

            ViewportTableRecord viewportRec = rec as ViewportTableRecord;

            if (viewportRec != null)
            {
                Stream(data, viewportRec);
                return;
            }

            ViewTableRecord viewRec = rec as ViewTableRecord;

            if (viewRec != null)
            {
                Stream(data, viewRec);
                return;
            }
        }
示例#6
0
        public void TestAddViewport()
        {
            var newId = ObjectId.Null;

            using (var db = AcadDatabase.Active())
            {
                var newViewport = new ViewportTableRecord()
                {
                    Name = "NewViewport"
                };
                db.Viewports.Add(newViewport);
                newId = newViewport.ObjectId;
            }

            AcadAssert.That.ViewportTable.Contains(newId);
        }
        public static string ZoomFilesAndSave(string fileName)
        {
            string newFileName = "";

            using (Database db = new Database(false, false))
            {
                db.ReadDwgFile(fileName, FileOpenMode.OpenForReadAndReadShare, true, null);
                Database prevDb = HostApplicationServices.WorkingDatabase;
                HostApplicationServices.WorkingDatabase = db;
                db.UpdateExt(true);
                using (ViewportTable vTab = db.ViewportTableId.GetObject(OpenMode.ForRead) as ViewportTable)
                {
                    ObjectId acVptId = vTab["*Active"];
                    using (ViewportTableRecord vpTabRec = acVptId.GetObject(OpenMode.ForWrite) as ViewportTableRecord)
                    {
                        double   scrRatio   = (vpTabRec.Width / vpTabRec.Height);
                        Matrix3d matWCS2DCS = Matrix3d.PlaneToWorld(vpTabRec.ViewDirection);
                        matWCS2DCS = Matrix3d.Displacement(vpTabRec.Target - Point3d.Origin) * matWCS2DCS;
                        matWCS2DCS = Matrix3d.Rotation(-vpTabRec.ViewTwist,
                                                       vpTabRec.ViewDirection,
                                                       vpTabRec.Target)
                                     * matWCS2DCS;
                        matWCS2DCS = matWCS2DCS.Inverse();
                        Extents3d extents = new Extents3d(db.Extmin, db.Extmax);
                        extents.TransformBy(matWCS2DCS);
                        double  width  = (extents.MaxPoint.X - extents.MinPoint.X);
                        double  height = (extents.MaxPoint.Y - extents.MinPoint.Y);
                        Point2d center = new Point2d((extents.MaxPoint.X + extents.MinPoint.X) * 0.5,
                                                     (extents.MaxPoint.Y + extents.MinPoint.Y) * 0.5);
                        if (width > (height * scrRatio))
                        {
                            height = width / scrRatio;
                        }
                        vpTabRec.Height      = height;
                        vpTabRec.Width       = height * scrRatio;
                        vpTabRec.CenterPoint = center;
                    }
                }

                HostApplicationServices.WorkingDatabase = prevDb;
                newFileName = fileName.Substring(0, fileName.Length - 4) + "z.dwg";
                db.SaveAs(newFileName, DwgVersion.Current);
            }

            return(newFileName);
        }
示例#8
0
        public void CreateViewPost()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                ViewportTable       vpt   = (ViewportTable)trans.GetObject(db.ViewportTableId, OpenMode.ForWrite);
                string              vName = "abc";
                ViewportTableRecord vptr1 = new ViewportTableRecord();
                vptr1.LowerLeftCorner  = new Point2d(0, 0);
                vptr1.UpperRightCorner = new Point2d(0.5, 0.5);
                vptr1.Name             = vName;
                ViewportTableRecord vptr2 = new ViewportTableRecord();
                vptr2.LowerLeftCorner  = new Point2d(0.5, 0);
                vptr2.UpperRightCorner = new Point2d(1, 0.5);
                vptr2.Name             = vName;
                ViewportTableRecord vptr3 = new ViewportTableRecord();
                vptr3.LowerLeftCorner  = new Point2d(0, 0.5);
                vptr3.UpperRightCorner = new Point2d(0.5, 1);
                vptr3.Name             = vName;
                ViewportTableRecord vptr4 = new ViewportTableRecord();
                vptr4.LowerLeftCorner  = new Point2d(0.5, 0.5);
                vptr4.UpperRightCorner = new Point2d(1, 1);
                vptr4.Name             = vName;
                vpt.Add(vptr1);
                vpt.Add(vptr2);
                vpt.Add(vptr3);
                vpt.Add(vptr4);
                trans.AddNewlyCreatedDBObject(vptr1, true);
                trans.AddNewlyCreatedDBObject(vptr2, true);
                trans.AddNewlyCreatedDBObject(vptr3, true);
                trans.AddNewlyCreatedDBObject(vptr4, true);
                Document doc = Application.DocumentManager.MdiActiveDocument;
                if (Application.GetSystemVariable("TILEMODE") == (object)1)
                {
                    doc.SendStringToExecute("-VPORTS 4 ", false, false, false);
                }
                else
                {
                    doc.SendStringToExecute("-VPORTS 4 ", false, false, false);
                }
                trans.Commit();
            }
        }
示例#9
0
        public void ModelZoomExtents()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction Tx = db.TransactionManager.StartTransaction())
            {
                ed.UpdateTiledViewportsInDatabase();

                ViewportTableRecord viewportTableRec = Tx.GetObject(ed.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord;

                SetViewportToExtents(db, viewportTableRec);

                ed.UpdateTiledViewportsFromDatabase();

                Tx.Commit();
            }
        }
示例#10
0
        // Apply our existing settings to the current view

        public void ApplyToCurrentView()
        {
            Editor ed = _doc.Editor;

            ViewportTableRecord vptr =
                (ViewportTableRecord)_tr.GetObject(
                    ed.ActiveViewportId, OpenMode.ForRead
                    );

            // Adjust the target

            if (_trgTrans != Matrix3d.Identity)
            {
                _target = _target.TransformBy(_trgTrans);
            }

            // Adjust the camera location

            if (_locTrans != Matrix3d.Identity)
            {
                _location = _location.TransformBy(_locTrans);
            }

            // Set up a view for the current settings

            ViewTableRecord vtr = new ViewTableRecord();

            vtr.CenterPoint        = Point2d.Origin;
            vtr.ViewTwist          = 0.0;
            vtr.PerspectiveEnabled = true;
            vtr.IsPaperspaceView   = false;
            vtr.Height             = vptr.Height;
            vtr.Width         = vptr.Width;
            vtr.ViewDirection =
                Target.GetVectorTo(Location).MultiplyBy(Zoom);
            vtr.Target     = Target;
            vtr.LensLength = LensLength;

            // Set it as the current view

            ed.SetCurrentView(vtr);
        }
示例#11
0
        public static bool GetActiveViewPortInfo(ref double height, ref double width, ref Point3d target, ref Vector3d viewDir, ref double viewTwist, bool getViewCenter)
        {
            // get the editor object
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            ed.UpdateTiledViewportsInDatabase();
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction t = db.TransactionManager.StartTransaction())
            {
                ViewportTable       vt  = (ViewportTable)t.GetObject(db.ViewportTableId, OpenMode.ForRead);
                ViewportTableRecord btr = (ViewportTableRecord)t.GetObject(vt["*Active"], OpenMode.ForRead);
                height    = btr.Height;
                width     = btr.Width;
                target    = btr.Target;
                viewDir   = btr.ViewDirection;
                viewTwist = btr.ViewTwist;
                t.Commit();
            }
            return(true);
        }
示例#12
0
        /// <summary>
        /// 将UCS表中已经存在的一个UCS设置为当前UCS
        /// </summary>
        /// <param name="db">数据库对象</param>
        /// <param name="UCSName">UCS名称</param>
        /// <returns>如果设置成功返回true,否则返回false</returns>
        public static bool SetCurrentUCS(this Database db, string UCSName)
        {
            var    trans = db.TransactionManager;
            Editor ed    = db.GetEditor();
            //打开UCS表
            UcsTable ut = (UcsTable)trans.GetObject(db.UcsTableId, OpenMode.ForRead);

            //如果不存在名为UCSName的UCS,则返回
            if (!ut.Has(UCSName))
            {
                return(false);
            }
            //打开当前活动的视口为写的状态
            ViewportTableRecord vtr = (ViewportTableRecord)trans.GetObject(db.CurrentViewportTableRecordId(), OpenMode.ForWrite);

            //设置当前UCS
            vtr.SetUcs(ut[UCSName]);
            vtr.DowngradeOpen();
            //更新视口
            ed.UpdateTiledViewportsFromDatabase();
            return(true);
        }
示例#13
0
        private void ZoomToExtentsofViewport(ViewportTableRecord vp)
        {
            Database db = vp.Database;
            // get the screen aspect ratio to calculate the height and width
            double aspect = (vp.Width / vp.Height);

            db.UpdateExt(true);
            Point3d minExt = db.Extmin;
            Point3d maxExt = db.Extmax;

            Extents3d extents = new Extents3d(minExt, maxExt);

            // prepare Matrix for DCS to WCS transformation
            Matrix3d matWCS2DCS = Matrix3d.PlaneToWorld(vp.ViewDirection);

            matWCS2DCS = Matrix3d.Displacement(vp.Target - Point3d.Origin) * matWCS2DCS;
            matWCS2DCS = Matrix3d.Rotation(-vp.ViewTwist, vp.ViewDirection, vp.Target) * matWCS2DCS;
            matWCS2DCS = matWCS2DCS.Inverse();

            // tranform the extents to the DCS defined by the viewdir
            extents.TransformBy(matWCS2DCS);

            double width  = (extents.MaxPoint.X - extents.MinPoint.X);
            double height = (extents.MaxPoint.Y - extents.MinPoint.Y);

            // get the view center point
            Point2d center = new Point2d(((extents.MaxPoint.X + extents.MinPoint.X) * 0.5), ((extents.MaxPoint.Y + extents.MinPoint.Y) * 0.5));

            // check if the width 'fits' in current window,
            if (width > (height * aspect))
            {
                height = width / aspect;
            }

            // set the view height - adjusted by 1%
            vp.Height = height * 1.01;
            // set the view center
            vp.CenterPoint = center;
        }
示例#14
0
        public override void Run(string filename, Database db)
        {
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    Point2d pmin = new Point2d(db.Extmin.X, db.Extmin.Y);
                    Point2d pmax = new Point2d(db.Extmax.X, db.Extmax.Y);

                    ViewportTable       vpt  = (ViewportTable)tr.GetObject(db.ViewportTableId, OpenMode.ForRead);
                    ViewportTableRecord vptr = (ViewportTableRecord)tr.GetObject(vpt["*Active"], OpenMode.ForWrite);
                    ZoomToExtentsofViewport(vptr);
                    db.UpdateExt(true);
                }
                catch (System.Exception ex)
                {
                    OnError(ex);
                }

                tr.Commit();
            }
        }
示例#15
0
        private void zoomDb(Autodesk.AutoCAD.DatabaseServices.Database db, Extents3d ext)
        {
            using (var switcher = new AcadLib.WorkingDatabaseSwitcher(db))
            {
                //db.UpdateExt(true);
                using (ViewportTable vTab = db.ViewportTableId.GetObject(OpenMode.ForRead) as ViewportTable)
                {
                    ObjectId acVptId = vTab["*Active"];
                    using (ViewportTableRecord vpTabRec = acVptId.GetObject(OpenMode.ForWrite) as ViewportTableRecord)
                    {
                        double scrRatio = (vpTabRec.Width / vpTabRec.Height);
                        //Matrix3d matWCS2DCS = Matrix3d.PlaneToWorld(vpTabRec.ViewDirection);
                        //matWCS2DCS = Matrix3d.Displacement(vpTabRec.Target - Point3d.Origin) * matWCS2DCS;
                        //matWCS2DCS = Matrix3d.Rotation(-vpTabRec.ViewTwist,
                        //                                vpTabRec.ViewDirection,
                        //                                vpTabRec.Target)
                        //                                * matWCS2DCS;
                        //matWCS2DCS = matWCS2DCS.Inverse();
                        //Extents3d extents = new Extents3d(db.Extmin, db.Extmax);
                        //extents.TransformBy(matWCS2DCS);
                        //double width = (extents.MaxPoint.X - extents.MinPoint.X);
                        //double height = (extents.MaxPoint.Y - extents.MinPoint.Y);
                        //Point2d center = new Point2d((extents.MaxPoint.X + extents.MinPoint.X) * 0.5,
                        //                             (extents.MaxPoint.Y + extents.MinPoint.Y) * 0.5);

                        double width  = (ext.MaxPoint.X - ext.MinPoint.X);
                        double height = (ext.MaxPoint.Y - ext.MinPoint.Y);
                        if (width > (height * scrRatio))
                        {
                            height = width / scrRatio;
                        }
                        vpTabRec.Height      = ext.MaxPoint.Y - ext.MinPoint.Y;
                        vpTabRec.Width       = height * scrRatio;
                        vpTabRec.CenterPoint = ext.Center().Convert2d();
                    }
                }
            }
        }
示例#16
0
        Stream(ArrayList data, ViewportTableRecord rec)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(ViewportTableRecord)));

            data.Add(new Snoop.Data.Point2d("Lower left corner", rec.LowerLeftCorner));
            data.Add(new Snoop.Data.Point2d("Upper right corner", rec.UpperRightCorner));
            data.Add(new Snoop.Data.Int("Circle sides", rec.CircleSides));
            data.Add(new Snoop.Data.Bool("Fast zooms enabled", rec.FastZoomsEnabled));
            data.Add(new Snoop.Data.Bool("Grid enabled", rec.GridEnabled));
            data.Add(new Snoop.Data.Bool("Grid adaptive", rec.GridAdaptive));
            data.Add(new Snoop.Data.Bool("Grid bound to limits", rec.GridBoundToLimits));
            data.Add(new Snoop.Data.Bool("Grid follow", rec.GridFollow));
            data.Add(new Snoop.Data.Int("Grid major", rec.GridMajor));
            data.Add(new Snoop.Data.Bool("Grid sub-division restricted", rec.GridSubdivisionRestricted));
            data.Add(new Snoop.Data.Point2d("Grid increments", rec.GridIncrements));
            data.Add(new Snoop.Data.Bool("Icon enabled", rec.IconEnabled));
            data.Add(new Snoop.Data.Bool("Icon at origin", rec.IconAtOrigin));
            data.Add(new Snoop.Data.Bool("Isometric snap enabled", rec.IsometricSnapEnabled));
            data.Add(new Snoop.Data.Bool("Snap enabled", rec.SnapEnabled));
            data.Add(new Snoop.Data.Point2d("Snap increments", rec.SnapIncrements));
            data.Add(new Snoop.Data.Int("Snap pair", rec.SnapPair));
            data.Add(new Snoop.Data.Bool("UCS follow mode", rec.UcsFollowMode));
            data.Add(new Snoop.Data.Bool("UCS saved with viewport", rec.UcsSavedWithViewport));
        }
示例#17
0
        // Create a new tiled viewport configuration with two windows
        public void Create_Mode_ViewPort()
        {
            // get the current database
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                // open the viewport table for read
                ViewportTable vtab = acTrans.GetObject(db.ViewportTableId, OpenMode.ForRead) as ViewportTable;

                // check to see if the named view 'Test Viewport' exists
                if (vtab.Has("Test_ViewPort") == false)
                {
                    // open the view table for write
                    vtab.UpgradeOpen();

                    // add the new viewport to the viewport table and the transaction
                    ViewportTableRecord vptableRecordLwr = new ViewportTableRecord();
                    vtab.Add(vptableRecordLwr);
                    acTrans.AddNewlyCreatedDBObject(vptableRecordLwr, true);

                    // name the new viewport 'Test_ViewPort' and assign it to be the lower half of the drawing window
                    vptableRecordLwr.Name             = "Test_ViewPort";
                    vptableRecordLwr.LowerLeftCorner  = new Point2d(0, 0);
                    vptableRecordLwr.UpperRightCorner = new Point2d(1, 0.5);

                    // Add the new viewport to the viewport table and the transaction
                    ViewportTableRecord vptableRecordUpr = new ViewportTableRecord();
                    vtab.Add(vptableRecordUpr);
                    acTrans.AddNewlyCreatedDBObject(vptableRecordUpr, true);

                    // name the new viewport 'Test_ViewPort' and assign it to be the upper half of the drawing window
                    vptableRecordUpr.Name             = "Test_ViewPort";
                    vptableRecordUpr.LowerLeftCorner  = new Point2d(0, .5);
                    vptableRecordUpr.UpperRightCorner = new Point2d(1, 1);

                    // to assign the new viewport as the active viewpport,
                    // the viewport named active nedd to be removed and recreated based on "Test_ViewPort"

                    // step through each object in the symbol table
                    foreach (ObjectId acObjectId in vtab)
                    {
                        // open the object for read
                        ViewportTableRecord acVportTblRec = acTrans.GetObject(acObjectId, OpenMode.ForRead) as ViewportTableRecord;

                        // see if it is one of the active viewports, and if so erase it
                        if (acVportTblRec.Name == "*Active")
                        {
                            acVportTblRec.UpgradeOpen();
                            acVportTblRec.Erase();
                        }
                    }
                    // clone the new viewport as the active viewports
                    foreach (ObjectId acObjId in vtab)
                    {
                        // open the object for read
                        ViewportTableRecord acVportTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as ViewportTableRecord;

                        // see if it is one of the active viewports, and if so erase it
                        if (acVportTblRec.Name == "*Test_ViewPort")
                        {
                            ViewTableRecord acVportTblRecClone = acVportTblRec.Clone() as ViewTableRecord;
                            // add the new viewport to the viewport table and the transaction
                            vtab.Add(acVportTblRecClone);
                            acVportTblRecClone.Name = "*Active";
                            acTrans.AddNewlyCreatedDBObject(acVportTblRecClone, true);
                        }
                    }
                    // update display with the new tiled viewports arrangment
                    Editor ed = doc.Editor;
                    ed.UpdateTiledViewportsFromDatabase();
                    // commit changes
                    acTrans.Commit();
                }
            }
        }
示例#18
0
        public static void SplitAndIterateModelViewports()
        {
            // Get the current database
            Document acDoc   = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Viewport table for write
                ViewportTable acVportTbl;
                acVportTbl = acTrans.GetObject(acCurDb.ViewportTableId,
                                               OpenMode.ForWrite) as ViewportTable;

                // Open the active viewport for write
                ViewportTableRecord acVportTblRec;
                acVportTblRec = acTrans.GetObject(acDoc.Editor.ActiveViewportId,
                                                  OpenMode.ForWrite) as ViewportTableRecord;

                using (ViewportTableRecord acVportTblRecNew = new ViewportTableRecord())
                {
                    // Add the new viewport to the Viewport table and the transaction
                    acVportTbl.Add(acVportTblRecNew);
                    acTrans.AddNewlyCreatedDBObject(acVportTblRecNew, true);

                    // Assign the name '*Active' to the new Viewport
                    acVportTblRecNew.Name = "*Active";

                    // Use the existing lower left corner for the new viewport
                    acVportTblRecNew.LowerLeftCorner = acVportTblRec.LowerLeftCorner;

                    // Get half the X of the existing upper corner
                    acVportTblRecNew.UpperRightCorner = new Point2d(acVportTblRec.UpperRightCorner.X,
                                                                    acVportTblRec.LowerLeftCorner.Y +
                                                                    ((acVportTblRec.UpperRightCorner.Y -
                                                                      acVportTblRec.LowerLeftCorner.Y) / 2));

                    // Recalculate the corner of the active viewport
                    acVportTblRec.LowerLeftCorner = new Point2d(acVportTblRec.LowerLeftCorner.X,
                                                                acVportTblRecNew.UpperRightCorner.Y);

                    // Update the display with the new tiled viewports arrangement
                    acDoc.Editor.UpdateTiledViewportsFromDatabase();

                    // Step through each object in the symbol table
                    foreach (ObjectId acObjId in acVportTbl)
                    {
                        // Open the object for read
                        ViewportTableRecord acVportTblRecCur;
                        acVportTblRecCur = acTrans.GetObject(acObjId,
                                                             OpenMode.ForRead) as ViewportTableRecord;

                        if (acVportTblRecCur.Name == "*Active")
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("CVPORT", acVportTblRecCur.Number);

                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Viewport: " + acVportTblRecCur.Number +
                                                                                             " is now active." +
                                                                                             "\nLower left corner: " +
                                                                                             acVportTblRecCur.LowerLeftCorner.X + ", " +
                                                                                             acVportTblRecCur.LowerLeftCorner.Y +
                                                                                             "\nUpper right corner: " +
                                                                                             acVportTblRecCur.UpperRightCorner.X + ", " +
                                                                                             acVportTblRecCur.UpperRightCorner.Y);
                        }
                    }
                }

                // Commit the changes and dispose of the transaction
                acTrans.Commit();
            }
        }
示例#19
0
        public static void CreateModelViewport()
        {
            // Get the current database
            Document acDoc   = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Viewport table for read
                ViewportTable acVportTbl;
                acVportTbl = acTrans.GetObject(acCurDb.ViewportTableId,
                                               OpenMode.ForRead) as ViewportTable;

                // Check to see if the named view 'TEST_VIEWPORT' exists
                if (acVportTbl.Has("TEST_VIEWPORT") == false)
                {
                    // Open the View table for write
                    acTrans.GetObject(acCurDb.ViewportTableId, OpenMode.ForWrite);

                    // Add the new viewport to the Viewport table and the transaction
                    using (ViewportTableRecord acVportTblRecLwr = new ViewportTableRecord())
                    {
                        acVportTbl.Add(acVportTblRecLwr);
                        acTrans.AddNewlyCreatedDBObject(acVportTblRecLwr, true);

                        // Name the new viewport 'TEST_VIEWPORT' and assign it to be
                        // the lower half of the drawing window
                        acVportTblRecLwr.Name             = "TEST_VIEWPORT";
                        acVportTblRecLwr.LowerLeftCorner  = new Point2d(0, 0);
                        acVportTblRecLwr.UpperRightCorner = new Point2d(1, 0.5);

                        // Add the new viewport to the Viewport table and the transaction
                        using (ViewportTableRecord acVportTblRecUpr = new ViewportTableRecord())
                        {
                            acVportTbl.Add(acVportTblRecUpr);
                            acTrans.AddNewlyCreatedDBObject(acVportTblRecUpr, true);

                            // Name the new viewport 'TEST_VIEWPORT' and assign it to be
                            // the upper half of the drawing window
                            acVportTblRecUpr.Name             = "TEST_VIEWPORT";
                            acVportTblRecUpr.LowerLeftCorner  = new Point2d(0, 0.5);
                            acVportTblRecUpr.UpperRightCorner = new Point2d(1, 1);

                            // To assign the new viewports as the active viewports, the
                            // viewports named '*Active' need to be removed and recreated
                            // based on 'TEST_VIEWPORT'.

                            // Step through each object in the symbol table
                            foreach (ObjectId acObjId in acVportTbl)
                            {
                                // Open the object for read
                                ViewportTableRecord acVportTblRec;
                                acVportTblRec = acTrans.GetObject(acObjId,
                                                                  OpenMode.ForRead) as ViewportTableRecord;

                                // See if it is one of the active viewports, and if so erase it
                                if (acVportTblRec.Name == "*Active")
                                {
                                    acTrans.GetObject(acObjId, OpenMode.ForWrite);
                                    acVportTblRec.Erase();
                                }
                            }

                            // Clone the new viewports as the active viewports
                            foreach (ObjectId acObjId in acVportTbl)
                            {
                                // Open the object for read
                                ViewportTableRecord acVportTblRec;
                                acVportTblRec = acTrans.GetObject(acObjId,
                                                                  OpenMode.ForRead) as ViewportTableRecord;

                                // See if it is one of the active viewports, and if so erase it
                                if (acVportTblRec.Name == "TEST_VIEWPORT")
                                {
                                    ViewportTableRecord acVportTblRecClone;
                                    acVportTblRecClone = acVportTblRec.Clone() as ViewportTableRecord;

                                    // Add the new viewport to the Viewport table and the transaction
                                    acVportTbl.Add(acVportTblRecClone);
                                    acVportTblRecClone.Name = "*Active";
                                    acTrans.AddNewlyCreatedDBObject(acVportTblRecClone, true);
                                }
                            }

                            // Update the display with the new tiled viewports arrangement
                            acDoc.Editor.UpdateTiledViewportsFromDatabase();
                        }
                    }

                    // Commit the changes
                    acTrans.Commit();
                }

                // Dispose of the transaction
            }
        }
示例#20
0
        public void exprotCAD(string o_cadFile, string file)
        {
            if (o_cadFile == null)
            {
                MessageBox.Show("请先读取CAD文件");
                return;
            }

            object filepath = file;

            Teigha.Runtime.Services trs = new Services();

            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            wordApp = new Microsoft.Office.Interop.Word.Application();
            wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;

            Document doc = null;

            doc = wordApp.Documents.Open(ref filepath, ref miss, ref miss, ref miss
                                         , ref miss, ref miss, ref miss, ref miss, ref miss
                                         , ref miss, ref miss, ref miss, ref miss);
            //搜索书签
            Boolean find = false;

            foreach (Microsoft.Office.Interop.Word.Bookmark bm in doc.Bookmarks)
            {
                if (bm.Name == "cad")
                {
                    find = true;
                }
            }
            if (!find)
            {
                MessageBox.Show("模板有误,请选择正确的模板");
                return;
            }
            if (!File.Exists(o_cadFile))
            {
                return;
            }
            Database db = new Database(false, true);                                           //CAD Database,CAD数据库

            db.ReadDwgFile((string)o_cadFile, FileOpenMode.OpenForReadAndAllShare, false, ""); //读取文件
            if (db == null)
            {
                return;
            }
            double x0 = 0, x1 = 0, y0 = 0, y1 = 0;
            bool   isIni = false;

            using (Transaction ts = db.TransactionManager.StartTransaction())                           //打开事务
            {
                BlockTableRecord btr = (BlockTableRecord)db.CurrentSpaceId.GetObject(OpenMode.ForRead); //块表记录
                foreach (var id in btr)                                                                 //遍历所有Entity
                {
                    Entity ent = (Entity)id.GetObject(OpenMode.ForRead);
                    if (isIni == false)
                    {
                        x0    = ent.GeometricExtents.MinPoint.X;
                        x1    = ent.GeometricExtents.MaxPoint.X;
                        y0    = ent.GeometricExtents.MinPoint.Y;
                        y1    = ent.GeometricExtents.MaxPoint.Y;
                        isIni = true;
                    }
                    else
                    {
                        try
                        {
                            if (x0 > ent.GeometricExtents.MinPoint.X)
                            {
                                x0 = ent.GeometricExtents.MinPoint.X;
                            }
                            if (x1 < ent.GeometricExtents.MaxPoint.X)
                            {
                                x1 = ent.GeometricExtents.MaxPoint.X;
                            }
                            if (y0 > ent.GeometricExtents.MinPoint.Y)
                            {
                                y0 = ent.GeometricExtents.MinPoint.Y;
                            }
                            if (y1 < ent.GeometricExtents.MaxPoint.Y)
                            {
                                y1 = ent.GeometricExtents.MaxPoint.Y;
                            }
                        }
                        catch { }
                    }
                }
                ViewportTableRecord vp = (ViewportTableRecord)Aux.active_viewport_id(db).GetObject(OpenMode.ForWrite);//视口表记录
                vp.CenterPoint = new Point2d((x0 + x1) / 2, (y0 + y1) / 2);

                vp.Width  = x1 - x0;
                vp.Height = y1 - y0;//稍微增大,以免地下有线没有被完全显示,到时候最好用比例
                ts.Commit();
            }
            db.SaveAs((string)o_cadFile, DwgVersion.Current);
            const string    progID = "AutoCAD.Application.18.0";
            AcadApplication acApp  = null;

            try
            {
                acApp = (AcadApplication)Marshal.GetActiveObject(progID);
            }
            catch
            {
                try
                {
                    Type acType = Type.GetTypeFromProgID(progID);
                    acApp = (AcadApplication)Activator.CreateInstance(acType, true);
                }
                catch
                {
                }
            }
            if (acApp != null)
            {
                acApp.Height = 500 + 55;
                acApp.Width  = (int)(500 * (x1 - x0) / (y1 - y0));
                acApp.Quit();
            }
            object link    = false;
            object cadFile = (object)o_cadFile;

            wordApp.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object oStart = "cad";
            object range  = (object)doc.Bookmarks.get_Item(ref oStart).Range;

            try
            {
                InlineShape cadShape = wordApp.Selection.InlineShapes.AddOLEObject(ref miss, ref cadFile, ref link, ref link, ref miss
                                                                                   , ref miss, ref miss, ref range);

                cadShape.Width  = (float)(200 * (x1 - x0) / (y1 - y0));
                cadShape.Height = 200f;
            }
            catch { }

            doc.Save();
            doc.Close();
            wordApp.Quit();
            trs.Dispose();
            MessageBox.Show("导出成功");
        }
        public static void LoadProcedures()
        {
            _ListProcedures.Clear();

            #region Purge

            if (_DWGCollection.Purge)
            {
                _ListProcedures.Add(new Procedure(delegate(Database db, Transaction tr, DWGFileModel objDWG)
                {
                    // Create the list of objects to "purge"
                    ObjectIdCollection idsToPurge = ArCaUtils.GetObjIdNonGrafical(db);

                    // Call the Purge function to filter the list
                    db.Purge(idsToPurge);

                    if (idsToPurge.Count != 0)
                    {
                        // Erase each of the objects we've been
                        // allowed to
                        foreach (ObjectId id in idsToPurge)
                        {
                            DBObject obj = tr.GetObject(id, OpenMode.ForWrite);
                            obj.Erase();
                        }

                        //Was Changed
                        objDWG.IsChanged = true;
                    }
                }));
            }

            #endregion

            #region Lock View Ports

            if (_DWGCollection.LockViewPorts)
            {
                _ListProcedures.Add(new Procedure(delegate(Database db, Transaction tr, DWGFileModel objDWG)
                {
                    //Block Table
                    BlockTable btBlock = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    foreach (ObjectId btrId in btBlock)
                    {
                        BlockTableRecord ltr = tr.GetObject(btrId, OpenMode.ForWrite) as BlockTableRecord;
                        foreach (ObjectId acObjId in ltr)
                        {
                            if (acObjId.ObjectClass.DxfName == "VIEWPORT")
                            {
                                Viewport vp = tr.GetObject(acObjId, OpenMode.ForWrite) as Viewport;
                                vp.Locked   = true;
                                //Was Changed
                                objDWG.IsChanged = true;
                            }
                        }
                    }
                }));
            }

            if (_DWGCollection.ZoomExtents)
            {
                _ListProcedures.Add(new Procedure(delegate(Database db, Transaction tr, DWGFileModel objDWG)
                {
                    //Model
                    ViewportTable vpt = tr.GetObject(db.ViewportTableId, OpenMode.ForWrite) as ViewportTable;
                    foreach (ObjectId btrId in vpt)
                    {
                        ViewportTableRecord vptrec = tr.GetObject(btrId, OpenMode.ForWrite) as ViewportTableRecord;
                        SetViewportToExtents(db, vptrec);
                    }

                    //Paper Spaces
                    BlockTable btBlock = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    foreach (ObjectId btrId in btBlock)
                    {
                        BlockTableRecord btr = tr.GetObject(btrId, OpenMode.ForWrite) as BlockTableRecord;

                        if (!btr.Name.StartsWith("*Paper_Space"))
                        {
                            continue;
                        }

                        //Retrieve paper space viewport (viewport with the lowest handle)
                        Viewport paperVp  = null;
                        long lowestHandle = -1;
                        foreach (ObjectId acObjId in btr)
                        {
                            if (acObjId.ObjectClass.Name == "AcDbViewport")
                            {
                                Viewport vp = tr.GetObject(acObjId, OpenMode.ForRead) as Viewport;

                                if (lowestHandle < 0)
                                {
                                    lowestHandle = vp.Handle.Value;
                                    paperVp      = vp;
                                }
                                else if (vp.Handle.Value < lowestHandle)
                                {
                                    paperVp      = vp;
                                    lowestHandle = vp.Handle.Value;
                                }
                            }
                        }
                        if (paperVp == null)
                        {
                            return;
                        }
                        paperVp.UpgradeOpen();

                        double scrRatio = (paperVp.Width / paperVp.Height);

                        Matrix3d matWCS2DCS = Matrix3d.PlaneToWorld(paperVp.ViewDirection);

                        matWCS2DCS = Matrix3d.Displacement(paperVp.ViewTarget - Point3d.Origin) * matWCS2DCS;

                        matWCS2DCS = Matrix3d.Rotation(-paperVp.TwistAngle,
                                                       paperVp.ViewDirection,
                                                       paperVp.ViewTarget)
                                     * matWCS2DCS;

                        matWCS2DCS = matWCS2DCS.Inverse();

                        Extents3d extents = GetExtents(db, btr);

                        extents.TransformBy(matWCS2DCS);

                        double width = (extents.MaxPoint.X - extents.MinPoint.X);

                        double height = (extents.MaxPoint.Y - extents.MinPoint.Y);

                        Point2d center = new Point2d((extents.MaxPoint.X + extents.MinPoint.X) * 0.5,
                                                     (extents.MaxPoint.Y + extents.MinPoint.Y) * 0.5);

                        if (width > (height * scrRatio))
                        {
                            height = width / scrRatio;
                        }

                        paperVp.ViewHeight = height;
                        paperVp.ViewCenter = center;

                        //Was Changed
                        objDWG.IsChanged = true;
                    }
                }));
            }

            #endregion
        }
        private static bool SwitchUCS(Point3d cornerCoords, double textAngle)
        {
            // Get the current document and database
            Document acDoc    = Application.DocumentManager.MdiActiveDocument;
            Database acCurrDb = acDoc.Database;
            Editor   acEditor = acDoc.Editor;

            using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction())
            {
                try
                {
                    UcsTable       acUCSTbl = acTrans.GetObject(acCurrDb.UcsTableId, OpenMode.ForRead) as UcsTable;
                    UcsTableRecord jppUCSTblRec;
                    // Check to see if JPP App UCS table record exists and create if not
                    if (acUCSTbl.Has("JPP_App_UCS") == false)
                    {
                        jppUCSTblRec      = new UcsTableRecord();
                        jppUCSTblRec.Name = "JPP_App_UCS";

                        acUCSTbl.UpgradeOpen();
                        acUCSTbl.Add(jppUCSTblRec);
                        acTrans.AddNewlyCreatedDBObject(jppUCSTblRec, true);
                    }
                    else
                    {
                        jppUCSTblRec = acTrans.GetObject(acUCSTbl["JPP_App_UCS"], OpenMode.ForWrite) as UcsTableRecord;
                    }
                    jppUCSTblRec.Origin = cornerCoords;
                    jppUCSTblRec.XAxis  = cornerCoords.GetVectorTo(new Point3d(cornerCoords.X + Math.Cos(textAngle),
                                                                               cornerCoords.Y + Math.Sin(textAngle),
                                                                               0.0));
                    jppUCSTblRec.YAxis = cornerCoords.GetVectorTo(new Point3d(cornerCoords.X - Math.Sin(textAngle),
                                                                              cornerCoords.Y + Math.Cos(textAngle),
                                                                              0.0));
                    // Open the active viewport
                    ViewportTableRecord acVportTblRec = acTrans.GetObject(acEditor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord;

                    // Display the UCS Icon as the origin of the current viewport
                    // acVportTblRec.IconAtOrigin = true;
                    // acVportTblRec.IconEnabled = true;

                    // Set the UCS current
                    acVportTblRec.SetUcs(jppUCSTblRec.ObjectId);
                    acEditor.UpdateTiledViewportsFromDatabase();

                    // Display the name of the current UCS
                    UcsTableRecord acUCSTblRecActive = acTrans.GetObject(acVportTblRec.UcsName, OpenMode.ForRead) as UcsTableRecord;
                    acEditor.WriteMessage("\nThe current UCS is: {0}", acUCSTblRecActive.Name);

                    // Save the new objects to the database
                    acTrans.Commit();
                    return(true);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception acException)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog
                        ("The following exception was caught: \n" + acException.Message
                        + "\nError creating UCS!");
                    acTrans.Abort();
                    return(false);
                }
            }
        }
示例#23
0
        // 开始具体的调试操作
        private void DoSomething(DocumentModifier docMdf, SelectionSet impliedSelection)
        {
            var acTrans = docMdf.acTransaction;

            // 以读模式打开UCSTable
            UcsTable acUCSTbl;

            acUCSTbl = acTrans.GetObject(docMdf.acDataBase.UcsTableId, OpenMode.ForRead) as UcsTable;
            UcsTableRecord acUCSTblRec;

            // 检查UCS表中是否有“New_UCS”这条记录
            if (acUCSTbl.Has("New_UCS") == false)
            {
                acUCSTblRec      = new UcsTableRecord();
                acUCSTblRec.Name = "New_UCS";
                // 以写模式打开UCSTable
                acUCSTbl.UpgradeOpen();
                // 往UCSTable添加新记录
                acUCSTbl.Add(acUCSTblRec);
                acTrans.AddNewlyCreatedDBObject(acUCSTblRec, true);
            }
            else
            {
                acUCSTblRec = acTrans.GetObject(acUCSTbl["New_UCS"], OpenMode.ForWrite) as UcsTableRecord;
            }
            acUCSTblRec.Origin = new Point3d(4, 5, 3);
            acUCSTblRec.XAxis  = new Vector3d(1, 0, 0);
            acUCSTblRec.YAxis  = new Vector3d(0, 1, 0);

            // 打开当前视口
            ViewportTableRecord acVportTblRec = acTrans.GetObject(docMdf.acEditor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord;

            // 在当前视口的原点显示UCS图标
            acVportTblRec.IconAtOrigin = true;
            acVportTblRec.IconEnabled  = true;

            // 设置UCS为当前坐标系
            acVportTblRec.SetUcs(acUCSTblRec.ObjectId);
            docMdf.acEditor.UpdateTiledViewportsFromDatabase();

            // 显示当前UCS坐标系的名称
            UcsTableRecord acUCSTblRecActive = acTrans.GetObject(acVportTblRec.UcsName, OpenMode.ForRead) as UcsTableRecord;

            Application.ShowAlertDialog("The current UCS is: " + acUCSTblRecActive.Name);

            // 另一种方式显示出当前用户坐标系的参数
            Matrix3d           curUCSMatrix = docMdf.acEditor.CurrentUserCoordinateSystem;
            CoordinateSystem3d curUCS       = curUCSMatrix.CoordinateSystem3d;

            // 在用户坐标系下绘制一条线
            var btrTable = acTrans.GetObject(docMdf.acDataBase.BlockTableId, OpenMode.ForRead) as BlockTable;
            var btr      = acTrans.GetObject(btrTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
            var line     = new Line(new Point3d(0, 0, 0), new Point3d(1, 0, 0));

            // Entity.TransformBy() 用来进行坐标变换,如果不进行变换,则上面的line的定位是相对于世界坐标系的。
            line.TransformBy(curUCSMatrix);
            btr.AppendEntity(line);
            acTrans.AddNewlyCreatedDBObject(line, true);

            // 提示选取一个点
            var pPtOpts = new PromptPointOptions("");

            pPtOpts.Message = "\nEnter a point: ";
            var pPtRes = docMdf.acEditor.GetPoint(pPtOpts);

            if (pPtRes.Status == PromptStatus.OK)
            {
                // 获得的点的坐标是在当前UCS下定义的
                var pt3dUCS = pPtRes.Value;

                // 将该点的当前UCS坐标转变为WCS坐标
                var newMatrix = Matrix3d.AlignCoordinateSystem(Point3d.Origin,
                                                               Vector3d.XAxis,
                                                               Vector3d.YAxis,
                                                               Vector3d.ZAxis,
                                                               acVportTblRec.Ucs.Origin,
                                                               acVportTblRec.Ucs.Xaxis,
                                                               acVportTblRec.Ucs.Yaxis,
                                                               acVportTblRec.Ucs.Zaxis);
                var pt3dWCS = pt3dUCS.TransformBy(newMatrix);

                Application.ShowAlertDialog("The WCS coordinates are: \n" + pt3dWCS.ToString() + "\n" +
                                            "The UCS coordinates are: \n" + pt3dUCS.ToString());
            }
        }
        private static bool MoveLevelText(ObjectId fflToEditId)
        {
            Document acDoc    = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database acCurrDb = acDoc.Database;
            Editor   acEditor = acDoc.Editor;


            // Loop so user can move multiple levels
            bool movingLevels = true;

            while (movingLevels)
            {
                // Prompt the user to select the level to move
                PromptNestedEntityOptions nestedEntOpt = new PromptNestedEntityOptions("\nPick the level to move (spacebar to finish):");
                PromptNestedEntityResult  nestedEntRes = acEditor.GetNestedEntity(nestedEntOpt);
                if (nestedEntRes.Status == PromptStatus.OK)
                {
                    using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            Entity ent = acTrans.GetObject(nestedEntRes.ObjectId, OpenMode.ForRead) as Entity;
                            if (ent.GetType() == typeof(MText))
                            {
                                MText textToEdit = ent as MText;

                                // All work will be done in the WCS so save the current UCS
                                // to restore later and set the UCS to WCS
                                Matrix3d CurrentUCS = acEditor.CurrentUserCoordinateSystem;
                                acEditor.CurrentUserCoordinateSystem = Matrix3d.Identity;

                                // Fetch the block reference for the outline
                                BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;

                                // Calculate the corner coordinates. Text rotation will either be 0 to 90 degrees or
                                // 270 - 360 degrees.
                                // What happens if text is not in these ranges?
                                // Point3d textLocation = textToEdit.Location.TransformBy(fflToEdit.BlockTransform);
                                Point3d cornerPoint = CalculateCornerPoint(textToEdit, fflToEdit);

                                // Save the current text rotation angle for use later
                                double oldTextAngle = textToEdit.Rotation;

                                // Create a new UCS basesd on the corner point and the text rotation. The new UCS
                                // origin will be at the corner point and the X-axis aligned with the text direction.
                                if (!SwitchUCS(cornerPoint, textToEdit.Rotation))
                                {
                                    acEditor.WriteMessage("\nError, unable to create UCS!");
                                    acTrans.Abort();
                                    // Restore current UCS
                                    acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                                    return(false);
                                }
                                // Prompt the user for the new position
                                Point3d            newLocation      = new Point3d(); // Declare here so in scope
                                AttachmentPoint    newJustification = new AttachmentPoint();
                                double             newAngle         = 0.0;
                                PromptPointResult  promptRes;
                                PromptPointOptions promptOpts = new PromptPointOptions("\nClick new text position: ");

                                promptRes = acEditor.GetPoint(promptOpts);
                                if (promptRes.Status != PromptStatus.OK)
                                {
                                    acEditor.WriteMessage("\nInvalid level text position picked - please try again.");
                                    acTrans.Abort();
                                    // Restore current UCS
                                    acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                                    continue;
                                }
                                // If the text is justified TC or BC it's on a straight line so move to the other side, swap the
                                // justification and maintain the same rotation
                                if ((textToEdit.Attachment == AttachmentPoint.TopCenter) ||
                                    (textToEdit.Attachment == AttachmentPoint.BottomCenter))
                                {
                                    newAngle = Constants.Deg_0;
                                    if (promptRes.Value.Y > 0)
                                    {
                                        newLocation      = new Point3d(0.0, Constants.TextOffset, 0.0);
                                        newJustification = AttachmentPoint.BottomCenter;
                                    }
                                    else
                                    {
                                        newLocation      = new Point3d(0.0, -Constants.TextOffset, 0.0);
                                        newJustification = AttachmentPoint.TopCenter;
                                    }
                                }
                                else
                                {
                                    // Ask user if text needs to be rotated.
                                    PromptKeywordOptions promptKeyOpts = new PromptKeywordOptions("\nRotate text [Yes/No]: ", "Yes No");
                                    promptKeyOpts.Keywords.Default = "No";
                                    PromptResult promptRotRes = acEditor.GetKeywords(promptKeyOpts);
                                    if (promptRotRes.Status != PromptStatus.OK)
                                    {
                                        acEditor.WriteMessage("\nInvalid option - please try again.");
                                        acTrans.Abort();
                                        // Restore current UCS
                                        acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                                        continue;
                                    }

                                    // Calculate the new location point and text justification
                                    if (promptRes.Value.X < 0)
                                    {
                                        if (promptRes.Value.Y < 0)
                                        {
                                            newLocation = new Point3d(-Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      -Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      0.0);
                                            if (promptRotRes.StringResult == "Yes")
                                            {
                                                if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90))
                                                {
                                                    newJustification = AttachmentPoint.TopLeft;
                                                    newAngle         = Constants.Deg_270; // The UCS is origin currently lies at the corner point
                                                                                          // and the x-axis at the text rotation
                                                }
                                                else
                                                {
                                                    newJustification = AttachmentPoint.BottomRight;
                                                    newAngle         = Constants.Deg_90;
                                                }
                                            }
                                            else
                                            {
                                                newJustification = AttachmentPoint.TopRight;
                                                newAngle         = Constants.Deg_0;
                                            }
                                        }
                                        else
                                        {
                                            newLocation = new Point3d(-Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      0.0);
                                            if (promptRotRes.StringResult == "Yes")
                                            {
                                                if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90))
                                                {
                                                    newJustification = AttachmentPoint.TopRight;
                                                    newAngle         = Constants.Deg_270;
                                                }
                                                else
                                                {
                                                    newJustification = AttachmentPoint.BottomLeft;
                                                    newAngle         = Constants.Deg_90;
                                                }
                                            }
                                            else
                                            {
                                                newJustification = AttachmentPoint.BottomRight;
                                                newAngle         = Constants.Deg_0;
                                            }
                                        }
                                    }
                                    else if (promptRes.Value.X > 0)
                                    {
                                        if (promptRes.Value.Y < 0)
                                        {
                                            newLocation = new Point3d(Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      -Constants.TextOffset * Math.Sin(Constants.Deg_45),
                                                                      0.0);
                                            if (promptRotRes.StringResult == "Yes")
                                            {
                                                if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90))
                                                {
                                                    newJustification = AttachmentPoint.BottomLeft;
                                                    newAngle         = Constants.Deg_270;
                                                }
                                                else
                                                {
                                                    newJustification = AttachmentPoint.TopRight;
                                                    newAngle         = Constants.Deg_90;
                                                }
                                            }
                                            else
                                            {
                                                newJustification = AttachmentPoint.TopLeft;
                                                newAngle         = Constants.Deg_0;
                                            }
                                        }
                                        else
                                        {
                                            newLocation = new Point3d(Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      0.0);
                                            if (promptRotRes.StringResult == "Yes")
                                            {
                                                if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90))
                                                {
                                                    newJustification = AttachmentPoint.BottomRight;
                                                    newAngle         = Constants.Deg_270;
                                                }
                                                else
                                                {
                                                    newJustification = AttachmentPoint.TopLeft;
                                                    newAngle         = Constants.Deg_90;
                                                }
                                            }
                                            else
                                            {
                                                newJustification = AttachmentPoint.BottomLeft;
                                                newAngle         = Constants.Deg_0;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        acEditor.WriteMessage("\nInvalid point picked - please try again.");
                                        acTrans.Abort();
                                        // Restore current UCS
                                        acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                                        continue;
                                    }
                                }
                                // Translate these points to the WCS
                                ViewportTableRecord acVportTblRec = acTrans.GetObject(acEditor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord;
                                Matrix3d            jppMatrix     = new Matrix3d();
                                jppMatrix = Matrix3d.AlignCoordinateSystem(Point3d.Origin,
                                                                           Vector3d.XAxis,
                                                                           Vector3d.YAxis,
                                                                           Vector3d.ZAxis,
                                                                           acVportTblRec.Ucs.Origin,
                                                                           acVportTblRec.Ucs.Xaxis,
                                                                           acVportTblRec.Ucs.Yaxis,
                                                                           acVportTblRec.Ucs.Zaxis);
                                Point3d wcsNewLoc = newLocation.TransformBy(jppMatrix);
                                // Transform the new location to coordinates relative to the block reference
                                wcsNewLoc = wcsNewLoc.TransformBy(fflToEdit.BlockTransform.Inverse());
                                // wcsNewLoc = new Point3d(wcsNewLoc.X - fflToEdit.BlockTransform.Translation.X,
                                //                        wcsNewLoc.Y - fflToEdit.BlockTransform.Translation.Y,
                                //                        wcsNewLoc.Z - fflToEdit.BlockTransform.Translation.Z);

                                // Update the text
                                textToEdit.UpgradeOpen();
                                textToEdit.Attachment = newJustification;
                                textToEdit.Location   = wcsNewLoc;
                                textToEdit.Rotation   = newAngle;
                                // Update block graphics
                                // BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;
                                fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;
                                fflToEdit.RecordGraphicsModified(true);

                                acTrans.Commit();
                                // Restore current UCS
                                acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                            }
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception acException)
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog
                                ("The following exception was caught: \n" + acException.Message
                                + "\nError moving level!\n");
                            acTrans.Abort();
                            return(false);
                        }
                    }
                }
                if (nestedEntRes.Status == PromptStatus.Cancel)
                {
                    movingLevels = false;
                }
            }
            return(true);
        }
示例#25
0
        public static void QuickView()
        {
            List <Point2d> viewsLower = new List <Point2d>()
            {
                new Point2d(0, 0.5), new Point2d(0, 0), new Point2d(0.5, 0)
            };
            List <Point2d> viewsUpper = new List <Point2d>()
            {
                new Point2d(0.5, 1), new Point2d(0.5, 0.5), new Point2d(1, 0.5)
            };
            List <OrthographicView> viewsDirection = new List <OrthographicView>()
            {
                OrthographicView.TopView, OrthographicView.FrontView, OrthographicView.RightView,
            };

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            Editor ed = doc.Editor;

            Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.Focus();

            LayoutManager layoutManager = LayoutManager.Current;

            if (layoutManager.LayoutExists("QuickView"))
            {
                layoutManager.CurrentLayout = "Model";
                FirstViewPort = (short)Application.GetSystemVariable("CVPORT");
                Application.SetSystemVariable("CVPORT", FirstViewPort);
                ed.Command("-vports", "toggle");
                return;
            }

            using (DocumentLock lockDoc = doc.LockDocument())
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    ViewportTable       vportTable    = trans.GetObject(db.ViewportTableId, OpenMode.ForWrite) as ViewportTable;
                    ViewportTableRecord vportTableRec = trans.GetObject(ed.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord;

                    BlockTable       bTable    = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord bTableRec = trans.GetObject(bTable[BlockTableRecord.PaperSpace], OpenMode.ForWrite) as BlockTableRecord;

                    FirstViewPort = System.Convert.ToInt16(vportTableRec.Number);

                    vportTableRec.LowerLeftCorner  = new Point2d(0.5, 0.5);
                    vportTableRec.UpperRightCorner = new Point2d(1, 1);

                    vportTableRec.ViewDirection = new Vector3d(Math.Sqrt(1.0 / 3.0), -Math.Sqrt(1.0 / 3.0), Math.Sqrt(1.0 / 3.0));

                    DBDictionary dict = trans.GetObject(db.VisualStyleDictionaryId, OpenMode.ForRead) as DBDictionary;

                    vportTableRec.VisualStyleId = dict.GetAt("2DWireframe");

                    for (int i = 0; i < 3; i++)
                    {
                        using (ViewportTableRecord vportTableRecNew = new ViewportTableRecord())
                        {
                            vportTable.Add(vportTableRecNew);

                            trans.AddNewlyCreatedDBObject(vportTableRecNew, true);

                            vportTableRecNew.SetViewDirection(viewsDirection[i]);

                            vportTableRecNew.Name = "*Active";

                            vportTableRecNew.LowerLeftCorner  = viewsLower[i];
                            vportTableRecNew.UpperRightCorner = viewsUpper[i];
                        }
                    }

                    ed.UpdateTiledViewportsFromDatabase();

                    foreach (ObjectId vp in vportTable)
                    {
                        ViewportTableRecord vpTR = trans.GetObject(vp, OpenMode.ForRead) as ViewportTableRecord;

                        if (vpTR.Name == "*Active")
                        {
                            Application.SetSystemVariable("CVPORT", vpTR.Number);

                            ed.Command("_.zoom", "_extents");
                            ed.Command("_.zoom", "_scale", "0.7x");
                        }
                    }

                    ObjectId layoutID = layoutManager.CreateLayout("QuickView");

                    Layout layout = trans.GetObject(layoutID, OpenMode.ForRead) as Layout;

                    if (layout.TabSelected == false)
                    {
                        layoutManager.CurrentLayout = layout.LayoutName;
                    }

                    BlockTableRecord blckTableRec = trans.GetObject(layout.BlockTableRecordId, OpenMode.ForWrite) as BlockTableRecord;

                    int count = 0;

                    foreach (ObjectId id in blckTableRec)
                    {
                        Viewport vp = trans.GetObject(id, OpenMode.ForRead) as Viewport;

                        if (vp != null && count != 0)
                        {
                            vp.UpgradeOpen();

                            vp.Height = layout.PlotPaperSize.X * 0.4;
                            vp.Width  = layout.PlotPaperSize.Y * 0.4;

                            vp.CenterPoint = new Point3d(layout.PlotPaperSize.Y * 0.75, layout.PlotPaperSize.X * 0.75, 0); vp.SetViewDirection(OrthographicView.NonOrthoView);

                            vp.ViewDirection = new Vector3d(Math.Sqrt(1.0 / 3.0), -Math.Sqrt(1.0 / 3.0), Math.Sqrt(1.0 / 3.0));

                            vp.GridOn = false;

                            ed.SwitchToModelSpace();

                            ed.Command("_.zoom", "_scale", "0.7x");

                            ed.SwitchToPaperSpace();
                        }

                        count++;
                    }

                    List <Point3d> centerPoints = new List <Point3d>()
                    {
                        new Point3d(layout.PlotPaperSize.Y * 0.25, layout.PlotPaperSize.X * 0.75, 0), new Point3d(layout.PlotPaperSize.Y * 0.25, layout.PlotPaperSize.X * 0.25, 0), new Point3d(layout.PlotPaperSize.Y * 0.75, layout.PlotPaperSize.X * 0.25, 0)
                    };

                    for (int i = 0; i < 3; i++)
                    {
                        using (Viewport vp = new Viewport())
                        {
                            ed.SwitchToPaperSpace();

                            blckTableRec.AppendEntity(vp);
                            trans.AddNewlyCreatedDBObject(vp, true);

                            vp.CenterPoint = centerPoints[i];

                            vp.Height = layout.PlotPaperSize.X * 0.4;
                            vp.Width  = layout.PlotPaperSize.Y * 0.4;

                            vp.SetViewDirection(viewsDirection[i]);

                            vp.On = true;

                            ed.SwitchToModelSpace();

                            ed.Command("_.zoom", "_extents");

                            ed.Command("_.zoom", "_scale", "0.7x");
                        }
                    }

                    ed.SwitchToPaperSpace();

                    trans.Commit();
                }
            }

            menu.QuickViewButton.Text = "Toggle viewport";
        }