moveCogoPoint(this ObjectId idCgPnt, Point3d pnt3dTo) { Point3d pnt3dNew = Pub.pnt3dO; try { using (Transaction tr = BaseObjs.startTransactionDb()) { CogoPoint cgPnt = (CogoPoint)tr.GetObject(idCgPnt, OpenMode.ForWrite); Matrix3d matrx3d = BaseObjs._editor.CurrentUserCoordinateSystem; CoordinateSystem3d coordSys = matrx3d.CoordinateSystem3d; Point3d pnt3dFrom = idCgPnt.getCogoPntCoordinates(); Vector3d v3d = new Vector3d(pnt3dTo.X - pnt3dFrom.X, pnt3dTo.Y - pnt3dFrom.Y, 0); pnt3dNew = pnt3dFrom.TransformBy(Matrix3d.Displacement(v3d)); cgPnt.Easting = pnt3dNew.X; cgPnt.Northing = pnt3dNew.Y; } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Mod.cs: line: 554"); } }
TranslateCoordinates(Point3dCollection pnts3d, Point3d pnt3dBase, double angle) { Point3dCollection pnts3dTrans = null; try { using (Transaction tr = BaseObjs.startTransactionDb()) { pnts3dTrans = new Point3dCollection(); // Translate the OCS to WCS Matrix3d matrx3d = BaseObjs._editor.CurrentUserCoordinateSystem; CoordinateSystem3d coordSys = matrx3d.CoordinateSystem3d; foreach (Point3d pnt3d in pnts3d) { pnts3dTrans.Add(pnt3d.TransformBy(Matrix3d.Rotation(angle, coordSys.Zaxis, pnt3dBase))); } // Save the new objects to the database tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " UCsys.cs: line: 379"); } return(pnts3dTrans); }
GetUcsPlane(Database db) { Matrix3d m = GetUcsMatrix(db); CoordinateSystem3d coordSys = m.CoordinateSystem3d; return(new Plane(coordSys.Origin, coordSys.Xaxis, coordSys.Yaxis)); }
public JigPolyBulge(Matrix3d ucs) : base(new Polyline()) { _ucs = ucs; // Get the coordinate system for the UCS passed in, and // create a plane with the same normal (but we won't use // the same origin) CoordinateSystem3d cs = ucs.CoordinateSystem3d; Vector3d normal = cs.Zaxis; _plane = new Plane(Point3d.Origin, normal); // Access our polyline and set its normal Polyline pline = Entity as Polyline; pline.SetDatabaseDefaults(); pline.Normal = normal; // Check the distance from the plane to the coordinate // system's origin (we could use Plane.DistanceTo(), but // then we also need the vector to determine whether it is // co-directional with the normal) Point3d closest = cs.Origin.Project(_plane, normal); Vector3d disp = closest - cs.Origin; // Set the elevation based on the direction of the vector pline.Elevation = disp.IsCodirectionalTo(normal) ? -disp.Length : disp.Length; AddDummyVertex(); }
public void cmdTestUCS() { var doc = AcApp.DocumentManager.MdiActiveDocument; var ed = doc.Editor; var db = doc.Database; using (var tr = db.TransactionManager.StartTransaction()) { var bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; var ms = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; var ucs = new CoordinateSystem3d(new Point3d(11, 22, 0), Vector3d.XAxis, Vector3d.YAxis); //UCS到WCS的转换矩阵 var matrix = Matrix3d.AlignCoordinateSystem(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis, ucs.Origin, ucs.Xaxis, ucs.Yaxis, ucs.Zaxis); ed.CurrentUserCoordinateSystem = matrix; //API中加进去的都是WCS的坐标,我们构造的时候是通过UCS里的坐标值来构造的,真正加进去之前需要转换到WCS var circle = new Autodesk.AutoCAD.DatabaseServices.Circle(); circle.Center = new Point3d(10, 10, 0); circle.Radius = 5; circle.TransformBy(matrix); ms.AppendEntity(circle); tr.AddNewlyCreatedDBObject(circle, true); tr.Commit(); } }
private static void CreateDrawingErrorReferences(Point3d startPoint, Point3d endPoint, global::Autodesk.AutoCAD.DatabaseServices.Database db, CoordinateSystem3d ucs) { try { var tr = db.TransactionManager.StartTransaction(); using (tr) { var btr = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForWrite ); var cir = new Circle(startPoint, ucs.Zaxis, 5); cir.Color = Color.FromColorIndex(ColorMethod.ByColor, 1); btr.AppendEntity(cir); tr.AddNewlyCreatedDBObject(cir, true); tr.Commit(); } } catch { MessengerManager.MessengerManager.AddLog( "\nError calculating enclosing circle." ); } }
public static Point3d[] GetAxisVectorCmd(CoordinateSystem3d ucs) { PromptPointOptions ppo = new PromptPointOptions("\nУкажите первую точку положения оси/грани"); ppo.Keywords.Add("Xaxis", "ОсьХ", "Ось Х", true, true); PromptPointResult ppr = Tools.GetAcadEditor().GetPoint(ppo); if (ppr.Status != PromptStatus.OK) { return(null); } ppo = new PromptPointOptions("\nУкажите вторую точку положения оси/грани"); ppo.UseBasePoint = true; ppo.BasePoint = ppr.Value; ppo.UseDashedLine = true; ppr = Tools.GetAcadEditor().GetPoint(ppo); if (ppr.Status != PromptStatus.OK) { return(null); } var res = new[] { ppo.BasePoint, ppr.Value }; return(res); }
TestImageAngle() { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptEntityOptions prOpts = new PromptEntityOptions("\nSelect an Image"); prOpts.SetRejectMessage("\nSelected entity must by of type RasterImage"); prOpts.AddAllowedClass(typeof(RasterImage), false); PromptEntityResult prRes = ed.GetEntity(prOpts); if (prRes.Status == PromptStatus.OK) { Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = prRes.ObjectId.Database.TransactionManager; using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) { RasterImage imgObj = (RasterImage)tr.GetObject(prRes.ObjectId, OpenMode.ForRead); CoordinateSystem3d entEcs = imgObj.Orientation; Vector3d arbXAxis = Utils.Db.GetEcsXAxis(entEcs.Zaxis); // get AutoCAD's arbitrary X-Axis double rotAngle1 = arbXAxis.GetAngleTo(entEcs.Xaxis, entEcs.Zaxis); ed.WriteMessage(string.Format("\nECS rotation angle: {0}", Autodesk.AutoCAD.Runtime.Converter.AngleToString(rotAngle1, AngularUnitFormat.Current, -1))); Plane ucsPlane = Utils.Db.GetUcsPlane(prRes.ObjectId.Database); double rotAngle2 = entEcs.Xaxis.AngleOnPlane(ucsPlane); ed.WriteMessage(string.Format("\nRotation angle relative to UCS: {0}", Autodesk.AutoCAD.Runtime.Converter.AngleToString(rotAngle2, AngularUnitFormat.Current, -1))); tr.Commit(); } } }
protected CoordinateSystem3d GetECS(ObjectId entityId) { CoordinateSystem3d coordinateSystem3D = new CoordinateSystem3d(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis); if (!entityId.IsNull) { using (OpenCloseTransaction openCloseTransaction = new OpenCloseTransaction()) { Entity obj = (Entity)openCloseTransaction.GetObject(entityId, OpenMode.ForRead); if (obj != null) { //if (obj.IsPlanar || obj is MLeader) //{ Plane plane = obj.GetPlane(); Plane plane1 = new Plane(plane.PointOnPlane, plane.Normal); coordinateSystem3D = plane1.GetCoordinateSystem(); //} //if (obj is Wipeout) //{ // CoordinateSystem3d orientation = (obj as Wipeout).Orientation; // Plane plane2 = new Plane(orientation.Origin, orientation.Zaxis.GetNormal()); // coordinateSystem3d = plane2.GetCoordinateSystem(); //} } openCloseTransaction.Commit(); } } return(coordinateSystem3D); }
public void DisplaceBlock(BlockReference br) { using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { // Open the Block table for read BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForWrite) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; float Zbottom = (float)(ZOnSurface - Z0); // Position the center of the block br.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, Zbottom) - Point3d.Origin)); Matrix3d curUCSMatrix = doc.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; // Rotate the block around the axis that is defined by the points Vector3d vRot = new Point3d(X1, Y1, Z1). GetVectorTo(new Point3d(X0, Y0, ZOnSurface)); br.TransformBy(Matrix3d.Rotation(Slope, vRot, new Point3d(X0, Y0, ZOnSurface))); // Save the new objects to the database acTrans.Commit(); } }
public static ObjectId InsertBlock(Point3d anchorPoint, double Rotation, ObjectId BlockID) { // Get the current document and database Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; ObjectContextCollection occ = acCurDb.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); Transaction acTrans = acDoc.TransactionManager.TopTransaction; // Open the Block table for read BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockDef = BlockID.GetObject(OpenMode.ForRead) as BlockTableRecord; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Insert the block into the current space using (BlockReference acBlkRef = new BlockReference(anchorPoint, BlockID)) { Matrix3d curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; acBlkRef.TransformBy(Matrix3d.Rotation(Rotation, curUCS.Zaxis, anchorPoint)); //For some unknown reason this is needed in Civil3D //TODO: Find reason below line is needed and fix it acBlkRef.TransformBy(Matrix3d.Scaling(1000, anchorPoint)); acBlkRef.AddContext(occ.GetContext("1:1")); acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acBlkTblRec.AppendEntity(acBlkRef); acTrans.AddNewlyCreatedDBObject(acBlkRef, true); // AttributeDefinitions foreach (ObjectId id in blockDef) { DBObject obj = id.GetObject(OpenMode.ForRead); AttributeDefinition attDef = obj as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { //This is a non-constant AttributeDefinition //Create a new AttributeReference using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attDef, acBlkRef.BlockTransform); attRef.TextString = "0"; //Add the AttributeReference to the BlockReference acBlkRef.AttributeCollection.AppendAttribute(attRef); acTrans.AddNewlyCreatedDBObject(attRef, true); } } } return(acBlkRef.ObjectId); } }
/// <summary> 根据给定的参数创建出视口 </summary> /// <param name="docMdf"></param> /// <param name="layout"></param> /// <param name="clipCurveInModel"></param> /// <param name="bottomLeftPt">图框的左下角点</param> /// <param name="bottomRightPt">图框的右下角点</param> /// <param name="bottomLength"></param> private void CreateViewport(DocumentModifier docMdf, CoordinateSystem3d modelUcs, Layout layout, Curve clipCurveInModel, Point3d bottomLeftPt, Point3d bottomRightPt, double bottomLength) { var brt = layout.BlockTableRecordId.GetObject(OpenMode.ForRead) as BlockTableRecord; brt.UpgradeOpen(); // 视口的裁剪区域,此区域可以由多段线、圆弧或样条曲线等来定义,而且曲线可以不闭合。 var layoutClipCurve = Curve.CreateFromGeCurve(geCurve: clipCurveInModel.GetGeCurve()); brt.AppendEntity(layoutClipCurve); docMdf.acTransaction.AddNewlyCreatedDBObject(layoutClipCurve, true); var viewExt = new AdvancedExtents3d(layoutClipCurve.GeometricExtents); var center = viewExt.GetAnchor(AdvancedExtents3d.Anchor.GeometryCenter); // 创建视口 Viewport acVport = new Viewport(); brt.AppendEntity(acVport); docMdf.acTransaction.AddNewlyCreatedDBObject(acVport, true); brt.DowngradeOpen(); // 设置视口所对应的裁剪图形 acVport.NonRectClipEntityId = layoutClipCurve.ObjectId; acVport.NonRectClipOn = true; acVport.On = true; // 如果是新创建的布局,则此视口必须要先设置其 on 为true。 // 将视口放置到不打印层 acVport.Layer = ACadConstants.LayerName_Defpoints; layoutClipCurve.Layer = ACadConstants.LayerName_Defpoints; // ----------------------------------------------- 设置视口的显示区域 acVport.PerspectiveOn = false; // ViewHeight属性– 表示视口内模型空间视图的高度。它决定的视口显示的缩放比例 // 如果要按1:1显示,则需要将其设置为视口多段线所对应的Extents3d的高度。 acVport.ViewHeight = viewExt.GetHeight(); // ViewCenter属性- 表示视口内视图的观察中心。它决定的视口显示的平面定位 // 如果要视图内容范围完全匹配多段线的区域,则需要将其设置为视口多段线的几何中心点。 acVport.ViewCenter = center.ToXYPlane(); //ViewHeight属性– 表示视口内模型空间视图的高度。 acVport.ViewDirection = new Vector3d(0, 0, 1); // ViewTarget属性– 表示视口内视图的目标点的位置。 acVport.ViewTarget = new Point3d(0, 0, 0); acVport.Locked = true; // ----------------------------------------------- 视口对象在布局中的定位 // 对视口所绑定的几何曲线的平移和缩放操作可以对视口进行变换,变换过程中视口中的显示内容在布局中的位置也发生同等变换,即是将视口与其中的内容作为一个整体进行变换 // 但是直接对acVport进行变换,并不会生效。 var scale = bottomLength / bottomLeftPt.DistanceTo(bottomRightPt); var layoutOrigin = new Point3d(0, 0, 0); var disp = bottomLeftPt.GetVectorTo(layoutOrigin).Subtract(modelUcs.Origin.GetAsVector()); docMdf.WriteNow(scale, disp, bottomLeftPt, modelUcs.Origin); layoutClipCurve.TransformBy(Matrix3d.Displacement(disp)); layoutClipCurve.TransformBy(Matrix3d.Scaling(scaleAll: scale, center: (new Point3d(0, 0, 0)))); // //var angle = origin.GetVectorTo(bottomRightPt).GetAngleTo(new Vector3d(1, 0, 0)); //ViewportUtil.RotateViewport(acVport, _docMdf, layout, new Point2d(0, 0), angle); }
/// <summary> /// Механизм определения базового вектора для отрисовки стрелок (XLine) /// </summary> /// <param name="ucs"></param> /// <returns></returns> public static Point3d[] GetAxisVectorCmd(CoordinateSystem3d ucs) { PromptPointOptions ppo = new PromptPointOptions("\nУкажите точку на проектной оси/грани [ОсьХ/ОсьУ/Указать/Выход]<X>:"); ppo.Keywords.Add("Xaxis", "ХОсь", "ХОсь", true, true); ppo.Keywords.Add("Yaxis", "УОсь", "УОсь", true, true); ppo.Keywords.Add("ENter", "УКазать", "УКазать", true, true); ppo.Keywords.Add("EXIt", "ВЫХод", "ВЫХод", true, true); ppo.AllowArbitraryInput = true; PromptPointResult ppr = Tools.GetAcadEditor().GetPoint(ppo); if (ppr.Status == PromptStatus.Keyword) { switch (ppr.StringResult) { case "Xaxis": { return(_vectorToScreen(ucs.Xaxis)); } case "Yaxis": { return(_vectorToScreen(ucs.Yaxis)); } case "Enter": { ppr = Tools.GetAcadEditor().GetPoint(ppo); if (ppr.Status != PromptStatus.OK) { return(null); } break; } case "Exit": { return(null); } } } ppo = new PromptPointOptions("\nУкажите вторую точку положения оси/грани"); ppo.UseBasePoint = true; ppo.BasePoint = ppr.Value; ppo.UseDashedLine = true; ppr = Tools.GetAcadEditor().GetPoint(ppo); if (ppr.Status != PromptStatus.OK) { return(null); } var res = new[] { ppo.BasePoint, ppr.Value }; return(res); }
private Matrix3d _mirror(Matrix3d mat) { CoordinateSystem3d cs = mat.CoordinateSystem3d; Matrix3d res = mat.PreMultiplyBy(Matrix3d.Mirroring( new Plane(cs.Origin, new Vector3d(Math.Abs(Math.Round(cs.Yaxis.X, 6)), Math.Abs(Math.Round(cs.Yaxis.Y, 6)), Math.Abs(Math.Round(cs.Yaxis.Z, 6))), cs.Zaxis))); return(res); }
/// <summary> /// Get a list of Vectors that is vertical to path of all points /// </summary> /// <param name="pts"></param> /// <param name="doc"></param> /// <returns></returns> public static List <Vector3d> getVectors(List <Point3d> pts, Document doc, ref List <Vector3d> vectorsAlongPath) { Editor ed = doc.Editor; //=========== rotate, move the W beam profile to the starting point of the line Matrix3d curUCSMatrix = doc.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; List <Vector3d> vectors = new List <Vector3d>(); int noOfpts = pts.Count(); #region get the first points vector Point3d pt1 = new Point3d(pts[0].X, pts[0].Y, 0); Point3d pt2 = new Point3d(pts[1].X, pts[1].Y, 0); Vector3d vect1 = pt1.GetVectorTo(pt2); ed.WriteMessage($"vect1 => {vect1.X}, {vect1.Y}, {vect1.Z}\n"); Vector3d vect2 = vect1.TransformBy(Matrix3d.Rotation(Helper.Angle.angToRad(90), curUCS.Zaxis, new Point3d(0, 0, 0)));//rotation 90 degree along Z axis ed.WriteMessage($"vect2 => {vect2.X}, {vect2.Y}, {vect2.Z}\n"); vectorsAlongPath.Add(vect1); vectors.Add(vect2); #endregion #region get middle points vectors for (int i = 1; i <= noOfpts - 2; i++) { pt1 = new Point3d(pts[i - 1].X, pts[i - 1].Y, 0); pt2 = new Point3d(pts[i + 1].X, pts[i + 1].Y, 0); vect1 = pt1.GetVectorTo(pt2); ed.WriteMessage($"vect1 => {vect1.X}, {vect1.Y}, {vect1.Z}\n"); vect2 = vect1.TransformBy(Matrix3d.Rotation(Helper.Angle.angToRad(90), curUCS.Zaxis, new Point3d(0, 0, 0)));//rotation 90 degree along Z axis ed.WriteMessage($"vect2 => {vect2.X}, {vect2.Y}, {vect2.Z}\n"); vectorsAlongPath.Add(vect1); vectors.Add(vect2); } #endregion #region get last points vector pt1 = new Point3d(pts[noOfpts - 2].X, pts[noOfpts - 2].Y, 0); pt2 = new Point3d(pts[noOfpts - 1].X, pts[noOfpts - 1].Y, 0); vect1 = pt1.GetVectorTo(pt2); ed.WriteMessage($"vect1 => {vect1.X}, {vect1.Y}, {vect1.Z}\n"); vect2 = vect1.TransformBy(Matrix3d.Rotation(Helper.Angle.angToRad(90), curUCS.Zaxis, new Point3d(0, 0, 0)));//rotation 90 degree along Z axis ed.WriteMessage($"vect2 => {vect2.X}, {vect2.Y}, {vect2.Z}\n"); vectorsAlongPath.Add(vect1); vectors.Add(vect2); #endregion return(vectors); }
/// <summary> /// Creates the new polyliness. /// </summary> /// <param name="_sourcedb">The _sourcedb.</param> /// <param name="_collection">The _collection.</param> public static void CreateNewPolyliness(Autodesk.AutoCAD.DatabaseServices.Database _sourcedb, Point2dCollection _collection) { // Get the current document and database Document acDoc = Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.Database acCurDb = acDoc.Database; Editor ed = acDoc.Editor; // Lock the current document PlanarEntity plane; CoordinateSystem3d ucs = ed.CurrentUserCoordinateSystem.CoordinateSystem3d; plane = new Plane(ucs.Origin, ucs.Xaxis); using (DocumentLock acLckDocCur = acDoc.LockDocument()) { // Start a transaction using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { #region MyRegion // Open the Block table record for read BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; DoubleCollection bulges = new DoubleCollection(); double[] bulgelist = new double[] {}; Point3dCollection p3DCollection = new Point3dCollection(); foreach (var point in _collection) { Point3d p3D = new Point3d(point.X, point.Y, 0.0); p3DCollection.Add(p3D); bulges.Add(0); } Polyline2d polyline2D = new Polyline2d(Poly2dType.SimplePoly, p3DCollection, 0, true, 0, 0, bulges); polyline2D.Color = Color.FromColorIndex(ColorMethod.ByAci, 1); acBlkTblRec.AppendEntity(polyline2D); acTrans.AddNewlyCreatedDBObject(polyline2D, true); #endregion acTrans.Commit(); } // // Unlock the document } }
private static CoordinateSystem3d GetCoordinateSystem(Point3d insertionPoint, decimal width, decimal height) { var widthVector = new Vector3d((double)width, 0, 0); var heightVector = new Vector3d(0, (double)height, 0); var insertionPoint2 = new Point3d(insertionPoint.X, insertionPoint.Y, 0); var coordinateSystem = new CoordinateSystem3d(insertionPoint2, widthVector, heightVector); return(coordinateSystem); }
public void SelectionRotate(Document doc, Point3D xyzAngles) { //if (first == false) //{ //xAnglePrev = xyzAngles.X; //yAnglePrev = xyzAngles.Y; //zAnglePrev = xyzAngles.Z; //first = true; //} Database currentDb = doc.Database; Matrix3d curUCSMatrix = doc.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; using (Transaction trans = currentDb.TransactionManager.StartTransaction()) { if (currentObjects != null) { foreach (SelectedObject curr in currentObjects) { if (curr != null) { Entity acEntity = trans.GetObject(curr.ObjectId, OpenMode.ForWrite) as Entity; if (acEntity != null) { double xRot, yRot, zRot; xRot = xAnglePrev - xyzAngles.X; yRot = yAnglePrev - xyzAngles.Y; zRot = zAnglePrev - xyzAngles.Z; xAnglePrev = xyzAngles.X; yAnglePrev = xyzAngles.Y; zAnglePrev = xyzAngles.Z; acEntity.TransformBy((Matrix3d.Rotation( yRot, Vector3d.YAxis, Point3d.Origin))); acEntity.TransformBy((Matrix3d.Rotation( xRot, Vector3d.XAxis, Point3d.Origin))); acEntity.TransformBy((Matrix3d.Rotation( zRot, Vector3d.ZAxis, Point3d.Origin))); trans.Commit(); } } } } } }
public static void Create() { BaseClass.UseTransaction(trans => { try { //Open the BlockTable for Read BlockTable bt; bt = trans.GetObject(BaseClass.Database.BlockTableId, OpenMode.ForRead) as BlockTable; //Open the BlockTableRecord for Write BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //send message to the user BaseClass.Editor.WriteMessage("\nManipulating an object: "); //create an mtext MText mt1 = new MText(); mt1.TextHeight = 3; mt1.Contents = "Rotating MText"; mt1.ColorIndex = 1; mt1.Location = new Point3d(10, 10, 0); MText mt2 = mt1.Clone() as MText; mt2.ColorIndex = 1; mt2.Contents = "Rotated MText"; //create matrix and move eachcopied entity 20 units to the right //get current coordinate system UCS Matrix3d curUCSMatrix = BaseClass.Document.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; // rotate the poliline 45deg around the Z-azis of the current UCS // using a basepoint of (4,4.25,0) mt2.TransformBy(Matrix3d.Rotation(0.523599, curUCS.Zaxis, new Point3d(0, 0, 0))); //append new objects btr.AppendEntity(mt2); //add line to the BlockTabeReccord trans.AddNewlyCreatedDBObject(mt2, true); //add to the transaction BaseClass.Editor.WriteMessage("\n mtext added to db"); //this command uses an existing AutoCAD command BaseClass.Document.SendStringToExecute("._zoom e ", false, false, false); BaseClass.Editor.WriteMessage("\n Zoom executed"); } catch (System.Exception ex) { BaseClass.Editor.WriteMessage("Error encountered: " + ex.Message); trans.Abort(); } }); }
public double getBulge(Point3d pt, int segNum) { CoordinateSystem3d cs = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d; Plane plane = new Plane(Point3d.Origin, cs.Zaxis); Vector3d vector = _runningLine.GetArcSegmentAt(segNum).Center.GetVectorTo(pt); double ang = vector.GetAngleTo(_runningLine.GetArcSegmentAt(segNum).Center.GetVectorTo(_runningLine.StartPoint)); return(Math.Tan(ang / 4)); }
/// <summary> /// 获取面域的惯性积 /// </summary> /// <param name="region">面域对象</param> /// <returns>返回惯性积</returns> public static double GetProdInertia(this Region region) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; CoordinateSystem3d coord = ed.CurrentUserCoordinateSystem.CoordinateSystem3d; Point3d origin = coord.Origin; Vector3d xAxis = coord.Xaxis; Vector3d yAxis = coord.Yaxis; getAreaProp(region.UnmanagedObject, ref origin, ref xAxis, ref yAxis, out perimeter, out area, out centroid, momInertia, out prodInertia, prinMoments, prinAxes, radiiGyration, out extentsLow, out extentsHigh); return(prodInertia); }
public static void DrawImg(Point3d location, string fileName, string layerName, double height, double width, short colour = 255, bool isClosed = true) { Document doc = Application.DocumentManager.MdiActiveDocument; Database currentDB = doc.Database; CreateLayer(layerName, colour); string imageName = System.IO.Path.GetFileNameWithoutExtension(fileName); using (Transaction tr = currentDB.TransactionManager.StartTransaction()) { RasterImageDef rasterImgDef; ObjectId imgDefId; ObjectId imageDictId = RasterImageDef.GetImageDictionary(currentDB); if (imageDictId.IsNull) { imageDictId = RasterImageDef.CreateImageDictionary(currentDB); } DBDictionary imageDictionary = tr.GetObject(imageDictId, OpenMode.ForRead) as DBDictionary; if (imageDictionary.Contains(imageName)) { imgDefId = imageDictionary.GetAt(imageName); rasterImgDef = tr.GetObject(imageDictId, OpenMode.ForWrite) as RasterImageDef; } else { RasterImageDef newRasterDef = new RasterImageDef(); newRasterDef.SourceFileName = fileName; newRasterDef.Load(); imageDictionary.UpgradeOpen(); imageDictId = imageDictionary.SetAt(imageName, newRasterDef); tr.AddNewlyCreatedDBObject(newRasterDef, true); rasterImgDef = newRasterDef; } BlockTable blockTable = tr.GetObject(currentDB.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockTableRecord = tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; using (RasterImage rasterImg = new RasterImage()) { rasterImg.ImageDefId = imageDictId; Vector3d widthV = new Vector3d(width, 0, 0); Vector3d heightV = new Vector3d(0, height, 0); CoordinateSystem3d coordinate = new CoordinateSystem3d(location, widthV, heightV); rasterImg.Orientation = coordinate; rasterImg.Rotation = 0; rasterImg.Layer = layerName; blockTableRecord.AppendEntity(rasterImg); tr.AddNewlyCreatedDBObject(rasterImg, true); RasterImage.EnableReactors(true); rasterImg.AssociateRasterDef(rasterImgDef); } tr.Commit(); } }
private Point3dCollection PointsForSquareGrip(double num, CoordinateSystem3d ecs) { var horUnit = num * ecs.Xaxis; var verUnit = num * ecs.Yaxis; return(new Point3dCollection { GripPoint - horUnit - verUnit, GripPoint - horUnit + verUnit, GripPoint + horUnit + verUnit, GripPoint + horUnit - verUnit }); }
private Point3dCollection PointsForMinusGrip(double num, CoordinateSystem3d ecs) { var num2 = num / 3; var horUnit = num * ecs.Xaxis; return(new Point3dCollection { GripPoint - horUnit + (num2 * ecs.Yaxis), GripPoint + horUnit + (num2 * ecs.Yaxis), GripPoint + horUnit - (num2 * ecs.Yaxis), GripPoint - horUnit - (num2 * ecs.Yaxis) }); }
public static void Create() { BaseClass.UseTransaction(trans => { try { //Open the BlockTable for Read BlockTable bt; bt = trans.GetObject(BaseClass.Database.BlockTableId, OpenMode.ForRead) as BlockTable; //Open the BlockTableRecord for Write BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //send message to the user BaseClass.Editor.WriteMessage("\nManipulating an object: "); //create a cirle using (Polyline pline = new Polyline()) { pline.AddVertexAt(0, new Point2d(1, 2), 0, 0, 0); pline.AddVertexAt(1, new Point2d(1, 3), 0, 0, 0); pline.AddVertexAt(2, new Point2d(2, 3), 0, 0, 0); pline.AddVertexAt(3, new Point2d(3, 3), 0, 0, 0); pline.AddVertexAt(4, new Point2d(4, 4), 0, 0, 0); pline.AddVertexAt(5, new Point2d(4, 2), 0, 0, 0); //pline.SetBulgeAt(1, -2);//Create bulge of -2 at vertex 1 pline.Closed = true; //Close polyline //get current coordinate system UCS Matrix3d curUCSMatrix = BaseClass.Document.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; // rotate the poliline 45deg around the Z-azis of the current UCS // using a basepoint of (4,4.25,0) pline.TransformBy(Matrix3d.Rotation(0.7845, curUCS.Zaxis, new Point3d(4, 4.25, 0))); //45deg = 0.7845 radiant //add the new object to the block table record btr.AppendEntity(pline); //add line to the BlockTabeReccord trans.AddNewlyCreatedDBObject(pline, true); //add to the transaction } } catch (System.Exception ex) { BaseClass.Editor.WriteMessage("Error encountered: " + ex.Message); trans.Abort(); } }); }
public static void Annotate(Polyline3d acPoly3d) { //Get lable point Point3d labelPoint3d = acPoly3d.GetPointAtDist(acPoly3d.Length / 2); Point3d labelPoint = new Point3d(labelPoint3d.X, labelPoint3d.Y, 0); Database acCurDb; acCurDb = Application.DocumentManager.MdiActiveDocument.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { // Open the Block table for read BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; ObjectId blkRecId = ObjectId.Null; if (!acBlkTbl.Has("PipeLabel")) { Main.LoadBlocks(); } Matrix3d curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; //calculate angle of line Point3d start = acPoly3d.GetPointAtDist(0); Point3d end = acPoly3d.GetPointAtDist(acPoly3d.Length); double angle = Math.Atan((end.Y - start.Y) / (end.X - start.X)); // Insert the block into the current space using (BlockReference acBlkRef = new BlockReference(labelPoint, acBlkTbl["PipeLabel"])) { acBlkRef.TransformBy(Matrix3d.Rotation(angle, curUCS.Zaxis, labelPoint)); BlockTableRecord acCurSpaceBlkTblRec; acCurSpaceBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acCurSpaceBlkTblRec.AppendEntity(acBlkRef); acTrans.AddNewlyCreatedDBObject(acBlkRef, true); } acTrans.Commit(); } }
private Point3dCollection PointsForTwoArrowsGripUpDownFirstArrow(double num, CoordinateSystem3d ecs) { var horUnit = num * ecs.Xaxis; var verUnit = num * ecs.Yaxis; return(new Point3dCollection { GripPoint - (verUnit * 0.25), GripPoint - (horUnit * 0.75) + (verUnit * 1.25), GripPoint - (horUnit * 1.5) - (verUnit * 0.25), GripPoint - (horUnit * 1.0) - (verUnit * 0.25), GripPoint - (horUnit * 1.0) - (verUnit * 1.25), GripPoint - (horUnit * 0.5) - (verUnit * 1.25), GripPoint - (horUnit * 0.5) - (verUnit * 0.25) }); }
private Point3dCollection PointsForReverseGripSecondArrow(double num, CoordinateSystem3d ecs) { var horUnit = num * ecs.Xaxis; var verUnit = num * ecs.Yaxis; return(new Point3dCollection { GripPoint + (verUnit * 0.25), GripPoint + (horUnit * 0.75) - (verUnit * 1.25), GripPoint + (horUnit * 1.5) + (verUnit * 0.25), GripPoint + (horUnit * 1.0) + (verUnit * 0.25), GripPoint + (horUnit * 1.0) + (verUnit * 1.25), GripPoint + (horUnit * 0.5) + (verUnit * 1.25), GripPoint + (horUnit * 0.5) + (verUnit * 0.25) }); }
public void InserirBlocoNoDesenho(string nomeArquivo) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database currDwgDb = acDoc.Database; Editor acDocEd = acDoc.Editor; try { using (DocumentLock docLock = acDoc.LockDocument()) { using (Database xDb = new Database(false, true)) { xDb.ReadDwgFile(nomeArquivo, System.IO.FileShare.Read, true, ""); using (Transaction tr = acDoc.TransactionManager.StartTransaction()) { string name = SymbolUtilityServices.GetBlockNameFromInsertPathName(nomeArquivo); ObjectId id = currDwgDb.Insert(name, xDb, true); if (id.IsNull) { acDocEd.WriteMessage("Failed to insert block"); return; } BlockTableRecord currSpace = (BlockTableRecord)(tr.GetObject(currDwgDb.CurrentSpaceId, OpenMode.ForWrite)); PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); //Escolher o ponto de inserção pPtOpts.Message = "\nEscolha o ponto de inserção do insumo: "; pPtRes = acDoc.Editor.GetPoint(pPtOpts); Point3d p3d = pPtRes.Value; CoordinateSystem3d coordS = new CoordinateSystem3d(p3d, currDwgDb.Ucsxdir, currDwgDb.Ucsydir); BlockReference insert = new BlockReference(p3d, id); insert.Normal = coordS.Zaxis; currSpace.AppendEntity(insert); insert.SetDatabaseDefaults(); tr.AddNewlyCreatedDBObject(insert, true); tr.Commit(); } } } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { acDocEd.WriteMessage("\nError during copy: " + ex.Message); } }
rotateEnt(this ObjectId id, Point3d pnt3d, double delta) { try { using (Transaction tr = BaseObjs.startTransactionDb()) { Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite); Matrix3d curUCSMatrix = BaseObjs._editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; ent.TransformBy(Matrix3d.Rotation(delta, curUCS.Zaxis, pnt3d)); tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Mod.cs: line: 685"); } }
public void NavigateWithKinect() { Document doc = Autodesk.AutoCAD.ApplicationServices. Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // As the user to select the camera and target locations PromptPointResult camRes = ed.GetPoint("\nPick camera location"); if (camRes.Status != PromptStatus.OK) return; PromptPointResult tgtRes = ed.GetPoint("\nPick target location"); if (tgtRes.Status != PromptStatus.OK) return; // And also the height from ground level PromptDoubleOptions pdo = new PromptDoubleOptions("\nEnter height from ground"); pdo.UseDefaultValue = true; // Default height of 6' or 2m pdo.DefaultValue = (db.Lunits > 2 ? 6 : 2); PromptDoubleResult hgtRes = ed.GetDouble(pdo); if (hgtRes.Status != PromptStatus.OK) return; _zoomDist = hgtRes.Value / 10.0; // We need a Kinect object KinectSensor kinect = null; // Make sure we dispose of our Camera (which will // commit the transaction) Camera camera = new Camera(doc); using (camera) { // Set the height from the ground as a vector Vector3d height = new Vector3d(0, 0, hgtRes.Value); camera.Location = camRes.Value + height; camera.Target = tgtRes.Value + height; camera.ApplyToCurrentView(); // Unset the loop termination flag _finished = false; _reset = true; if (KinectSensor.KinectSensors.Count <= 0) { ed.WriteMessage( "\nUnable to start Kinect sensor - " + "are you sure it's plugged in?" ); return; } // We need our Kinect sensor kinect = KinectSensor.KinectSensors[0]; // We only care about skeleton information kinect.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>( OnSkeletonFrameReady ); kinect.SkeletonStream.Enable(); kinect.Start(); // Loop until user terminates or cancels while ( !_finished && !HostApplicationServices.Current.UserBreak() ) { // Direction from Kinect is: // // 0, 0, 1 - arm pointing directly at the center // 1, 0, 0 - arm pointing directly left // -1, 0, 0 - arm pointing directly right // 0, 1, 0 - arm pointing directly down // 0, -1, 0 - arm pointing directly up const double distFac = 0.001; const double angFac = 0.003; if (_reset) { // Reset to the initial view parameters camera.Location = camRes.Value + height; camera.Target = tgtRes.Value + height; camera.ApplyToCurrentView(); _reset = false; } else if (_orbiting || _navigating) { Matrix3d locMat = Matrix3d.Identity; // We only orbit if not too close to the centre if (Math.Abs(_direction.X) > 0.2) { locMat = Matrix3d.Rotation( -_direction.X * angFac, Vector3d.ZAxis, camera.Target ) * locMat; } // And the same for upwards/downwards tilt if (Math.Abs(_direction.Y) > 0.2) { // To tilt upwards/downwards, we need the right axis // of rotation. Use a coordinate system object taking // the view direction as the Y axis and the Z axis of // WCS as the X axis, leaving the Z axis of the // coordinate system as our axis of rotation Vector3d newYaxis = camera.Location - camera.Target; newYaxis = newYaxis / newYaxis.Length; CoordinateSystem3d cs = new CoordinateSystem3d( camera.Target, Vector3d.ZAxis, newYaxis ); locMat = Matrix3d.Rotation( -_direction.Y * angFac, cs.Zaxis, camera.Target ) * locMat; } // If we're zooming, we adjust the camera and target // locations by a displacement along the viewing // direction if (_navigating) { Matrix3d trgMat = Matrix3d.Displacement( (camera.Target - camera.Location) * distFac ); locMat = trgMat * locMat; camera.TargTransform = trgMat; } camera.LocTransform = locMat; camera.ApplyToCurrentView(); } // Reset the transformation values camera.LocTransform = Matrix3d.Identity; camera.TargTransform = Matrix3d.Identity; System.Windows.Forms.Application.DoEvents(); } } kinect.Stop(); kinect.SkeletonFrameReady -= new EventHandler<SkeletonFrameReadyEventArgs>( OnSkeletonFrameReady ); }