コード例 #1
0
        Matrix3d BendMatrix(Point3d origin, Point3d fromp, Point3d to)
        {
            Vector3d oldx = fromp.GetAsVector().Subtract(origin.GetAsVector());
            Vector3d newx = to.GetAsVector().Subtract(origin.GetAsVector());

            Plane xoy = new Plane(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis);

            double angle = newx.AngleOnPlane(xoy) - oldx.AngleOnPlane(xoy);

            return(Matrix3d.Rotation(angle, Vector3d.ZAxis, origin));
        }
コード例 #2
0
ファイル: DrawTails.cs プロジェクト: koropet/PKUserTools
        void TransformTail(Point3d p1, Point3d p11, double bulge, sbyte flip, ref Polyline tail, out double offset)
        {
            double angle = 2 * Math.Atan(bulge);

            /*угол касательной аналитически получен как 2 вписанных угла. Например, если bulge равно 1, то
             * имеем дугу с хордой равной двум выпуклостям. Это соответствует углу между хордой и касательной 90 градусов, а угол между хордой
             * и хордой к середине дуги 45 градусов
             */
            angle *= flip;           //чтобы было в нужную сторону на обоих концах

            Vector3d p1p2v = p1.Subtract(p11.GetAsVector()).GetAsVector();

            p1p2v = p1p2v.RotateBy(angle, Vector3d.ZAxis * -1);          //-1здесь служит для корректировки направления (по результатам отладки)

            Point2d first = tail.GetPoint2dAt(0);

            offset = first.Y * offsetMode * side;

            //смысл смещения заключается в том, что иногда требуется нарисовать шпильки со смещением от базовой линии
            //смещение управляется начальной координатой хвоста

            Matrix3d M = Matrix3d.AlignCoordinateSystem(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis,
                                                        p1, p1p2v.DivideBy(p1p2v.Length), p1p2v.GetPerpendicularVector().MultiplyBy(side * flip), Vector3d.ZAxis);

            M *= Matrix3d.Displacement(Vector3d.YAxis * first.Y * -1 * (offsetMode ^ 1));


            tail.TransformBy(M);
        }
コード例 #3
0
ファイル: Commands.cs プロジェクト: jajazhou/PIOTM-QRCode
        private static void SetXDataAndMoveToLocation(
            Entity ent, ResultBuffer rbdata, Point3d pt
            )
        {
            Database db =
                Application.DocumentManager.MdiActiveDocument.Database;
            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                ent =
                    tr.GetObject(ent.ObjectId, OpenMode.ForWrite) as Entity;

                // Let's add our message information as XData,
                // for later editing

                RbEncoder.AddRegAppTableRecord(APPLICATION_PREFIX);
                ResultBuffer rb = rbdata;
                ent.XData = rb;
                rb.Dispose();

                // Move to the correct location

                Matrix3d disp = Matrix3d.Displacement(pt.GetAsVector());
                ent.TransformBy(disp);

                tr.Commit();
            }
        }
コード例 #4
0
ファイル: Db.cs プロジェクト: zhengjian211/MgdDbg
        MakeExtentsBlock(BoundBlock3d ext, int colorIndex, Database db)
        {
            Point3d minPt = ext.GetMinimumPoint();
            Point3d maxPt = ext.GetMaximumPoint();

            double deltaX = Math.Abs(maxPt.X - minPt.X);
            double deltaY = Math.Abs(maxPt.Y - minPt.Y);
            double deltaZ = Math.Abs(maxPt.Z - minPt.Z);

            Point3d[] pts = new Point3d[8];

            pts[0] = minPt;
            pts[6] = maxPt;

            // make bottom face
            pts[1] = new Point3d(pts[0].X + deltaX, pts[0].Y, pts[0].Z);
            pts[2] = new Point3d(pts[1].X, pts[1].Y + deltaY, pts[1].Z);
            pts[3] = new Point3d(pts[0].X, pts[0].Y + deltaY, pts[0].Z);

            // project up by Z
            pts[4] = new Point3d(pts[0].X, pts[0].Y, pts[0].Z + deltaZ);
            pts[5] = new Point3d(pts[1].X, pts[1].Y, pts[1].Z + deltaZ);
            pts[7] = new Point3d(pts[3].X, pts[3].Y, pts[3].Z + deltaZ);

            Vector3d offset = minPt.GetAsVector();

            // move points so that they are centered at WCS origin
            // for block creation.  Express everything in WCS since
            // that is what Entity.Extents works in.
            for (int i = 0; i < pts.Length; i++)
            {
                pts[i] -= offset;
            }

            DBObjectCollection faceEnts = new DBObjectCollection();

            faceEnts.Add(new Face(pts[0], pts[1], pts[2], pts[3], true, true, true, true));  // bottom face
            faceEnts.Add(new Face(pts[4], pts[5], pts[6], pts[7], true, true, true, true));  // top face
            faceEnts.Add(new Face(pts[0], pts[1], pts[5], pts[4], true, true, true, true));  // front face
            faceEnts.Add(new Face(pts[1], pts[2], pts[6], pts[5], true, true, true, true));  // right side face
            faceEnts.Add(new Face(pts[2], pts[3], pts[7], pts[6], true, true, true, true));  // back side face
            faceEnts.Add(new Face(pts[3], pts[0], pts[4], pts[7], true, true, true, true));  // left side face

            CompBldrAnonBlkDef compBldr = new CompBldrAnonBlkDef(db);

            compBldr.Start();

            foreach (Entity ent in faceEnts)
            {
                compBldr.SetToDefaultProps(ent);
                compBldr.AddToDb(ent);
            }

            compBldr.Commit();

            BlockReference blkRef = new BlockReference(minPt, compBldr.BlockDefId);

            blkRef.ColorIndex = colorIndex;
            Utils.SymTbl.AddToCurrentSpaceAndClose(blkRef, compBldr.Database);
        }
コード例 #5
0
ファイル: Utilities.cs プロジェクト: koropet/PKUserTools
        /// <summary>
        /// Везвращает вектор единичной длины из 2 точек
        /// </summary>
        /// <param name="p1">Конец</param>
        /// <param name="p2">Начало</param>
        /// <returns></returns>
        public static Vector3d GetUniteVector(Point3d p1, Point3d p2)
        {
            var vp1p2 = (p2.GetAsVector().Subtract(p1.GetAsVector()));

            vp1p2 = vp1p2.MultiplyBy(1 / vp1p2.Length);
            return(vp1p2);
        }
コード例 #6
0
ファイル: StepsParser.cs プロジェクト: koropet/PKUserTools
		public List<Point3d> Points (Point3d start, Point3d dir)
		{
			Vector3d delta = dir.GetAsVector().Subtract(start.GetAsVector());
			delta=delta.DivideBy(delta.Length);
			
			return steps.Select(d=>start.Add(delta*d)).ToList();
		}
コード例 #7
0
                public void RedirectVerticalArrow(Vector3d direction)
                {
                    double rd = 1;

                    if (IsVerticalRedirected)
                    {
                        rd *= -1;
                    }
                    if (IsVerticalMirrored)
                    {
                        rd *= -1;
                    }
                    if (rd * direction.Y >= 0)
                    {
                        return;
                    }

                    rd = IsVerticalRedirected ? -1 : 1;

                    Point3d  destPoint = Point3d.Origin.Add(_verticalTarnsform.CoordinateSystem3d.Yaxis.MultiplyBy(-rd * (_spaceLength * 2d + _length + _arrowLength)));
                    Matrix3d mat       = Matrix3d.Displacement(destPoint.GetAsVector());

                    VerticalTarnsform    = mat;
                    IsVerticalRedirected = !IsVerticalRedirected;
                }
コード例 #8
0
        public static void TecTest()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction Tx = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord ms      = (BlockTableRecord)Tx.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead);
                RXObject         brClass = RXObject.GetClass(typeof(BlockReference));

                Point3d lastrightpt = new Point3d(0, 0, 0);

                foreach (ObjectId id in ms)
                {
                    if (id.ObjectClass == brClass)
                    {
                        BlockReference br = (BlockReference)Tx.GetObject(id, OpenMode.ForWrite);
                        ed.WriteMessage("NAME:{0}\n", br.Name);
                        Extents3d bounds = br.GeometricExtents;
                        ed.WriteMessage("BOUNDS: {0}\n", bounds.ToString());
                        Vector3d vec = (Vector3d)(lastrightpt - bounds.MinPoint);
                        ed.WriteMessage("VECTOR: {0}\n", vec.ToString());

                        Point3d  rightpt = new Point3d(bounds.MaxPoint.X, bounds.MinPoint.Y, 0);;
                        Vector3d newrp   = (Vector3d)(vec + rightpt.GetAsVector() + (new Vector3d(50, 0, 0)));
                        lastrightpt = new Point3d(newrp.X, newrp.Y, 0);
                        ed.WriteMessage("NEWLASTRIGHT SET to {0}\n", lastrightpt);
                        Matrix3d mat = Matrix3d.Displacement(vec);
                        br.TransformBy(mat);
                    }
                }
                Tx.Commit();
            }
        }
コード例 #9
0
        int CheckSegment(Point3d origin, Point3d fromp, ref Polyline pl, out bool forward)
        {
            forward = true;
            int segment = 0;

            Point3d  back, forw;
            Vector3d back_v, forw_v, from_v;
            double   angle_forw_backw, angle_from_back;

            for (int i = 0; i < pl.NumberOfVertices; i++)
            {
                back = pl.GetPoint3dAt(i);
                forw = pl.GetPoint3dAt(i + 1);

                back_v = back.GetAsVector().Subtract(origin.GetAsVector());
                forw_v = forw.GetAsVector().Subtract(origin.GetAsVector());
                from_v = fromp.GetAsVector().Subtract(origin.GetAsVector());

                angle_forw_backw = forw_v.GetAngleTo(back_v);
                angle_from_back  = from_v.GetAngleTo(back_v);

                if (angle_forw_backw > Math.PI * 0.5)
                {
                    segment = i;
                    if (angle_from_back >= Math.PI * 0.5 && angle_from_back <= Math.PI * 1.5)
                    {
                        forward = true;
                    }
                    else
                    {
                        if (angle_from_back < Math.PI * 0.5 || angle_from_back > Math.PI * 1.5)
                        {
                            forward = false;
                        }
                        else
                        {
                            Tweet("Что-то не так с углами " + angle_forw_backw + " " + angle_from_back);
                        }
                    }

                    break;
                }
            }
            return(segment);
        }
コード例 #10
0
        private Polyline CalcPassPline(Curve rail, Point3d point, Polyline profilePline, int processSide)
        {
            var angle  = Math.PI - rail.GetFirstDerivative(point).ToVector2d().MinusPiToPiAngleTo(processSide * Vector2d.YAxis);
            var matrix = Matrix3d.Displacement(point.GetAsVector()) *
                         Matrix3d.Rotation(angle, Vector3d.ZAxis, Point3d.Origin) *
                         Matrix3d.Rotation(Math.PI / 2, Vector3d.XAxis, Point3d.Origin);

            return(profilePline.GetTransformedCopy(matrix) as Polyline);
        }
コード例 #11
0
ファイル: Valve.cs プロジェクト: coordinate/MyLearnning
        /// <summary>
        /// 使用阀门1打断管道。
        /// </summary>
        /// <param name="poly"></param>
        /// <param name="insPt"></param>
        private static void BreakPipeWithValveType1(Polyline poly, Point3d insPt)
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;

            for (var i = 0; i < poly.NumberOfVertices - 1; i++)
            {
                if (poly.OnSegmentAt(i, new Point2d(insPt.X, insPt.Y), 0))
                {
                    var lineSeg = poly.GetLineSegmentAt(i);

                    var angle = Vector3d.XAxis.GetAngleTo(lineSeg.Direction);
                    if (Vector3d.XAxis.CrossProduct(lineSeg.Direction).Z < 0)
                    {
                        angle = -angle;
                    }

                    // 块坐标变换。
                    var transform = Matrix3d.Displacement(insPt.GetAsVector()) *
                                    Matrix3d.Rotation(angle, Vector3d.ZAxis, Point3d.Origin);

                    // 将阀门插入到指定位置。
                    var valveId = DBHelper.Insert(DBHelper.GetSymbol(db.BlockTableId, kValve1BlkName), transform);

                    // 插入阀门顶点,隐藏原始线条。
                    var insIdx = i + 1;
                    // 保存原有线条宽度。
                    var sw = poly.GetStartWidthAt(i);
                    var ew = poly.GetEndWidthAt(i);
                    // 求插入顶点。
                    var insPts = new[]
                    {
                        new Point3d(-kValve1Length * 0.5, 0, 0).TransformBy(transform),
                        new Point3d(-kValve1Length * 0.5, -kValve1Width * 0.5, 0).TransformBy(transform),
                        new Point3d(kValve1Length * 0.5, kValve1Width * 0.5, 0).TransformBy(transform),
                        new Point3d(kValve1Length * 0.5, 0, 0).TransformBy(transform),
                    };
                    // 将插入点顺序调整至与线段朝向相反。(插入时按insIdx插入会再次反向)
                    if (lineSeg.Direction.DotProduct(insPts[insPts.Length - 1] - insPts[0]) > 0)
                    {
                        Array.Reverse(insPts);
                    }

                    poly.AddVertexAt(insIdx, new Point2d(insPts[0].X, insPts[0].Y), 0, 0, 0);
                    poly.AddVertexAt(insIdx, new Point2d(insPts[1].X, insPts[1].Y), 0, 0, 0);
                    poly.AddVertexAt(insIdx, new Point2d(insPts[2].X, insPts[2].Y), 0, 0, 0);
                    poly.AddVertexAt(insIdx, new Point2d(insPts[3].X, insPts[3].Y), 0, sw, ew);

                    break;
                }
            }
        }
コード例 #12
0
        private void NewPos()
        {
            Autodesk.AutoCAD.EditorInput.Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointResult result = ed.GetPoint("Baz noktası: ");

            if (result.Status == PromptStatus.OK)
            {
                Database db = HostApplicationServices.WorkingDatabase;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                        Point3d  pt  = result.Value;
                        RebarPos pos = new RebarPos();
                        pos.TransformBy(Matrix3d.Displacement(pt.GetAsVector()));
                        pos.TransformBy(Matrix3d.Scaling(25.0, pt));

                        pos.Pos      = "";
                        pos.Count    = "1";
                        pos.Diameter = "12";
                        pos.Spacing  = "";
                        pos.Shape    = "GENEL";
                        pos.A        = "1000";
                        pos.Note     = "";

#if DEBUG
                        pos.Pos      = "1";
                        pos.Count    = "2x3";
                        pos.Diameter = "12";
                        pos.Spacing  = "200";
                        pos.Shape    = "00";
                        pos.A        = "1000";
                        pos.Note     = "";
#endif

                        pos.SetDatabaseDefaults(db);

                        btr.AppendEntity(pos);
                        tr.AddNewlyCreatedDBObject(pos, true);

                        tr.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message, "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
コード例 #13
0
            public void Redirect()
            {
                if (IsCodirectional || this.BaseArrow == null)
                {
                    Point3d destPoint = Point3d.Origin.Add(_lineTarnsform.CoordinateSystem3d.Xaxis.Negate()
                                                           .MultiplyBy((IsRedirected ? -1 : 1) * (_spaceLength * 2d + _length + _arrowLength)));
                    Matrix3d mat = Matrix3d.Displacement(destPoint.GetAsVector());
                    LineTarnsform = mat;
                    IsRedirected  = !IsRedirected;

                    if (IsCodirectional)
                    {
                        this.BaseArrow.Redirect();
                    }
                }
            }
コード例 #14
0
ファイル: Db.cs プロジェクト: zhengjian211/MgdDbg
        GetUcsToWcsOriginMatrix(Point3d wcsBasePt, Database db)
        {
            Matrix3d m = GetUcsMatrix(db);

            Point3d origin = m.CoordinateSystem3d.Origin;

            origin += wcsBasePt.GetAsVector();

            m = Matrix3d.AlignCoordinateSystem(origin,
                                               m.CoordinateSystem3d.Xaxis,
                                               m.CoordinateSystem3d.Yaxis,
                                               m.CoordinateSystem3d.Zaxis,
                                               Utils.Ge.kOrigin, Utils.Ge.kXAxis, Utils.Ge.kYAxis, Utils.Ge.kZAxis);

            return(m);
        }
コード例 #15
0
        private BlockReference CreateBlockRef(DocumentModifier docMdf, BlockTableRecord space, BlockTableRecord blockDef, AttributeDefinition attDef,
                                              Point3d position)
        {
            BlockReference bref = new BlockReference(position, blockDef.Id);

            space.AppendEntity(bref);
            docMdf.acTransaction.AddNewlyCreatedDBObject(bref, true);
            //
            AttributeReference ar = new AttributeReference(attDef.Position.Add(position.GetAsVector()),
                                                           position.Z.ToString(), BlockAttributeName, style: attDef.TextStyleId);

            bref.AttributeCollection.AppendAttribute(ar);
            ar.DowngradeOpen();  //  AttributeReference 在 DowngradeOpen 后,才会立即显示,否则要通过Refresh等方法使其 DowngradeOpen 才能显示。
            bref.DowngradeOpen();
            return(bref);
        }
コード例 #16
0
        private void btn_adjust_road_start_Click(object sender, EventArgs e)
        {
            Editor ed = cadSer.Application.DocumentManager.MdiActiveDocument.Editor;


            Database db     = HostApplicationServices.WorkingDatabase;
            var      middoc = cadSer.Application.DocumentManager.MdiActiveDocument;


            ObjectId plineID  = ed.GetEntity(new PromptEntityOptions("\n选取多段线!!!")).ObjectId;
            var      doc_lock = middoc.LockDocument();

            DBObject dbo;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                dbo = trans.GetObject(plineID, OpenMode.ForWrite);

                while (!dbo.GetType().Equals(typeof(Polyline)))
                {
                    ed.WriteMessage("\n刚才选取的不是Pline,请重新选择!!!");
                    plineID = ed.GetEntity(new PromptEntityOptions("\n选取多段线!!!")).ObjectId;
                    dbo     = trans.GetObject(plineID, OpenMode.ForWrite);
                }



                Point3d poindstart = ed.GetPoint(new PromptPointOptions("\n选取起点")).Value;

                Polyline polyline = (Polyline)dbo;

                Vector3d tmp_vector = polyline.StartPoint.GetAsVector() - poindstart.GetAsVector();
                tmp_vector = new Vector3d(tmp_vector.X, tmp_vector.Y, 0);

                if (tmp_vector.Length > 1.0)
                {
                    polyline.ReverseCurve();
                    zjyCAD.ToModelSpace(polyline, db);
                }



                trans.Commit();
            }
            doc_lock.Dispose();
        }
コード例 #17
0
ファイル: PatternCopy.cs プロジェクト: koropet/PKUserTools
 void Copy(List <Point3d> points, List <Entity> to_clone, Point3d basept)
 {
     using (TransactionHelper th = new TransactionHelper())
     {
         foreach (Point3d pt in points)
         {
             offset = pt.Subtract(basept.GetAsVector());
             if (offset == Point3d.Origin)
             {
                 continue;                                              //исключаем копирование в ту же точку
             }
             M = Matrix3d.Displacement(offset.GetAsVector());
             foreach (Entity ent in to_clone)
             {
                 Entity ent_clone = ent.GetTransformedCopy(M);
                 th.WriteObject(ent_clone);
             }
         }
     }
 }
コード例 #18
0
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            var jppo = new JigPromptPointOptions(_message)
            {
                Cursor            = CursorType.EntitySelect,
                UseBasePoint      = false,
                UserInputControls = UserInputControls.NullResponseAccepted
            };

            jppo.Keywords.Add(""); // mod 20140527
            var    corner  = prompts.AcquirePoint(jppo).Value;
            var    pos     = Point3d.Origin + 0.5 * (_basePoint.GetAsVector() + corner.GetAsVector());
            var    extents = Ent.GeometricExtents;
            double scale   = Math.Min(
                Math.Abs(corner.X - _basePoint.X) / (extents.MaxPoint.X - extents.MinPoint.X),
                Math.Abs(corner.Y - _basePoint.Y) / (extents.MaxPoint.Y - extents.MinPoint.Y));

            // NOTE: the scale is likely small at the beginning. Too small a scale leads to non-proportional scaling for matrix operation, and thus gets rejected by AutoCAD and causes exception.
            if (scale < Consts.Epsilon)
            {
                scale = Consts.Epsilon;
            }
            if (pos.IsNull())
            {
                return(SamplerStatus.Cancel);
            }
            else if (pos != _pos)
            {
                _move = pos - _pos;
                _pos  = pos;
                //_mag = scale / _scale;
                //_scale = scale;
                _mag = scale;
                return(SamplerStatus.OK);
            }
            else
            {
                _move = pos - _pos;
                return(SamplerStatus.NoChange);
            }
        }
コード例 #19
0
        private void ZoomWindow(Point3d pt1, Point3d pt2)
        {
            using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
            {
                using (AbstractViewPE pVpPE = new AbstractViewPE(pView))
                {
                    pt1 = pt1.TransformBy(pVpPE.WorldToEye);
                    pt2 = pt2.TransformBy(pVpPE.WorldToEye);
                    Vector3d eyeVec = pt2 - pt1;

                    if (((eyeVec.X < -1E-10) || (eyeVec.X > 1E-10)) && ((eyeVec.Y < -1E-10) || (eyeVec.Y > 1E-10)))
                    {
                        Point3d newPos = pt1 + eyeVec / 2.0;
                        pView.Dolly(newPos.GetAsVector());
                        double wf = pView.FieldWidth / Math.Abs(eyeVec.X);
                        double hf = pView.FieldHeight / Math.Abs(eyeVec.Y);
                        pView.Zoom(wf < hf ? wf : hf);
                        Invalidate();
                    }
                }
            }
        }
コード例 #20
0
        public static void UpdateSolid3D(ObjectId objectId, dynamic xb)
        {
            Editor   ed      = acApp.DocumentManager.MdiActiveDocument.Editor;
            Document acDoc   = acApp.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            Point3d p1 = new Point3d(Convert.ToDouble(xb.x1), Convert.ToDouble(xb.y1), Convert.ToDouble(xb.z1));
            Point3d p2 = new Point3d(Convert.ToDouble(xb.x2), Convert.ToDouble(xb.y2), Convert.ToDouble(xb.z2));

            //acCurDb.TryGetObjectId();
            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                Solid3d acSol3DBox = (Solid3d)acTrans.GetObject(objectId, OpenMode.ForWrite);
                acSol3DBox.CreateBox(Math.Abs(p2.X - p1.X), Math.Abs(p2.Y - p1.Y), Math.Abs(p2.Z - p1.Z));
                Point3d center = new Point3d(p1.X + ((p2.X - p1.X) / 2), p1.Y + ((p2.Y - p1.Y) / 2), p1.Z + ((p2.Z - p1.Z) / 2));
                acSol3DBox.TransformBy(Matrix3d.Displacement(center.GetAsVector()));
                acSol3DBox.Draw();
                acTrans.Commit();
                ed.UpdateScreen();
            }
        }
コード例 #21
0
ファイル: Interaction.cs プロジェクト: iamHXQ/Oy
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            JigPromptPointOptions jppo = new JigPromptPointOptions(_message);

            jppo.Keywords.Add(""); // mod 20140527
            jppo.Cursor            = CursorType.EntitySelect;
            jppo.UseBasePoint      = false;
            jppo.UserInputControls = UserInputControls.NullResponseAccepted;
            Point3d corner  = prompts.AcquirePoint(jppo).Value;
            Point3d pos     = Point3d.Origin + 0.5 * (_basePoint.GetAsVector() + corner.GetAsVector());
            var     extents = _ent.GeometricExtents;
            double  scale   = Math.Min(
                Math.Abs(corner.X - _basePoint.X) / (extents.MaxPoint.X - extents.MinPoint.X),
                Math.Abs(corner.Y - _basePoint.Y) / (extents.MaxPoint.Y - extents.MinPoint.Y));

            if (scale < Consts.Epsilon) // 在一开始scale势必很小。过小的scale会导致矩阵运算出现非等比缩放变换,从而被CAD拒绝,导致异常。
            {
                scale = Consts.Epsilon;
            }
            if (pos.IsNull())
            {
                return(SamplerStatus.Cancel);
            }
            else if (pos != _pos)
            {
                _move = pos - _pos;
                _pos  = pos;
                //_mag = scale / _scale;
                //_scale = scale;
                _mag = scale;
                return(SamplerStatus.OK);
            }
            else
            {
                _move = pos - _pos;
                return(SamplerStatus.NoChange);
            }
        }
コード例 #22
0
ファイル: DrawTails.cs プロジェクト: koropet/PKUserTools
        Polyline DrawTwoTails(Point3d p1, Point3d p2, Polyline tail)
        {
            Vector3d p1p2v = p1.Subtract(p2.GetAsVector()).GetAsVector();
            Vector3d p2p1v = p1p2v.Negate();

            Polyline tail1  = tail.Clone() as Polyline;
            Polyline tail2  = tail.Clone() as Polyline;
            Polyline result = new Polyline();


            //first tail
            double bulge = 0;           //у отрезков балдж будет ноль, лол

            double offset = 0;          //заглушка чтобы работала функция. При прикреплении к отрезку, смещение получится автоматически.

            TransformTail(p1, p2, bulge, 1, ref tail1, out offset);

            for (int i = 0; i < tail1.NumberOfVertices; i++)
            {
                if (i > 0)
                {
                    result.AddVertexAt(0, tail1.GetPoint2dAt(i), tail1.GetBulgeAt(i - 1) * -1, 0, 0);
                }
                else
                {
                    result.AddVertexAt(0, tail1.GetPoint2dAt(i), 0, 0, 0);
                }
            }

            //second tail
            TransformTail(p2, p1, bulge, -1, ref tail2, out offset);

            for (int i = 0; i < tail2.NumberOfVertices; i++)
            {
                result.AddVertexAt(result.NumberOfVertices, tail2.GetPoint2dAt(i), tail2.GetBulgeAt(i), 0, 0);
            }
            return(result);
        }
コード例 #23
0
        public bool ZoomTo(int row, int scale)
        {
            var layout = Found[row].Layout;
            var entity = Found[row].DBObject as DB.Entity;

            using (var tr = doc.Database.TransactionManager.StartTransaction()) {
                if (DB.LayoutManager.Current.CurrentLayout != layout.LayoutName)
                {
                    DB.LayoutManager.Current.CurrentLayout = layout.LayoutName;
                }

                var vp = tr.GetObject(doc.Editor.CurrentViewportObjectId, DB.OpenMode.ForRead, false) as DB.Viewport;
                if (vp == null || vp.Number != 1)
                {
                    tr.Commit();
                    return(true);
                }

                var width  = entity.GeometricExtents.MaxPoint.X - entity.GeometricExtents.MinPoint.X;
                var height = entity.GeometricExtents.MaxPoint.Y - entity.GeometricExtents.MinPoint.Y;

                Point3d pos;
                if (entity is DB.Table)
                {
                    var tbl = entity as DB.Table;

                    double minX, minY, maxX, maxY;

                    var pts = new Point3dCollection();
                    tbl.GetCellExtents(Found[row].RowIndex, Found[row].ColumnIndex, true, pts);
                    if (pts.Count == 4)
                    {
                        minX = maxX = pts[0].X;
                        minY = maxY = pts[0].Y;

                        for (int p = 1; p < pts.Count; p++)
                        {
                            if (pts[p].X < minX)
                            {
                                minX = pts[p].X;
                            }
                            if (pts[p].Y < minY)
                            {
                                minY = pts[p].Y;
                            }
                            if (pts[p].X > maxX)
                            {
                                maxX = pts[p].X;
                            }
                            if (pts[p].Y > maxY)
                            {
                                maxY = pts[p].Y;
                            }
                        }

                        width  = maxX - minX;
                        height = maxY - minY;
                    }
                    else
                    {
                        minX = entity.GeometricExtents.MinPoint.X;
                        minY = entity.GeometricExtents.MinPoint.Y;
                    }

                    pos = new Point3d(minX + width / 2, minY + height / 2, 0);
                }
                else if (entity is DB.MText)
                {
                    var text = entity as DB.MText;

                    width  = text.ActualWidth;
                    height = text.ActualHeight;

                    var p1 = new Point3d(text.ActualWidth, -text.ActualHeight, 0);
                    var v1 = p1.GetAsVector().RotateBy(text.Rotation, Vector3d.ZAxis);
                    pos = text.Location.Add(v1.DivideBy(2.0));
                }
                else if (entity is DB.DBText)
                {
                    var text = entity as DB.DBText;

                    var v1 = new Vector3d(width, height, 0);
                    pos = text.Position.Add(v1.DivideBy(2.0));
                }

                using (var acView = doc.Editor.GetCurrentView()) {
                    acView.Width       = width * 10 / scale;
                    acView.Height      = height * 10 / scale;
                    acView.CenterPoint = new Point2d(pos.X, pos.Y);
                    doc.Editor.SetCurrentView(acView);
                }
                tr.Commit();
            }
            doc.Editor.SetImpliedSelection(new DB.ObjectId[0]);
            doc.Editor.UpdateScreen();

            return(false);
        }
コード例 #24
0
        void GetTextBoxCorners(DBText dbText, out Point3d pt1, out Point3d pt2, out Point3d pt3, out Point3d pt4)

        {
            ads_name name = new ads_name();



            int result = acdbGetAdsName(

                ref name,

                dbText.ObjectId);



            ResultBuffer rb = new ResultBuffer();



            Interop.AttachUnmanagedObject(

                rb,

                acdbEntGet(ref name), true);



            double[] point1 = new double[3];

            double[] point2 = new double[3];



            // Call imported arx function

            acedTextBox(rb.UnmanagedObject, point1, point2);



            pt1 = new Point3d(point1);

            pt2 = new Point3d(point2);



            // Create rotation matrix

            Matrix3d rotMat = Matrix3d.Rotation(

                dbText.Rotation,

                dbText.Normal,

                pt1);



            // The returned points from acedTextBox need

            // to be transformed as follow

            pt1 = pt1.TransformBy(rotMat).Add(dbText.Position.GetAsVector());

            pt2 = pt2.TransformBy(rotMat).Add(dbText.Position.GetAsVector());



            Vector3d rotDir = new Vector3d(

                -Math.Sin(dbText.Rotation),

                Math.Cos(dbText.Rotation), 0);



            Vector3d linDir = rotDir.CrossProduct(dbText.Normal);



            double actualWidth =

                Math.Abs((pt2.GetAsVector() - pt1.GetAsVector())

                         .DotProduct(linDir));



            pt3 = pt1.Add(linDir * actualWidth);

            pt4 = pt2.Subtract(linDir * actualWidth);
        }
コード例 #25
0
        void GetTextBoxCorners(DBText dbText, out Point3d pt1, out Point3d pt2, out Point3d pt3, out Point3d pt4)

        {
            ads_name name = new ads_name();



            int result = acdbGetAdsName(

                ref name,

                dbText.ObjectId);



            ResultBuffer rb = new ResultBuffer();



            Interop.AttachUnmanagedObject(

                rb,

                acdbEntGet(ref name), true);



            double[] point1 = new double[3];

            double[] point2 = new double[3];



            // Call imported arx function

            acedTextBox(rb.UnmanagedObject, point1, point2);



            pt1 = new Point3d(point1);

            pt2 = new Point3d(point2);

            var ptX = pt1 + Vector3d.XAxis * 40;
            var ptY = pt2 + Vector3d.YAxis * 50;


            var lX = new Line(pt1, ptX);
            var lY = new Line(pt2, ptY);

            lX.Color = Color.FromColor(System.Drawing.Color.Green);
            lY.Color = Color.FromColor(System.Drawing.Color.Orange);


            Line line = new Line(pt1, pt2);

            line.Color = Color.FromColor(System.Drawing.Color.Red);

            line.ToSpace();
            lX.ToSpace();
            lY.ToSpace();

            // Create rotation matrix

            Matrix3d rotMat = Matrix3d.Rotation(

                dbText.Rotation,

                dbText.Normal,

                pt1);



            // The returned points from acedTextBox need

            // to be transformed as follow

            pt1 = pt1.TransformBy(rotMat).Add(dbText.Position.GetAsVector());

            pt2 = pt2.TransformBy(rotMat).Add(dbText.Position.GetAsVector());

            Line linetrans = new Line(pt1, pt2);

            linetrans.Color = Color.FromColor(System.Drawing.Color.Yellow);

            linetrans.ToSpace();


            Vector3d rotDir = new Vector3d(

                -Math.Sin(dbText.Rotation),

                Math.Cos(dbText.Rotation), 0);


            //求垂直于rotDir和normal的法向量
            Vector3d linDir = rotDir.CrossProduct(dbText.Normal);



            double actualWidth =

                Math.Abs((pt2.GetAsVector() - pt1.GetAsVector())

                         .DotProduct(linDir));



            pt3 = pt1.Add(linDir * actualWidth);

            pt4 = pt2.Subtract(linDir * actualWidth);

            Line linetrans2 = new Line(pt3, pt4);

            linetrans2.Color = Color.FromColor(System.Drawing.Color.Blue);

            linetrans2.ToSpace();
        }
コード例 #26
0
        private Dictionary<string, PanelBase> matchingPlans(List<FacadeMounting> facadesMounting, List<FloorArchitect> floorsAr)
        {
            // Определение окон в монтажных планах по архитектурным планам
             var panelsBase = new Dictionary<string, PanelBase>(); // string - ключ - маркаСБ + Марки Окон по порядку.

             // Список монтажных планов - уникальных
             var floorsMount = facadesMounting.SelectMany(f => f.Floors);
             foreach (var floorMount in floorsMount)
             {
            // Найти соотв арх план
            var floorAr = floorsAr.Find(f =>
                              f.Section == floorMount.Section &&
                              f.IsEqualMountingStorey(floorMount.Storey)
                           );

            //Test Добавить текст имени плана Ар в блок монтажного плана
            #if Test
            {
               if (floorAr != null)
               {
                  using (var btrMount = floorMount.IdBtrMounting.Open(OpenMode.ForWrite) as BlockTableRecord)
                  {
                     DBText textFindPlanAr = new DBText();
                     textFindPlanAr.TextString = floorAr.BlName;
                     btrMount.AppendEntity(textFindPlanAr);
                     //btrMount.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(textFindPlanAr, true);
                  }
               }
            }
            #endif

            if (floorAr == null)
            {
               Inspector.AddError($"Не найден блок архитектурного плана для соответствующего монтажного плана '{floorMount.BlRefName}'",
                  floorMount.IdBlRefMounting,
                  icon: System.Drawing.SystemIcons.Error);
            }
            else if (floorAr.Windows.Count == 0)
            {
               Inspector.AddError($"Не найдено ни одного окна в блоке архитектурного плана '{floorMount.BlRefName}'.",
                  floorAr.IdBlRef,
                  icon: System.Drawing.SystemIcons.Error);
            }

            foreach (var panelMount in floorMount.PanelsSbInFront)
            {
               Panel panelXml = GetPanelXml(panelMount.MarkSb, panelMount);
               if (panelXml == null) continue;

               PanelBase panelBase = new PanelBase(panelXml, this, panelMount);

               // Определение окон в панели по арх плану
               if (panelXml.windows?.window != null)
               {
                  foreach (var window in panelXml.windows.window)
                  {
                     if (floorAr == null || floorAr.Windows.Count==0)
                     {
                        break;
                     }

                     // Точка окна внутри панели по XML описанию
                     Point3d ptOpeningCenter = new Point3d(window.posi.X + window.width * 0.5, 0, 0);
                     // Точка окна внутри монтажного плана
                     Point3d ptWindInModel = panelMount.ExtTransToModel.MinPoint.Add(ptOpeningCenter.GetAsVector());
                     Point3d ptWindInArPlan = ptWindInModel.TransformBy(floorMount.Transform.Inverse());

                     var windowKey = floorAr?.Windows.GroupBy(w => w.Key.DistanceTo(ptWindInArPlan))?.MinBy(w => w.Key);
                     if (windowKey == null || windowKey.Key > 600)
                     {
                        Inspector.AddError(
                           $"Не найдено соответствующее окно в архитектурном плане. Блок монтажной панели {panelMount.MarkSb}",
                           panelMount.ExtTransToModel, panelMount.IdBlRef, icon: System.Drawing.SystemIcons.Error);
                        continue;
                     }
                     panelBase.WindowsBaseCenters.Add(ptOpeningCenter, windowKey.First().Value);

                     // Test Добавление точек окна в блоке монтажки
            #if Test
                     {
                        using (var btrMountPlan = floorMount.IdBtrMounting.Open(OpenMode.ForWrite) as BlockTableRecord)
                        {
                           using (DBPoint ptWinInPlan = new DBPoint(ptWindInArPlan))
                           {
                              ptWinInPlan.ColorIndex = 2;
                              btrMountPlan.AppendEntity(ptWinInPlan);
                              //btrMountPlan.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(ptWinInPlan, true);
                           }

                           using (DBText dbText = new DBText())
                           {
                              dbText.Position = ptWindInArPlan;
                              dbText.TextString = windowKey.First().Value;
                              btrMountPlan.AppendEntity(dbText);
                              //btrMountPlan.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(dbText, true);
                           }
                        }
                        using (var btrArPlan = floorAr.IdBtr.Open(OpenMode.ForWrite) as BlockTableRecord)
                        {
                           using (DBPoint ptWinInArPlan = new DBPoint(ptWindInArPlan))
                           {
                              ptWinInArPlan.ColorIndex = 1;
                              btrArPlan.AppendEntity(ptWinInArPlan);
                              //btrArPlan.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(ptWinInArPlan, true);
                           }
                        }
                     }
            #endif
                  }
               }
               // Уникальный ключ панели - МаркаСБ + Марки окон
               string key = panelBase.MarkWithoutElectric;
               if (panelBase.WindowsBaseCenters.Count > 0)
               {
                  string windowMarks = string.Join(";", panelBase.WindowsBaseCenters.Values);
                  key += windowMarks;
               }
               PanelBase panelBaseUniq;
               if (!panelsBase.TryGetValue(key, out panelBaseUniq))
               {
                  panelsBase.Add(key, panelBase);
                  panelBaseUniq = panelBase;
               }
               panelMount.PanelBase = panelBaseUniq;
            }
             }
             return panelsBase;
        }
コード例 #27
0
ファイル: Macros.cs プロジェクト: 15831944/KojtoCAD
        /// <summary>
        /// /// * Insert Drawing As Block - DWG or DXF *
        /// the source drawig should be drawn as number of
        /// separate entites with or without attributes 
        /// 
        /// </summary>
        /// <param name="destinationDocument"></param>
        /// <param name="sourceDrawing"></param>
        /// <param name="insertionPoint"></param>
        /// <param name="transforMatrix"> </param>
        /// <exception cref="NotImplementedException">Not implemented for DXFs</exception>
        /// <returns>ObjectID of the Block Def that was imported.</returns>
        private void ReplaceBlockRefWithDWG(Document destinationDocument, string sourceDrawing, Point3d insertionPoint,
            Matrix3d transforMatrix)
        {
            Point3d oldPoint = insertionPoint.TransformBy(transforMatrix.Inverse());
            insertionPoint = new Point3d(0, 0, 0);

            Database destinationDb = destinationDocument.Database;
            Editor ed = destinationDocument.Editor;

            string blockname = sourceDrawing.Remove(0, sourceDrawing.LastIndexOf("\\", StringComparison.Ordinal) + 1);
            blockname = blockname.Substring(0, blockname.Length - 4); // remove the extension

            using (destinationDocument.LockDocument())
            {
                using (var inMemoryDb = new Database(false, true))
                {
                    if (sourceDrawing.LastIndexOf(".dwg", StringComparison.Ordinal) > 0)
                    {
                        inMemoryDb.ReadDwgFile(sourceDrawing, FileShare.ReadWrite, true, "");
                    }
                    else if (sourceDrawing.LastIndexOf(".dxf", StringComparison.Ordinal) > 0)
                    {
                        throw new NotImplementedException("DXFs not suppported");
                        //inMemoryDb.DxfIn(string filename, string logFilename);
                    }

                    using (var transaction = destinationDocument.TransactionManager.StartTransaction())
                    {
                        var destinationDatabaseBlockTable =
                            (BlockTable) transaction.GetObject(destinationDb.BlockTableId, OpenMode.ForRead);
                        ObjectId sourceBlockObjectId;
                        if (destinationDatabaseBlockTable.Has(blockname))
                        {

                            ed.WriteMessage("Block " + blockname +
                                            " already exists.\n Attempting to create block reference...");

                            var destinationDatabaseCurrentSpace =
                                (BlockTableRecord) destinationDb.CurrentSpaceId.GetObject(OpenMode.ForWrite);

                            var destinationDatabaseBlockDefinition =
                                (BlockTableRecord)
                                    transaction.GetObject(destinationDatabaseBlockTable[blockname], OpenMode.ForRead);
                            sourceBlockObjectId = destinationDatabaseBlockDefinition.ObjectId;

                            // Create a block reference to the existing block definition
                            using (var blockReference = new BlockReference(insertionPoint, sourceBlockObjectId))
                            {
                                //Matrix3d Mat = Matrix3d.Identity;   

                                Vector3d mov = new Vector3d(oldPoint.X, oldPoint.Y, oldPoint.Z);
                                mov = mov.TransformBy(transforMatrix);
                                blockReference.TransformBy(transforMatrix);
                                blockReference.TransformBy(Matrix3d.Displacement(mov));

                                blockReference.ScaleFactors = new Scale3d(1, 1, 1);
                                destinationDatabaseCurrentSpace.AppendEntity(blockReference);
                                transaction.AddNewlyCreatedDBObject(blockReference, true);
                                ed.Regen();
                                transaction.Commit();
                                // At this point the Bref has become a DBObject and can be disposed
                            }
                            return;
                        }

                        // There is not such block definition, so we are inserting/creating new one
                        sourceBlockObjectId = destinationDb.Insert(blockname, inMemoryDb, true);

                        #region Create Block Ref from the already imported Block Def

                        // We continue here the creation of the new block reference of the already imported block definition
                        var sourceDatabaseCurrentSpace =
                            (BlockTableRecord) destinationDb.CurrentSpaceId.GetObject(OpenMode.ForWrite);

                        using (var blockReference = new BlockReference(insertionPoint, sourceBlockObjectId))
                        {
                            blockReference.ScaleFactors = new Scale3d(1, 1, 1);
                            sourceDatabaseCurrentSpace.AppendEntity(blockReference);
                            transaction.AddNewlyCreatedDBObject(blockReference, true);

                            var blockTableRecord =
                                (BlockTableRecord) blockReference.BlockTableRecord.GetObject(OpenMode.ForRead);
                            var atcoll = blockReference.AttributeCollection;
                            foreach (ObjectId subid in blockTableRecord)
                            {
                                var entity = (Entity) subid.GetObject(OpenMode.ForRead);
                                var attributeDefinition = entity as AttributeDefinition;

                                if (attributeDefinition == null)
                                {
                                    continue;
                                }
                                var attributeReference = new AttributeReference();
                                attributeReference.SetPropertiesFrom(attributeDefinition);
                                attributeReference.Visible = attributeDefinition.Visible;
                                attributeReference.SetAttributeFromBlock(attributeDefinition,
                                    blockReference.BlockTransform);
                                attributeReference.HorizontalMode = attributeDefinition.HorizontalMode;
                                attributeReference.VerticalMode = attributeDefinition.VerticalMode;
                                attributeReference.Rotation = attributeDefinition.Rotation;
                                attributeReference.Position = attributeDefinition.Position +
                                                              insertionPoint.GetAsVector();
                                attributeReference.Tag = attributeDefinition.Tag;
                                attributeReference.FieldLength = attributeDefinition.FieldLength;
                                attributeReference.TextString = attributeDefinition.TextString;
                                attributeReference.AdjustAlignment(destinationDb);

                                atcoll.AppendAttribute(attributeReference);
                                transaction.AddNewlyCreatedDBObject(attributeReference, true);
                            }

                            var mov = new Vector3d(oldPoint.X, oldPoint.Y, oldPoint.Z);
                            mov = mov.TransformBy(transforMatrix);
                            blockReference.TransformBy(transforMatrix);
                            blockReference.TransformBy(Matrix3d.Displacement(mov));

                            transaction.Commit();
                        }

                        #endregion

                        ed.Regen();
                    }
                }
            }
        }
コード例 #28
0
        public static ObjectId CreateExtrusion(Point2d[] pts, Point3d destPt, Vector3d normal, WoodGrainAlignment grain)
        {
            ObjectId entId = ObjectId.Null;

            Document activeDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database db = activeDoc.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                BlockTableRecord btr = null;
                if (String.IsNullOrEmpty(blockName))
                    btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                else
                {
                    if (bt.Has(blockName))
                        btr = tr.GetObject(bt[blockName], OpenMode.ForWrite) as BlockTableRecord;
                    else
                    {
                        btr = new BlockTableRecord();
                        btr.Name = blockName;
                        bt.UpgradeOpen();
                        bt.Add(btr);
                        tr.AddNewlyCreatedDBObject(btr, true);
                    }
                }

                Solid3d extrudedSolid = new Solid3d();
                using (Autodesk.AutoCAD.DatabaseServices.Polyline outline = new Autodesk.AutoCAD.DatabaseServices.Polyline())
                {
                    outline.SetDatabaseDefaults();
                    outline.Normal = normal;

                    int cnt = 0;
                    foreach (Point2d pt in pts)
                    {
                        outline.AddVertexAt(cnt, pt, 0, 0, 0);
                        cnt++;
                    }
                    outline.Closed = true;

                    Extents3d exts = outline.GeometricExtents;
                    Point3d minPt = exts.MinPoint;
                    Point3d maxPt = exts.MaxPoint;

                    double p1 = maxPt.X - minPt.X;
                    double p2 = maxPt.Y - minPt.Y;
                    double p3 = maxPt.Z - minPt.Z;

                    double pmin = 0.0;
                    if (p1 == 0)
                    {
                        pmin = Math.Min(p2, p3);
                    }
                    if (p2 == 0)
                    {
                        pmin = Math.Min(p1, p3);
                    }
                    if (p3 == 0)
                    {
                        pmin = Math.Min(p1, p2);
                    }
                    double pmax = Math.Max(Math.Max(p1, p2), p3);

                    extrudedSolid.RecordHistory = true;

                    plyIndex++;

                    Vector3d heightVector = outline.Normal * t;

                    SweepOptions sweepOptions = new SweepOptions();

                    SweepOptionsBuilder builder = new SweepOptionsBuilder(sweepOptions);

                    extrudedSolid.CreateExtrudedSolid(outline, heightVector, sweepOptions);
                }

                entId = btr.AppendEntity(extrudedSolid);
                tr.AddNewlyCreatedDBObject(extrudedSolid, true);

                extrudedSolid.TransformBy(Matrix3d.Displacement(destPt.GetAsVector()));

                tr.Commit();
            }

            return entId;
        }
コード例 #29
0
        public static void DrawBoreholeDetails()
        {
            if (!CheckLicense.Check())
            {
                return;
            }

            using (DrawBoreholeDetailsForm form = new DrawBoreholeDetailsForm())
            {
                if (Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(null, form, false) == System.Windows.Forms.DialogResult.OK)
                {
                    Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                    Autodesk.AutoCAD.DatabaseServices.Database    db  = doc.Database;

                    PromptPointResult res = doc.Editor.GetPoint("Sondaj çizimi başlangıç noktası: ");
                    Point3d           pt  = res.Value;

                    Dictionary <string, string>         headers = form.GetHeaders();
                    Dictionary <string, List <string> > data    = form.GetData();
                    List <double> depths     = form.GetDepths();
                    string        layerName  = form.LayerName;
                    double        textHeight = form.TextHeight;
                    bool          hasGW      = form.HasGroundwater;
                    double        gwLevel    = form.GroundwaterLevel;

                    Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs;

                    double xSpacing = 5.3 * textHeight;
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                        using (LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead))
                            using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite))
                            {
                                // Get layer
                                ObjectId layerId     = ObjectId.Null;
                                Color    headerColor = Color.FromColorIndex(ColorMethod.ByAci, 4);
                                Color    textColor   = Color.FromColorIndex(ColorMethod.ByAci, 1);
                                Color    gwColor     = Color.FromColorIndex(ColorMethod.ByAci, 4);
                                double   tickSize    = 0.5 * textHeight;

                                if (lt.Has(layerName))
                                {
                                    layerId = lt[layerName];
                                }
                                else
                                {
                                    LayerTableRecord ltr = new LayerTableRecord();
                                    ltr.Name  = layerName;
                                    ltr.Color = textColor;
                                    lt.UpgradeOpen();
                                    layerId = lt.Add(ltr);
                                    tr.AddNewlyCreatedDBObject(ltr, true);
                                }

                                Point3d depthLineTop    = Point3d.Origin;
                                Point3d depthLineBottom = Point3d.Origin;

                                // Header underline
                                if (data.Count > 0)
                                {
                                    Point3d pt1  = new Point3d(pt.X - xSpacing, pt.Y + 0.9 * textHeight, pt.Z);
                                    Point3d pt2  = new Point3d(pt.X + xSpacing * data.Count - xSpacing, pt.Y + 0.9 * textHeight, pt.Z);
                                    Line    line = AcadUtility.AcadEntity.CreateLine(db, pt1.TransformBy(ucs2wcs), pt2.TransformBy(ucs2wcs));
                                    line.LayerId = layerId;
                                    line.Color   = headerColor;
                                    btr.AppendEntity(line);
                                    tr.AddNewlyCreatedDBObject(line, true);
                                }

                                // Process columns
                                int j = 0;
                                foreach (KeyValuePair <string, List <string> > item in data)
                                {
                                    string key = item.Key;

                                    // Header text of this column
                                    string headerText = headers[key];
                                    if (!string.IsNullOrEmpty(headerText))
                                    {
                                        string[] lines  = headerText.Split(' ');
                                        Point3d  ptText = new Point3d(pt.X + xSpacing * j - xSpacing / 2, pt.Y + 0.6 * textHeight + lines.Length * 1.3 * textHeight, pt.Z);
                                        foreach (string line in lines)
                                        {
                                            DBText dbtext = AcadUtility.AcadEntity.CreateText(db, ptText.TransformBy(ucs2wcs), line, textHeight, 0, 1, TextHorizontalMode.TextMid, TextVerticalMode.TextVerticalMid);
                                            dbtext.LayerId = layerId;
                                            dbtext.Color   = headerColor;
                                            btr.AppendEntity(dbtext);
                                            tr.AddNewlyCreatedDBObject(dbtext, true);
                                            ptText = new Point3d(ptText.X, ptText.Y - textHeight * 1.3, ptText.Z);
                                        }
                                    }

                                    // Item texts for this column
                                    int i = 0;
                                    foreach (string text in item.Value)
                                    {
                                        if (!string.IsNullOrEmpty(text))
                                        {
                                            if (string.Compare(key, "Depth", StringComparison.InvariantCultureIgnoreCase) == 0)
                                            {
                                                // Item text
                                                double  depth  = depths[i];
                                                Point3d ptText = new Point3d(pt.X + xSpacing * j, pt.Y - depth, pt.Z);
                                                DBText  dbtext = AcadUtility.AcadEntity.CreateText(db, ptText.TransformBy(ucs2wcs), text, textHeight, 0, 1, TextHorizontalMode.TextRight, TextVerticalMode.TextVerticalMid);
                                                dbtext.LayerId = layerId;
                                                btr.AppendEntity(dbtext);
                                                tr.AddNewlyCreatedDBObject(dbtext, true);

                                                // Horizontal depth ticks
                                                Point3d pt1  = new Point3d(ptText.X + 0.25, ptText.Y, ptText.Z);
                                                Point3d pt2  = new Point3d(ptText.X + 0.25 + tickSize, ptText.Y, ptText.Z);
                                                Line    line = AcadUtility.AcadEntity.CreateLine(db, pt1.TransformBy(ucs2wcs), pt2.TransformBy(ucs2wcs));
                                                line.LayerId = layerId;
                                                btr.AppendEntity(line);
                                                tr.AddNewlyCreatedDBObject(line, true);

                                                if (depthLineTop.GetAsVector().IsZeroLength())
                                                {
                                                    depthLineTop = pt1;
                                                }
                                                depthLineBottom = pt1;
                                            }
                                            else
                                            {
                                                // Item text
                                                double  depth  = depths[i];
                                                Point3d ptText = new Point3d(pt.X + xSpacing * j - xSpacing / 2, pt.Y - depth, pt.Z);
                                                DBText  dbtext = AcadUtility.AcadEntity.CreateText(db, ptText.TransformBy(ucs2wcs), text, textHeight, 0, 1, TextHorizontalMode.TextMid, TextVerticalMode.TextVerticalMid);
                                                dbtext.LayerId = layerId;
                                                btr.AppendEntity(dbtext);
                                                tr.AddNewlyCreatedDBObject(dbtext, true);
                                            }
                                        }
                                        i++;
                                    }
                                    j++;
                                }

                                // Vertical depth line
                                if (!depthLineTop.GetAsVector().IsZeroLength())
                                {
                                    Point3d pt1  = new Point3d(depthLineTop.X + tickSize / 2, pt.Y, depthLineTop.Z);
                                    Point3d pt2  = new Point3d(depthLineBottom.X + tickSize / 2, depthLineBottom.Y, depthLineBottom.Z);
                                    Line    line = AcadUtility.AcadEntity.CreateLine(db, pt1.TransformBy(ucs2wcs), pt2.TransformBy(ucs2wcs));
                                    line.LayerId = layerId;
                                    btr.AppendEntity(line);
                                    tr.AddNewlyCreatedDBObject(line, true);
                                }

                                // Ground water
                                if (hasGW)
                                {
                                    // Horizontal line
                                    Point3d pt1  = new Point3d(pt.X + 0.25 - 6.6 * textHeight, pt.Y - gwLevel, pt.Z);
                                    Point3d pt2  = new Point3d(pt.X + 0.25, pt.Y - gwLevel, pt.Z);
                                    Line    line = AcadUtility.AcadEntity.CreateLine(db, pt1.TransformBy(ucs2wcs), pt2.TransformBy(ucs2wcs));
                                    line.LayerId = layerId;
                                    line.Color   = gwColor;
                                    btr.AppendEntity(line);
                                    tr.AddNewlyCreatedDBObject(line, true);

                                    // GW marker
                                    double markerSize = 0.8 * textHeight;

                                    Polyline pline = new Polyline(1);
                                    pline.Normal = ucs2wcs.CoordinateSystem3d.Zaxis;
                                    pline.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
                                    Plane plinePlane = new Plane(Point3d.Origin, pline.Normal);
                                    pline.Reset(false, 3);
                                    Point3d wcsPt1 = new Point3d(pt.X + 0.25 - 4.6 * textHeight, pt.Y - gwLevel, pt.Z).TransformBy(ucs2wcs);                           // Convert to WCS
                                    Point2d ecsPt1 = plinePlane.ParameterOf(wcsPt1);                                                                                   // Convert to ECS
                                    pline.AddVertexAt(pline.NumberOfVertices, ecsPt1, 0, 0, 0);
                                    Point3d wcsPt2 = new Point3d(pt.X + 0.25 - 4.6 * textHeight - markerSize, pt.Y - gwLevel + markerSize, pt.Z).TransformBy(ucs2wcs); // Convert to WCS
                                    Point2d ecsPt2 = plinePlane.ParameterOf(wcsPt2);                                                                                   // Convert to ECS
                                    pline.AddVertexAt(pline.NumberOfVertices, ecsPt2, 0, 0, 0);
                                    Point3d wcsPt3 = new Point3d(pt.X + 0.25 - 4.6 * textHeight + markerSize, pt.Y - gwLevel + markerSize, pt.Z).TransformBy(ucs2wcs); // Convert to WCS
                                    Point2d ecsPt3 = plinePlane.ParameterOf(wcsPt3);                                                                                   // Convert to ECS
                                    pline.AddVertexAt(pline.NumberOfVertices, ecsPt3, 0, 0, 0);
                                    pline.Closed  = true;
                                    pline.LayerId = layerId;
                                    pline.Color   = gwColor;
                                    btr.AppendEntity(pline);
                                    tr.AddNewlyCreatedDBObject(pline, true);

                                    // GW text
                                    Point3d ptText = new Point3d(pt.X + 0.25 - 4.6 * textHeight, pt.Y - gwLevel + markerSize, pt.Z);
                                    DBText  dbtext = AcadUtility.AcadEntity.CreateText(db, ptText.TransformBy(ucs2wcs), gwLevel.ToString(), textHeight, 0, 1, TextHorizontalMode.TextCenter, TextVerticalMode.TextBottom);
                                    dbtext.LayerId = layerId;
                                    dbtext.Color   = gwColor;
                                    btr.AppendEntity(dbtext);
                                    tr.AddNewlyCreatedDBObject(dbtext, true);
                                }

                                tr.Commit();
                            }
                }
            }
        }
コード例 #30
0
ファイル: Commands.cs プロジェクト: jajazhou/PIOTM-QRCode
        public static void EditQR()
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Editor   ed = doc.Editor;
            Database db = doc.Database;

            // Ask user to select an QR code, hatch or raster image

            PromptEntityOptions peo =
                new PromptEntityOptions("Select a QR code: ");

            peo.SetRejectMessage(
                "\nMust be a hatch or a raster image"
                );
            peo.AddAllowedClass(typeof(Hatch), true);

            // AutoCAD crash if we try AddAllowedClass for RasterImage
            // when no raster image is defined or just hatch QRs were
            // defined, probably because in C++ we need to call
            // acedArxLoad("acismui.arx"), which is not exposed in .NET,
            // so let's check before if the drawing contains any
            // RasterImages, if not we don't need this filter.

            if (!RasterImageDef.GetImageDictionary(db).IsNull)
            {
                peo.AddAllowedClass(typeof(RasterImage), true);
            }
            PromptEntityResult entityResult = ed.GetEntity(peo);

            if (entityResult.Status != PromptStatus.OK)
            {
                return;
            }

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                Entity ent =
                    tr.GetObject(entityResult.ObjectId, OpenMode.ForRead)
                    as Entity;
                ResultBuffer rb =
                    ent.GetXDataForApplication(APPLICATION_PREFIX);

                if (rb != null && rb.AsArray().Length == 0)
                {
                    ed.WriteMessage("\nThis is not a valid QR code");
                    tr.Commit(); //faster
                    return;
                }

                // Show the form with current information

                QRCodeForm form = new QRCodeForm();
                form.IsEditing = true;
                form.QREncodeDataAsResultBuffer = rb;
                rb.Dispose();
                System.Windows.Forms.DialogResult res =
                    Application.ShowModalDialog(form);
                if (res != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                //Get insert point and size

                double size =
                    ent.GeometricExtents.MaxPoint.X -
                    ent.GeometricExtents.MinPoint.X;
                Point3d inspt = ent.GeometricExtents.MinPoint;


                if (ent is RasterImage)
                {
                    // Just update the raster image definition

                    RasterImage    image    = ent as RasterImage;
                    RasterImageDef imageDef =
                        tr.GetObject(image.ImageDefId, OpenMode.ForWrite)
                        as RasterImageDef;
                    imageDef.SourceFileName =
                        FormatDataHelper.EncodeQrCodeUrl(form.QREncodeData);
                    imageDef.Load();
                }
                else
                {
                    // Erase current entity

                    ent.UpgradeOpen();
                    ent.Erase();

                    // Create a new one

                    Entity newEnt =
                        GenerateQRHatch(
                            form.QREncodeData, form.QREncode,
                            form.QRVersion, form.QRErrorCorrect, (int)size
                            );
                    if (newEnt == null)
                    {
                        return;
                    }
                    ResultBuffer newRb = form.QREncodeDataAsResultBuffer;
                    newEnt.XData = newRb;
                    newRb.Dispose();
                    newEnt.TransformBy(
                        Matrix3d.Displacement(inspt.GetAsVector())
                        );
                    AppendEntityToCurrentSpace(newEnt);
                }

                tr.Commit();
            }
        }
コード例 #31
0
        public static void DoIt()
        {
            Document            doc       = Application.DocumentManager.MdiActiveDocument;
            Editor              ed        = doc.Editor;
            PromptDoubleOptions optDouble = new PromptDoubleOptions("\n请输入箭头长度:");

            optDouble.AllowNone       = true;
            optDouble.AllowZero       = false;
            optDouble.DefaultValue    = CurrArrowLength;
            optDouble.UseDefaultValue = true;
            PromptDoubleResult resDouble = ed.GetDouble(optDouble);

            if (resDouble.Status == PromptStatus.OK)
            {
                //改变箭头长度设定值
                CurrArrowLength = resDouble.Value;
                PromptPointResult resStartPoint = ed.GetPoint("\n请输入起点:");
                if (resStartPoint.Status == PromptStatus.OK)
                {
                    PromptPointOptions optEndPoint = new PromptPointOptions("\n请输入终点:");
                    optEndPoint.BasePoint    = resStartPoint.Value;
                    optEndPoint.UseBasePoint = true;
                    PromptPointResult resEndPoint = ed.GetPoint(optEndPoint);
                    if (resEndPoint.Status == PromptStatus.OK)
                    {
                        Point3d  startpnt = resStartPoint.Value;
                        Point3d  endpnt   = resEndPoint.Value;
                        Database db       = doc.Database;
                        using (Transaction tr = db.TransactionManager.StartTransaction())
                        {
                            BlockTableRecord btr =
                                (BlockTableRecord)tr.GetObject(
                                    db.CurrentSpaceId,
                                    OpenMode.ForWrite,
                                    false);
                            Line line = new Line(startpnt, endpnt);
                            btr.AppendEntity(line);
                            tr.AddNewlyCreatedDBObject(line, true);
                            RegAppTable rat =
                                (RegAppTable)tr.GetObject(
                                    db.RegAppTableId,
                                    OpenMode.ForRead,
                                    false);
                            if (!rat.Has(RegAppName))
                            {
                                rat.UpgradeOpen();
                                RegAppTableRecord regapp = new RegAppTableRecord();
                                regapp.Name = RegAppName;
                                rat.Add(regapp);
                                tr.AddNewlyCreatedDBObject(regapp, true);
                            }
                            Point3d midpnt = (startpnt + endpnt.GetAsVector()) / 2;
                            LArrow3 la     = new LArrow3(line);
                            //附着当前设定的箭头长度
                            la.ArrowLength = CurrArrowLength;
                            la.Scale       = 0.5;
                            la.SaveExtendedData();
                            tr.Commit();
                        }
                    }
                }
            }
        }
コード例 #32
0
        private bool DrawBOQ()
        {
            using (DrawBOQForm form = new DrawBOQForm())
            {
                // Pos error check
                PromptSelectionResult sel = DWGUtility.SelectAllPosUser();
                if (sel.Status != PromptStatus.OK)
                {
                    return(false);
                }
                ObjectId[] items = sel.Value.GetObjectIds();

                List <PosCheckResult> errors   = PosCheckResult.CheckAllInSelection(items, true, false);
                List <PosCheckResult> warnings = PosCheckResult.CheckAllInSelection(items, false, true);

                if (errors.Count != 0)
                {
                    PosCheckResult.ConsoleOut(errors);
                }
                if (warnings.Count != 0)
                {
                    PosCheckResult.ConsoleOut(warnings);
                }

                if (errors.Count != 0)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.DisplayTextScreen = true;
                    return(false);
                }

                // Pos similarity check
                if (warnings.Count != 0)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.DisplayTextScreen = true;
                    PromptKeywordOptions opts = new PromptKeywordOptions("\nMetraja devam edilsin mi? [Evet/Hayir]", "Yes No");
                    PromptResult         res  = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(opts);
                    if (res.Status != PromptStatus.OK || res.StringResult == "No")
                    {
                        return(true);
                    }
                }

                if (!form.Init())
                {
                    return(false);
                }

                if (Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(null, form, false) != System.Windows.Forms.DialogResult.OK)
                {
                    return(true);
                }

                List <PosCopy> posList = new List <PosCopy>();
                try
                {
                    posList = PosCopy.ReadAllInSelection(items, true, PosCopy.PosGrouping.PosMarker);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message, "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                if (posList.Count == 0)
                {
                    MessageBox.Show("Seçilen grupta poz mevcut değil.", "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return(false);
                }

                posList = RemoveEmpty(posList);
                if (!form.HideMissing)
                {
                    posList = AddMissing(posList);
                }
                posList = SortList(posList);

                PromptPointResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint("Baz noktası: ");
                if (result.Status != PromptStatus.OK)
                {
                    return(true);
                }

                Database db = HostApplicationServices.WorkingDatabase;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                        BOQTable table = new BOQTable();
                        table.SuspendUpdate();

                        Point3d pt = result.Value;
                        table.TransformBy(Matrix3d.Displacement(pt.GetAsVector()));
                        table.TransformBy(Matrix3d.Scaling(form.TextHeight, pt));
                        table.Note    = form.TableNote;
                        table.Heading = form.TableHeader;
                        table.Footing = form.TableFooter;

                        table.DisplayUnit = form.DisplayUnit;
                        table.Precision   = form.Precision;

                        table.Multiplier = form.Multiplier;

                        BOQStyle style = form.TableStyle;
                        table.ColumnDef = style.Columns;

                        table.TextStyleId    = style.TextStyleId;
                        table.HeadingStyleId = style.HeadingStyleId;
                        table.FootingStyleId = style.FootingStyleId;

                        table.PosLabel               = style.PosLabel;
                        table.CountLabel             = style.CountLabel;
                        table.DiameterLabel          = style.DiameterLabel;
                        table.LengthLabel            = style.LengthLabel;
                        table.ShapeLabel             = style.ShapeLabel;
                        table.TotalLengthLabel       = style.TotalLengthLabel;
                        table.DiameterListLabel      = style.DiameterListLabel;
                        table.DiameterLengthLabel    = style.DiameterLengthLabel;
                        table.UnitWeightLabel        = style.UnitWeightLabel;
                        table.WeightLabel            = style.WeightLabel;
                        table.GrossWeightLabel       = style.GrossWeightLabel;
                        table.MultiplierHeadingLabel = style.MultiplierHeadingLabel;

                        table.MaxRows      = form.TableRows;
                        table.TableSpacing = form.TableMargin;

                        double lengthScale = 1.0;
                        switch (table.DisplayUnit)
                        {
                        case BOQTable.DrawingUnits.Millimeter:
                            lengthScale = 1.0;
                            break;

                        case BOQTable.DrawingUnits.Centimeter:
                            lengthScale = 0.1;
                            break;

                        case BOQTable.DrawingUnits.Decimeter:
                            lengthScale = 0.01;
                            break;

                        case BOQTable.DrawingUnits.Meter:
                            lengthScale = 0.001;
                            break;
                        }

                        // Add rows
                        foreach (PosCopy copy in posList)
                        {
                            if (copy.existing)
                            {
                                string a = string.Empty;
                                string b = string.Empty;
                                string c = string.Empty;
                                string d = string.Empty;
                                string e = string.Empty;
                                string f = string.Empty;

                                if (copy.isVarA)
                                {
                                    a = (copy.minA * lengthScale).ToString("F0") + "~" + (copy.maxA * lengthScale).ToString("F0");
                                }
                                else
                                {
                                    a = (copy.minA * lengthScale).ToString("F0");
                                }
                                if (copy.isVarB)
                                {
                                    b = (copy.minB * lengthScale).ToString("F0") + "~" + (copy.maxB * lengthScale).ToString("F0");
                                }
                                else
                                {
                                    b = (copy.minB * lengthScale).ToString("F0");
                                }
                                if (copy.isVarC)
                                {
                                    c = (copy.minC * lengthScale).ToString("F0") + "~" + (copy.maxC * lengthScale).ToString("F0");
                                }
                                else
                                {
                                    c = (copy.minC * lengthScale).ToString("F0");
                                }
                                if (copy.isVarD)
                                {
                                    d = (copy.minD * lengthScale).ToString("F0") + "~" + (copy.maxD * lengthScale).ToString("F0");
                                }
                                else
                                {
                                    d = (copy.minD * lengthScale).ToString("F0");
                                }
                                if (copy.isVarE)
                                {
                                    e = (copy.minE * lengthScale).ToString("F0") + "~" + (copy.maxE * lengthScale).ToString("F0");
                                }
                                else
                                {
                                    e = (copy.minE * lengthScale).ToString("F0");
                                }
                                if (copy.isVarF)
                                {
                                    f = (copy.minF * lengthScale).ToString("F0") + "~" + (copy.maxF * lengthScale).ToString("F0");
                                }
                                else
                                {
                                    f = (copy.minF * lengthScale).ToString("F0");
                                }

                                table.Items.Add(int.Parse(copy.pos), copy.count, double.Parse(copy.diameter), copy.length1, copy.length2, copy.isVarLength, copy.shapename, a, b, c, d, e, f);
                            }
                            else
                            {
                                table.Items.Add(int.Parse(copy.pos));
                            }
                        }

                        table.ResumeUpdate();

                        table.SetDatabaseDefaults(db);

                        btr.AppendEntity(table);
                        tr.AddNewlyCreatedDBObject(table, true);

                        tr.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message, "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }

            return(true);
        }