Пример #1
1
 public static Icon GetPreviewIcon(BlockTableRecord btr)
 {
     var imgsrc = CMLContentSearchPreviews.GetBlockTRThumbnail(btr);
     var bitmap = ImageSourceToGDI((BitmapSource)imgsrc) as Bitmap;
     var iconPtr = bitmap.GetHicon();
     return Icon.FromHandle(iconPtr);
 }
Пример #2
1
        public void CreateContour(BlockTableRecord btr)
        {
            if (panelBtr.ExtentsByTile.Diagonal() < endOffset)
            {
                return;
            }

            // из всех плиток отделить торцевые плитки????
            // дерево границ плиток
            TreeTiles = new RTree<Tuple<ObjectId, Extents3d>>();
            panelBtr.Tiles.ForEach(t =>
                           {
                               try
                               {
                                   var r = new Rectangle(t.Item2.MinPoint.X, t.Item2.MinPoint.Y, t.Item2.MaxPoint.X, t.Item2.MaxPoint.Y, 0, 0);
                                   TreeTiles.Add(r, t);
                               }
                               catch { }
                           });

            // Первый угол панели - левый нижний
            var pt1 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MinPoint, EnumCorner.LeftLower);
            var pt2 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MinPoint.X, panelBtr.ExtentsByTile.MaxPoint.Y, 0), EnumCorner.LeftTop);
            var pt3 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MaxPoint, EnumCorner.RightTop);
            var pt4 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MaxPoint.X, panelBtr.ExtentsByTile.MinPoint.Y, 0), EnumCorner.RightLower);

            Extents3d extNoEnd = new Extents3d(pt1, pt2);
            extNoEnd.AddPoint(pt3);
            extNoEnd.AddPoint(pt4);
            panelBtr.ExtentsNoEnd = extNoEnd;

            Point3dCollection pts = new Point3dCollection();
            pts.Add(pt1);
            pts.Add(pt2);
            pts.Add(pt3);
            pts.Add(pt4);
            using (Polyline3d poly = new Polyline3d(Poly3dType.SimplePoly, pts, true))
            {
                poly.LayerId = panelBtr.CPS.IdLayerContour;
                btr.AppendEntity(poly);
                btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(poly, true);
            }
        }
Пример #3
0
        public void Create(BlockTableRecord btrPanel, Transaction t)
        {
            Polyline plContour = new Polyline();
             plContour.LayerId = panelBase.Service.Env.IdLayerContourPanel;

             // Определение подрезок и пустот
             defineUndercuts();

             // Outsides - части сторон панели без плитки - заходит под торец другой угловой панели
             addOutsides(btrPanel, t);

             definePtsLeftSide();
             definePtsTopSide();
             definePtsRightSide();
             definePtsBotSide();

             int i = 0;
             ptsLeftSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0));
             ptsTopSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0));
             ptsRightSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0));
             ptsBotSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0));

             plContour.Closed = true;
             btrPanel.AppendEntity(plContour);
             t.AddNewlyCreatedDBObject(plContour, true);
        }
 private static BlockReference findOBR(BlockTableRecord btr)
 {
     foreach (var idEnt in btr)
     {
         var blRefObr = idEnt.GetObject(OpenMode.ForRead, false, true) as BlockReference;
         if (blRefObr == null) continue;
         if (blRefObr.Name.StartsWith("ОБР_", StringComparison.OrdinalIgnoreCase))
         {
             var btrObr = blRefObr.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord;
             foreach (var item in btrObr)
             {
                 if (item.ObjectClass.Name != "AcDbMText") continue;
                 var mtextDesc = item.GetObject(OpenMode.ForRead, false, true) as MText;
                 if (mtextDesc.Text.StartsWith("Примечан"))
                 {
                     mtextDesc.UpgradeOpen();
                     mtextDesc.Erase();
                     return blRefObr;
                 }
             }
             break;
         }
     }
     return null;
 }
Пример #5
0
        private static void addLayout(Point3d pt,int layout ,double width, double height , BlockTableRecord cs, Transaction t)
        {
            // Полилиния контура листа
            Polyline pl = new Polyline(4);
            pl.AddVertexAt(0, new Point2d(pt.X, pt.Y), 0, 0, 0);
            pl.AddVertexAt(1, new Point2d(pt.X +width, pt.Y), 0, 0, 0);
            pl.AddVertexAt(2, new Point2d(pt.X + width, pt.Y - height), 0, 0, 0);
            pl.AddVertexAt(3, new Point2d(pt.X,  pt.Y-height), 0, 0, 0);
            pl.Closed = true;
            pl.SetDatabaseDefaults();

            cs.AppendEntity(pl);
            t.AddNewlyCreatedDBObject(pl, true);

            // Подпись номера листа
            var textHeight = height * 0.008;
            Point3d ptText = new Point3d(pt.X+textHeight*0.5, pt.Y-textHeight*1.5, 0);

            DBText text = new DBText();
            text.SetDatabaseDefaults();
            text.Height = textHeight;
            text.TextStyleId = IdTextStylePik;
            text.TextString = layout.ToString();
            text.Position = ptText;

            cs.AppendEntity(text);
            t.AddNewlyCreatedDBObject(text, true);

            // Layout
            //createLayout(pl, layout, width, height, t);
        }
 public RedefineBlock(BlockTableRecord btr)
 {
     IdBtr = btr.Id;
     Name = btr.Name;
     OldName = Name;
     IsDynamic = btr.IsDynamicBlock;
 }
Пример #7
0
 public void Create(BlockTableRecord btr, Transaction t)
 {
     var table = GetTable();
     table.Position = ptPlan;
     table.TransformBy(Matrix3d.Scaling(100, table.Position));
     btr.AppendEntity(table);
     t.AddNewlyCreatedDBObject(table, true);
 }
Пример #8
0
 public static ObjectIdCollection Draw(String block, params Entity[] ents)
 {
     ObjectIdCollection ids = new ObjectIdCollection();
     //Abrimos el documento activo
     Document doc = Application.DocumentManager.MdiActiveDocument;
     Editor ed = doc.Editor;
     //Abrimos la BD
     Database dwg = doc.Database;
     //Se utiliza el using para cerrar la
     //transacción
     //El Transaction Manager administra las transacciones y se
     //encuentra dentro de la BD
     using (Transaction tr = dwg.TransactionManager.StartTransaction())
     {
         try
         {
             //1: Abrir tabla de bloques en modo lectura
             BlockTable blkTab = (BlockTable)
                 dwg.BlockTableId.GetObject(OpenMode.ForRead);
             //2: Checar si existe mi bloque
             BlockTableRecord myRecord;
             if (!blkTab.Has(block))
             {
                 //3: Upgrade Open cambia un objeto de lectura
                 //a escritura
                 blkTab.UpgradeOpen();
                 BlockTableRecord newRecord = new BlockTableRecord();
                 newRecord.Name = block;
                 //4: Agregar a la tabla y notificar
                 blkTab.Add(newRecord);
                 tr.AddNewlyCreatedDBObject(newRecord, true);
                 myRecord = newRecord;
             }
             else
             {
                 //3: Solo lo abro
                 myRecord = (BlockTableRecord)
                     blkTab[block].GetObject(OpenMode.ForWrite);
             }
             //Dibujar en myRecord
             foreach (Entity ent in ents)
             {
                 myRecord.AppendEntity(ent);
                 tr.AddNewlyCreatedDBObject(ent, true);
                 ids.Add(ent.Id);
             }
             tr.Commit();
         }
         catch (Exception exc)
         {
             //Si algo sale mal aborta
             ed.WriteMessage(exc.Message);
             tr.Abort();
         }
     }
     return ids;
 }
Пример #9
0
 // Повортот подписи марки (Марки СБ и Марки Покраски) и добавление фоновой штриховки
 public void Convert(BlockTableRecord btr)
 {
     // Расположение и поворот марки СБ
     if (!panelBtr.IdCaptionMarkSb.IsNull)
     {
         Point3d posMarkSb = new Point3d(panelBtr.ExtentsNoEnd.MinPoint.X + 230, panelBtr.ExtentsNoEnd.MinPoint.Y + 20, 0);
         Extents3d extMarkSb = convertText(panelBtr.IdCaptionMarkSb, 90, posMarkSb, true);
         Point3d posMarkPaint = new Point3d(posMarkSb.X + 250, posMarkSb.Y + 20, 0);
         Extents3d extPaint = convertText(panelBtr.IdCaptionPaint, 90, posMarkPaint, false);
         Extents3d extTexts = extMarkSb;
         extTexts.AddExtents(extPaint);
         сreateHatch(extTexts, btr);
     }
 }
Пример #10
0
        //--------------------------------------------------------------
        // ����:����һ���鶨�壨����¼��
        // ���ߣ�
        // ���ڣ�2007-7-20
        // ˵����
        //
        //----------------------------------------------------------------
        public ObjectId CreateBlkDef()
        {
            //���庯���ķ���ֵObjectId
            ObjectId blkObjId = new ObjectId();
            Database db = HostApplicationServices.WorkingDatabase;

            // ʹ�� "using"�ؼ���ָ������ı߽�
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //��ȡ���
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                //ͨ������myBlkName�жϿ�����Ƿ��������¼
                if ((bt.Has("myBlkName")))
                {
                    blkObjId = bt["myBlkName"];//����Ѿ����ڣ�ͨ��������ȡ���Ӧ��ObjectId
                }
                else
                {
                    //����һ��Բ
                    Point3d center = new Point3d(10, 10, 0);
                    Circle circle = new Circle(center, Vector3d.ZAxis, 2);
                    circle.ColorIndex = 1;
                    //�����ı�Text:
                    MText text = new MText();
                    text.Contents = " ";
                    text.Location = center;
                    text.ColorIndex = 2;

                    //�����µĿ���¼ myBlkName
                    BlockTableRecord newBtr = new BlockTableRecord();
                    newBtr.Name = "myBlkName";
                    newBtr.Origin = center;
                    //�������¼�����
                    blkObjId = bt.Add(newBtr); // ���ؿ��Ӧ��ObjectId
                    trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database!

                    //�����´�����ʵ�嵽����¼
                    newBtr.AppendEntity(circle);
                    newBtr.AppendEntity(text);
                    // ֪ͨ�����´����˶���
                    trans.AddNewlyCreatedDBObject(circle, true);
                    trans.AddNewlyCreatedDBObject(text, true);
                }
                trans.Commit(); //�ύ����
            }
            return blkObjId;
        }
Пример #11
0
        public void Create(Point2d ptCell, BlockTableRecord cs, Transaction t)
        {
            var cellWidth = ColorBookHelper.CellWidth;
            var cellHeight = ColorBookHelper.CellHeight;
            var margin = ColorBookHelper.Margin;
            var marginHalf = margin * 0.5;

            Point3d ptText = new Point3d(ptCell.X + cellWidth * 0.5, ptCell.Y - ColorBookHelper.TextHeight-margin, 0);

            Polyline pl = new Polyline(4);
            pl.AddVertexAt(0, new Point2d(ptCell.X+margin, ptText.Y- marginHalf), 0, 0, 0);
            pl.AddVertexAt(1, new Point2d(ptCell.X+cellWidth- margin, ptText.Y- marginHalf), 0, 0, 0);
            pl.AddVertexAt(2, new Point2d(ptCell.X + cellWidth-margin, ptCell.Y-cellHeight+margin), 0, 0, 0);
            pl.AddVertexAt(3, new Point2d(ptCell.X+margin, ptCell.Y - cellHeight+margin), 0, 0, 0);
            pl.Closed = true;
            pl.SetDatabaseDefaults();
            pl.Color = Color;

            cs.AppendEntity(pl);
            t.AddNewlyCreatedDBObject(pl, true);

            Hatch h = new Hatch();
            h.SetDatabaseDefaults();
            h.SetHatchPattern(HatchPatternType.PreDefined, "Solid");
            h.Annotative = AnnotativeStates.False;

            cs.AppendEntity(h);
            t.AddNewlyCreatedDBObject(h, true);

            h.Associative = true;
            h.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection(new[] { pl.Id }));
            h.Color = Color;
            h.EvaluateHatch(true);

            DBText text = new DBText();
            text.SetDatabaseDefaults();
            text.HorizontalMode = TextHorizontalMode.TextCenter;
            text.Annotative = AnnotativeStates.False;
            text.Height = ColorBookHelper.TextHeight;
            text.AlignmentPoint = ptText;
            text.AdjustAlignment(cs.Database);
            text.TextStyleId = ColorBookHelper.IdTextStylePik;
            text.TextString = Name;

            cs.AppendEntity(text);
            t.AddNewlyCreatedDBObject(text, true);
        }
Пример #12
0
        /**
         * @brief   Metodo que descompone una curva en un conjunto de segmentos de línea que aproximan o recubren la curva original.
         *
         * @param   cur         Entidad curva que debe ser linealizada.
         * @param   numSeg      Número de líneas en las que tiene que ser partida la curva.
         * @param   acBlkTbl    Tabla de bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados.
         * @param   acBlkTblRec Tabla de registros de los bloques de AutoCAD para buscar nuevos objetos y añadir nuevos objetos generados.
         * @param   t           Transaccion abierta para manipular la tabla de bloques de AutoCAD.
         * @param   LayerId     Parámetro del tipo ObjectId que identifica la capa a la que tendrán que asociarse las nuevas líneas generadas por el proceso
         *                      de descomposición de la curva.
         * @param   dwfg        Parámetro del tipo dwgFile donde se almacenaran las nuevas líneas creadas a partir del proceso de descomposición de la curva.
         *
         * @return              Devuelve una colección de entidades tipo linea bajo la clase DBObjectCollection.
         **/
        public static DBObjectCollection curvaAlineas(Curve cur, int numSeg, BlockTable acBlkTbl, BlockTableRecord acBlkTblRec,Transaction t, ObjectId LayerId, dwgFile dwfg)
        {
            DBObjectCollection ret = new DBObjectCollection();

            // Collect points along our curve
            Point3dCollection pts = new Point3dCollection();

            // Split the curve's parameter space into
            // equal parts
            double startParam = cur.StartParam;
            double segLen = (cur.EndParam - startParam) / numSeg;

            // Loop along it, getting points each time
            for (int i = 0; i < numSeg + 1; i++)
            {
                Point3d pt = cur.GetPointAtParameter(startParam + segLen * i);
                pts.Add(pt);
            }

            if (pts != null && pts.Count > 0)
            {
                if (pts.Count == 1)
                {
                    // Retornamos un punto.
                }
                else if (pts.Count >= 2)
                {
                    // Retornamos una secuencia de lineas
                    for (int i = 0; i < pts.Count - 1; i++)
                    {
                        Line ln = new Line();
                        ln.StartPoint = pts[i];
                        ln.EndPoint = pts[i + 1];
                        ln.LayerId = LayerId;
                        acBlkTblRec.AppendEntity(ln);
                        t.AddNewlyCreatedDBObject(ln, true);
                        dwfg.objetosArtificiales.Add(ln.ObjectId);
                        ret.Add(ln);
                    }
                }
            }

            return ret;
        }
Пример #13
0
        public static List<FacadeFrontBlock> GetFacadeFrontBlocks(BlockTableRecord ms, List<FloorMounting> floors)
        {
            List<FacadeFrontBlock> facadeFrontBlocks = new List<FacadeFrontBlock>();
            foreach (ObjectId idEnt in ms)
            {
                var blRef = idEnt.GetObject(OpenMode.ForRead, false, true) as BlockReference;
                if (blRef == null) { continue; }
                // Если это блок обозначения стороны фасада - по имени блока
                if (string.Equals(blRef.GetEffectiveName(), Settings.Default.BlockFacadeName, StringComparison.CurrentCultureIgnoreCase))
                {
                    FacadeFrontBlock front = new FacadeFrontBlock(blRef);
                    facadeFrontBlocks.Add(front);
                }
            }
            // Найти все блоки монтажных панелей входящих в фасад
            RTree<FloorMounting> rtreeFloors = new RTree<FloorMounting>();
            foreach (var front in floors)
            {
                try
                {
                    rtreeFloors.Add(front.RectangleRTree, front);
                }
                catch { }
            }
            foreach (var front in facadeFrontBlocks)
            {
                // найти соотв обозн стороны фасада
                var frontsIntersects = rtreeFloors.Intersects(front.RectangleRTree);

                // если нет пересечений фасадов - пропускаем блок монтажки - он не входит в
                // фасады, просто так вставлен
                if (frontsIntersects.Count == 0)
                {
                    Inspector.AddError($"Для блока обозначения стороны фасада не найдены монтажные планы.", front.IdBlRef, System.Drawing.SystemIcons.Error);
                    continue;
                }
                foreach (var item in frontsIntersects)
                {
                    front.AddPanels(item);
                }
                front.DefineMinMax();
            }
            return facadeFrontBlocks;
        }
Пример #14
0
 /// <summary>
 /// Добавление атрибутов к вставке блока
 /// </summary>        
 public static void AddAttributes(BlockReference blRef, BlockTableRecord btrBl, Transaction t)
 {
     foreach (ObjectId idEnt in btrBl)
     {
         if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition")
         {
             var atrDef = t.GetObject(idEnt, OpenMode.ForRead) as AttributeDefinition;
             if (!atrDef.Constant)
             {
                 using (var atrRef = new AttributeReference())
                 {
                     atrRef.SetAttributeFromBlock(atrDef, blRef.BlockTransform);
                     //atrRef.TextString = atrDef.TextString;
                     blRef.AttributeCollection.AppendAttribute(atrRef);
                     t.AddNewlyCreatedDBObject(atrRef, true);
                 }
             }
         }
     }
 }
Пример #15
0
        private void addOutsides(BlockTableRecord btrPanel, Transaction t)
        {
            if (panelBase.Panel.outsides?.outside?.Count()>0)
             {
            foreach (var outside in panelBase.Panel.outsides.outside)
            {
               Polyline plOut = new Polyline();
               Point2d pt;// =new Point2d(outside.posi.X, outside.posi.Y);
               double width = Math.Abs(outside.width)+70;
               // Если это левое примыкание Outside
               if (Math.Abs(outside.posi.X)<10)
               {
                  pt = new Point2d(outside.posi.X, outside.posi.Y);
                  panelBase.XMinContour = width;
                  panelBase.XStartTile = width+11;
                  //panelBase.XMinPanel = pt.X;
                  panelBase.IsOutsideLeft = true;
               }
               else
               {
                  pt = new Point2d(outside.posi.X-70, outside.posi.Y);
                  panelBase.XMaxContour += -70;
                  panelBase.XMaxPanel = pt.X + width;
                  panelBase.IsOutsideRight = true;
               }

               plOut.AddVertexAt(0, pt, 0, 0, 0);
               pt = new Point2d(pt.X+ width, pt.Y);
               plOut.AddVertexAt(1, pt, 0, 0, 0);
               pt = new Point2d(pt.X, pt.Y+outside.height);
               plOut.AddVertexAt(2, pt, 0, 0, 0);
               pt = new Point2d(pt.X- width, pt.Y);
               plOut.AddVertexAt(3, pt, 0, 0, 0);
               plOut.Closed = true;

               plOut.Layer = "0";
               btrPanel.AppendEntity(plOut);
               t.AddNewlyCreatedDBObject(plOut, true);
            }
             }
        }
Пример #16
0
        public static void Create(Database db, Grevit.Types.Door door, Wall wall, Transaction tr, BlockTableRecord ms)
        {
            Door d = new Door();
            DictionaryDoorStyle dds = new DictionaryDoorStyle(db);
            bool newEnt = false;
            if (Command.existing_objects.ContainsKey(door.GID))
            {
                d = (Door)tr.GetObject(Command.existing_objects[door.GID], OpenMode.ForWrite);
            }
            else
            {
                d.SetDatabaseDefaults(db);
                d.SetToStandard(db);
                AnchorOpeningBaseToWall w = new AnchorOpeningBaseToWall();
                w.SetToStandard(db);
                w.SubSetDatabaseDefaults(db);
                d.SetAnchor(w);
                newEnt = true;
                w.SetSingleReference(wall.Id, Autodesk.Aec.DatabaseServices.RelationType.OwnedBy);
            }

            Point3d pkt = new Point3d(door.locationPoint.x, door.locationPoint.y + (wall.Width / 2), door.locationPoint.z);
            d.Location = pkt;

            LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
            if (door.TypeOrLayer != "") { if (lt.Has(door.TypeOrLayer)) d.LayerId = lt[door.TypeOrLayer]; }
            if (dds.Has(door.FamilyOrStyle, tr)) d.StyleId = dds.GetAt(door.FamilyOrStyle);

            if (newEnt)
            {
                AddXData(door, d);
                ms.AppendEntity(d);
                tr.AddNewlyCreatedDBObject(d, true);
            }

            writeProperties(d, door.parameters, tr);
            storeID(door, d.Id);
        }
Пример #17
0
        /// <summary>
        /// Создание ассоциативной штриховки по полилинии
        /// Полилиния должна быть в базе чертежа
        /// </summary>        
        public static Hatch CreateAssociativeHatch(Curve loop, BlockTableRecord cs, Transaction t,
            string pattern = "SOLID", string layer = null, LineWeight lw = LineWeight.LineWeight015)
        {
            var h = new Hatch();
            h.SetDatabaseDefaults();
            if (layer != null)
            {
                Layers.LayerExt.CheckLayerState(layer);
                h.Layer = layer;
            }
            h.LineWeight = lw;
            h.Linetype = SymbolUtilityServices.LinetypeContinuousName;
            h.SetHatchPattern(HatchPatternType.PreDefined, pattern);
            cs.AppendEntity(h);
            t.AddNewlyCreatedDBObject(h, true);
            h.Associative = true;
            h.HatchStyle = HatchStyle.Normal;

            // добавление контура полилинии в гштриховку
            var ids = new ObjectIdCollection();
            ids.Add(loop.Id);
            try
            {
                h.AppendLoop(HatchLoopTypes.Default, ids);
            }
            catch (Exception ex)
            {
                Logger.Log.Error(ex, $"CreateAssociativeHatch");
                h.Erase();
                return null;
            }
            h.EvaluateHatch(true);

            var orders = cs.DrawOrderTableId.GetObject(OpenMode.ForWrite) as DrawOrderTable;
            orders.MoveToBottom(new ObjectIdCollection(new[] { h.Id }));

            return h;
        }
Пример #18
0
 public DimensionFacade(BlockTableRecord btrPanel, Transaction t, PanelBase panel)
     : base(btrPanel, t, panel)
 {
 }
Пример #19
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);
        }
Пример #20
0
        public static void DrawVolumesTableInBlock(decimal[] decVolumesArray/*, Point3d tablePosition */)
        {
            if (decVolumesArray == null)
            {
                AcVolShowForm();
                return;
            }

            string tableLayerName = "acVlm_Таблицы объемов";
            CreateLayer(tableLayerName, true, false);
            string tableAttributeLayerName = "acVlm_Invisible Layers";
            CreateLayer(tableAttributeLayerName, false, true);

            Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ.
            //Editor acDocEd = acDoc.Editor; // Editor текущего документа.
            Database acDocDb = acDoc.Database; // Database текущего документа.
            using (acDoc.LockDocument()) // блокировка документа
            {
                // начинаем транзакцию
                using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction())
                {

                    //***
                    // ШАГ 0 - запрос ПК поперечника и его распознание
                    //***
                    double doublePk = ParcePk(SelectPk("Укажите ПК поперечного профиля:"));
                    if (doublePk < 0)
                    {
                        MessageBox.Show("Пикет не распознан или выбор пикета отменен!\nТаблица объемов не будет привязана к пикету и не будет учитываться при экспорте объемов в Excel.",
                            myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }


                    //***
                    //ШАГ 1 - создаем таблицу и заполняем ее
                    //***

                    Table objTable = new Table();
                    int tableColNumber = 3;
                    int tableRowNumber = _form.listBoxLayers.Items.Count + 1;// количество слоев +1 строка на заголовок таблицы
                    objTable.SetSize(tableRowNumber, tableColNumber);
                    Point3d tablePosition = GetUserPoint("Укажите точку вставки таблицы:");

                    if (tablePosition == new Point3d(2147483647, 2147483647, 2147483647))
                    {
                        acTrans.Abort();
                        AcVolShowForm();
                        return;
                    }
                    objTable.Position = tablePosition;

                    //создаем массив значений для таблицы включая заголовки.
                    string[,] strTableArray = new string[tableRowNumber, tableColNumber];
                    //Записываем в массив заголовки
                    strTableArray[0, 0] = "Наименование";
                    strTableArray[0, 1] = "Ед.Изм.";
                    strTableArray[0, 2] = "Значение";
                    //Записываем в массив Имя объема, Ед.Изм и значение объема и так для каждого объема из лист бокса
                    for (int rowNumber = 1; rowNumber < tableRowNumber; rowNumber++)
                    {
                        strTableArray[rowNumber, 0] = (string)_form.listBoxLayers.Items[rowNumber - 1];
                        strTableArray[rowNumber, 1] = (string)_form.listBoxLayersUnits.Items[rowNumber - 1];
                        strTableArray[rowNumber, 2] = Convert.ToString(Math.Round(decVolumesArray[rowNumber - 1], 2), CultureInfo.InvariantCulture);
                    }

                    // Заполняем таблицу значениями из массива String[,] strTableArray
                    for (int rowNumber = 0; rowNumber < tableRowNumber; rowNumber++)
                    {
                        for (int colNumber = 0; colNumber < tableColNumber; colNumber++)
                        {
                            objTable.Cells[rowNumber, colNumber].TextHeight = 2.5;
                            switch (colNumber)
                            {
                                case 0:
                                    objTable.Columns[colNumber].Width = 60;
                                    break;
                                case 1:
                                    objTable.Columns[colNumber].Width = 15;
                                    break;
                                case 2:
                                    objTable.Columns[colNumber].Width = 20;
                                    break;
                            }
                            objTable.Rows[rowNumber].Height = 8;
                            if (colNumber == 0 & rowNumber > 0)
                            {
                                objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleLeft;
                            }
                            else
                            {
                                objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleCenter;
                            }
                            objTable.Cells[rowNumber, colNumber].SetValue(strTableArray[rowNumber, colNumber], ParseOption.ParseOptionNone);
                        }
                    }

                    // задаем слой таблице
                    objTable.Layer = tableLayerName;

                    //***
                    //  если ПК распознан, то создаем блок, помещаем таблицу в блок и присваиваем атрибут "ПК"
                    //***

                    if (doublePk >= 0)
                    {
                        string pk = Convert.ToString(doublePk, CultureInfo.InvariantCulture);

                        // имя создаваемого блока
                        string objTableBlockName = "acVlm_" + Convert.ToString((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds, CultureInfo.InvariantCulture);

                        // открываем таблицу блоков на чтение
                        BlockTable blockTable = (BlockTable)acTrans.GetObject(acDocDb.BlockTableId, OpenMode.ForRead);

                        // вначале проверяем, нет ли в таблице блока с таким именем
                        // если есть - выводим сообщение об ошибке и заканчиваем выполнение команды
                        if (blockTable.Has(objTableBlockName))
                        {
                            MessageBox.Show("A block with the name \"" + objTableBlockName + "\" already exists.", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        // создаем новое определение блока, задаем ему имя
                        BlockTableRecord objBtr = new BlockTableRecord { Name = objTableBlockName };

                        blockTable.UpgradeOpen(); //переоткрываем blockTable на запись.

                        // добавляем созданное определение блока в таблицу блоков и в транзакцию,
                        // запоминаем ID созданного определения блока (оно пригодится чуть позже)
                        ObjectId objBtrId = blockTable.Add(objBtr);
                        acTrans.AddNewlyCreatedDBObject(objBtr, true);

                        //добавляем таблицу в блок и в транзацию
                        objBtr.AppendEntity(objTable);
                        acTrans.AddNewlyCreatedDBObject(objTable, true);

                        // создаем определение аттрибута
                        AttributeDefinition objAttribute = new AttributeDefinition
                        {
                            Position = new Point3d(0, 0, 0),
                            Tag = "ПК",
                            Layer = tableAttributeLayerName
                        };

                        // добавляем атрибут в блок и в транзакцию
                        objBtr.AppendEntity(objAttribute);
                        acTrans.AddNewlyCreatedDBObject(objAttribute, true);

                        //***
                        // добавляем вхождение созданного блока на чертеж
                        //***

                        var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                        // создаем новое вхождение блока, используя ранее сохраненный ID определения блока
                        BlockReference objBlockReference = new BlockReference(Point3d.Origin, objBtrId)
                        {
                            Layer = tableLayerName
                        };


                        // добавляем созданное вхождение блока на пространство чертежа и в транзакцию
                        if (acBtr != null) acBtr.AppendEntity(objBlockReference);
                        acTrans.AddNewlyCreatedDBObject(objBlockReference, true);

                        // задаем значение аттрибута
                        AttributeReference objAttributeReference = new AttributeReference();
                        objAttributeReference.SetAttributeFromBlock(objAttribute, objBlockReference.BlockTransform);
                        objAttributeReference.TextString = pk;
                        objAttributeReference.Layer = tableAttributeLayerName;
                        objBlockReference.AttributeCollection.AppendAttribute(objAttributeReference);
                        acTrans.AddNewlyCreatedDBObject(objAttributeReference, true);

                    }
                    //***
                    //  если ПК _НЕ_распознан, то помещаем таблицу на чертеж без создания блока с выводом предупреждения
                    //***
                    else
                    {
                        
                        var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                        if (acBtr != null) acBtr.AppendEntity(objTable);
                        acTrans.AddNewlyCreatedDBObject(objTable, true);
                    }

                    // фиксируем транзакцию
                    acTrans.Commit();

                    AcVolShowForm();
                }
            }
        }
        static public void CmdInsertBlock()
        {
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            PromptStringOptions optName = new PromptStringOptions("\nEnter the name of the block: ");

            optName.AllowSpaces = true;

            if (_sLastBlock == string.Empty)
            {
                optName.UseDefaultValue = true;
                optName.DefaultValue    = _sLastBlock;
            }

            //Loop
            do
            {
                //Esk the user by block name
                PromptResult ProNameRes = ed.GetString(optName);

                if (ProNameRes.Status == PromptStatus.Cancel)
                {
                    break;//Command canceled, go out of loop
                }
                else
                {
                    //Get objId
                    ObjectId objId = GetBlockId(ProNameRes.StringResult);

                    if (objId.IsValid)
                    {
                        //Create BlockReference
                        BlockReference blockRef = new BlockReference(new Point3d(), objId);

                        //Strategy for Preview in PointMonitor
                        _PointMonitorStrategy = new PointMonitorStrategy(delegate(object sender, PointMonitorEventArgs e)
                        {
                            try
                            {
                                //Refresh gost block.
                                blockRef.Position = e.Context.ComputedPoint;
                                e.Context.DrawContext.Geometry.Draw(blockRef);
                            }
                            catch (System.Exception ex)
                            {
                            }
                        });


                        //add pointMonitor
                        ed.PointMonitor += new PointMonitorEventHandler(PointMonitor);

                        //Get Second point
                        PromptPointOptions opcoesPonto = new PromptPointOptions("\nClick on the place where block will be inserted: ");
                        opcoesPonto.AllowNone = false;

                        PromptPointResult ProPtRes = ed.GetPoint(opcoesPonto);

                        //remove pointMonitor
                        ed.PointMonitor -= new PointMonitorEventHandler(PointMonitor);

                        //Definitive insertion
                        switch (ProPtRes.Status)
                        {
                        case PromptStatus.OK:
                            //Create Grating
                            using (Transaction trans = db.TransactionManager.StartTransaction())
                            {
                                try
                                {
                                    //Set Position
                                    blockRef.Position = ProPtRes.Value;
                                    //We need clone the block reference to obtain a block wiht other objectID in each iteration
                                    BlockReference blockRefClone = blockRef.Clone() as BlockReference;
                                    //Get block table records
                                    BlockTableRecord currSpace = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                                    //Insert Block
                                    currSpace.AppendEntity(blockRefClone);
                                    trans.AddNewlyCreatedDBObject(blockRefClone, true);
                                    trans.Commit();
                                }
                                catch (System.Exception ex)
                                {
                                    trans.Abort();
                                }
                            }
                            break;

                        case PromptStatus.Cancel:
                            //Command Canceled
                            break;
                        }

                        //Save the name of inserted block
                        _sLastBlock = ProNameRes.StringResult;

                        //Go out of Loop
                        break;
                    }
                    else
                    {
                        ed.WriteMessage("\nNot foud any block with name \"" + ProNameRes.StringResult + "\".");
                    }
                }
            }while(true);
        }
        static public void CmdRampa()
        {
            Database db = Application.DocumentManager.MdiActiveDocument.Database;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            //Get First point
            Point3d Pt1 = ed.GetPoint("\nClick on initial point of the ramp (Lower side): ").Value;

            //Strategy for Preview in PointMonitor
            _PointMonitorStrategy = new PointMonitorStrategy(delegate(object sender, PointMonitorEventArgs e)
            {
                try
                {
                    ArCaWrpRampa objRampa = new ArCaWrpRampa();
                    objRampa.p3dStart     = Pt1;
                    objRampa.p3dEnd       = e.Context.ComputedPoint;
                    e.Context.DrawContext.Geometry.Draw(objRampa);
                }
                catch (System.Exception ex)
                {
                }
            });

            //add pointMonitor
            ed.PointMonitor += new PointMonitorEventHandler(PointMonitor);

            //Get Second point
            PromptPointOptions opcoesPonto = new PromptPointOptions("\nClick on final point of the ramp (Higher side): ");

            opcoesPonto.AllowNone = false;
            opcoesPonto.BasePoint = Pt1;
            PromptPointResult ProPtRes = ed.GetPoint(opcoesPonto);

            //remove pointMonitor
            ed.PointMonitor -= new PointMonitorEventHandler(PointMonitor);

            switch (ProPtRes.Status)
            {
            case PromptStatus.OK:
                //Crate Rampa
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        BlockTableRecord currSpace = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                        ArCaWrpRampa objRampa = new ArCaWrpRampa();
                        objRampa.p3dStart = Pt1;
                        objRampa.p3dEnd   = ProPtRes.Value;

                        currSpace.AppendEntity(objRampa);
                        trans.AddNewlyCreatedDBObject(objRampa, true);
                        trans.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        trans.Abort();
                    }
                }
                break;

            case PromptStatus.Cancel:
                //Command Canceled
                break;
            }
        }
Пример #23
0
        static PreviewEndPlotStatus MultiplePlotOrPreview(PlotEngine pe, bool isPreview, ObjectIdCollection layoutSet, int layoutNumIfPreview, string dirPath, string jobnumber)
        {
            Document             doc = AcApp.DocumentManager.MdiActiveDocument;
            Database             db  = doc.Database;
            PreviewEndPlotStatus ret = PreviewEndPlotStatus.Cancel;
            ObjectIdCollection   layoutsToPlot;

            if (isPreview && layoutNumIfPreview >= 0)
            {
                // Preview is really pre-sheet, so we reduce the
                // sheet collection to contain the one we want
                layoutsToPlot = new ObjectIdCollection
                {
                    layoutSet[layoutNumIfPreview]
                };
            }
            else
            {
                // If we're plotting we need all the sheets,
                // so copy the ObjectIds across
                ObjectId[] ids = new ObjectId[layoutSet.Count];
                layoutSet.CopyTo(ids, 0);
                layoutsToPlot = new ObjectIdCollection(ids);
            }
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // Create a Progress Dialog to provide info
                // and allow thej user to cancel
                using (PlotProgressDialog ppd = new PlotProgressDialog(isPreview, layoutsToPlot.Count, true))
                {
                    int numSheet = 1;
                    foreach (ObjectId btrId in layoutsToPlot)
                    {
                        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead);
                        Layout           lo  = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                        // We need a PlotSettings object
                        // based on the layout settings
                        // which we then customize
                        PlotSettings ps = new PlotSettings(lo.ModelType);
                        ps.CopyFrom(lo);

                        // The PlotSettingsValidator helps
                        // create a valid PlotSettings object
                        PlotSettingsValidator psv = PlotSettingsValidator.Current;

                        // We need a PlotInfo object
                        // linked to the layout
                        PlotInfo pi = new PlotInfo
                        {
                            Layout = btr.LayoutId
                        };
                        // Make the layout we're plotting current
                        LayoutManager.Current.CurrentLayout = lo.LayoutName;
                        // We need to link the PlotInfo to the
                        // PlotSettings and then validate it
                        pi.OverrideSettings = ps;
                        PlotInfoValidator piv = new PlotInfoValidator
                        {
                            MediaMatchingPolicy = MatchingPolicy.MatchEnabled
                        };
                        piv.Validate(pi);
                        // We set the sheet name per sheet
                        ppd.set_PlotMsgString(PlotMessageIndex.SheetName, doc.Name.Substring(doc.Name.LastIndexOf("\\") + 1) + " - " + lo.LayoutName);
                        if (numSheet == 1)
                        {
                            // All other messages get set once
                            ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Preview Progress");
                            ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                            ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                            ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                            ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                            ppd.LowerPlotProgressRange = 0;
                            ppd.UpperPlotProgressRange = 100;
                            ppd.PlotProgressPos        = 0;

                            // Let's start the plot/preview, at last
                            ppd.OnBeginPlot();
                            ppd.IsVisible = true;
                            pe.BeginPlot(ppd, null);

                            // We'll be plotting a single document
                            string file = dirPath + "\\" + jobnumber + " Combined " + DateTime.Now.ToString("MM-dd-yy");
                            pe.BeginDocument(pi, doc.Name, null, 1, !isPreview, file);
                        }

                        // Which may contains multiple sheets
                        ppd.LowerSheetProgressRange = 0;
                        ppd.UpperSheetProgressRange = 100;
                        ppd.SheetProgressPos        = 0;
                        PlotPageInfo ppi = new PlotPageInfo();
                        pe.BeginPage(ppi, pi, (numSheet == layoutsToPlot.Count), null);
                        ppd.OnBeginSheet();
                        pe.BeginGenerateGraphics(null);
                        ppd.SheetProgressPos = 50;
                        pe.EndGenerateGraphics(null);

                        // Finish the sheet
                        PreviewEndPlotInfo pepi = new PreviewEndPlotInfo();
                        pe.EndPage(pepi);
                        ret = pepi.Status;
                        ppd.SheetProgressPos = 100;
                        ppd.OnEndSheet();
                        numSheet++;

                        // Update the overall progress
                        ppd.PlotProgressPos +=
                            (100 / layoutsToPlot.Count);
                    }

                    // Finish the document
                    pe.EndDocument(null);

                    // And finish the plot
                    ppd.PlotProgressPos = 100;
                    ppd.OnEndPlot();
                    pe.EndPlot(null);
                }
            }
            return(ret);
        }
Пример #24
0
        static public void CornerRecordData()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;

            try
            {
                var acDB = doc.Database;

                using (var trans = acDB.TransactionManager.StartTransaction())
                {
                    DBDictionary layoutPages = (DBDictionary)trans.GetObject(acDB.LayoutDictionaryId,
                                                                             OpenMode.ForRead);

                    // Handle Corner Record meta data dictionary extracted from Properties and Content
                    Dictionary <String, object> cornerRecordForms = new Dictionary <string, object>();

                    CivilDB.CogoPointCollection cogoPointsColl = CivilDB.CogoPointCollection.GetCogoPoints(doc.Database);
                    var cogoPointCollected = CogoPointJson.geolocationCapture(cogoPointsColl);

                    List <string> layoutNamesList = new List <string>();

                    foreach (DBDictionaryEntry layoutPage in layoutPages)
                    {
                        var crFormItems  = layoutPage.Value.GetObject(OpenMode.ForRead) as Layout;
                        var isModelSpace = crFormItems.ModelType;

                        ObjectIdCollection textObjCollection = new ObjectIdCollection();

                        // Formatted Dictionary to create JSON output
                        Dictionary <string, object> textObjResults = new Dictionary <string, object>();

                        if (isModelSpace != true)
                        {
                            BlockTableRecord blkTblRec = trans.GetObject(crFormItems.BlockTableRecordId,
                                                                         OpenMode.ForRead) as BlockTableRecord;

                            layoutNamesList.Add(crFormItems.LayoutName.Trim().ToString().ToLower().Replace(" ", ""));

                            foreach (ObjectId btrId in blkTblRec)
                            {
                                if (btrId.ObjectClass.DxfName.Contains("TEXT") || btrId.ObjectClass.DxfName.Contains("MTEXT"))
                                {
                                    textObjCollection.Add(btrId);
                                }
                            }

                            // List of the Dictionary txtProps
                            List <object>   crFormElements = new List <object>();
                            List <object>   crFormInputs   = new List <object>();
                            List <ObjectId> crFormInputId  = new List <ObjectId>();

                            foreach (ObjectId txtItem in textObjCollection)
                            {
                                // Dictionary to collect Contents of the Corner Records Sheet
                                Dictionary <string, object> txtProps = new Dictionary <string, object>();

                                var txtItemName = trans.GetObject(txtItem, OpenMode.ForRead) as Entity;

                                if (txtItemName.Layer == "-SHEET")
                                {
                                    if (txtItem.ObjectClass.DxfName == "MTEXT")
                                    {
                                        var mtextValues = trans.GetObject(txtItem, OpenMode.ForRead)
                                                          as MText;

                                        //txtProps.Add("Class Type", "MTEXT");
                                        //txtProps.Add("Layer Name", mtextValues.Layer);
                                        txtProps.Add("Content", mtextValues.Text);
                                        //txtProps.Add("X", mtextValues.Location.X);
                                        //txtProps.Add("Y", mtextValues.Location.Y);

                                        crFormElements.Add(txtProps);
                                    }
                                    else if (txtItem.ObjectClass.DxfName == "TEXT")
                                    {
                                        //Capture Brief Legal Description here

                                        var textValues = trans.GetObject(txtItem, OpenMode.ForRead)
                                                         as DBText;

                                        //txtProps.Add("Class Type", "TEXT");
                                        //txtProps.Add("Layer Name", textValues.Layer);
                                        txtProps.Add("Content", textValues.TextString);
                                        //txtProps.Add("X", textValues.Position.X);
                                        //txtProps.Add("Y", textValues.Position.Y);

                                        crFormElements.Add(txtProps);
                                    }
                                }
                                else if (txtItemName.Layer == "$--SHT-ANNO")
                                {
                                    if (txtItem.ObjectClass.DxfName == "MTEXT")
                                    {
                                        var mtextValues = trans.GetObject(txtItem, OpenMode.ForRead)
                                                          as MText;

                                        //txtProps.Add("Class Type", "MTEXT");
                                        //txtProps.Add("Layer Name", mtextValues.Layer);
                                        txtProps.Add("Content", mtextValues.Text);
                                        //txtProps.Add("X", mtextValues.Location.X);
                                        //txtProps.Add("Y", mtextValues.Location.Y);

                                        crFormInputs.Add(txtProps);
                                        crFormInputId.Add(txtItem);
                                    }
                                    else if (txtItem.ObjectClass.DxfName == "TEXT")
                                    {
                                        var textValues = trans.GetObject(txtItem, OpenMode.ForRead)
                                                         as DBText;

                                        //txtProps.Add("Class Type", "TEXT");
                                        //txtProps.Add("Layer Name", textValues.Layer);
                                        txtProps.Add("Content", textValues.TextString);
                                        //txtProps.Add("X", textValues.Position.X);
                                        //txtProps.Add("Y", textValues.Position.Y);

                                        crFormInputs.Add(txtProps);
                                        crFormInputId.Add(txtItem);
                                    }
                                }
                            }
                            var briefLegalCollected = BriefLegalDescription.briefLegalCapture(textObjCollection, crFormInputId);
                            textObjResults.Add("Legal_Description_c", briefLegalCollected);
                            //textObjResults.Add("Form Inputs", crFormInputs);
                            //textObjResults.Add("Form Elements", crFormElements);
                            cornerRecordForms.Add(crFormItems.LayoutName.Trim().ToString().ToLower().Replace(" ", ""), textObjResults);
                        }
                    }

                    // Checks to see whether the points from the cogo point collection exist within
                    // the layout by searching for the correct collection key and layout name
                    List <string> cogoPointCollectedCheck = cogoPointCollected.Keys.ToList();
                    List <bool>   boolCheckResults        = new List <bool>();

                    IEnumerable <string> cogoPointNameCheck        = layoutNamesList.Except(cogoPointCollectedCheck);
                    List <string>        cogoPointNameCheckResults = cogoPointNameCheck.ToList();
                    var layoutNameChecker = new Regex("^(\\s*cr\\s*\\d\\d*)$");

                    if (!cogoPointNameCheckResults.Where(f => layoutNameChecker.IsMatch(f)).ToList().Any())
                    {
                        boolCheckResults.Add(true);
                    }
                    else
                    {
                        foreach (string cogoPointNameResultItem in cogoPointNameCheckResults)
                        {
                            Match layoutNameMatch = Regex.Match(cogoPointNameResultItem, "^(\\s*cr\\s*\\d\\d*)$",
                                                                RegexOptions.IgnoreCase);

                            if (layoutNameMatch.Success)
                            {
                                string layoutNameX = layoutNameMatch.Value;
                                ed.WriteMessage("\nLayout Named {0} does not have an associated cogo point", layoutNameX);
                            }
                        }
                        boolCheckResults.Add(false);
                    }


                    IEnumerable <string> layoutNameCheck        = cogoPointCollectedCheck.Except(layoutNamesList);
                    List <string>        layoutNameCheckResults = layoutNameCheck.ToList();
                    var cogoNameChecker = new Regex("^(\\s*cr\\s*\\d\\d*)$");


                    // If the layout name has any value other than CR == PASS
                    // If CR point exists and does not match then throw an error for user to fix
                    if (!layoutNameCheckResults.Where(f => cogoNameChecker.IsMatch(f)).ToList().Any())
                    {
                        boolCheckResults.Add(true);
                    }
                    else // Found a CR point that DID NOT match a layout name
                    {
                        foreach (string layoutNameCheckResultItem in layoutNameCheckResults)
                        {
                            Match cogoNameMatch = Regex.Match(layoutNameCheckResultItem, "^(\\s*cr\\s*\\d\\d*)$",
                                                              RegexOptions.IgnoreCase);

                            if (cogoNameMatch.Success)
                            {
                                string cogoNameX = cogoNameMatch.Value;
                                ed.WriteMessage("\nCorner Record point named {0} does not have an associated Layout",
                                                cogoNameX);
                            }
                        }
                        boolCheckResults.Add(false);
                    }

                    // Output JSON file to BIN folder
                    // IF there are two true booleans in the list then add the data to the corresponding keys (cr1 => cr1)
                    if ((boolCheckResults.Count(v => v == true)) == 2)
                    {
                        foreach (string cornerRecordFormKey in cornerRecordForms.Keys)
                        {
                            if (cogoPointCollected.ContainsKey(cornerRecordFormKey))
                            {
                                //ed.WriteMessage("THIS SHIT FINALLY WORKS FOR {0}", cornerRecordFormKey);
                                var cogoFinal     = (Dictionary <string, object>)cornerRecordForms[cornerRecordFormKey];
                                var cogoFinalType = ((Dictionary <string, object>)cogoPointCollected[cornerRecordFormKey])
                                                    ["Corner_Type_c"];
                                var cogoFinalLong = ((Dictionary <string, object>)cogoPointCollected[cornerRecordFormKey])
                                                    ["Geolocation_Longitude_s"];
                                var cogoFinalLat = ((Dictionary <string, object>)cogoPointCollected[cornerRecordFormKey])
                                                   ["Geolocation_Latitude_s"];

                                cogoFinal.Add("Corner_Type_c", cogoFinalType);
                                cogoFinal.Add("Geolocation_Longitude_s", cogoFinalLong);
                                cogoFinal.Add("Geolocation_Latitude_s", cogoFinalLat);
                            }
                        }
                        using (var writer = File.CreateText("CornerRecordForms.json"))
                        {
                            string strResultJson = JsonConvert.SerializeObject(cornerRecordForms,
                                                                               Formatting.Indented);
                            writer.WriteLine(strResultJson);
                        }
                    }
                    trans.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("Error: {0}", ex);
            }
        }
Пример #25
0
        public static void CreateSphere()
        {
            try
            {
                Document doc =
                    Application.DocumentManager.MdiActiveDocument;
                Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database;
                Editor ed = doc.Editor;

                Transaction tr =
                    doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    BlockTable bt =
                        (BlockTable)tr.GetObject(
                            db.BlockTableId,
                            OpenMode.ForRead
                            );
                    BlockTableRecord btr =
                        (BlockTableRecord)tr.GetObject(
                            bt[BlockTableRecord.ModelSpace],
                            OpenMode.ForWrite
                            );
                    Solid3d sol = new Solid3d();
                    sol.CreateSphere(10.0);

                    const string matname =
                        "Sitework.Paving - Surfacing.Riverstone.Mortared";
                    DBDictionary matdict =
                        (DBDictionary)tr.GetObject(
                            db.MaterialDictionaryId,
                            OpenMode.ForRead
                            );
                    if (matdict.Contains(matname))
                    {
                        sol.Material = matname;
                    }
                    else
                    {
                        ed.WriteMessage(
                            "\nMaterial (" + matname + ") not found" +
                            " - sphere will be rendered without it.",
                            matname
                            );
                    }
                    btr.AppendEntity(sol);

                    tr.AddNewlyCreatedDBObject(sol, true);
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                PGA.MessengerManager.MessengerManager.AddLog(ex.Message);
            }

            using (var doc = Active.Document.LockDocument())
            {
                AcadUtilities.ZoomExtents();
            }
        }
Пример #26
0
        public static void SnapshotToFile(
            string filename,
            VisualStyleType vst
            )
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database;
            Manager gsm = doc.GraphicsManager;

            // Get some AutoCAD system variables
            int vpn =
                System.Convert.ToInt32(
                    Application.GetSystemVariable("CVPORT")
                    );

            using (View view = new View())
            {
                gsm.SetViewFromViewport(view, vpn);

                // Set the visual style to the one passed in
                view.VisualStyle = new VisualStyle(vst);
                Device dev =
                    gsm.CreateAutoCADOffScreenDevice(new GraphicsKernel());
                using (dev)
                {
                    dev.OnSize(new Size((int)gsm.DeviceIndependentDisplaySize.Height, (int)gsm.DeviceIndependentDisplaySize.Width));

                    // Set the render type and the background color
                    dev.DeviceRenderType = RendererType.Default;
                    dev.BackgroundColor  = Color.White;

                    // Add the view to the device and update it
                    dev.Add(view);
                    dev.Update();

                    using (Model model = gsm.CreateAutoCADModel(new GraphicsKernel()))
                    {
                        Transaction tr =
                            db.TransactionManager.StartTransaction();
                        using (tr)
                        {
                            // Add the modelspace to the view
                            // It's a container but also a drawable
                            BlockTable bt =
                                (BlockTable)tr.GetObject(
                                    db.BlockTableId,
                                    OpenMode.ForRead
                                    );
                            BlockTableRecord btr =
                                (BlockTableRecord)tr.GetObject(
                                    bt[BlockTableRecord.ModelSpace],
                                    OpenMode.ForRead
                                    );
                            view.Add(btr, model);
                            tr.Commit();
                        }

                        // Take the snapshot
                        Rectangle rect = new Rectangle
                                             (new System.Drawing.Point(
                                                 (int)view.ViewportExtents.MinPoint.X,
                                                 (int)view.ViewportExtents.MinPoint.Y),
                                             new Size((int)gsm.DeviceIndependentDisplaySize.Height,
                                                      (int)gsm.DeviceIndependentDisplaySize.Width)
                                             );
                        System.Threading.Thread.Sleep(1000);

                        using (Bitmap bitmap = view.GetSnapshot(rect))
                        {
                            System.Threading.Thread.Sleep(1000);

                            bitmap.Save(filename);

                            // Clean up
                            view.EraseAll();
                            dev.Erase(view);
                        }
                    }
                }
            }
        }
Пример #27
0
        private static void PlacementColors(BlockTableRecord cs, [NotNull] ColorBook colorBookNcs, Point3d ptStart)
        {
            var t = db.TransactionManager.TopTransaction;

            double widthLayout  = Options.Instance.Width;
            double heightLayout = Options.Instance.Height;

            var widthCells  = widthLayout - widthLayout * 0.1;
            var heightCells = heightLayout - heightLayout * 0.1;

            var columns = Options.Instance.Columns;
            var rows    = Options.Instance.Rows;

            // Определение длины и высоты для каждой ячейки цвета
            CellWidth  = widthCells / columns;
            CellHeight = heightCells / rows;

            Margin     = CellWidth * 0.1;
            TextHeight = Convert.ToInt32(CellWidth * 0.09);

            var ptLayout = ptStart;

            var progress = new ProgressMeter();

            progress.SetLimit(colorBookNcs.Colors.Count);
            progress.Start("Расстановка цветов...");

            // Кол листов
            double cellsCount = columns * rows;
            var    layCount   = Convert.ToInt32(Math.Ceiling(colorBookNcs.Colors.Count / cellsCount));

            var index = 0;

            for (var l = 1; l < layCount + 1; l++)
            {
                // создание рамки листа
                AddLayout(ptLayout, l, widthLayout, heightLayout, cs, t);
                var ptCellFirst = new Point2d(ptLayout.X + (widthLayout - widthCells) * 0.5,
                                              ptLayout.Y - (heightLayout - heightCells) * 0.5);

                // Заполнение ячейками цветов
                for (var r = 0; r < rows; r++)
                {
                    var isBreak = false;
                    for (var c = 0; c < columns; c++)
                    {
                        index++;
                        if (index == colorBookNcs.Colors.Count)
                        {
                            isBreak = true;
                            break;
                        }

                        var colorItem = colorBookNcs.Colors[index];
                        var ptCell    = new Point2d(ptCellFirst.X + c * CellWidth, ptCellFirst.Y - r * CellHeight);
                        colorItem.Create(ptCell, cs, t);
                        progress.MeterProgress();
                    }

                    if (isBreak)
                    {
                        break;
                    }
                }

                ptLayout = new Point3d(ptLayout.X, ptLayout.Y + heightLayout, 0);
            }

            progress.Stop();
        }
        public static void ComputeMinAreaEnclosingRectangle(ObjectId[] idArray, CoordinateSystem actualCS)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();
            MessageFilter value           = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(value);
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    progressMeter.SetLimit(idArray.Length);
                    if ((double)idArray.Length > 10000.0)
                    {
                        progressMeter.Start("Computing min. area rectangle...");
                    }
                    CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), actualCS);
                    CoordinateTransformator inverseTransformation   = coordinateTransformator.GetInverseTransformation();
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    ObjectId         layerId          = DBManager.CurrentLayerId();
                    DBManager.CurrentLayerName();
                    PointSet pointSet = new PointSet();
                    for (int i = 0; i < idArray.Length; i++)
                    {
                        progressMeter.MeterProgress();
                        DBPoint dBPoint = (DBPoint)transaction.GetObject(idArray[i], (OpenMode)0, true);
                        Point   point   = new Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                        coordinateTransformator.Transform(point);
                        pointSet.Add(point);
                    }
                    ConvexHull2d convexHull2d = new ConvexHull2d();
                    convexHull2d.InitialPoints = pointSet;
                    convexHull2d.ComputeHull();
                    PointSet vertices = convexHull2d.Vertices;
                    double   z        = vertices[0].Z;
                    for (int j = 0; j < vertices.Count; j++)
                    {
                        vertices[j].Z = z;
                    }
                    BoundingRectangle boundingRectangle = convexHull2d.MinimumAreaEnclosingRectangle();
                    PointSet          vertices2         = boundingRectangle.GetVertices();
                    for (int k = 0; k < vertices2.Count; k++)
                    {
                        inverseTransformation.Transform(vertices2[k]);
                    }
                    Point3dCollection point3dCollection = Conversions.ToPoint3dCollection(vertices2.ToList());
                    Polyline3d        polyline3d        = new Polyline3d(0, point3dCollection, true);
                    polyline3d.LayerId = (layerId);
                    blockTableRecord.AppendEntity(polyline3d);
                    transaction.AddNewlyCreatedDBObject(polyline3d, true);
                    editor.WriteMessage("\nMinimum area enclosing rectangle properties:");
                    editor.WriteMessage("\n--------------------------------------------");
                    editor.WriteMessage("\nWidth           : " + boundingRectangle.Width.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nHeight          : " + boundingRectangle.Length.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nArea            : " + (boundingRectangle.Length * boundingRectangle.Width).ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nPerimeter length: " + (2.0 * boundingRectangle.Length + 2.0 * boundingRectangle.Width).ToString(DBManager.GetFormatFromLUPREC()));
                    transaction.Commit();
                }
                progressMeter.Stop();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Пример #29
0
        private void StreamExplodeSample()
        {
            // intro message
            Editor editor = GetEditor();

            editor.WriteMessage("* StreamExplode *\n");
            editor.WriteMessage("StreamExplode converts all entities to AutoCAD primitive entities.\n");
            editor.WriteMessage("Pick an object in the current drawing. The object you picked will be packaged to an anonymous block and finally referenced in the current space. The block-referenced object will be overlapping with the original one.\n");

            // pick a object to be exploded
            ObjectId id = PickObject(typeof(Entity), false);

            if (id.IsNull)
            {
                editor.WriteMessage("No object is picked\n");
                return;
            }

            Database           db            = GetDatabase();
            DBObjectCollection objects       = new DBObjectCollection();
            StreamExplode      streamExplode = new StreamExplode(db, objects);

            streamExplode.IsVisualExplode = true;
            streamExplode.SetForBoundarySearch(false);

            TransactionManager tm = db.TransactionManager;

            using (Transaction trans = tm.StartTransaction())
            {
                Entity ent = trans.GetObject(id, OpenMode.ForRead) as Entity;

                streamExplode.PushDisplayParameters(DictionaryDisplayConfiguration.GetStandardDisplayConfiguration(db), trans);
                streamExplode.PushEntity(ent);
                streamExplode.PushProperties(ent);

                streamExplode.Stream(ent);
                streamExplode.PackageExplodedEntities();

                streamExplode.PopProperties();
                streamExplode.PopEntity();
                streamExplode.PopDisplayParameters();

                trans.Commit();
            }

            BlockReference blockRef = null;

            foreach (DBObject obj in objects)
            {
                if (obj.GetType() == typeof(BlockReference))
                {
                    blockRef = obj as BlockReference;
                }
            }

            if (blockRef == null)
            {
                return;
            }

            blockRef.Position = Point3d.Origin;

            using (Transaction trans = tm.StartTransaction())
            {
                BlockTableRecord btr = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                btr.AppendEntity(blockRef);
                trans.AddNewlyCreatedDBObject(blockRef, true);
                trans.Commit();
            }
        }
Пример #30
0
        public void Cmd_AutoBlock()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            var objIds = acCurEd.GetAllSelection(false);

            if (objIds.Length <= 0)
            {
                return;
            }

            var bNameTaken = true;
            var bName      = string.Empty;

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Block table for read
                var acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForWrite) as BlockTable;

                if (acBlkTbl == null)
                {
                    acTrans.Abort();
                    return;
                }

                while (bNameTaken)
                {
                    var checkName = acCurEd.GetSimpleString("\nEnter desired block name: ");

                    if (string.IsNullOrEmpty(checkName))
                    {
                        acTrans.Abort();
                        return;
                    }

                    if (acBlkTbl.Has(checkName))
                    {
                        acCurEd.WriteMessage("\nBlock name already exists.");
                        continue;
                    }

                    bName      = checkName;
                    bNameTaken = false;
                }

                var objCol = new ObjectIdCollection();

                foreach (var obj in objIds)
                {
                    objCol.Add(obj);
                }

                var extents = acTrans.GetExtents(objIds, acCurDb);

                var acBtr = new BlockTableRecord();

                acBtr.Name         = bName;
                acBtr.Origin       = extents.MinPoint;
                acBtr.BlockScaling = BlockScaling.Uniform;
                acBtr.Explodable   = true;
                acBtr.Units        = UnitsValue.Inches;

                #region TODO replace with xml reading

                ////Add attribute definitions
                ////TODO read XML to get attributes to add
                ////For now we'll use a test value

                //var attTag = new AttributeDefinition
                //{
                //    Justify = AttachmentPoint.MiddleCenter,
                //    AlignmentPoint = extents.MinPoint,
                //    Prompt = "TAG:",
                //    Tag = "TAG",
                //    TextString = bName,
                //    Height = 1,
                //    Invisible = true,
                //    LockPositionInBlock = true
                //};

                //var attCrate = new AttributeDefinition
                //{
                //    Justify = AttachmentPoint.MiddleCenter,
                //    AlignmentPoint = extents.MinPoint,
                //    Prompt = "CRATE:",
                //    Tag = "CRATE",
                //    TextString = "",
                //    Height = 1,
                //    Invisible = true,
                //    LockPositionInBlock = true
                //};

                #endregion

                var blockId = acBlkTbl.Add(acBtr);

                //acBtr.AppendEntity(attTag);
                //acBtr.AppendEntity(attCrate);
                acTrans.AddNewlyCreatedDBObject(acBtr, true);

                var map = new IdMapping();
                acCurDb.DeepCloneObjects(objCol, acBtr.ObjectId, map, false);
                var objCol2 = new ObjectIdCollection();

                foreach (IdPair pair in map)
                {
                    if (!pair.IsPrimary)
                    {
                        continue;
                    }
                    var ent = acTrans.GetObject(pair.Value, OpenMode.ForWrite) as Entity;

                    if (ent == null)
                    {
                        continue;
                    }
                    objCol2.Add(ent.ObjectId);
                }

                acBtr.AssumeOwnershipOf(objCol2);

                var acBr = new BlockReference(extents.MinPoint, blockId);
                acCurDb.AppendEntity(acBr);
                acBr.AppendAttributes(acBtr, acTrans);

                foreach (var obj in objIds)
                {
                    var acEnt = acTrans.GetObject(obj, OpenMode.ForWrite) as Entity;
                    if (acEnt == null)
                    {
                        continue;
                    }
                    acEnt.Erase();
                }

                acTrans.Commit();
            }

            acCurDb.Audit(true, false);
        }
Пример #31
0
        public void MyCommand() // This method can have any name
        {
            // Put your command code here
            Document doc           = Application.DocumentManager.MdiActiveDocument;
            Database db            = doc.Database;
            Editor   ed            = doc.Editor;
            string   ClipLayerName = "TK-视口";

            using (Transaction Trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    //获取布局列表(剔除模型空间)
                    DBDictionary Layouts    = Trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                    ArrayList    Layoutlist = new ArrayList();
                    foreach (DBDictionaryEntry item in Layouts)
                    {
                        if (item.Key != "Model")
                        {
                            Layout layoutobject = Trans.GetObject(item.Value, OpenMode.ForRead) as Layout;
                            Layoutlist.Add(layoutobject);
                        }
                    }
                    //获取view列表,注意哦,是symbotable,不能用viewtable,会闪退
                    SymbolTable MyVt     = Trans.GetObject(db.ViewTableId, OpenMode.ForRead) as SymbolTable;
                    ArrayList   viewlist = new ArrayList();
                    foreach (ObjectId viewID in MyVt)
                    {
                        ViewTableRecord VR = Trans.GetObject(viewID, OpenMode.ForRead) as ViewTableRecord;
                        viewlist.Add(VR);
                        //ed.WriteMessage("\nhehe:{0}", viewID.ToString());
                    }

                    LayerStateManager layerState = db.LayerStateManager;


                    /*
                     * foreach(ViewTableRecord VR in viewlist)
                     * {
                     *
                     *  ed.WriteMessage("\n视图名:{0}", VR.Name);
                     *  ed.WriteMessage("\n视图中心坐标:{0}", VR.CenterPoint);
                     *  ed.WriteMessage("\n视图高度:{0}", VR.Height);
                     *  ed.WriteMessage("\n视图target:{0}", VR.Target);
                     *  ed.WriteMessage("\n视图宽度:{0}", VR.Width);
                     *  ed.WriteMessage("\n视图角度:{0}", VR.ViewTwist);
                     *
                     *  ed.WriteMessage("\n图层状况{0}", VR.LayerState);
                     * }
                     */

                    int scale = 1;
                    PromptIntegerOptions GetNumberOption = new PromptIntegerOptions("\n输入视口比例,默认为1");
                    GetNumberOption.AllowNegative = false;
                    GetNumberOption.AllowZero     = false;
                    GetNumberOption.AllowNone     = true;
                    PromptIntegerResult GetNumberResult = ed.GetInteger(GetNumberOption);
                    if (GetNumberResult.Status == PromptStatus.OK)
                    {
                        scale = GetNumberResult.Value;
                    }

                    for (int i = 0; i < Layoutlist.Count; i++)
                    {
                        if (i == viewlist.Count)
                        {
                            continue;
                        }
                        ViewTableRecord VR = viewlist[i] as ViewTableRecord;
                        Viewport        VP = SetViewport(VR, new Point2d(0, 0), scale);

                        Layout           LT  = Layoutlist[i] as Layout;
                        BlockTableRecord BTR = Trans.GetObject(LT.BlockTableRecordId, OpenMode.ForWrite) as BlockTableRecord;
                        BTR.AppendEntity(VP);
                        Trans.AddNewlyCreatedDBObject(VP, true);

                        LayoutManager.Current.SetCurrentLayoutId(LT.Id);
                        VP.On = true;

                        //恢复视图的图层状态
                        layerState.RestoreLayerState(VR.LayerState, VP.Id, 1, LayerStateMasks.CurrentViewport);

                        TypedValue[] Filter = new TypedValue[]
                        {
                            new TypedValue((int)DxfCode.Operator, "<and"),
                            new TypedValue((int)DxfCode.LayoutName, LT.LayoutName),
                            new TypedValue((int)DxfCode.LayerName, ClipLayerName),
                            new TypedValue((int)DxfCode.Operator, "<or"),
                            new TypedValue((int)DxfCode.Start, "POLYLINE"),
                            new TypedValue((int)DxfCode.Start, "POLYLINE3D"),
                            new TypedValue((int)DxfCode.Start, "POLYLINE2D"),
                            new TypedValue((int)DxfCode.Start, "LWPOLYLINE"),
                            new TypedValue((int)DxfCode.Operator, "or>"),
                            new TypedValue((int)DxfCode.Operator, "and>")
                        };
                        PromptSelectionResult selresult = ed.SelectAll(new SelectionFilter(Filter));
                        if (selresult.Status == PromptStatus.OK)
                        {
                            ObjectId[] IDs = selresult.Value.GetObjectIds();
                            VP.NonRectClipEntityId = IDs[0];
                            VP.NonRectClipOn       = true;
                            //ed.WriteMessage("\n呵呵,剪裁了视口哦");
                        }
                        else
                        {
                            ed.WriteMessage("\n布局“{0}”中未找到裁剪视口的多义线!视口裁剪失败!", LT.LayoutName);
                        }
                    }

                    Trans.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception Ex)
                {
                    ed.WriteMessage("出错啦!{0}", Ex.ToString());
                }
                finally
                {
                    Trans.Dispose();
                }
            }
        }
Пример #32
0
        private static Extents3d createChangePlan(List<ChangePanel> chPanels, Point3d ptPlan, ObjectId idBtrFloor,
                                                    BlockTableRecord btr,Transaction t)
        {
            // Вставить блок монтажки
            var blRefFloor = new BlockReference(ptPlan, idBtrFloor);
            btr.AppendEntity(blRefFloor);
            t.AddNewlyCreatedDBObject(blRefFloor, true);

            // Обвести облачком каждую панель с изменившейся покраской
            foreach (var chPanel in chPanels)
            {
                // Границы монт. панели на монт. плане в координатах Модели.
                var extMP = chPanel.ExtMountPanel;
                extMP.TransformBy(blRefFloor.BlockTransform);

                Point3d ptCloudMin;
                Point3d ptCloudMax;
                Point3d ptText;

                if (chPanel.IsHorizontal)
                {
                    ptCloudMin = new Point3d(extMP.MinPoint.X + 150, extMP.MinPoint.Y - 150, 0);
                    ptCloudMax = new Point3d(extMP.MaxPoint.X - 150, extMP.MaxPoint.Y + 150, 0);
                    ptText = new Point3d(ptCloudMin.X, ptCloudMin.Y - 100, 0);
                }
                else
                {
                    ptCloudMin = new Point3d(extMP.MinPoint.X - 150, extMP.MinPoint.Y + 150, 0);
                    ptCloudMax = new Point3d(extMP.MaxPoint.X + 150, extMP.MaxPoint.Y - 150, 0);
                    ptText = new Point3d(ptCloudMax.X+100, ptCloudMin.Y+(ptCloudMax.Y-ptCloudMin.Y)*0.5, 0);
                }
                var extCloud = new Extents3d(ptCloudMin, ptCloudMax);

                // Полилиния облака изменения
                var pl = extCloud.GetPolyline();
                var plCloud = getCloudPolyline(pl);
                plCloud.SetDatabaseDefaults();
                plCloud.Color = ColorChange;
                btr.AppendEntity(plCloud);
                t.AddNewlyCreatedDBObject(plCloud, true);

                // Текст изменения
                MText text = new MText();
                text.SetDatabaseDefaults();
                text.Color = ColorChange;
                text.TextHeight = 250;
                text.Contents = $"Старая марка покраски: {chPanel.PaintOld}, \n\rНовая марка покраски: {chPanel.PaintNew} " +
                    $"\n\rПанель: {chPanel.MarkSb}";
                text.Location = ptText;
                btr.AppendEntity(text);
                t.AddNewlyCreatedDBObject(text, true);

                chPanel.PanelMount.SetPaintingToAttr(chPanel.PanelAKR.MarkAr);
            }
            // Разбить
            //blRefFloor.ExplodeToOwnerSpace();
            return blRefFloor.GeometricExtents;
        }
Пример #33
0
        private void сreateHatch(Extents3d extText, BlockTableRecord btr)
        {
            if (extText.Diagonal() < 100)
            {
                return;
            }
            // Отступ контура штриховки от границ текста
            Extents3d ext = new Extents3d(new Point3d(extText.MinPoint.X - 10, extText.MinPoint.Y - 10, 0),
                                          new Point3d(extText.MaxPoint.X + 10, extText.MaxPoint.Y + 10, 0));
            var h = new Hatch();
            h.SetDatabaseDefaults(btr.Database);
            if (!panelBtr.CaptionLayerId.IsNull)
                h.LayerId = panelBtr.CaptionLayerId;
            h.LineWeight = LineWeight.LineWeight015;
            h.Linetype = SymbolUtilityServices.LinetypeContinuousName;
            h.Color = Color.FromRgb(250, 250, 250);
            h.Transparency = new Transparency(80);
            h.SetHatchPattern(HatchPatternType.PreDefined, "ANGLE");
            h.PatternScale = 25.0;
            btr.AppendEntity(h);
            var t = btr.Database.TransactionManager.TopTransaction;
            t.AddNewlyCreatedDBObject(h, true);
            h.Associative = true;
            h.HatchStyle = HatchStyle.Normal;

            // Полилиния по контуру текста
            Polyline pl = new Polyline();
            pl.SetDatabaseDefaults(btr.Database);
            pl.LineWeight = LineWeight.LineWeight015;
            pl.Linetype = SymbolUtilityServices.LinetypeContinuousName;
            pl.ColorIndex = 256; // ПоСлою
            if (!panelBtr.CaptionLayerId.IsNull)
                pl.LayerId = panelBtr.CaptionLayerId;
            pl.AddVertexAt(0, ext.MinPoint.Convert2d(), 0, 0, 0);
            pl.AddVertexAt(0, new Point2d(ext.MaxPoint.X, ext.MinPoint.Y), 0, 0, 0);
            pl.AddVertexAt(0, ext.MaxPoint.Convert2d(), 0, 0, 0);
            pl.AddVertexAt(0, new Point2d(ext.MinPoint.X, ext.MaxPoint.Y), 0, 0, 0);
            pl.Closed = true;

            ObjectId idPl = btr.AppendEntity(pl);
            t.AddNewlyCreatedDBObject(pl, true);

            // добавление контура полилинии в гштриховку
            var ids = new ObjectIdCollection();
            ids.Add(idPl);
            h.AppendLoop(HatchLoopTypes.Default, ids);
            h.EvaluateHatch(true);

            // Замена текстов - чтобы они стали поверх штриховки.
            panelBtr.IdCaptionMarkSb = replaceText(panelBtr.IdCaptionMarkSb, btr);
            panelBtr.IdCaptionPaint = replaceText(panelBtr.IdCaptionPaint, btr);
        }
Пример #34
0
        public void LoadXrefs()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            ed.WriteMessage("\n=== +++ Command Load and Bind Xrefs Start +++");

            LayoutManager lm = LayoutManager.Current;

            lm.CurrentLayout = "Layout1";

            Database db = doc.Database;

            try
            {

                string dwgName = Path.GetFileNameWithoutExtension(doc.Name);

                string folderPath = Path.GetDirectoryName(doc.Name);

                List<SheetObject> sheetObjects = Helpers.SheetsObjectsFromCSV(folderPath, dwgName);

                List<ObjectId[]> viewportContentList = new List<ObjectId[]>();
                //get document name
                ed.WriteMessage("\n=== Dwg Name: " + doc.Name + "\n");

                //to bind after have been loaded
                List<string> xrefsToBind = new List<string>();

                foreach (SheetObject sheetObject in sheetObjects)
                {
                    ed.WriteMessage("=== Xref(s): " + sheetObject.xrefName + "\n");

                    string layerName = $"0-{sheetObject.xrefName}";

                    //redundant. We want to bind all the xrefs
                    //if (sheetObject.group == "bind")
                    //{
                        xrefsToBind.Add(sheetObject.xrefName);
                    //}

                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {

                        LayerTable layerTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                        ObjectId layer = new ObjectId();

                        foreach (ObjectId layerId in layerTable)
                        {
                            LayerTableRecord currentLayer = trans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord;
                            if (currentLayer.Name == layerName)
                            {
                                layer = layerId;

                            }
                        }

                        //Load Xref
                        //https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2015/ENU/AutoCAD-NET/files/GUID-D6EE5FE7-C0BC-4E9B-AAE3-3B5A14B870FE-htm.html
                        #region
                        string PathName = $"{folderPath}\\{sheetObject.xrefName}";

                        ObjectId acXrefId = db.AttachXref(PathName, sheetObject.xrefName);

                        if (!acXrefId.IsNull)
                        {
                            // Attach the DWG reference to the model space
                            Point3d insPt = new Point3d(0, 0, 0);
                            using (BlockReference blockRef = new BlockReference(insPt, acXrefId))
                            {
                                //load the xref to Layer 0
                                //blockRef.SetLayerId(layer, true);
                                BlockTable blocktable = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                                BlockTableRecord modelSpace = trans.GetObject(blocktable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                                modelSpace.AppendEntity(blockRef);

                                trans.AddNewlyCreatedDBObject(blockRef, true);
                            }

                            ed.WriteMessage("=== xref loaded\n");
                        }

                        #endregion


                        trans.Commit();
                    }//close transaction


                }

                ed.WriteMessage($"=== Check if the xref has to be bound\n");
                
                if (xrefsToBind.Count > 0)
                {
                    foreach (string xrefName in xrefsToBind)
                    {
                        //it seems nested xrefs are moved back to origin when binded...
                        //Helpers.BindXrefs(db);
                        //try this:
                        ed.Command("-xref", "bind", xrefName, " ");
                        ed.WriteMessage($"=== xrefs binded\n");
                    }
                }
                
                ed.WriteMessage($"=== Check xref group for binding\n");
                
                ed.WriteMessage("Save file \n");

                db.SaveAs(doc.Name, true, DwgVersion.Current, doc.Database.SecurityParameters);

                ed.WriteMessage("\n=== +++ Command Load and Bind Xrefs End +++");
            }//close try
            catch { }
            finally
            {
            }
        }
Пример #35
0
        private void method_1(ObjectId[] objectId_0, double double_1, ref int int_1, ref int int_2, ref int int_3)
        {
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            Editor        arg_15_0        = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            ProgressMeter progressMeter   = new ProgressMeter();
            MessageFilter messageFilter   = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            progressMeter.SetLimit(objectId_0.Length);
            progressMeter.Start("Simplifying polylines");
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    for (int i = 0; i < objectId_0.Length; i++)
                    {
                        try
                        {
                            progressMeter.MeterProgress();
                            messageFilter.CheckMessageFilter((long)i, 10);
                            DBObject @object  = transaction.GetObject(objectId_0[i], (OpenMode)1);
                            bool     flag     = false;
                            Polyline polyline = @object as Polyline;
                            if (polyline != null)
                            {
                                flag = polyline.Closed;
                            }
                            Polyline2d polyline2d = @object as Polyline2d;
                            if (polyline2d != null)
                            {
                                flag = polyline2d.Closed;
                            }
                            Polyline3d polyline3d = @object as Polyline3d;
                            if (polyline3d != null)
                            {
                                flag = polyline3d.Closed;
                            }
                            List <ngeometry.VectorGeometry.Point> p = PointGeneration.SubdividePolyline(@object, transaction, 0.0).ToList();
                            int_1 += Conversions.GetNumberOfPoyllineVertices(@object);
                            List <ngeometry.VectorGeometry.Point> list = this.method_2(p, double_1);
                            int_2 += list.Count;
                            Point3dCollection point3dCollection = Conversions.ToPoint3dCollection(list);
                            Polyline3d        polyline3d2       = new Polyline3d(0, point3dCollection, flag);
                            polyline3d2.SetPropertiesFrom((Entity)@object);
                            if (PLine_1.string_2 == "N" & [email protected])
                            {
                                @object.Erase();
                            }
                            blockTableRecord.AppendEntity(polyline3d2);
                            transaction.AddNewlyCreatedDBObject(polyline3d2, true);
                        }
                        catch (System.Exception ex)
                        {
                            int_3++;
                        }
                    }
                    transaction.Commit();
                }
                progressMeter.Stop();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw ex;
            }
        }
Пример #36
0
        public void Test1()

        {
            Document doc = Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            Transaction trans = db.TransactionManager.StartTransaction();

            BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

            BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;



            Circle c = new Circle();

            Point3d a = new Point3d();

            //获取圆

            TypedValue[] tv = new TypedValue[1];

            tv.SetValue(new TypedValue(0, "CIRCLE"), 0);

            SelectionFilter sf = new SelectionFilter(tv);

            PromptSelectionResult psr = ed.GetSelection(sf);

            if (psr.Status == PromptStatus.OK)

            {
                SelectionSet ss = psr.Value;

                c = trans.GetObject(ss[0].ObjectId, OpenMode.ForRead) as Circle;
            }

            //获取点

            DBPoint dba = new DBPoint();

            tv = new TypedValue[1];

            tv.SetValue(new TypedValue(0, "POINT"), 0);

            sf = new SelectionFilter(tv);

            psr = ed.GetSelection(sf);

            if (psr.Status == PromptStatus.OK)

            {
                SelectionSet ss = psr.Value;

                dba = trans.GetObject(ss[0].ObjectId, OpenMode.ForRead) as DBPoint;
            }

            a = dba.Position;

            Point3d p = new Point3d((a.X + c.Center.X) / 2, (a.Y + c.Center.Y) / 2, 0);

            Vector3d v = p.GetVectorTo(a);

            double r = v.Length;

            if (r <= c.Radius)

            {
                ed.WriteMessage("\n点在所选圆内,无法做切线!");

                trans.Dispose();//一定要终止交易

                return;
            }

            Circle cp = new Circle();

            cp.SetDatabaseDefaults();

            cp.Radius = r;

            cp.Center = p;

            //切点

            Point3dCollection t = new Point3dCollection();

            cp.IntersectWith(c, Intersect.OnBothOperands, t, 0, 0);

            //画切线

            foreach (Point3d tt in t)

            {
                Line l = new Line(tt, a);

                btr.AppendEntity(l);

                trans.AddNewlyCreatedDBObject(l, true);
            }

            trans.Commit();

            trans.Dispose();
        }
Пример #37
0
        private static double DrawOffset(int N1, int N2, double dist, bool boo)
        {
            double rez = 0;

            using (Transaction transaction = _db.TransactionManager.StartTransaction())
            {
                BlockTable blockTable = transaction.GetObject(_db.BlockTableId, OpenMode.ForRead) as BlockTable;

                // Open the Block table record Model space for write
                BlockTableRecord modelSpace = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                LayerTable layerTable = transaction.GetObject(_db.LayerTableId, OpenMode.ForRead) as LayerTable;

                Polyline bpLine = (Polyline)transaction.GetObject(_polylineId, OpenMode.ForWrite);

                int      off       = -1;
                Polyline firstPoly = new Polyline();
                firstPoly.SetDatabaseDefaults();

                #region make poly
                ArrayList arrayList = new ArrayList();
                for (int j = 1; j <= (bpLine.NumberOfVertices >> 1); j++)
                {
                    if ((N1 + j) > (bpLine.NumberOfVertices - 1))
                    {
                        off++;
                    }
                    int           i   = (off < 0) ? (N1 + j) : off;
                    LineSegment2d seg = bpLine.GetLineSegment2dAt(i);
                    double        bulge;
                    if ((i - 1) < 0)
                    {
                        bulge = bpLine.GetBulgeAt(bpLine.NumberOfVertices - 1);
                    }
                    else
                    {
                        if ((i - 1) > bpLine.NumberOfVertices - 1)
                        {
                            bulge = bpLine.GetBulgeAt(0);
                        }
                        else
                        {
                            bulge = -bpLine.GetBulgeAt(i - 1);
                        }
                    }
                    firstPoly.AddVertexAt(0, new Point2d(seg.StartPoint.X, seg.StartPoint.Y), bulge, 0, 0);
                    arrayList.Add(bpLine.GetBulgeAt(i));
                }

                modelSpace.AppendEntity(firstPoly);
                transaction.AddNewlyCreatedDBObject(firstPoly, true);
                #endregion

                #region coating
                if (boo)
                {
                    LineSegment2d seg1 = firstPoly.GetLineSegment2dAt(0);
                    LineSegment2d seg2 = bpLine.GetLineSegment2dAt(N2);
                    Complex       mid  = new Complex((seg2.StartPoint.X + seg2.EndPoint.X) / 2, (seg2.StartPoint.Y + seg2.EndPoint.Y) / 2);
                    Line2d        l    = new Line2d(new Complex(seg1.StartPoint.X, seg1.StartPoint.Y), new Complex(seg1.EndPoint.X, seg1.EndPoint.Y));

                    int k = l.PositionOfТhePointToLineSign(mid);

                    DBObjectCollection oc = firstPoly.GetOffsetCurves((k < 0) ? dist : -dist);
                    foreach (Entity acEnt in oc)
                    {
                        modelSpace.AppendEntity(acEnt);
                        transaction.AddNewlyCreatedDBObject(acEnt, true);
                        acEnt.TransformBy(_ed.CurrentUserCoordinateSystem);
                        try
                        {
                            acEnt.Layer = _sheetDescriptionForm.GetCoatingLayer();
                        }
                        catch
                        {
                            LayerTableRecord acLyrTblRec = transaction.GetObject(_db.Clayer, OpenMode.ForWrite) as LayerTableRecord;
                            acEnt.Layer = acLyrTblRec.Name;
                        }
                        try
                        {
                            System.Drawing.Color color = _sheetDescriptionForm.GetCoatingColor();
                            if (color.Name == "ByLayer")
                            {
                                throw new ArgumentNullException();
                            }
                            acEnt.Color = Color.FromColor(color);
                        }
                        catch
                        {
                            //LayerTableRecord acLyrTblRec = acTrans.GetObject(Db.Clayer, OpenMode.ForWrite) as LayerTableRecord;
                            LayerTableRecord acLyrTblRec = transaction.GetObject(layerTable[acEnt.Layer], OpenMode.ForWrite) as LayerTableRecord;
                            acEnt.Color = acLyrTblRec.Color;
                        }

                        _entityTemp.Add(acEnt);
                    }
                    Polyline acPoly11 = oc[0] as Polyline;
                }
                #endregion

                #region calculate length
                for (int j = 0; j < firstPoly.NumberOfVertices - 1; j++)
                {
                    if (Math.Abs(firstPoly.GetBulgeAt(j)) != 0.0)
                    {
                        CircularArc2d arc = firstPoly.GetArcSegment2dAt(j);
                        double        rad = arc.Radius;
                        double        ang = Math.Abs(Math.Atan(firstPoly.GetBulgeAt(j)));
                        rez += (4 * ang * rad);
                    }
                    else
                    {
                        LineSegment2d seg = firstPoly.GetLineSegment2dAt(j);
                        Complex       s   = new Complex(seg.StartPoint.X, seg.StartPoint.Y);
                        Complex       e   = new Complex(seg.EndPoint.X, seg.EndPoint.Y);
                        rez += (s - e).abs();
                    }
                }
                #endregion

                firstPoly.Erase();
                transaction.Commit();
            }
            _ed.Regen();
            return(rez);
        }
Пример #38
0
        public void PprArc()

        {
            //准备工作

            Document doc = Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            Transaction trans = db.TransactionManager.StartTransaction();

            BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

            BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;



            PromptPointOptions ppo = new PromptPointOptions("");

            PromptPointResult ppr;

            Point3d temp = new Point3d();

            Point2d p1, p2;

            //获取两个点

            ppo.Message = "\n请输入第一个点:";

            do

            {
                ppr = ed.GetPoint(ppo);

                temp = ppr.Value;

                p1 = new Point2d(temp.X, temp.Y);
            } while (ppr.Status != PromptStatus.OK);



            ppo.Message = "\n请输入第二个点:";

            do

            {
                ppr = ed.GetPoint(ppo);

                temp = ppr.Value;

                p2 = new Point2d(temp.X, temp.Y);
            } while (ppr.Status != PromptStatus.OK);



            double L = p1.GetDistanceTo(p2);

            double R = 0;



            //获取半径

            do

            {//避免出现半径比弦长一半还小的情况出现
                PromptDoubleOptions pdo = new PromptDoubleOptions("\n最后,请输入半径:");

                PromptDoubleResult pdr = ed.GetDouble(pdo);

                if (pdr.Status == PromptStatus.OK)
                {
                    R = pdr.Value;
                }
            } while (R < L / 2);

            double H = R - Math.Sqrt(R * R - L * L / 4);



            Polyline poly = new Polyline();

            poly.AddVertexAt(0, p1, 2 * H / L, 0, 0);

            poly.AddVertexAt(1, p2, 0, 0, 0);

            btr.AppendEntity(poly);

            trans.AddNewlyCreatedDBObject(poly, true);

            trans.Commit();

            trans.Dispose();
        }
        static public void CmdCota()
        {
            Database db = Application.DocumentManager.MdiActiveDocument.Database;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            //Set Type of Quota
            PromptKeywordOptions optionType = new PromptKeywordOptions("\nSelect the type of quota: ");

            optionType.AllowNone = false;
            optionType.Keywords.Add("Arrow");
            optionType.Keywords.Add("Leader");
            optionType.Keywords.Add("Plane");
            optionType.Keywords.Default = "Arrow";
            PromptResult ProTypeRes = ed.GetKeywords(optionType);
            int          iType      = 0;

            switch (ProTypeRes.StringResult)
            {
            case "Arrow":
                iType = 0;
                break;

            case "Leader":
                iType = 1;
                break;

            case "Plane":
                iType = 2;
                break;
            }

            //Strategy for Preview in PointMonitor
            _PointMonitorStrategy = new PointMonitorStrategy(delegate(object sender, PointMonitorEventArgs e)
            {
                try
                {
                    ArCaWrpCota objCota  = new ArCaWrpCota();
                    objCota.Type         = iType;
                    objCota.p3dInsertion = e.Context.ComputedPoint;
                    e.Context.DrawContext.Geometry.Draw(objCota);
                }
                catch (System.Exception ex)
                {
                }
            });

            //add pointMonitor
            ed.PointMonitor += new PointMonitorEventHandler(PointMonitor);

            //Get Second point
            PromptPointOptions opcoesPonto = new PromptPointOptions("\nClick on the local where the quota will be inserted: ");

            opcoesPonto.AllowNone = false;

            PromptPointResult ProPtRes = ed.GetPoint(opcoesPonto);

            //remove pointMonitor
            ed.PointMonitor -= new PointMonitorEventHandler(PointMonitor);

            switch (ProPtRes.Status)
            {
            case PromptStatus.OK:
                //Create Grating
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        ArCaWrpCota objCota = new ArCaWrpCota();
                        objCota.Type         = iType;
                        objCota.p3dInsertion = ProPtRes.Value;
                        BlockTableRecord currSpace = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                        currSpace.AppendEntity(objCota);
                        trans.AddNewlyCreatedDBObject(objCota, true);
                        trans.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        trans.Abort();
                    }
                }
                break;

            case PromptStatus.Cancel:
                //Command Canceled
                break;
            }
        }
        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;
        }
        private void createImages(jsonAttribute eachatt, Transaction tr, ObjectId lyid)
        {
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor; 

            //produce the bitmap of the signature from base64 string
            string imgPath = "temp.png";
            try
            {
                //remove the header of the base64
                var base64str = eachatt.imgbase64.Replace("data:image/png;base64,", "");
                byte[] arr = Convert.FromBase64String(base64str);
                using (MemoryStream ms = new MemoryStream(arr))
                {
                    System.Drawing.Image streamImage = System.Drawing.Image.FromStream(ms);

                    streamImage.Save(imgPath, ImageFormat.Png);
                    
                } 

            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nBase64StringToImage failed :" + ex.Message);
                return;
            }


            try
            {
                //get block table and model space
                Database db = HostApplicationServices.WorkingDatabase;
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                BlockTableRecord msBtr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                //get the position of this attribute
                string[] split = eachatt.position.Split(new Char[] { ',' });
                double posX = Convert.ToDouble(split[0]);
                double posY = Convert.ToDouble(split[1]);
                double posZ = Convert.ToDouble(split[2]);

                //get the range of this attribute
                double fieldheight = Convert.ToDouble(eachatt.height);
                double fieldwidth = Convert.ToDouble(eachatt.width_ratio) * fieldheight;
                double field_center_x = posX + fieldwidth / 2;
                double field_center_y = posY + fieldheight / 2;

                //read the signature image
                
                System.Drawing.Bitmap operateimage = new System.Drawing.Bitmap(imgPath); 
                
                System.Drawing.Color c;

                double maxX = 0, minX = operateimage.Width;
                double maxY = 0, minY = operateimage.Height;

                ed.WriteMessage("\nbegin create block def for image");
                ObjectId blkRecId = ObjectId.Null;

                using (BlockTableRecord signatureBlkDef = new BlockTableRecord())
                {
                    System.Guid guid = System.Guid.NewGuid();

                    //block definition name
                    signatureBlkDef.Name = "sigblk" + guid.ToString();
                    ArrayList ptArr = new ArrayList();

                    //each pixel color
                    for (int y = 0; y < operateimage.Height; y++)
                        for (int x = 0; x < operateimage.Width; x++)
                        {
                            c = operateimage.GetPixel(x, y);

                            if (c.R == 0 && c.G == 0 && c.B == 0 && c.A == 255)
                            {
                                Autodesk.AutoCAD.Geometry.Point3d pt = new Autodesk.AutoCAD.Geometry.Point3d(x, operateimage.Height - y, 0);

                                minY = y < minY ? y : minY;
                                maxY = y > maxY ? y : maxY;

                                minX = x < minX ? x : minX;
                                maxX = x > maxX ? x : maxX;

                                var sol =
                               new Solid(
                                 new Point3d(pt.X, pt.Y, 0),
                                 new Point3d(pt.X + 1, pt.Y, 0),
                                 new Point3d(pt.X, pt.Y + 1, 0),
                                 new Point3d(pt.X + 1, pt.Y + 1, 0)
                               );

                                //set the solid to the specific layer
                                sol.LayerId = lyid;
                                signatureBlkDef.AppendEntity(sol);
                            }
                        }

                    ed.WriteMessage("\ncreate and add block def");

                    signatureBlkDef.Origin = new Point3d((maxX + minX) / 2, operateimage.Height - (maxY + minY) / 2, 0);
                    bt.Add(signatureBlkDef);
                    tr.AddNewlyCreatedDBObject(signatureBlkDef, true);

                    //set the block definition to the specific layer
                    blkRecId = signatureBlkDef.Id;

                    ed.WriteMessage("\nend creating block def");
                }

                operateimage.Dispose();
                //scale the signature to fit the field along X, Y

                double blkscaleY = fieldheight / (maxY - minY) * 2;
                double blkscaleX = (maxX - minX) / (maxY - minY) * blkscaleY;

                ed.WriteMessage("\nto begin create block ref");

                using (BlockReference acBlkRef = new BlockReference(new Point3d(field_center_x, field_center_y, 0), blkRecId))
                {
                    acBlkRef.ScaleFactors = new Scale3d(blkscaleY, blkscaleY, 1);
                    acBlkRef.LayerId = lyid;
                    msBtr.AppendEntity(acBlkRef);
                    tr.AddNewlyCreatedDBObject(acBlkRef, true);
                }

                ed.WriteMessage("\nend of creating block ref");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex){
                ed.WriteMessage("\nfailed to produce the image: " + ex.ToString());
            }

        }
Пример #42
0
        //private bool checkBlockRefs(BlockTableRecord btrFrame, Transaction t)
        //{
        //   bool res = false;
        //   var ms = t.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(_db), OpenMode.ForRead) as BlockTableRecord;
        //   foreach (ObjectId idEnt in ms)
        //   {
        //      if (idEnt.ObjectClass.Name == "AcDbBlockReference")
        //      {
        //         var blRef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as BlockReference;
        //         if (blRef.GetEffectiveName().Equals(_blFrameName, StringComparison.OrdinalIgnoreCase))
        //         {
        //            // считывание атрибутов
        //            var atrCol = blRef.AttributeCollection;
        //            _attrs = new Dictionary<string, string>();
        //            foreach (ObjectId idAtrRef in atrCol)
        //            {
        //               var atrRef = t.GetObject(idAtrRef, OpenMode.ForRead, false, true) as AttributeReference;
        //               string key = atrRef.Tag.ToUpper();
        //               if (!_attrs.ContainsKey(key))
        //               {
        //                  _attrs.Add(key, atrRef.TextString);
        //               }
        //            }
        //            res = true;
        //         }
        //      }
        //   }
        //   return res;
        //}
        //private bool checkBtrFrame(BlockTableRecord btrFrame, Transaction t)
        //{
        //   bool res = false;
        //   if (btrFrame.HasAttributeDefinitions)
        //   {
        //      Dictionary<string, string> attrsChecks = new Dictionary<string, string>();
        //      foreach (ObjectId idEnt in btrFrame)
        //      {
        //         if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition")
        //         {
        //            var atrDef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as AttributeDefinition;
        //            switch (atrDef.Tag.ToUpper())
        //            {
        //               case "ВИД":
        //                  attrsChecks.Add("ВИД", atrDef.TextString);
        //                  break;
        //               case "НАИМЕНОВАНИЕ":
        //                  attrsChecks.Add("НАИМЕНОВАНИЕ", atrDef.TextString);
        //                  break;
        //               case "ЛИСТ":
        //                  attrsChecks.Add("ЛИСТ", atrDef.TextString);
        //                  break;
        //               default:
        //                  break;
        //            }
        //         }
        //      }
        //      if (attrsChecks.Count == 3)
        //      {
        //         res = true;
        //      }
        //   }
        //   return res;
        //}
        private void updateBlRefFrame(BlockReference blRef, BlockTableRecord btrFrame, Transaction t, bool insertDescription)
        {
            // Обновление вхождения блока рамки
             if (!IsOk)
            return;

             // Удаление атрибутов
             foreach (ObjectId idAtrRef in blRef.AttributeCollection)
             {
            var atrRef = t.GetObject(idAtrRef, OpenMode.ForWrite, false, true) as AttributeReference;
            atrRef.Erase(true);
             }

             blRef.UpgradeOpen();
             foreach (ObjectId idEnt in btrFrame)
             {
            if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition")
            {
               var atrDef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as AttributeDefinition;
               if (!atrDef.Constant)
               {
                  if (!insertDescription && atrDef.Tag.Equals("ПРИМЕЧАНИЕ", StringComparison.OrdinalIgnoreCase))
                  {
                     continue;
                  }
                  using (var atrRef = new AttributeReference())
                  {
                     atrRef.SetAttributeFromBlock(atrDef, blRef.BlockTransform);
                     string key = atrDef.Tag.ToUpper();
                     if (_attrs.ContainsKey(key))
                     {
                        atrRef.TextString = _attrs[key];
                     }
                     else
                     {
                        atrRef.TextString = atrDef.TextString;
                     }
                     blRef.AttributeCollection.AppendAttribute(atrRef);
                     t.AddNewlyCreatedDBObject(atrRef, true);
                  }
               }
            }
             }
        }
Пример #43
0
        public void Generate(Point3dCollection hatchBoundaryPoints)
        {
            Database acCurDb;

            acCurDb = Application.DocumentManager.MdiActiveDocument.Database;

            Transaction acTrans = acCurDb.TransactionManager.TopTransaction;

            // Open the Block table for read
            BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

            // Open the Block table record Model space for write
            BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

            Polyline hatchBoundary = new Polyline();

            // need to transform the outline by the block reference transform
            //BlockReference fflBlock = acTrans.GetObject(fflBlockId, OpenMode.ForRead) as BlockReference;

            for (int index = 0; index < hatchBoundaryPoints.Count; index++)
            {
                hatchBoundary.AddVertexAt(index, new Point2d(hatchBoundaryPoints[index].X, hatchBoundaryPoints[index].Y), 0, 0, 0);
            }
            hatchBoundary.Closed = true;

            /*if (isExposed)
             *  hatchBoundary.Layer = StyleNames.JPP_App_Exposed_Brick_Layer;
             * else
             *  hatchBoundary.Layer = StyleNames.JPP_App_Tanking_Layer;*/
            hatchBoundary.Layer = Civils.Constants.JPP_HS_PlotPerimiter;

            // Add the hatch boundary to modelspace

            Outline = acBlkTblRec.AppendEntity(hatchBoundary);
            acTrans.AddNewlyCreatedDBObject(hatchBoundary, true);

            // Add the hatch boundry to an object Id collection
            ObjectIdCollection acObjIdColl = new ObjectIdCollection();

            acObjIdColl.Add(hatchBoundary.Id);

            // Set the hatch properties
            using (Hatch exposedHatch = new Hatch())
            {
                Hatch = acBlkTblRec.AppendEntity(exposedHatch);
                acTrans.AddNewlyCreatedDBObject(exposedHatch, true);

                // Set the hatch properties
                exposedHatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");

                /*if (isExposed)
                 * {
                 *  exposedHatch.Layer = StyleNames.JPP_App_Exposed_Brick_Layer;
                 *  exposedHatch.BackgroundColor = Color.FromColorIndex(ColorMethod.ByAci, 80);
                 * }
                 * else
                 * {
                 *  exposedHatch.Layer = StyleNames.JPP_App_Tanking_Layer;
                 *  exposedHatch.BackgroundColor = Color.FromColorIndex(ColorMethod.ByAci, 130);
                 * }*/
                exposedHatch.Layer           = Civils.Constants.JPP_HS_PlotPerimiter;
                exposedHatch.BackgroundColor = Color.FromColorIndex(ColorMethod.ByAci, 80);
                exposedHatch.PatternScale    = 0.1;
                exposedHatch.PatternSpace    = 0.1;
                //exposedHatch.PatternAngle = Constants.Deg_45;
                exposedHatch.Associative = true;
                exposedHatch.Annotative  = AnnotativeStates.False;
                exposedHatch.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl);
                exposedHatch.EvaluateHatch(true);
            }
        }
Пример #44
0
        // This function returns the ObjectId for the BlockTableRecord called "EmployeeBlock",
        // creating it if necessary.  The block contains three entities - circle, text
        // and ellipse.
        private ObjectId CreateEmployeeDefinition()
        {
            ObjectId newBtrId = new ObjectId(); //The return value for this function
            Database db = HostApplicationServices.WorkingDatabase; //save some space
            using (Transaction trans = db.TransactionManager.StartTransaction()) //begin the transaction
            {
                // Now, access the database and obtain a reference to the BlockTable
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                if ((bt.Has("EmployeeBlock")))
                {
                    newBtrId = bt["EmployeeBlock"];
                }
                else
                {
                    Point3d center = new Point3d(0, 0, 0);
                    // Declare and define the entities we want to add:
                    // Circle:
                    Circle circle = new Circle(center, Vector3d.ZAxis, 2);

                    // Attribute Definition
                    AttributeDefinition text = new AttributeDefinition(center, "NoName", "Name:", "Enter Name", db.Textstyle);
                    text.ColorIndex = 2;

                    // Ellipse:
                    Ellipse ellipse = new Ellipse(center, Vector3d.ZAxis, new Vector3d(3, 0, 0), 0.5, 0, 0);

                    // Next, create a layer with the helper function, and assign the layer to our entities.
                    ObjectId empId = CreateLayer();
                    text.LayerId = empId;
                    circle.LayerId = empId;
                    ellipse.LayerId = empId;
                    // Set the color for each entity irrespective of the layer's color.
                    text.ColorIndex = 2;
                    circle.ColorIndex = 1;
                    ellipse.ColorIndex = 3;

                    // Create a new block definition called EmployeeBlock
                    BlockTableRecord newBtr = new BlockTableRecord();
                    newBtr.Name = "EmployeeBlock";
                    newBtrId = bt.Add(newBtr); //Add the block, and set the id as the return value of our function
                    trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database!

                    newBtr.AppendEntity(circle); //Append our entities...
                    newBtr.AppendEntity(text);
                    newBtr.AppendEntity(ellipse);
                    trans.AddNewlyCreatedDBObject(circle, true); //Again, let the transaction know about our newly added entities.
                    trans.AddNewlyCreatedDBObject(text, true);
                    trans.AddNewlyCreatedDBObject(ellipse, true);
                }

                trans.Commit(); //All done, no errors?  Go ahead and commit!
            }
            return newBtrId;
        }
Пример #45
0
        //This function returns the ObjectId for the BlockTableRecord called "EmployeeBlock",
        //creating it if necessary.  The block contains three entities - circle, text
        //and ellipse.
        public ObjectId CreateEmployeeDefinition()
        {
            ObjectId newBtrId = new ObjectId(); //The return value for this function
            Database db = HostApplicationServices.WorkingDatabase; //save some space

            // The "using" keyword used below automatically calls "Dispose"
            // on the "trans" object.
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //Now, drill into the database and obtain a reference to the BlockTable
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                if ((bt.Has("EmployeeBlock")))
                {
                    newBtrId = bt["EmployeeBlock"];
                }
                else
                {
                    Point3d center = new Point3d(10, 10, 0); // convenient declaration...
                    //  Declare and define the entities we want to add:
                    //Circle:
                    Circle circle = new Circle(center, Vector3d.ZAxis, 2);
                    //Text:
                    MText text = new MText();
                    text.Contents = "Earnest Shackleton";
                    text.Location = center;
                    //Ellipse:
                    Ellipse ellipse = new Ellipse(center, Vector3d.ZAxis, new Vector3d(3, 0, 0), 0.5, 0, 0);

                    //Next, create a layer with the helper function, and assign
                    //the layer to our entities.
                    ObjectId empId = CreateLayer();
                    text.LayerId = empId;
                    circle.LayerId = empId;
                    ellipse.LayerId = empId;
                    //Set the color for each entity irrespective of the layer's color.
                    text.ColorIndex = 2;
                    circle.ColorIndex = 1;
                    ellipse.ColorIndex = 3;

                    //Create a new block definition called EmployeeBlock
                    BlockTableRecord newBtr = new BlockTableRecord();
                    newBtr.Name = "EmployeeBlock";
                    newBtrId = bt.Add(newBtr); //Add the block, and set the id as the return value of our function
                    trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database!

                    newBtr.AppendEntity(circle); //Append our entities...
                    newBtr.AppendEntity(text);
                    newBtr.AppendEntity(ellipse);
                    trans.AddNewlyCreatedDBObject(circle, true); //Again, let the transaction know about our newly added entities.
                    trans.AddNewlyCreatedDBObject(text, true);
                    trans.AddNewlyCreatedDBObject(ellipse, true);
                }
                trans.Commit(); //All done, no errors?  Go ahead and commit!
            }
            return newBtrId;
        }
Пример #46
0
        public static void CreatePointOnCurve(ObjectId curId, Point3d pickedPoint)
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor   ed = doc.Editor;

            // Ask the user to select a curve

            PromptEntityOptions opts =
                new PromptEntityOptions(
                    "\n选择线: "
                    );

            opts.SetRejectMessage(
                "\n实体必须是线."
                );
            opts.AddAllowedClass(typeof(Polyline), false);

            PromptEntityResult per = ed.GetEntity(opts);

            curId = per.ObjectId;
            if (curId != ObjectId.Null)
            {
                // Let's make sure we'll be able to see our point
                using (doc.LockDocument())
                {
                    db.Pdmode = 97;  // square with a circle
                    db.Pdsize = -10; // relative to the viewport size

                    Transaction tr =
                        doc.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        DBObject obj =
                            tr.GetObject(curId, OpenMode.ForRead);

                        Curve cur = obj as Curve;
                        if (cur != null)
                        {
                            // Out initial point should be the closest point
                            // on the curve to the one picked

                            Point3d pos =
                                cur.GetClosestPointTo(pickedPoint, false);
                            DBPoint pt = new DBPoint(pos);

                            // Add it to the same space as the curve

                            BlockTableRecord btr =
                                (BlockTableRecord)tr.GetObject(
                                    cur.BlockId,
                                    OpenMode.ForWrite
                                    );
                            ObjectId ptId = btr.AppendEntity(pt);
                            tr.AddNewlyCreatedDBObject(pt, true);
                        }
                        tr.Commit();
                    }
                    // And add the curve to our central list

                    _curves.Add(curId);
                }

                // Turn on the transform overrule if it isn't already

                if (!overruling)
                {
                    AddOverrule(
                        GetClass(typeof(DBPoint)),
                        theOverrule,
                        true
                        );
                    overruling = true;
                    Overruling = true;
                }
            }
        }
Пример #47
0
 private static DBText addText(BlockTableRecord btr, Transaction t, Point3d pt, string value, double height,
     TextHorizontalMode horMode = TextHorizontalMode.TextCenter)
 {
     // Подпись развертки - номер вида
     DBText text = new DBText();
     text.SetDatabaseDefaults();
     text.Height = height;
     text.TextStyleId = IdTextStylePik;
     text.TextString = value;
     if (horMode == TextHorizontalMode.TextLeft)
     {
         text.Position = pt;
     }
     else
     {
         text.HorizontalMode = horMode;
         text.AlignmentPoint = pt;
         text.AdjustAlignment(btr.Database);
     }
     btr.AppendEntity(text);
     t.AddNewlyCreatedDBObject(text, true);
     return text;
 }
Пример #48
0
        public void Compute3dHull(ObjectId[] idArray)
        {
            Editor   editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database workingDatabase = HostApplicationServices.WorkingDatabase;

            DBManager.SetEpsilon();
            this.progressMeter_0 = new ProgressMeter();
            this.messageFilter_0 = new MessageFilter();
            System.Windows.Forms.Application.AddMessageFilter(this.messageFilter_0);
            this.int_0 = 0;
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    this.progressMeter_0.SetLimit(3 * idArray.Length);
                    if ((double)idArray.Length > 10000.0)
                    {
                        this.progressMeter_0.Start("Computing 3d hull...");
                    }
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    ObjectId         layerId          = DBManager.CurrentLayerId();
                    DBManager.CurrentLayerName();
                    PointSet pointSet = new PointSet();
                    for (int i = 0; i < idArray.Length; i++)
                    {
                        DBPoint dBPoint = (DBPoint)transaction.GetObject(idArray[i], (OpenMode)0, true);
                        Point   point   = new Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                        pointSet.Add(point);
                        this.vmethod_0(null, null);
                    }
                    ConvexHull3d convexHull3d = new ConvexHull3d();
                    convexHull3d.PointInsertionHandler += new HullPointInsertionEventHandler(this.vmethod_0);
                    convexHull3d.InitialPoints          = pointSet;
                    convexHull3d.ComputeHull();
                    PointSet        vertices  = convexHull3d.Vertices;
                    List <Triangle> triangles = convexHull3d.Triangles;
                    for (int j = 0; j < triangles.Count; j++)
                    {
                        Point   vertex   = triangles[j].Vertex1;
                        Point   vertex2  = triangles[j].Vertex2;
                        Point   vertex3  = triangles[j].Vertex3;
                        Point3d point3d  = new Point3d(vertex.X, vertex.Y, vertex.Z);
                        Point3d point3d2 = new Point3d(vertex2.X, vertex2.Y, vertex2.Z);
                        Point3d point3d3 = new Point3d(vertex3.X, vertex3.Y, vertex3.Z);
                        Face    face     = new Face(point3d, point3d2, point3d3, true, true, true, true);
                        face.LayerId = (layerId);
                        blockTableRecord.AppendEntity(face);
                        transaction.AddNewlyCreatedDBObject(face, true);
                    }
                    editor.WriteMessage("\n3d convex hull properties:");
                    editor.WriteMessage("\n--------------------------");
                    editor.WriteMessage("\nNumber of vertices on hull: " + vertices.Count);
                    editor.WriteMessage("\nNumber of invalid vertices: " + convexHull3d.BadPoints.Count);
                    editor.WriteMessage("\nNumber of faces on hull   : " + triangles.Count);
                    editor.WriteMessage("\nNumber of degenerate faces: " + convexHull3d.NumberOfDegenerateTriangles);
                    editor.WriteMessage("\nHull surface area         : " + convexHull3d.Area().ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nHull volume               : " + convexHull3d.Volume().ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nCenter of mass            : " + convexHull3d.CenterOfMass().ToString());
                    transaction.Commit();
                }
                this.progressMeter_0.Stop();
            }
            catch (System.Exception ex)
            {
                this.progressMeter_0.Stop();
                throw;
            }
        }
Пример #49
0
 private ObjectId replaceText(ObjectId idBdText, BlockTableRecord btr)
 {
     using (var text = idBdText.GetObject(OpenMode.ForWrite, false, true) as DBText)
     {
         using (var copyText = text.Clone() as DBText)
         {
             text.Erase();
             return btr.AppendEntity(copyText);
         }
     }
 }
Пример #50
0
        private void click_btn_AddPart(object sender, EventArgs e)
        {
            DocumentLock loc = doc.LockDocument();

            using (loc)
            {
                drawingToAdd.Replace(@"/", @"\");
                string drawingFileName = drawingToAdd.Substring(drawingToAdd.IndexOf(@"/", (drawingToAdd.IndexOf(@"/") + 1)) + 1, drawingToAdd.Length - drawingToAdd.IndexOf(@"/", (drawingToAdd.IndexOf(@"/") + 1)) - 1);

                Database tmpDb = new Database(false, true);
                tmpDb.ReadDwgFile(@"\\thehaskellco.net\Remote\AtlantaData\_Disciplines\Controls\4 Controls Programming\DVBs and DLLs\Footprints\Panel\" + drawingToAdd + ".dwg", System.IO.FileShare.Read, true, "");
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                    if (!bt.Has(drawingFileName))
                    {
                        db.Insert(drawingFileName, tmpDb, true);
                    }
                    tr.Commit();
                }

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                    btr = (BlockTableRecord)bt[drawingFileName].GetObject(OpenMode.ForRead);
                    bool tagFound = false;

                    if (btr != null)
                    {
                        foreach (ObjectId objId in btr)
                        {
                            AttributeDefinition attDef = tr.GetObject(objId, OpenMode.ForRead) as AttributeDefinition;
                            if (attDef != null)
                            {
                                if (attDef.Tag.ToUpper() == "TABLE_PART_NUM")
                                {
                                    tagFound = true;
                                }
                                else if (attDef.Tag.ToUpper() == "TABLE_DESCRIPTION")
                                {
                                    tagFound = true;
                                }
                            }
                        }
                        try
                        {
                            if (!tagFound)
                            {
                                AttributeDefinition acAttDef = new AttributeDefinition();

                                acAttDef.Position  = new Point3d(0, 0, 0);
                                acAttDef.Prompt    = "Part Number?";
                                acAttDef.Tag       = "TABLE_PART_NUM";
                                acAttDef.Invisible = true;
                                acAttDef.Height    = 1;
                                acAttDef.Justify   = AttachmentPoint.MiddleCenter;

                                AttributeDefinition acAttDef2 = new AttributeDefinition();

                                acAttDef2.Position  = new Point3d(0, 0, 0);
                                acAttDef2.Prompt    = "Description?";
                                acAttDef2.Tag       = "TABLE_DESCRIPTION";
                                acAttDef2.Invisible = true;
                                acAttDef2.Height    = 1;
                                acAttDef2.Justify   = AttachmentPoint.MiddleCenter;

                                AttributeDefinition acAttDef3 = new AttributeDefinition();

                                acAttDef3.Position   = new Point3d(0, -10, 0);
                                acAttDef3.Prompt     = "DO NOT CHANGE";
                                acAttDef3.Tag        = "AUTO_UPDATE";
                                acAttDef3.TextString = "1";
                                acAttDef3.Invisible  = true;
                                acAttDef3.Height     = 1;
                                acAttDef3.Justify    = AttachmentPoint.MiddleCenter;

                                btr.UpgradeOpen();
                                btr.AppendEntity(acAttDef);
                                btr.AppendEntity(acAttDef2);
                                btr.AppendEntity(acAttDef3);
                                tr.AddNewlyCreatedDBObject(acAttDef, true);
                                tr.AddNewlyCreatedDBObject(acAttDef2, true);
                                tr.AddNewlyCreatedDBObject(acAttDef3, true);
                                btr.DowngradeOpen();
                                tr.Commit();
                            }
                        }
                        catch
                        {
                            ed.WriteMessage("Could not add attributes to block.");
                        }
                    }
                }

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    if (btr != null)
                    {
                        MyBlockJig   blockJig = new MyBlockJig();
                        Point3d      point;
                        PromptResult res = blockJig.DragMe(btr.ObjectId, out point);

                        if (res.Status == PromptStatus.OK)
                        {
                            BlockTableRecord curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            BlockReference   insert   = new BlockReference(point, btr.ObjectId);

                            curSpace.AppendEntity(insert);
                            tr.AddNewlyCreatedDBObject(insert, true);

                            foreach (ObjectId id in btr)
                            {
                                DBObject            obj    = id.GetObject(OpenMode.ForWrite);
                                AttributeDefinition attDef = obj as AttributeDefinition;
                                if ((attDef != null) && (!attDef.Constant))
                                {
                                    using (AttributeReference attRef = new AttributeReference())
                                    {
                                        attRef.SetAttributeFromBlock(attDef, insert.BlockTransform);
                                        insert.AttributeCollection.AppendAttribute(attRef);
                                        tr.AddNewlyCreatedDBObject(attRef, true);
                                    }
                                }
                            }
                        }
                    }
                    tr.Commit();
                    doc.SendStringToExecute("regenall ", true, false, false);
                }

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    ObjectId msId = bt[BlockTableRecord.ModelSpace];

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(msId, OpenMode.ForRead);
                    foreach (ObjectId entId in btr)
                    {
                        Entity ent = (Entity)tr.GetObject(entId, OpenMode.ForWrite);
                        if (ent != null)
                        {
                            BlockReference br = ent as BlockReference;
                            if (br != null)
                            {
                                BlockTableRecord bd = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForRead);
                                if (bd.Name.ToUpper() == drawingFileName.ToUpper())
                                {
                                    foreach (ObjectId arId in br.AttributeCollection)
                                    {
                                        DBObject           obj = tr.GetObject(arId, OpenMode.ForWrite);
                                        AttributeReference ar  = obj as AttributeReference;
                                        if (ar != null)
                                        {
                                            if (ar.Tag == "AUTO_UPDATE")
                                            {
                                                if (ar.TextString == "1")
                                                {
                                                    foreach (ObjectId attRefId in br.AttributeCollection)
                                                    {
                                                        DBObject           objRef = tr.GetObject(attRefId, OpenMode.ForWrite);
                                                        AttributeReference aRef   = objRef as AttributeReference;
                                                        if (aRef.Tag == "TABLE_PART_NUM")
                                                        {
                                                            aRef.UpgradeOpen();
                                                            aRef.TextString = partNumberToAdd;
                                                            aRef.DowngradeOpen();
                                                        }
                                                        else if (aRef.Tag == "TABLE_DESCRIPTION")
                                                        {
                                                            aRef.UpgradeOpen();
                                                            aRef.TextString = descriptionToAdd;
                                                            aRef.DowngradeOpen();
                                                        }
                                                    }
                                                }

                                                ar.TextString = "0";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    tr.Commit();
                }
            }
        }
Пример #51
0
        private void CreateBlockRefs(DocumentModifier docMdf, BlockTableRecord space, BlockTableRecord blockDef,
                                     Point3d[] points, double[] elevations)
        {
            AttributeDefinition attDef = blockDef.GetAttributeDefinition(BlockAttributeName);

            for (int i = 0; i < points.Length; i++)
            {
                Point3d        pos      = new Point3d(points[i].X, points[i].Y, elevations[i]);
                BlockReference blockRef = CreateBlockRef(docMdf, space, blockDef, attDef, pos);
            }
        }
Пример #52
0
        public static void CADini()
        {
            // Get the current document and database
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            Editor   ed      = acDoc.Editor;

            // Start a transaction
            using (Transaction tr = acCurDb.TransactionManager.StartTransaction())
            {
                Dictionary <string, short> ldic = new Dictionary <string, short>()
                {
                    ["粗线"]  = 4,
                    ["细线"]  = 2,
                    ["标注"]  = 7,
                    ["中心线"] = 1,
                    ["虚线"]  = 3,
                    ["填充"]  = 8,
                    ["图框"]  = 8,
                    ["地质"]  = 8,
                };
                List <string> Lname = new List <string>()
                {
                    "CENTER", "DASHED"
                };
                LayerTable acLyrTbl;
                acLyrTbl = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
                LinetypeTable acLinTbl;
                acLinTbl = tr.GetObject(acCurDb.LinetypeTableId, OpenMode.ForRead) as LinetypeTable;
                foreach (string ltname in Lname)
                {
                    if (!acLinTbl.Has(ltname))
                    {
                        acCurDb.LoadLineTypeFile(ltname, "acad.lin");
                    }
                }
                LayerTableRecord acLyrTblRec = new LayerTableRecord();
                foreach (string key in ldic.Keys)
                {
                    short cid = ldic[key];
                    acLyrTblRec = new LayerTableRecord();
                    if (!acLyrTbl.Has(key))
                    {
                        acLyrTblRec.Color = Color.FromColorIndex(ColorMethod.ByAci, cid);
                        if (cid != 4)
                        {
                            acLyrTblRec.LineWeight = LineWeight.LineWeight013;
                        }
                        else
                        {
                            acLyrTblRec.LineWeight = LineWeight.LineWeight030;
                        }
                        if (cid == 1)
                        {
                            acLyrTblRec.LinetypeObjectId = acLinTbl["CENTER"];
                        }
                        if (cid == 3)
                        {
                            acLyrTblRec.LinetypeObjectId = acLinTbl["DASHED"];
                        }
                        if (key == "图框")
                        {
                            acLyrTblRec.IsPlottable = false;
                        }
                        if (key == "地质")
                        {
                            acLyrTblRec.IsPlottable = false;
                        }
                        acLyrTblRec.Name = key;
                        if (acLyrTbl.IsWriteEnabled == false)
                        {
                            acLyrTbl.UpgradeOpen();
                        }
                        acLyrTbl.Add(acLyrTblRec);
                        tr.AddNewlyCreatedDBObject(acLyrTblRec, true);
                    }
                    else
                    {
                        acLyrTblRec       = tr.GetObject(acLyrTbl[key], OpenMode.ForWrite) as LayerTableRecord;
                        acLyrTblRec.Color = Color.FromColorIndex(ColorMethod.ByAci, cid);
                        if (cid != 4)
                        {
                            acLyrTblRec.LineWeight = LineWeight.LineWeight013;
                        }
                        else
                        {
                            acLyrTblRec.LineWeight = LineWeight.LineWeight030;
                        }
                        if (cid == 1)
                        {
                            acLyrTblRec.LinetypeObjectId = acLinTbl["CENTER"];
                        }
                        if (cid == 3)
                        {
                            acLyrTblRec.LinetypeObjectId = acLinTbl["DASHED"];
                        }
                        if (key == "图框")
                        {
                            acLyrTblRec.IsPlottable = false;
                        }
                        if (key == "地质")
                        {
                            acLyrTblRec.IsPlottable = false;
                        }
                    }
                }
                if (!acLyrTbl.Has("sjx"))
                {
                    acLyrTblRec            = new LayerTableRecord();
                    acLyrTblRec.Color      = Color.FromColorIndex(ColorMethod.ByAci, 1);
                    acLyrTblRec.Name       = "sjx";
                    acLyrTblRec.LineWeight = LineWeight.LineWeight015;
                    if (acLyrTbl.IsWriteEnabled == false)
                    {
                        acLyrTbl.UpgradeOpen();
                    }
                    acLyrTbl.Add(acLyrTblRec);
                    tr.AddNewlyCreatedDBObject(acLyrTblRec, true);
                }
                if (!acLyrTbl.Has("dmx"))
                {
                    acLyrTblRec            = new LayerTableRecord();
                    acLyrTblRec.Color      = Color.FromColorIndex(ColorMethod.ByAci, 8);
                    acLyrTblRec.Name       = "dmx";
                    acLyrTblRec.LineWeight = LineWeight.LineWeight015;
                    if (acLyrTbl.IsWriteEnabled == false)
                    {
                        acLyrTbl.UpgradeOpen();
                    }
                    acLyrTbl.Add(acLyrTblRec);
                    tr.AddNewlyCreatedDBObject(acLyrTblRec, true);
                }


                //-------------------------------------------------------------------------------------------
                TextStyleTable st = tr.GetObject(acCurDb.TextStyleTableId, OpenMode.ForWrite) as TextStyleTable;
                if (!st.Has("EN"))
                {
                    TextStyleTableRecord str = new TextStyleTableRecord()
                    {
                        Name     = "En",
                        FileName = "times.ttf",
                        XScale   = 0.85,
                    };
                    st.Add(str);
                    tr.AddNewlyCreatedDBObject(str, true);
                }
                else
                {
                    TextStyleTableRecord str = tr.GetObject(st["En"], OpenMode.ForWrite) as TextStyleTableRecord;
                    str.FileName = "Times New Roman";
                    str.XScale   = 0.85;
                }
                if (!st.Has("fsdb"))
                {
                    TextStyleTableRecord str2 = new TextStyleTableRecord()
                    {
                        Name            = "fsdb",
                        FileName        = "fsdb_e.shx",
                        BigFontFileName = "fsdb.shx",
                        XScale          = 0.75,
                    };
                    ObjectId textstyleid = st.Add(str2);
                    tr.AddNewlyCreatedDBObject(str2, true);
                }
                else
                {
                    TextStyleTableRecord str = tr.GetObject(st["fsdb"], OpenMode.ForWrite) as TextStyleTableRecord;
                    str.FileName        = "fsdb_e.shx";
                    str.BigFontFileName = "fsdb.shx";
                    str.XScale          = 0.75;
                }
                //-------------------------------------------------------------------------------------------
                DimStyleTable dst = (DimStyleTable)tr.GetObject(acCurDb.DimStyleTableId, OpenMode.ForWrite);
                foreach (int thescale in new int[] { 75, 100, 125, 150, 200 })
                {
                    string scname            = "1-" + thescale.ToString();
                    DimStyleTableRecord dstr = new DimStyleTableRecord();
                    if (!dst.Has(scname))
                    {
                        dstr.Name       = "1-" + thescale.ToString();
                        dstr.Dimscale   = thescale;
                        dstr.Dimtxsty   = st["fsdb"];
                        dstr.Dimclrd    = Color.FromColorIndex(ColorMethod.ByAci, 6);
                        dstr.Dimclre    = Color.FromColorIndex(ColorMethod.ByAci, 6);
                        dstr.Dimdli     = 5.0;
                        dstr.Dimexe     = 1.0;
                        dstr.Dimexo     = 1.0;
                        dstr.DimfxlenOn = true;
                        dstr.Dimfxlen   = 4;
                        dstr.Dimtxt     = 2.5;
                        dstr.Dimasz     = 1.5;
                        dstr.Dimtix     = true;
                        dstr.Dimtmove   = 1;
                        dstr.Dimtad     = 1;
                        dstr.Dimgap     = 0.8;
                        dstr.Dimdec     = 0;
                        dstr.Dimtih     = false;
                        dstr.Dimtoh     = false;
                        dstr.Dimdsep    = '.';
                        dstr.Dimlfac    = 0.1;
                        dst.Add(dstr);
                        tr.AddNewlyCreatedDBObject(dstr, true);
                    }
                    else
                    {
                        dstr            = tr.GetObject(dst[scname], OpenMode.ForWrite) as DimStyleTableRecord;
                        dstr.Name       = "1-" + thescale.ToString();
                        dstr.Dimscale   = thescale;
                        dstr.Dimtxsty   = st["fsdb"];
                        dstr.Dimclrd    = Color.FromColorIndex(ColorMethod.ByAci, 6);
                        dstr.Dimclre    = Color.FromColorIndex(ColorMethod.ByAci, 6);
                        dstr.Dimdli     = 5.0;
                        dstr.Dimexe     = 1.0;
                        dstr.Dimexo     = 1.0;
                        dstr.DimfxlenOn = true;
                        dstr.Dimfxlen   = 4;
                        dstr.Dimtxt     = 2.5;
                        dstr.Dimasz     = 1.5;
                        dstr.Dimtix     = true;
                        dstr.Dimtmove   = 1;
                        dstr.Dimtad     = 1;
                        dstr.Dimgap     = 0.8;
                        dstr.Dimdec     = 0;
                        dstr.Dimtih     = false;
                        dstr.Dimtoh     = false;
                        dstr.Dimdsep    = '.';
                        dstr.Dimlfac    = 0.1;
                    }
                }
                //-------------------------------------------------------------------------------------------
                // 自定义块
                //-------------------------------------------------------------------------------------------
                BlockTable       bt  = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = new BlockTableRecord();
                if (!bt.Has("BG"))
                {
                    btr.Name = "BG";
                    bt.UpgradeOpen();
                    bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);
                    Polyline Paa = new Polyline()
                    {
                        //Color = Color.FromColorIndex(ColorMethod.ByAci, 9),
                        //Layer = "标注",
                    };
                    Paa.AddVertexAt(0, new Point2d(0, 0), 0, 0, 200);
                    Paa.AddVertexAt(1, new Point2d(0, 200), 0, 0, 0);
                    btr.AppendEntity(Paa);
                    tr.AddNewlyCreatedDBObject(Paa, true);
                    AttributeDefinition curbg = new AttributeDefinition();
                    curbg.Position    = new Point3d(120, 200, 0);
                    curbg.Height      = 250;
                    curbg.WidthFactor = 0.75;
                    curbg.Tag         = "标高";
                    //curbg.Layer = "标注";
                    curbg.TextStyleId = st["fsdb"];
                    btr.AppendEntity(curbg);
                    tr.AddNewlyCreatedDBObject(curbg, true);
                }
                //-------------------------------------------------------------------------------------------
                if (!bt.Has("ZP"))
                {
                    BlockTableRecord btr2 = new BlockTableRecord();
                    btr2.Name = "ZP";
                    bt.UpgradeOpen();
                    bt.Add(btr2);
                    tr.AddNewlyCreatedDBObject(btr2, true);
                    Polyline Paa2 = new Polyline()
                    {
                        Color = Color.FromColorIndex(ColorMethod.ByAci, 9),
                    };
                    Paa2.AddVertexAt(0, new Point2d(0 - 350, 0), 0, 0, 80);
                    Paa2.AddVertexAt(1, new Point2d(200 - 350, 0), 0, 0, 0);
                    Paa2.AddVertexAt(2, new Point2d(900 - 350, 0), 0, 0, 0);
                    btr2.AppendEntity(Paa2);
                    tr.AddNewlyCreatedDBObject(Paa2, true);
                    AttributeDefinition curzp = new AttributeDefinition();
                    curzp.Position    = new Point3d(220 - 350, 0, 0);
                    curzp.Height      = 250;
                    curzp.WidthFactor = 0.75;
                    curzp.Tag         = "左坡";
                    curzp.TextStyleId = st["fsdb"];
                    btr2.AppendEntity(curzp);
                    tr.AddNewlyCreatedDBObject(curzp, true);
                }

                //-------------------------------------------------------------------------------------------
                if (!bt.Has("YP"))
                {
                    BlockTableRecord btr3 = new BlockTableRecord();
                    btr3.Name = "YP";
                    bt.UpgradeOpen();
                    bt.Add(btr3);
                    tr.AddNewlyCreatedDBObject(btr3, true);
                    Polyline Paa3 = new Polyline()
                    {
                        Color = Color.FromColorIndex(ColorMethod.ByAci, 9),
                    };
                    Paa3.AddVertexAt(0, new Point2d(0 + 350, 0), 0, 0, 80);
                    Paa3.AddVertexAt(1, new Point2d(-200 + 350, 0), 0, 0, 0);
                    Paa3.AddVertexAt(2, new Point2d(-900 + 350, 0), 0, 0, 0);
                    btr3.AppendEntity(Paa3);
                    tr.AddNewlyCreatedDBObject(Paa3, true);
                    AttributeDefinition curyp = new AttributeDefinition();
                    curyp.Position       = new Point3d(-220 + 350, 0, 0);
                    curyp.HorizontalMode = TextHorizontalMode.TextRight;
                    curyp.AlignmentPoint = curyp.Position;
                    curyp.Height         = 250;
                    curyp.WidthFactor    = 0.75;
                    curyp.Tag            = "右坡";
                    curyp.TextStyleId    = st["fsdb"];
                    btr3.AppendEntity(curyp);
                    tr.AddNewlyCreatedDBObject(curyp, true);
                }
                //-------------------------------------------------------------------------------------------

                //-------------------------------------------------------------------------------------------
                tr.Commit();
            }
        }
Пример #53
0
        static PreviewEndPlotStatus PlotOrPreview(PlotEngine pe, bool isPreview, ObjectId layout, string dirPath, string jobnumber)
        {
            Document doc = AcApp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            PreviewEndPlotStatus ret = PreviewEndPlotStatus.Cancel;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // We'll be plotting the current layout
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(layout, OpenMode.ForRead);
                Layout           lo  = (Layout)tr.GetObject(btr.LayoutId, OpenMode.ForRead);

                PlotSettings ps = new PlotSettings(lo.ModelType);
                ps.CopyFrom(lo);

                PlotInfo pi = new PlotInfo
                {
                    Layout = btr.LayoutId
                };

                // Make the layout we're plotting current
                LayoutManager.Current.CurrentLayout = lo.LayoutName;
                // We need to link the PlotInfo to the
                // PlotSettings and then validate it
                pi.OverrideSettings = ps;
                PlotInfoValidator piv = new PlotInfoValidator
                {
                    MediaMatchingPolicy = MatchingPolicy.MatchEnabled
                };

                piv.Validate(pi);

                /*
                 * // We need a PlotInfo object
                 * // linked to the layout
                 * PlotInfo pi = new PlotInfo();
                 * pi.Layout = lo.BlockTableRecordId;
                 *
                 * // We need a PlotSettings object
                 * // based on the layout settings
                 * // which we then customize
                 * PlotSettings ps = new PlotSettings(lo.ModelType);
                 * ps.CopyFrom(lo);
                 *
                 * // The PlotSettingsValidator helps
                 * // create a valid PlotSettings object
                 * PlotSettingsValidator psv = PlotSettingsValidator.Current;
                 *
                 * // We need to link the PlotInfo to the
                 * // PlotSettings and then validate it
                 * pi.OverrideSettings = ps;
                 * PlotInfoValidator piv = new PlotInfoValidator();
                 * piv.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                 * piv.Validate(pi);*/

                // Create a Progress Dialog to provide info
                // and allow thej user to cancel
                PlotProgressDialog ppd = new PlotProgressDialog(isPreview, 1, true);
                using (ppd)
                {
                    ppd.set_PlotMsgString(PlotMessageIndex.DialogTitle, "Custom Preview Progress");
                    ppd.set_PlotMsgString(PlotMessageIndex.SheetName, doc.Name.Substring(doc.Name.LastIndexOf("\\") + 1));
                    ppd.set_PlotMsgString(PlotMessageIndex.CancelJobButtonMessage, "Cancel Job");
                    ppd.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "Cancel Sheet");
                    ppd.set_PlotMsgString(PlotMessageIndex.SheetSetProgressCaption, "Sheet Set Progress");
                    ppd.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "Sheet Progress");
                    ppd.LowerPlotProgressRange = 0;
                    ppd.UpperPlotProgressRange = 100;
                    ppd.PlotProgressPos        = 0;

                    // Let's start the plot/preview, at last
                    ppd.OnBeginPlot();
                    ppd.IsVisible = true;
                    pe.BeginPlot(ppd, null);

                    // We'll be plotting/previewing
                    // a single document
                    string file = dirPath + "\\" + jobnumber + " " + lo.LayoutName + " " + DateTime.Now.ToString("MM-dd-yy");
                    pe.BeginDocument(pi, doc.Name, null, 1, !isPreview, file);

                    // Which contains a single sheet
                    ppd.OnBeginSheet();
                    ppd.LowerSheetProgressRange = 0;
                    ppd.UpperSheetProgressRange = 100;
                    ppd.SheetProgressPos        = 0;
                    PlotPageInfo ppi = new PlotPageInfo();
                    pe.BeginPage(ppi, pi, true, null);
                    pe.BeginGenerateGraphics(null);
                    ppd.SheetProgressPos = 50;
                    pe.EndGenerateGraphics(null);

                    // Finish the sheet
                    PreviewEndPlotInfo pepi = new PreviewEndPlotInfo();
                    pe.EndPage(pepi);
                    ret = pepi.Status;
                    ppd.SheetProgressPos = 100;
                    ppd.OnEndSheet();

                    // Finish the document
                    pe.EndDocument(null);

                    // And finish the plot
                    ppd.PlotProgressPos = 100;
                    ppd.OnEndPlot();
                    pe.EndPlot(null);
                }
                // Committing is cheaper than aborting
                tr.Commit();
            }
            return(ret);
        }
        static public void CmdDynarea() // This method can have any name
        {
            Database          db       = Application.DocumentManager.MdiActiveDocument.Database;
            Editor            ed       = Application.DocumentManager.MdiActiveDocument.Editor;
            List <Point3d>    lstP3d   = new List <Point3d>();
            PromptPointResult ProPtRes = ed.GetPoint("\nSelect the first point: ");

            //If nothing point, return
            if (ProPtRes.Status != PromptStatus.OK)
            {
                return;
            }

            lstP3d.Add(ProPtRes.Value);

            //Strategy for Preview in PointMonitor
            _PointMonitorStrategy = new PointMonitorStrategy(delegate(object sender, PointMonitorEventArgs e)
            {
                try
                {
                    ArCaWrpDynamicArea objDynArea = new ArCaWrpDynamicArea();
                    foreach (Point3d pt in lstP3d)
                    {
                        objDynArea.put_PolyLPoint3D(pt);
                    }

                    objDynArea.put_PolyLPoint3D(e.Context.ComputedPoint);
                    e.Context.DrawContext.Geometry.Dispose();
                    e.Context.DrawContext.Geometry.Draw(objDynArea);
                }
                catch (System.Exception ex)
                {
                }
            });

            //add pointMonitor
            ed.PointMonitor += new PointMonitorEventHandler(PointMonitor);

            PromptPointOptions opcoesPonto = new PromptPointOptions("\nSelect the second point: ");

            opcoesPonto.AllowNone = true;

            Boolean doLoop = true;

            while (doLoop)
            {
                ProPtRes = ed.GetPoint(opcoesPonto);
                switch (ProPtRes.Status)
                {
                case PromptStatus.OK:
                    lstP3d.Add(ProPtRes.Value);
                    break;

                case PromptStatus.None:
                    //Create DynamicArea
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            ArCaWrpDynamicArea objDynArea = new ArCaWrpDynamicArea();
                            foreach (Point3d pt in lstP3d)
                            {
                                objDynArea.put_PolyLPoint3D(pt);
                            }

                            objDynArea.switch_IsFinished();

                            BlockTableRecord currSpace = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                            currSpace.AppendEntity(objDynArea);
                            trans.AddNewlyCreatedDBObject(objDynArea, true);
                            trans.Commit();
                        }
                        catch (System.Exception ex)
                        {
                            trans.Abort();
                        }
                    }
                    doLoop = false;
                    break;

                case PromptStatus.Cancel:
                    //Command Canceled
                    doLoop = false;
                    break;
                }
            }

            //remove pointMonitor
            ed.PointMonitor -= new PointMonitorEventHandler(PointMonitor);
        }
Пример #55
0
        public void Test()

        {
            if (i == 0)

            {
                i = 4 * n;

                return;
            }

            Document doc = Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            //先清除图形

            using (Transaction trans = db.TransactionManager.StartTransaction())

            {
                PromptSelectionResult psr = ed.SelectAll();

                SelectionSet ss = psr.Value;

                if (ss != null)

                {
                    foreach (SelectedObject so in ss)

                    {
                        Entity ent = trans.GetObject(so.ObjectId, OpenMode.ForWrite) as Entity;

                        ent.Erase(true);
                    }
                }

                trans.Commit();
            }

            //清除完毕开始绘图

            using (Transaction trans = db.TransactionManager.StartTransaction())

            {
                BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                p2 = new Point3d(L1 * Math.Cos(theta), L1 * Math.Sin(theta), 0);

                p4 = new Point3d(300, 0, 0);

                Line MyL1 = new Line(p1, p2);

                btr.AppendEntity(MyL1);

                trans.AddNewlyCreatedDBObject(MyL1, true);//L1

                Circle c1 = new Circle();

                c1.SetDatabaseDefaults();

                c1.Center = p2;

                c1.Radius = L2;

                Circle c2 = new Circle();

                c2.SetDatabaseDefaults();

                c2.Center = p4;

                c2.Radius = L3;

                Point3dCollection pointcoll = new Point3dCollection();

                c2.IntersectWith(c1, Intersect.OnBothOperands, pointcoll, 0, 0);

                p3 = pointcoll[1];

                Line MyL2 = new Line(p2, p3);

                Line MyL3 = new Line(p3, p4);

                btr.AppendEntity(MyL2);

                trans.AddNewlyCreatedDBObject(MyL2, true);//L2

                btr.AppendEntity(MyL3);

                trans.AddNewlyCreatedDBObject(MyL3, true);//L3

                trans.Commit();
            }

            ed.UpdateScreen();

            System.Threading.Thread.Sleep(50);

            theta += delt;

            i--;

            Test();
        }
Пример #56
0
        public ObjectIdCollection Draw(Transaction trans, BlockTableRecord btr, string[] categories)
        {
            var    ids = new ObjectIdCollection();
            double top, bottom, left, right;

            GetRec(categories, out top, out bottom, out left, out right);
            var middleH = (left + right) / 2;
            var middleV = (top + bottom) / 2;
            //

            // 创建一条多段线
            var acPoly = new Polyline();

            acPoly.SetDatabaseDefaults();
            acPoly.AddVertexAt(0, new Point2d(left, bottom), 0, 0, 0);
            acPoly.AddVertexAt(0, new Point2d(left, top), 0, 0, 0);
            acPoly.AddVertexAt(0, new Point2d(right, top), 0, 0, 0);
            acPoly.AddVertexAt(0, new Point2d(right, bottom), 0, 0, 0);
            acPoly.Closed = true;
            // 添加新对象到块表记录和事务中
            btr.AppendEntity(acPoly);
            trans.AddNewlyCreatedDBObject(acPoly, true);
            ids.Add(acPoly.Id);

            // 对设计变通知项进行填充
            if (Subject == Subject.Inform)
            {
                // 创建Hatch对象并添加到块表记录
                var acHatch = new Hatch();
                btr.AppendEntity(acHatch);
                trans.AddNewlyCreatedDBObject(acHatch, true);
                // 设置填充对象的属性
                // 关联属性必须在将填充对象添加到块表记录之后,执行AppendLoop之前设置

                acHatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");
                acHatch.Associative = true;
                acHatch.AppendLoop(HatchLoopTypes.Outermost, ids);
                acHatch.EvaluateHatch(true);
                //
                ids.Add(acHatch.Id);
            }

            // 添加文字与标注
            var txtStart = new DBText
            {
                TextString = Start.ToString(),
                Height     = TextHeight,

                HorizontalMode = TextHorizontalMode.TextLeft,
                VerticalMode   = TextVerticalMode.TextVerticalMid,
                AlignmentPoint = new Point3d(left, middleV, 0),
            };

            btr.AppendEntity(txtStart);
            trans.AddNewlyCreatedDBObject(txtStart, true);
            ids.Add(txtStart.Id);

            var txtEnd = new DBText
            {
                TextString = End.ToString(),
                Height     = TextHeight,

                HorizontalMode = TextHorizontalMode.TextRight,
                VerticalMode   = TextVerticalMode.TextVerticalMid,
                AlignmentPoint = new Point3d(right, middleV, 0),
            };

            btr.AppendEntity(txtEnd);
            trans.AddNewlyCreatedDBObject(txtEnd, true);
            ids.Add(txtEnd.Id);

            var txtPaper = new DBText
            {
                TextString = PaperId,
                Height     = TextHeight,

                HorizontalMode = TextHorizontalMode.TextCenter,
                VerticalMode   = TextVerticalMode.TextVerticalMid,
                AlignmentPoint = new Point3d(middleH, middleV, 0), // 如果要设置对齐,则一定要先设置 HorizontalMode 与 VerticalMode,最后设置 AlignmentPoint。设置了对齐后,Position属性被屏蔽,不论设置为什么值都不起作用。
            };

            btr.AppendEntity(txtPaper);
            trans.AddNewlyCreatedDBObject(txtPaper, true);
            ids.Add(txtPaper.Id);

            return(ids);
        }
        public static void CreateHandleBlock()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

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

                if (bt.Has("Handle"))
                    btr = tr.GetObject(bt["Handle"], OpenMode.ForWrite) as BlockTableRecord;
                else
                {
                    btr = new BlockTableRecord();
                    btr.Name = "Handle";
                    bt.UpgradeOpen();
                    bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);
                }

                using (Autodesk.AutoCAD.DatabaseServices.Polyline outline = new Autodesk.AutoCAD.DatabaseServices.Polyline())
                {
                    outline.SetDatabaseDefaults();
                    outline.Normal = Vector3d.XAxis;

                    outline.AddVertexAt(0, new Point2d(0.0, 0.0), 0, 0, 0);
                    outline.AddVertexAt(1, new Point2d(0.0, 0.5 * t), 0, 0, 0);
                    outline.AddVertexAt(2, new Point2d(-t, 0.5 * t), 0, 0, 0);
                    outline.AddVertexAt(3, new Point2d(-t, 0.75 * t), 0, 0, 0);
                    outline.AddVertexAt(4, new Point2d(-1.25 * t, t), 0, 0, 0);
                    outline.AddVertexAt(5, new Point2d(-1.75 * t, t), 0, 0, 0);
                    outline.AddVertexAt(6, new Point2d(-2.0 * t, 0.75 * t), 0, 0, 0);
                    outline.AddVertexAt(7, new Point2d(-2.0 * t, 0.0), 0, 0, 0);
                    outline.Closed = true;

                    RevolveOptions opts = new RevolveOptions();
                    RevolveOptionsBuilder rob = new RevolveOptionsBuilder(opts);
                    rob.CloseToAxis = true;
                    rob.DraftAngle = 0;
                    rob.TwistAngle = 0;

                    Solid3d handle = new Solid3d(); ;
                    handle.CreateRevolvedSolid(outline, new Point3d(0, 0, 0), Vector3d.YAxis, 2.0 * Math.PI, 0, rob.ToRevolveOptions());
                    handle.ColorIndex = 0;

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

                    tr.Commit();
                }
            }
        }
        public void OU()
        {
            //need editor to prompt user
            Editor ed = doc.Editor;

            while (true)
            {
                //Prompt options for utility line
                PromptEntityOptions promptUtilityLineOpt = new PromptEntityOptions("Select Utility Line: \n");
                PromptEntityResult  utilityLineResults   = ed.GetEntity(promptUtilityLineOpt);

                if (utilityLineResults.Status != PromptStatus.OK)
                {
                    //ed.WriteMessage("\nThe selected object is not utility line");
                    return;
                }

                Transaction trans = database.TransactionManager.StartTransaction();
                using (trans)
                {
                    //access block table and create block table record
                    BlockTable       bt            = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord btr           = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    LinetypeTable    linetypeTable = trans.GetObject(database.LinetypeTableId, OpenMode.ForRead) as LinetypeTable;

                    if (!linetypeTable.Has("BLDG"))
                    {
                        ed.WriteMessage("Please load Linetype:BLDG \n");
                        return;
                    }

                    //get the running line
                    Type type = trans.GetObject(utilityLineResults.ObjectId, OpenMode.ForRead).GetType();

                    String   resultString;
                    Line     line;
                    Polyline polyline;
                    double   offset;

                    if (type == typeof(Line))
                    {
                        line = trans.GetObject(utilityLineResults.ObjectId, OpenMode.ForRead) as Line;

                        resultString = Regex.Match(line.Linetype, @"\d+").Value;

                        if (resultString != "")
                        {
                            offset = Double.Parse(resultString);
                        }
                        else
                        {
                            ed.WriteMessage("Line has no width. Utility linetype with size must be used.");
                            break;
                        }

                        offset = (offset / 12) / 2;

                        DBObjectCollection objCollection = line.GetOffsetCurves(offset);

                        foreach (Entity entity in objCollection)
                        {
                            Line newLine = (Line)entity;
                            newLine.LinetypeScale = .05;
                            if (offset < 1.5)
                            {
                                newLine.Linetype = "CONTINUOUS";
                            }
                            else
                            {
                                newLine.Linetype = "BLDG";
                            }

                            newLine.LineWeight = LineWeight.LineWeight009;
                            newLine.ReverseCurve();
                            btr.AppendEntity(newLine);
                            trans.AddNewlyCreatedDBObject(newLine, true);
                        }

                        DBObjectCollection objCollection2 = line.GetOffsetCurves(-offset);

                        foreach (Entity entity in objCollection2)
                        {
                            Line newLine = (Line)entity;
                            newLine.LinetypeScale = .05;
                            if (offset < 1.5)
                            {
                                newLine.Linetype = "CONTINUOUS";
                            }
                            else
                            {
                                newLine.Linetype = "BLDG";
                            }

                            newLine.LineWeight = LineWeight.LineWeight009;
                            btr.AppendEntity(newLine);
                            trans.AddNewlyCreatedDBObject(newLine, true);
                        }
                    }
                    else if (type == typeof(Polyline))
                    {
                        polyline = trans.GetObject(utilityLineResults.ObjectId, OpenMode.ForRead) as Polyline;

                        resultString = Regex.Match(polyline.Linetype, @"\d+").Value;

                        if (resultString != "")
                        {
                            offset = Double.Parse(resultString);
                        }
                        else
                        {
                            ed.WriteMessage("Line has no width. Utility linetype with size must be used.\n");
                            break;
                        }

                        offset = (offset / 12) / 2;

                        DBObjectCollection objCollection = polyline.GetOffsetCurves(offset);

                        foreach (Entity entity in objCollection)
                        {
                            Polyline newLine = (Polyline)entity;
                            newLine.LinetypeScale = .05;
                            if (offset < 1.5)
                            {
                                newLine.Linetype = "CONTINUOUS";
                            }
                            else
                            {
                                newLine.Linetype = "BLDG";
                            }

                            newLine.LineWeight = LineWeight.LineWeight009;
                            btr.AppendEntity(newLine);
                            trans.AddNewlyCreatedDBObject(newLine, true);
                        }

                        DBObjectCollection objCollection2 = polyline.GetOffsetCurves(-offset);

                        foreach (Entity entity in objCollection2)
                        {
                            Polyline newLine = (Polyline)entity;
                            newLine.LinetypeScale = .05;
                            if (offset < 1.5)
                            {
                                newLine.Linetype = "CONTINUOUS";
                            }
                            else
                            {
                                newLine.Linetype = "BLDG";
                            }

                            newLine.LineWeight = LineWeight.LineWeight009;
                            newLine.ReverseCurve();
                            btr.AppendEntity(newLine);
                            trans.AddNewlyCreatedDBObject(newLine, true);
                        }
                    }
                    else
                    {
                        ed.WriteMessage("Must me Line or Polyline. \n");
                    }

                    trans.Commit();
                }
            }
        }
Пример #59
0
        public void CreateNewHatch(BlockTableRecord btr)
        {
            var h = new Hatch();

             h.Annotative = AnnotativeStates.False;
             h.Layer = Layer;
             h.Color = Color;
             h.LineWeight = Lineweight;
             h.SetHatchPattern(PatternType, PatternName);
             h.PatternAngle = PatternAngle;
             h.PatternScale = PatternScale;
             h.SetHatchPattern(PatternType, PatternName);

             Id = btr.AppendEntity(h);
             btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(h, true);

             if (IdsAssociate != null && IdsAssociate.Count > 0)
             {
            h.Associative = true;
            h.AppendLoop(HatchLoopTypes.Default, IdsAssociate);
            h.EvaluateHatch(false);
             }
        }
Пример #60
0
        /// <summary>
        /// 将数据填入本图形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.AllParts.Count > 0)
            {
                //提起本图纸的图框
                Document        acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                Database        acDb  = acDoc.Database;
                Editor          acEd  = acDoc.Editor;
                List <Polyline> listAllTitleBlocks = new List <Polyline>();
                using (DocumentLock m_DocumentLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
                {
                    using (Transaction trans = acDb.TransactionManager.StartTransaction())
                    {
                        BlockTable bt = (BlockTable)trans.GetObject(acDb.BlockTableId, OpenMode.ForWrite);
                        //打开数据库的模型空间块表记录对象
                        BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                        //循环遍历模型空间中的实体
                        foreach (ObjectId id in btr)
                        {
                            Entity ent = trans.GetObject(id, OpenMode.ForWrite) as Entity;
                            if (ent is Polyline && ent.ColorIndex.ToString() == "171")
                            {
                                listAllTitleBlocks.Add(ent as Polyline);
                            }
                        }
                        //提取单元件名称,编号,数量
                        PromptSelectionResult psr = null;
                        if (listAllTitleBlocks.Count > 0)
                        {
                            foreach (var item in listAllTitleBlocks)
                            {
                                var pnts = item.GeometricExtents;
                                psr = acEd.SelectWindow(pnts.MaxPoint, pnts.MinPoint, new SelectionFilter(new TypedValue[] { new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(DBText)).DxfName),
                                                                                                                             new TypedValue((int)DxfCode.Color, 171), new TypedValue((int)DxfCode.LayerName, "A3") }));
                                List <DBText> listText = new List <DBText>();
                                if (psr.Status == PromptStatus.OK)
                                {
                                    foreach (SelectedObject txtid in psr.Value)
                                    {
                                        listText.Add(trans.GetObject(txtid.ObjectId, OpenMode.ForWrite) as DBText);
                                    }
                                }
                                List <myPart> partBelongCurTb = new List <myPart>();
                                if (listText.Count > 0)
                                {
                                    string 单元件名称 = "";
                                    foreach (var partDwg in this.AllParts)
                                    {
                                        foreach (var titleBlk in partDwg.CurDwgPanels)
                                        {
                                            var t = listText.Where(c => c.TextString == titleBlk.单元件编号).ToList();
                                            if (t.Count == 1)
                                            {
                                                partBelongCurTb.AddRange(titleBlk.listMyParts);
                                                单元件名称 = t[0].TextString;
                                            }
                                        }
                                    }
                                    if (partBelongCurTb.Count > 0)
                                    {
                                        using (Transaction trans1 = acDb.TransactionManager.StartTransaction())
                                        {
                                            var   tbScale = (int)(pnts.MaxPoint.Y - pnts.MinPoint.Y) / 297;
                                            var   oid     = TableTools.AddTableStyle(acDb, "myTableStyle", tbScale * 2);
                                            Table table   = new Table();
                                            table.TableStyle = oid;
                                            table.NumColumns = 9;
                                            table.NumRows    = partBelongCurTb.Count + 3;
                                            table.Position   = new Point3d(pnts.MaxPoint.X - tbScale * 3 * 8 * 9, pnts.MinPoint.Y + tbScale * 3 * (table.NumRows + 6), 0);
                                            table.SetRowHeight(tbScale * 3);
                                            table.SetColumnWidth(tbScale * 3 * 7.5);
                                            table.SetTextString(0, 0, 单元件名称 + " 单元件配套表(单件)");
                                            string[] arr = new string[] { "序号", " 零件名称", "零件编号", "材质", "零件规格(mm)", "数量", "单重(Kg)", "总重(Kg)", "备注" };
                                            for (int i = 0; i < arr.Length; i++)
                                            {
                                                table.SetTextString(1, i, arr[i]);
                                            }
                                            //Z-DWFB01 单元件配套表(单件)

                                            for (int i = 2; i < partBelongCurTb.Count + 2; i++)
                                            {
                                                var part = partBelongCurTb[i - 2];
                                                table.SetTextString(i, 0, (i - 1).ToString());
                                                table.SetTextString(i, 1, "N.A.");
                                                table.SetTextString(i, 2, part.PieceMark);
                                                table.SetTextString(i, 3, part.Material);
                                                table.SetTextString(i, 4, part.Thk + "x" + (int)part.Width + "x" + (int)part.Length);
                                                table.SetTextString(i, 5, part.Qty.ToString());
                                                table.SetTextString(i, 6, (part.Area * part.Thk * 7.85 / 1000).ToString("0"));
                                                table.SetTextString(i, 7, (part.Qty * part.Area * part.Thk * 7.85 / 1000).ToString("0"));
                                                table.SetTextString(i, 8, "N.A.");
                                            }
                                            btr.AppendEntity(table);
                                            trans1.AddNewlyCreatedDBObject(table, true);
                                            trans1.Commit();
                                        }
                                    }
                                    else
                                    {
                                        Circle cir = new Circle();
                                        cir.Center     = new Point3d(0.5 * (pnts.MaxPoint.X + pnts.MinPoint.X), 0.5 * (pnts.MaxPoint.Y + pnts.MinPoint.Y), 0.5 * (pnts.MaxPoint.Z + pnts.MinPoint.Z));
                                        cir.Radius     = Math.Sqrt((pnts.MaxPoint.X - pnts.MinPoint.X) * (pnts.MaxPoint.X - pnts.MinPoint.X) + (pnts.MaxPoint.Y - pnts.MinPoint.Y) * (pnts.MaxPoint.Y - pnts.MinPoint.Y)) / 2;
                                        cir.ColorIndex = 2;
                                        btr.AppendEntity(cir);
                                        trans.AddNewlyCreatedDBObject(cir, true);
                                    }
                                }
                            }
                            trans.Commit();
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("自动生成零件汇总表格完成!!!!");
                        }
                        else
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("请给图框外轮廓设置成A3图层,颜色171 号颜色!");
                        }
                    }
                }
            }
            else
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("请先执行第二步操作,谢谢!!");
            }
        }