public void IncrementAttribute(BlockTableRecord TableRecord, int index, string prefix, string suffix)
        {
            string           startValue = this.dlg.StartValue;
            int              num        = 0;
            Stack <ObjectId> objectIds  = new Stack <ObjectId>();
            Stack <string>   strs       = new Stack <string>();

            while (true)
            {
                using (BlockReference blockRef = new BlockReference(Point3d.Origin, TableRecord.ObjectId))
                {
                    blockRef.Rotation     = this.dlg.BlockRotation;
                    blockRef.ScaleFactors = new Scale3d(this.dlg.BlockScale);
                    blockRef.TransformBy(this.ed.CurrentUserCoordinateSystem);
                    if (blockRef.Annotative == AnnotativeStates.True)
                    {
                        ObjectContextCollection contextCollection = this.db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
                        Autodesk.AutoCAD.Internal.ObjectContexts.AddContext(blockRef, contextCollection.CurrentContext);
                    }
                    ObjectId objectId = this.db.GetCurrentSpace(OpenMode.ForWrite).Add(blockRef);
                    blockRef.AddAttributeReferences(index, string.Concat(prefix, startValue, suffix));
                    BlockJig     blockJig     = new BlockJig(blockRef, num, TableRecord.GetAttributesTextInfos());
                    PromptResult promptResult = this.ed.Drag(blockJig);
                    if (promptResult.Status == PromptStatus.Keyword)
                    {
                        blockRef.Erase();
                        if (num != 0)
                        {
                            objectIds.Pop().GetObject <BlockReference>(OpenMode.ForWrite).Erase();
                            this.db.TransactionManager.QueueForGraphicsFlush();
                            startValue = strs.Pop();
                            num--;
                        }
                        else
                        {
                            this.ed.WriteMessage("\nNothing to undo !");
                        }
                    }
                    else if (promptResult.Status == PromptStatus.OK)
                    {
                        this.db.TransactionManager.QueueForGraphicsFlush();
                        strs.Push(startValue);
                        objectIds.Push(objectId);
                        startValue = this.Increment(startValue);
                        num++;
                    }
                    else
                    {
                        blockRef.Erase();
                        break;
                    }
                }
            }
            this.dlg.txtValue.Text = startValue;
        }
Beispiel #2
0
        protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw)
        {
            lock (Entities)
            {
                Entities.Clear();
                Entities.AddRange(_arrow.Explode().Select(x =>
                {
                    if (x is DBText)
                    {
                        return(_convertToAttribute((DBText)x));
                    }
                    return(x);
                }));

                ObjectId btrId = AcadBlocks.BlockTools.CreateBlockTableRecordEx(_insertPoint, "*U", Entities.Select(x => (Entity)x.Clone()).ToList(), AnnotativeStates.True);
                ObjectId brId  = AcadBlocks.BlockTools.AddBlockRefToModelSpace(btrId, null, _insertPoint, _ucs);

                Tools.StartTransaction(() =>
                {
                    BlockReference br = brId.GetObjectForWrite <BlockReference>();
                    br.SetDatabaseDefaults(HostApplicationServices.WorkingDatabase);
                    br.RecordGraphicsModified(true);

                    Entity inMemoryEntity = (Entity)br.Clone();
                    draw.Geometry.Draw(inMemoryEntity);

                    var btr = br.BlockTableRecord.GetObjectForWrite <BlockTableRecord>();
                    br.Erase();
                    btr.EraseBolckTableRecord();
                    inMemoryEntity.Dispose();
                });
            }

            return(true);
        }
Beispiel #3
0
        public virtual void TrasientDisplayAtBlock(Point3d insertPoint, IEnumerable <Entity> entities)
        {
            if (_transient == null)
            {
                _transient = new IgorKL.ACAD3.Model.Helpers.Display.DynamicTransient();
            }

            Calculate();
            ObjectId btrId   = AcadBlocks.BlockTools.CreateBlockTableRecord("*U", insertPoint, entities.Select(ent => (Entity)ent.Clone()), _annotative);
            ObjectId blockId = AcadBlocks.BlockTools.AppendBlockItem(insertPoint, btrId, null, _ucs);

            BlockReference block = null;

            Tools.StartTransaction(() =>
            {
                block      = blockId.GetObjectForWrite <BlockReference>();
                var buffer = (BlockReference)block.Clone();
                block.Erase(true);
                block = buffer;
            });

            _transient.AddMarker((DBObject)block);

            _transient.Display();
        }
Beispiel #4
0
        public virtual void TrasientDisplayAtBlock()
        {
            if (_transient == null)
            {
                _transient = new IgorKL.ACAD3.Model.Helpers.Display.DynamicTransient();
            }

            Calculate();
            ObjectId btrId   = _createTableRecord(_entities.Select(ent => (Entity)ent.Clone()));
            ObjectId blockId = _createBlockItem(btrId, _insertPointUcs);

            BlockReference block = null;

            Tools.StartTransaction(() =>
            {
                block      = blockId.GetObjectForWrite <BlockReference>();
                var buffer = (BlockReference)block.Clone();
                block.Erase(true);
                block = buffer;
            });

            _transient.AddMarker((DBObject)block);

            _transient.Display();
        }
        public static bool EraseBlkRefs(ObjectId blkId)
        {
            bool blkRefsErased = false;

            if (blkId.IsNull)
            {
                return(false);
            }

            Database db = blkId.Database;

            if (db == null)
            {
                return(false);
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord blk = (BlockTableRecord)tr.GetObject(blkId, OpenMode.ForRead);
                var blkRefs          = blk.GetBlockReferenceIds(true, true);
                if (blkRefs != null && blkRefs.Count > 0)
                {
                    foreach (ObjectId blkRefId in blkRefs)
                    {
                        BlockReference blkRef = (BlockReference)tr.GetObject(blkRefId, OpenMode.ForWrite);
                        blkRef.Erase();
                    }
                    blkRefsErased = true;
                }
                tr.Commit();
            }
            return(blkRefsErased);
        }
Beispiel #6
0
        private void _setEntitiesFromInnerGrid()
        {
            int rowCount    = SimpleGride.CalculateCeilingCount(_boundRectg.GetLeftVerticalVector(), _step) + 1;
            int columnCount = SimpleGride.CalculateCeilingCount(_boundRectg.GetLowertHorizontalVector(), _step) + 1;

            if (rowCount * columnCount > Math.Pow(50, 2))
            {
                return;
            }
            if (rowCount * columnCount == 0d)
            {
                return;
            }

            Entities.ForEach(ent => ent.Dispose());
            Entities.Clear();
            CoordinateLable lableFactory = new CoordinateLable();

            Tools.StartTransaction(() =>
            {
                for (int row = 0; row < rowCount; row++)
                {
                    for (int col = 0; col < columnCount; col++)
                    {
                        //Entities.Add(new DBPoint(_innerGridUcs.CalculateGridPoint(row, col)));
                        Point3d point     = _innerGridUcs.CalculateGridPoint(row, col);
                        BlockReference br = lableFactory.CreateItem(point, Matrix3d.Identity).GetObjectForRead <BlockReference>();
                        Entities.Add((Entity)br.Clone());
                        br.Erase(true);
                    }
                }
                Tools.GetAcadDatabase().TransactionManager.QueueForGraphicsFlush();
            });
        }
Beispiel #7
0
        static public void test()
        {
            string      comp = "D:\\Temp\\test.dwg";
            Document    doc  = Application.DocumentManager.MdiActiveDocument;
            Editor      ed   = doc.Editor;
            Transaction tr   = doc.TransactionManager.StartTransaction();

            try
            {
                string   dwgName = HostApplicationServices.Current.FindFile(comp, Application.DocumentManager.MdiActiveDocument.Database, FindFileHint.Default);
                Database db      = new Database(false, false);
                db.ReadDwgFile(dwgName, System.IO.FileShare.Read, true, "");
                ObjectId BlkId;
                BlkId = doc.Database.Insert(dwgName, db, false);
                BlockTable       bt   = (BlockTable)tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead, true);
                BlockTableRecord btr  = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                BlockReference   bref = new BlockReference(new Point3d(10, 10, 0), BlkId);
                btr.AppendEntity(bref);
                tr.AddNewlyCreatedDBObject(bref, true);
                bref.ExplodeToOwnerSpace();
                bref.Erase();
                tr.Commit();
            }
            finally
            {
                tr.Dispose();
            }
        }
Beispiel #8
0
        private static DBObjectCollection SuperExplode(BlockReference bf, BlockTableRecord modelspace)
        {
            var result = new DBObjectCollection();

            bf.UpgradeOpen();
            var objSet = new DBObjectCollection();

            bf.Explode(objSet);
            foreach (var obj in objSet)
            {
                var id  = modelspace.AppendEntity(obj as Entity);
                var ent = id.GetObject(OpenMode.ForRead);
                if (ent is BlockReference)
                {
                    ent.UpgradeOpen();
                    var col = SuperExplode(obj as BlockReference, modelspace);
                    foreach (var explodedObj in col)
                    {
                        result.Add(explodedObj as DBObject);
                    }
                }
                else
                {
                    result.Add(obj as Entity);
                }
            }
            bf.Erase();
            return(result);
        }
Beispiel #9
0
        private static void ForceExpold(BlockReference ent)
        {
            var doc = Application.DocumentManager.MdiActiveDocument;

            using (var doclock = doc.LockDocument())
            {
                var db = HostApplicationServices.WorkingDatabase;
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    using (var coll = new DBObjectCollection())
                    {
                        ent.Explode(coll);
                        BlockTableRecord table = (BlockTableRecord)tr.GetObject(ent.OwnerId, OpenMode.ForWrite);
                        foreach (DBObject obj in coll)
                        {
                            if (obj is Entity)
                            {
                                table.AppendEntity((Entity)obj);
                                tr.AddNewlyCreatedDBObject(obj, true);
                            }
                        }
                    }
                    var e = tr.GetObject(ent.Id, OpenMode.ForWrite);
                    ent.Erase();
                    tr.Commit();
                }
            }
        }
Beispiel #10
0
        public static ObjectIdCollection ExplodeBlock(this BlockReference br, Transaction tr, Database db,
                                                      bool erase = true)
        {
            // We'll collect the BlockReferences created in a collection
            var toExplode = new ObjectIdCollection();
            var objIds    = new ObjectIdCollection();

            // Define our handler to capture the nested block references
            void Handler(object s, ObjectEventArgs e)
            {
                switch (e.DBObject)
                {
                case BlockReference _:
                    toExplode.Add(e.DBObject.ObjectId);
                    break;

                default:
                    objIds.Add(e.DBObject.ObjectId);
                    break;
                }
            }

            // Add our handler around the explode call, removing it
            // directly afterwards

            db.ObjectAppended += Handler;
            br.ExplodeToOwnerSpace();
            db.ObjectAppended -= Handler;

            // Go through the results and recurse, exploding the
            // contents

            foreach (ObjectId bid in toExplode)
            {
                var nBr = (BlockReference)tr.GetObject(bid, OpenMode.ForRead);

                var exIds = nBr.ExplodeBlock(tr, db);

                foreach (ObjectId id in exIds)
                {
                    objIds.Add(id);
                }
            }


            // We might also just let it drop out of scope
            toExplode.Clear();

            // To replicate the explode command, we're delete the
            // original entity

            if (erase)
            {
                br.UpgradeOpen();
                br.Erase();
                br.DowngradeOpen();
            }

            return(objIds);
        }
Beispiel #11
0
        public void TestAnonyBlock2()
        {
            Matrix3d          ucs          = CoordinateSystem.CoordinateTools.GetCurrentUcs();
            ArrowDirectional2 adHorizontal = new ArrowDirectional2(ucs, ArrowDirectional2.DirectionMode.Horizontal);

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

            PromptPointOptions ppo = new PromptPointOptions("\nУкажите втору точку");

            ppo.BasePoint     = insertPoint;
            ppo.UseDashedLine = true;
            ppo.UseBasePoint  = true;

            PromptPointResult ppr = Tools.GetAcadEditor().GetPoint(ppo);

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

            var res = adHorizontal.PastNewArrowItem(insertPoint, ppr.Value);

            ppo               = new PromptPointOptions("\nУкажите сторону отрисовки");
            ppo.BasePoint     = insertPoint;
            ppo.UseDashedLine = true;
            ppo.UseBasePoint  = true;

            ppr = Tools.GetAcadEditor().GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK)
            {
                return;
            }

            BlockReference br = null;

            Tools.StartTransaction(() =>
            {
                br = res.ArrowId.GetObjectForRead <BlockReference>();
                BlockReference cloneBr = adHorizontal.GetRedirectBlockReferenceCopy(br, ppr.Value);
                var id = br.GetAnonymClone(cloneBr.Position);
                if (cloneBr != null)
                {
                    br.UpgradeOpen();
                    br.Erase(true);
                    br = cloneBr;
                }
                else
                {
                    br = null;
                }
            });
            if (br != null)
            {
                Tools.AppendEntityEx(br);
            }
        }
Beispiel #12
0
        private void ReplaceBlocks()
        {
            if (Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.Count > 0)
            {
                Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.CurrentDocument.Editor.WriteMessage("Close the open documents:\n");
                foreach (Document doc in Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager)
                {
                    Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.CurrentDocument.Editor.WriteMessage(doc.Name + "\n");
                }
                return;
            }

            foreach (DWG item in DWGs)
            {
                Database acDb = new Database(false, true);
                using (acDb)
                {
                    acDb.ReadDwgFile(item.Path, FileShare.ReadWrite, false, "");
                    using (Transaction trans = acDb.TransactionManager.StartTransaction())
                    {
                        BlockTable                 bt      = (BlockTable)trans.GetObject(acDb.BlockTableId, OpenMode.ForWrite);
                        BlockTableRecord           ms      = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                        BlockTableRecordEnumerator recEnum = ms.GetEnumerator();

                        while (recEnum.MoveNext())
                        {
                            Entity ent = (Entity)trans.GetObject(recEnum.Current, OpenMode.ForWrite);
                            if (ent.GetType() == typeof(BlockReference))
                            {
                                BlockReference blockRef = ent as BlockReference;
                                if (blockRef.Handle.Value.CompareTo(hBlockReplace.Value) == 0)
                                {
                                    using (BlockReference acBlkRef = new BlockReference(blockRef.Position, bt[BlockReplacement]))
                                    {
                                        BlockTableRecord acCurSpaceBlkTblRec;
                                        acCurSpaceBlkTblRec = trans.GetObject(acDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                                        acCurSpaceBlkTblRec.AppendEntity(acBlkRef);
                                        trans.AddNewlyCreatedDBObject(acBlkRef, true);
                                        AddAttributes(acBlkRef);
                                    }
                                    item.Check = true;
                                    blockRef.Erase();
                                    break;
                                }
                            }
                        }
                        trans.Commit();
                        acDb.SaveAs(item.Path, DwgVersion.Current);
                        item.Check = true;
                    }
                }
            }
        }
Beispiel #13
0
        public static List <Entity> ExplodeBlock(this BlockReference refEnt)
        {
            DBObjectCollection dbObjs = new DBObjectCollection();

            refEnt.Explode(dbObjs);

            var query = from DBObject dbObj in dbObjs
                        let ent = dbObj as Entity
                                  select ent;
            List <Entity> lstEnt = query.ToList();

            refEnt.Erase();

            return(lstEnt);
        }
        protected static void ExplodeBlockReference(BlockReference ent)
        {
            var doc = Application.DocumentManager.MdiActiveDocument;

            using (var doclock = doc.LockDocument())
            {
                var db = HostApplicationServices.WorkingDatabase;
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    ent.ExplodeToOwnerSpace();
                    var e = tr.GetObject(ent.Id, OpenMode.ForWrite);
                    ent.Erase();
                    tr.Commit();
                }
            }
        }
Beispiel #15
0
        private void _setEntitiesToBlock(bool erase)
        {
            Tools.StartTransaction(() => {
                var btrId = AcadBlocks.BlockTools.CreateBlockTableRecord("*U", _insertPoint, Entities, AnnotativeStates.True);
                //var brId = AcadBlocks.BlockTools.AppendBlockItem(_lowerPointUcs.TransformBy(_ucs.Inverse()), btrId, null, Matrix3d.Identity);
                var brId          = AcadBlocks.BlockTools.AppendBlockItem(_insertPoint, btrId, null, _ucs);
                BlockReference br = brId.GetObjectForRead <BlockReference>();
                Entities.Add((Entity)br.Clone());

                if (erase)
                {
                    br.UpgradeOpen();
                    br.Erase();
                }
            });
        }
        /// <summary>
        /// Вставка блока с атрибутами
        /// </summary>
        /// <param name="promptCounter">0 - только вставка, 1 - с поворотом</param>
        /// <param name="tr">Транзакция</param>
        /// <param name="db">База данных чертежа</param>
        /// <param name="ed">Editor</param>
        /// <param name="blkDefId">ObjectId блока</param>
        /// <param name="attributes">Список имен атрибутов</param>
        /// <param name="isAnnotative">Аннотативность блока-исходника</param>
        /// <returns></returns>
        public static ObjectId InsertBlockRef(
            int promptCounter,
            Transaction tr,
            Database db,
            Editor ed,
            ObjectId blkDefId,
            List <string> attributes,
            bool isAnnotative)
        {
            var btr            = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
            var blockReference = new BlockReference(Point3d.Origin, blkDefId);

            if (isAnnotative)
            {
                var ocm = db.ObjectContextManager;
                var occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES");
                ObjectContexts.AddContext(blockReference, occ.CurrentContext);
            }

            var id = btr.AppendEntity(blockReference);

            tr.AddNewlyCreatedDBObject(blockReference, true);
            var jig = new BlockRefJig(blockReference, AppendAttribToBlock(tr, blockReference, attributes));

            jig.SetPromptCounter(0);
            var res = ed.Drag(jig);

            if (res.Status == PromptStatus.OK)
            {
                if (promptCounter == 1)
                {
                    jig.SetPromptCounter(promptCounter);
                    res = ed.Drag(jig);
                    if (res.Status == PromptStatus.OK)
                    {
                        return(id);
                    }
                }
                else
                {
                    return(id);
                }
            }

            blockReference.Erase();
            return(ObjectId.Null);
        }
        private void placementSpots(List <Spot> spots)
        {
            using (var lockdoc = _doc.LockDocument())
            {
                using (var t = _db.TransactionManager.StartTransaction())
                {
                    var bt = t.GetObject(_db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    var cs = t.GetObject(_db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                    _idMS = cs.Id;
                    var btrColorArea           = t.GetObject(bt[Settings.Default.BlockColorAreaName], OpenMode.ForRead) as BlockTableRecord;
                    var blRefColorAreaTemplate = new BlockReference(Point3d.Origin, btrColorArea.Id);
                    cs.AppendEntity(blRefColorAreaTemplate);
                    t.AddNewlyCreatedDBObject(blRefColorAreaTemplate, true);
                    _idBlRefColorAreaTemplate = blRefColorAreaTemplate.Id;
                    SetDynParamColorAreaBlock(blRefColorAreaTemplate, _colorAreaSize);
                    using (_idColCopy = new ObjectIdCollection())
                    {
                        _idColCopy.Add(_idBlRefColorAreaTemplate);
                        ProgressMeter progressMeter = new ProgressMeter();
                        progressMeter.SetLimit(spots.Count);
                        progressMeter.Start("Вставка блоков зон покраски...");

                        _countInsertBlocksSpot = 0;
                        foreach (var spot in spots)
                        {
                            progressMeter.MeterProgress();
                            if (HostApplicationServices.Current.UserBreak())
                            {
                                break;
                            }
                            if (spot != null)
                            {
                                insertSpot(spot, spot.Index / _ysize, spot.Index % _ysize, t);
                            }
                        }
                        progressMeter.Stop();
                    }
                    Logger.Log.Debug("Вставлено блоков {0}", _countInsertBlocksSpot);

                    blRefColorAreaTemplate.Erase(true);
                    t.Commit();
                }
            }
        }
Beispiel #18
0
        public static ObjectIdCollection explodeFFL(BlockReference blockToExplode)
        {
            Document acDoc    = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database acCurrDb = acDoc.Database;
            Editor   acEditor = acDoc.Editor;

            using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction())
            {
                try
                {
                    // explode the block
                    DBObjectCollection fflEntities = new DBObjectCollection();
                    blockToExplode.Explode(fflEntities);

                    // Erase the block
                    blockToExplode.UpgradeOpen();
                    blockToExplode.Erase();

                    // Add the entities back into modelspace
                    BlockTable       acBlkTbl    = acTrans.GetObject(acCurrDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                                     OpenMode.ForWrite) as BlockTableRecord;
                    ObjectIdCollection newEntsIDs = new ObjectIdCollection();
                    foreach (DBObject obj in fflEntities)
                    {
                        Entity newEnt = (Entity)obj;
                        acBlkTblRec.AppendEntity(newEnt);
                        acTrans.AddNewlyCreatedDBObject(newEnt, true);
                        newEntsIDs.Add(newEnt.Id);
                    }
                    acTrans.Commit();
                    return(newEntsIDs);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception acException)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog
                        ("The following exception was caught: \n" + acException.Message
                        + "\nError exploding FFL block!\n");
                    acTrans.Commit();
                    return(null);
                }
            }
        }
Beispiel #19
0
 public static void Delete(ObjectId oid)
 {
     try {
         if (oid.IsErased == false & oid.IsEffectivelyErased == false)
         {
             using (World.Docu.LockDocument()) {
                 using (Database db = World.Docu.Database) {
                     using (Transaction tr = db.TransactionManager.StartTransaction()) {
                         using (BlockReference br = (BlockReference)tr.GetObject(oid, OpenMode.ForWrite)) {
                             br.Erase();
                         }
                         tr.Commit();
                     }
                 }
             }
         }
     }
     catch (System.Exception ex) {
         Err.Log(ex);
     }
 }
        private void _setEntitiesToBlock(Point3d insertPointUcs, IEnumerable <Entity> entities, Dictionary <string, string> attrInfo, bool erase)
        {
            ObjectId btrId = AcadBlocks.BlockTools.CreateBlockTableRecord("*U", Point3d.Origin, entities, Annotative);
            ObjectId brId  = AcadBlocks.BlockTools.AppendBlockItem(insertPointUcs.TransformBy(Ucs), btrId, attrInfo);

            Tools.StartTransaction(() =>
            {
                BlockReference br = brId.GetObjectForRead <BlockReference>();
                br.UpgradeOpen();
                if (_arrowUpper != null)
                {
                    _arrowUpper.SaveToEntity(br);
                }
                br.RecordGraphicsModified(true);
                Entities.Add((Entity)br.Clone());
                if (erase)
                {
                    br.Erase(true);
                }
            });
        }
Beispiel #21
0
        public List <Entity> exploreBlock(ref BlockTableRecord spaceRecord, BlockReference block, ref Transaction tr)
        {
            List <Entity> ans = new List <Entity>();

            using (DBObjectCollection dbObjCol = new DBObjectCollection())
            {
                block.Explode(dbObjCol);

                foreach (DBObject dbObj in dbObjCol)
                {
                    Entity acEnt = dbObj as Entity;
                    acEnt.Layer = frameBlockAboveLayer;
                    spaceRecord.AppendEntity(acEnt);
                    tr.AddNewlyCreatedDBObject(acEnt, true);

                    ans.Add(acEnt);
                }
            }
            block.Erase();
            return(ans);
        }
Beispiel #22
0
        public static List <Entity> ExplodeBlock(this BlockReference refEnt, List <Entity> lstEnt)
        {
            if (lstEnt == null)
            {
                lstEnt = new List <Entity>();
            }
            DBObjectCollection dbObjs = new DBObjectCollection();

            refEnt.Explode(dbObjs);
            if (refEnt.Database != null)
            {
                refEnt.Erase();
            }

            var query = from DBObject dbObj in dbObjs
                        let ent = dbObj as Entity
                                  where ent is BlockReference
                                  select ent;

            var queryEnt = from DBObject dbObj in dbObjs
                           let ent = dbObj as Entity
                                     where !(ent is BlockReference)
                                     select ent;
            List <Entity> lst = queryEnt.ToList();

            if (lst != null && lst.Count > 0)
            {
                lstEnt.AddRange(lst);
            }
            if (query.Count() > 0)
            {
                foreach (BlockReference block in query)
                {
                    ExplodeBlock(block, lstEnt);
                }
            }

            return(lstEnt);
        }
            /// <summary>
            /// Вставка блока с атрибутами
            /// </summary>
            /// <param name="promptCounter">0 - только вставка, 1 - с поворотом</param>
            /// <param name="tr">Транзакция</param>
            /// <param name="db">База данных чертежа</param>
            /// <param name="ed">Editor</param>
            /// <param name="blkdefid">ObjectId блока</param>
            public static ObjectId InsertBlockRef(
                int promptCounter,
                Transaction tr,
                Database db,
                Editor ed,
                ObjectId blkdefid)
            {
                var btr    = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                var blkref = new BlockReference(Point3d.Origin, blkdefid);
                var id     = btr.AppendEntity(blkref);

                tr.AddNewlyCreatedDBObject(blkref, true);
                var jig = new BlockRefJig(blkref);

                jig.SetPromptCounter(0);
                var res = ed.Drag(jig);

                if (res.Status == PromptStatus.OK)
                {
                    if (promptCounter == 1)
                    {
                        jig.SetPromptCounter(promptCounter);
                        res = ed.Drag(jig);
                        if (res.Status == PromptStatus.OK)
                        {
                            return(id);
                        }
                    }
                    else
                    {
                        return(id);
                    }
                }

                blkref.Erase();
                return(ObjectId.Null);
            }
Beispiel #24
0
        public static Point3d?CopyAllEntity(FileInfo file, Point3d basepoint)
        {
            Point3d?result = null;

            if (!file.Exists)
            {
                throw new FileNotFoundException("找不到文件", file.FullName);
            }
            var db  = HostApplicationServices.WorkingDatabase;
            var doc = Application.DocumentManager.MdiActiveDocument;

            using (doc.LockDocument())
            {
                var blockName       = Guid.NewGuid().ToString();
                var importObjectIds = new ObjectIdCollection();
                var layoutIds       = new ObjectIdCollection();
                using (var sourceDb = new Database(false, true))
                {
                    if (file.Extension.ToLower() == ".dwg")
                    {
                        sourceDb.ReadDwgFile(file.FullName, FileShare.Read, true, "");
                    }
                    else if (file.Extension.ToLower() == ".dxf")
                    {
                        sourceDb.DxfIn(file.FullName, $@"{Environment.CurrentDirectory}\logs\importdxf\{file.Name}.log");
                    }
                    else
                    {
                        throw new Exception("不能识别的文件类型:" + file.FullName);
                    }
                    using (var tran = sourceDb.TransactionManager.StartTransaction())
                    {
                        //读取源数据库
                        using (var bt = (BlockTable)tran.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false))
                        {
                            BlockTableRecord btr = (BlockTableRecord)tran.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead, false);
                            foreach (ObjectId id in btr)
                            {
                                var ent = tran.GetObject(id, OpenMode.ForRead) as Entity;
                                if (ent == null)
                                {
                                    continue;
                                }
                                importObjectIds.Add(id);
                            }
                        }
                    }
                    using (var tr = db.TransactionManager.StartTransaction())
                    {
                        using (var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite, false))
                        {
                            using (var btr = new BlockTableRecord())
                            {
                                btr.Name       = blockName;
                                btr.Explodable = true;
                                bt.Add(btr);
                                tr.AddNewlyCreatedDBObject(btr, true);
                                sourceDb.WblockCloneObjects(importObjectIds, btr.Id, new IdMapping(), DuplicateRecordCloning.Replace, false);
                                foreach (var oid in btr)
                                {
                                    var ent = tr.GetObject(oid, OpenMode.ForWrite) as Entity;
                                    if (ent != null)
                                    {
                                        var mtx = Matrix3d.Displacement(Point3d.Origin - basepoint);
                                        ent.TransformBy(mtx);
                                    }
                                }
                                tr.Commit();
                            }
                        }
                    }
                }
                using (var tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                    using (var ent = new BlockReference(Point3d.Origin, bt[blockName]))
                    {
                        var space = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                        space.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);
                        var jig = new Jig.BlockReferenceJig(ent);
                        if (jig.Run())
                        {
                            ent.ExplodeToOwnerSpace();
                            var e = tr.GetObject(ent.Id, OpenMode.ForWrite);
                            ent.Erase();
                            var b = tr.GetObject(bt[blockName], OpenMode.ForWrite);
                            b.Erase();
                            tr.Commit();
                            result = ent.Position;
                        }
                    }
                }
            }
            return(result);
        }
Beispiel #25
0
        /// <summary>
        /// Вставка блока в чертеж - интерактивная (BlockInsertJig)
        /// </summary>        
        public static ObjectId Insert(string blName, Layers.LayerInfo layer, List<Property> props)
        {
            ObjectId idBlRefInsert = ObjectId.Null;
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            if (doc == null) return ObjectId.Null;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            using (doc.LockDocument())
            using (var t = db.TransactionManager.StartTransaction())
            {
                var bt = t.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                if (!bt.Has(blName))
                {
                    throw new Exception("Блок не определен в чертеже " + blName);
                }

                ObjectId idBlBtr = bt[blName];
                Point3d pt = Point3d.Origin;
                BlockReference br = new BlockReference(pt, idBlBtr);
                br.SetDatabaseDefaults();
                if (layer != null)
                {
                    Layers.LayerExt.CheckLayerState(layer);
                    br.Layer = layer.Name;
                }

                var spaceBtr = (BlockTableRecord)t.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                idBlRefInsert = spaceBtr.AppendEntity(br);
                t.AddNewlyCreatedDBObject(br, true);

                if (props != null && br.IsDynamicBlock)
                {
                    foreach (DynamicBlockReferenceProperty item in br.DynamicBlockReferencePropertyCollection)
                    {
                        var prop = props.FirstOrDefault(p => p.Name.Equals(item.PropertyName, StringComparison.OrdinalIgnoreCase));
                        if (prop != null)
                        {
                            try
                            {
                                item.Value = prop.Value;
                            }
                            catch (Exception ex)
                            {
                                Logger.Log.Error(ex, $"Ошибка типа значения для дин параметра '{item.PropertyName}' " +
                                $"при вставке блока '{blName}': тип устанавливаемого значение '{prop.Value.GetType()}', " +
                                $"а должен быть тип '{item.UnitsType}'");
                            }
                        }
                    }
                }

                // jig
                Jigs.BlockInsertJig entJig = new Jigs.BlockInsertJig(br);
                var pr = ed.Drag(entJig);
                if (pr.Status == PromptStatus.OK)
                {
                    var btrBl = t.GetObject(idBlBtr, OpenMode.ForRead) as BlockTableRecord;
                    if (btrBl.HasAttributeDefinitions)
                        AddAttributes(br, btrBl, t);
                }
                else
                {
                    br.Erase();
                    idBlRefInsert = ObjectId.Null;
                }
                t.Commit();
            }
            return idBlRefInsert;
        }
        private void placementSpots(List<Spot> spots)
        {
            using (var lockdoc = _doc.LockDocument())
            {
                using (var t = _db.TransactionManager.StartTransaction())
                {
                    var bt = t.GetObject(_db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    var cs = t.GetObject(_db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                    _idMS = cs.Id;
                    var btrColorArea = t.GetObject(bt[Settings.Default.BlockColorAreaName], OpenMode.ForRead) as BlockTableRecord;
                    var blRefColorAreaTemplate = new BlockReference(Point3d.Origin, btrColorArea.Id);
                    cs.AppendEntity(blRefColorAreaTemplate);
                    t.AddNewlyCreatedDBObject(blRefColorAreaTemplate, true);
                    _idBlRefColorAreaTemplate = blRefColorAreaTemplate.Id;
                    SetDynParamColorAreaBlock(blRefColorAreaTemplate, _colorAreaSize);
                    using (_idColCopy = new ObjectIdCollection())
                    {
                        _idColCopy.Add(_idBlRefColorAreaTemplate);
                        ProgressMeter progressMeter = new ProgressMeter();
                        progressMeter.SetLimit(spots.Count);
                        progressMeter.Start("Вставка блоков зон покраски...");

                        _countInsertBlocksSpot = 0;
                        foreach (var spot in spots)
                        {
                            progressMeter.MeterProgress();
                            if (HostApplicationServices.Current.UserBreak())
                                break;
                            if (spot != null)
                            {
                                insertSpot(spot, spot.Index / _ysize, spot.Index % _ysize, t);
                            }
                        }
                        progressMeter.Stop();
                    }
                    Logger.Log.Debug("Вставлено блоков {0}", _countInsertBlocksSpot);

                    blRefColorAreaTemplate.Erase(true);
                    t.Commit();
                }
            }
        }
Beispiel #27
0
        //public List<Line> InsectLine(ref Transaction tr, ref BlockTableRecord spaceRecord, ref Line line)
        //{
        //
        //}

        //Carry all.
        public void InspectBlockReference(ref BlockTable bt, ref Transaction tr, ref BlockTableRecord spaceRecord,
                                          ref BlockReference bref, ref List <BlockReference> blocks, ref List <Line> lines, ref HashSet <String> NothingBlocks)
        {
            BlockTableRecord gePostBt      = (BlockTableRecord)tr.GetObject(bt[gePost], OpenMode.ForRead);
            BlockTableRecord geDBLSTUBPost = (BlockTableRecord)tr.GetObject(bt[geDBLSTUD], OpenMode.ForRead);
            BlockTableRecord geTRISTUDPost = (BlockTableRecord)tr.GetObject(bt[geTRISTUD], OpenMode.ForRead);
            List <Point2d>   boundary      = new List <Point2d>();
            bool             isInverted    = false;
            bool             hasBoundary   = false;

            if (bref != null)
            {
                if (!bref.ExtensionDictionary.IsNull)
                {
                    DBDictionary extDict = (DBDictionary)tr.GetObject(bref.ExtensionDictionary, OpenMode.ForRead);
                    if (extDict != null && extDict.Contains(filterDictName))
                    {
                        DBDictionary fildict = (DBDictionary)tr.GetObject(extDict.GetAt(filterDictName), OpenMode.ForRead);
                        if (fildict != null)
                        {
                            if (fildict.Contains(spatialName))
                            {
                                var fil = (SpatialFilter)tr.GetObject(fildict.GetAt(spatialName), OpenMode.ForRead);
                                if (fil != null)
                                {
                                    Extents3d ext = fil.GetQueryBounds();
                                    isInverted = fil.Inverted;
                                    var pts = fil.Definition.GetPoints();

                                    //Matrix3d inverseMatrix = brefMatrix.Inverse();
                                    foreach (var pt in pts)
                                    {
                                        Point3d point3 = new Point3d(pt.X, pt.Y, 0);
                                        point3 = point3.TransformBy(fil.OriginalInverseBlockTransform);
                                        boundary.Add(new Point2d(point3.X, point3.Y));
                                        //ed.WriteMessage("\nBoundary point at {0}", pt);
                                    }
                                }
                            }
                            if (boundary.Count >= 2)
                            {
                                hasBoundary = true;
                            }
                        }
                    }
                }

                BlockTableRecord newBtr = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead);

                foreach (ObjectId id in newBtr)
                {
                    if (id.ObjectClass.DxfName == "INSERT")
                    {
                        BlockReference newBref1 = (BlockReference)tr.GetObject(id, OpenMode.ForRead);
                        Matrix3d       matrix3d = newBref1.BlockTransform;
                        string         brefName = newBref1.IsDynamicBlock ? ((BlockTableRecord)newBref1.DynamicBlockTableRecord.GetObject(OpenMode.ForRead)).Name : newBref1.Name;
                        if (brefName.Split('|').Last() == gePost && !NothingBlocks.Contains(brefName))
                        {
                            BlockReference bref2 = copyDynamicBlock(spaceRecord, ref newBref1, ref gePostBt, tr);
                            if (!hasBoundary || canAdd(isInverted, boundary, bref2.Position))
                            {
                                blocks.Add(bref2);
                            }
                            else
                            {
                                bref2.Erase();
                            }
                        }
                        else if (brefName.Split('|').Last() == geDBLSTUD && !NothingBlocks.Contains(brefName))
                        {
                            BlockReference bref2 = copyDynamicBlock(spaceRecord, ref newBref1, ref geDBLSTUBPost, tr);
                            if (!hasBoundary || canAdd(isInverted, boundary, bref2.Position))
                            {
                                blocks.Add(bref2);
                            }
                            else
                            {
                                bref2.Erase();
                            }
                        }
                        else if (brefName.Split('|').Last() == geTRISTUD && !NothingBlocks.Contains(brefName))
                        {
                            BlockReference bref2 = copyDynamicBlock(spaceRecord, ref newBref1, ref geTRISTUDPost, tr);
                            if (!hasBoundary || canAdd(isInverted, boundary, bref2.Position))
                            {
                                blocks.Add(bref2);
                            }
                            else
                            {
                                bref2.Erase();
                            }
                        }
                        else
                        {
                            List <BlockReference> newObjects = new List <BlockReference>();
                            List <Line>           newLines   = new List <Line>();

                            InspectBlockReference(ref bt, ref tr, ref spaceRecord, ref newBref1, ref newObjects, ref newLines, ref NothingBlocks);

                            if (newObjects.Count == 0 && newLines.Count == 0)
                            {
                                NothingBlocks.Add(brefName);
                            }
                            if (hasBoundary)
                            {
                                foreach (BlockReference nbref in newObjects)
                                {
                                    if (canAdd(isInverted, boundary, nbref.Position))
                                    {
                                        blocks.Add(nbref);
                                    }
                                    else
                                    {
                                        nbref.Erase();
                                    }
                                }
                            }
                            else
                            {
                                blocks.AddRange(newObjects);
                            }
                        }
                    }
                    else if (id.ObjectClass == RXObject.GetClass(typeof(Line)))
                    {
                        Line line = (Line)tr.GetObject(id, OpenMode.ForRead);
                        if (line.Layer.Split('|').Last() == swallLayer)
                        {
                            Line newLine = copyLine(spaceRecord, ref line, tr);
                            if (canAdd(isInverted, boundary, newLine.StartPoint) || canAdd(isInverted, boundary, newLine.EndPoint))
                            {
                                lines.Add(newLine);
                            }
                        }
                    }
                }

                for (int i = 0; i < blocks.Count; i++)
                {
                    blocks[i].TransformBy(bref.BlockTransform);
                }

                for (int i = 0; i < lines.Count; i++)
                {
                    lines[i].TransformBy(bref.BlockTransform);
                }
            }
        }
Beispiel #28
0
        public void BoxJig()
        {
            DateTime first, second;

            CheckLinetype();
            createLayer(frameBlockAboveLayer, 1);
            m_pts.Clear();

            var doc = Application.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;
            var ed  = doc.Editor;

            if (!getSelectedWindow(ref m_pts, ref ed, ref db))
            {
                return;
            }

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

                    List <BlockReference> blocks = new List <BlockReference>();
                    List <Line>           lines  = new List <Line>();
                    List <Polyline>       plines = new List <Polyline>();

                    HashSet <string> NothingBlocks = new HashSet <string>();

                    first = DateTime.Now;
                    //RunCode(rec.firstPoint, rec.secondPoint, tr, ref db, ed, ref blocks, ref lines);
                    RunCode(m_pts, tr, ref db, ed, ref blocks, ref lines, ref plines, ref NothingBlocks);


                    BlockReference bref = createAnonymousBlock(bt, MergeEntity(ref lines, ref plines, ref blocks, btr, tr), btr, tr, db);

                    second = DateTime.Now;
                    ed.WriteMessage(string.Format("\nRun Time: {0}", (second - first).TotalSeconds));

                    bref.Layer = frameBlockAboveLayer;
                    if (blocks.Count != 0 || lines.Count != 0 || plines.Count != 0)
                    {
                        var ppr2 = ed.GetPoint("\nSpecify base point: ");

                        if (ppr2.Status == PromptStatus.OK)
                        {
                            DragBref     dragBref = new DragBref(bref, ppr2.Value);
                            PromptResult result   = ed.Drag(dragBref);
                            if (result.Status == PromptStatus.Cancel)
                            {
                                bref.Erase();
                            }
                        }
                        //foreach (var entity in lines) entity.Erase();
                        //foreach (var entity in plines) entity.Erase();
                        //foreach (var entity in blocks) entity.Erase();
                    }
                    tr.Commit();
                }
            }
        }
Beispiel #29
0
        private void PosUpgrade()
        {
            TypedValue[] tvs = new TypedValue[] {
                new TypedValue((int)DxfCode.Start, "INSERT")
            };
            PromptSelectionResult res = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetSelection(new SelectionFilter(tvs));

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

            string blockName = "POZ_*";

            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // Filter pos blocks
                    List <ObjectId> list = new List <ObjectId>();
                    foreach (ObjectId id in res.Value.GetObjectIds())
                    {
                        if (id.ObjectClass == Autodesk.AutoCAD.Runtime.RXObject.GetClass(typeof(BlockReference)))
                        {
                            BlockReference blockRef = tr.GetObject(id, OpenMode.ForRead) as BlockReference;

                            BlockTableRecord block = null;
                            if (blockRef.IsDynamicBlock)
                            {
                                block = tr.GetObject(blockRef.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
                            }
                            else
                            {
                                block = tr.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
                            }

                            if (block != null)
                            {
                                if (WCMatch(block.Name, blockName))
                                {
                                    list.Add(id);
                                }
                            }
                        }
                    }

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    foreach (ObjectId id in list)
                    {
                        // Read pos block
                        OldPos oldPos = new OldPos(tr, id);

                        // Insert new pos
                        RebarPos pos = new RebarPos();

                        pos.SuspendUpdate();

                        pos.TransformBy(Matrix3d.Displacement(oldPos.insPoint.GetAsVector()));
                        pos.TransformBy(Matrix3d.Scaling(oldPos.scale, oldPos.insPoint));
                        pos.TransformBy(Matrix3d.Rotation(oldPos.rotation, Vector3d.ZAxis, oldPos.insPoint));

                        pos.Pos        = oldPos.pos;
                        pos.Count      = oldPos.count;
                        pos.Diameter   = oldPos.diameter;
                        pos.Spacing    = oldPos.spacing;
                        pos.Shape      = oldPos.shapeName;
                        pos.A          = oldPos.a;
                        pos.B          = oldPos.b;
                        pos.C          = oldPos.c;
                        pos.D          = oldPos.d;
                        pos.E          = oldPos.e;
                        pos.F          = oldPos.f;
                        pos.Multiplier = oldPos.multiplier;
                        pos.Note       = oldPos.note;

                        // Align note text
                        if (oldPos.noteInText)
                        {
                            pos.NoteAlignment = RebarPos.SubTextAlignment.Right;
                        }
                        else if (!oldPos.noteId.IsNull)
                        {
                            pos.NoteGrip = oldPos.notePt;
                        }

                        // Align length text
                        if (oldPos.lengthInText)
                        {
                            pos.LengthAlignment = RebarPos.SubTextAlignment.Right;
                        }
                        else if (!oldPos.lengthId.IsNull)
                        {
                            pos.LengthGrip = oldPos.lengthPt;
                        }

                        pos.Detached = oldPos.detached;
                        if (!oldPos.detached && !oldPos.showLength)
                        {
                            pos.Display = RebarPos.DisplayStyle.WithoutLength;
                        }

                        pos.ResumeUpdate();

                        pos.SetDatabaseDefaults(db);

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

                        // Erase old pos block
                        BlockReference bref = tr.GetObject(id, OpenMode.ForWrite) as BlockReference;
                        bref.Erase();
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message, "RebarPos", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                tr.Commit();
            }
        }
Beispiel #30
0
        /// <summary>
        /// Вставка блока в чертеж - интерактивная (BlockInsertJig)
        /// </summary>
        public static ObjectId Insert(string blName, LayerInfo?layer, List <Property>?props, bool explode = false)
        {
            var doc = Application.DocumentManager.MdiActiveDocument;

            if (doc == null)
            {
                return(ObjectId.Null);
            }
            var db = doc.Database;
            var ed = doc.Editor;

            using var @lock = doc.LockDocument();
            using var t     = db.TransactionManager.StartTransaction();
            var bt = (BlockTable)t.GetObject(db.BlockTableId, OpenMode.ForRead);

            if (!bt.Has(blName))
            {
                throw new Exception("Блок не определен в чертеже " + blName);
            }

            var idBlBtr = bt[blName];
            var pt      = Point3d.Origin;
            var br      = new BlockReference(pt, idBlBtr);

            br.SetDatabaseDefaults();

            if (layer != null)
            {
                layer.CheckLayerState();
                br.Layer = layer.Name;
            }

            var spaceBtr      = (BlockTableRecord)t.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
            var idBlRefInsert = spaceBtr.AppendEntity(br);

            t.AddNewlyCreatedDBObject(br, true);

            if (props != null && br.IsDynamicBlock)
            {
                foreach (DynamicBlockReferenceProperty item in br.DynamicBlockReferencePropertyCollection)
                {
                    var prop = props.FirstOrDefault(p =>
                                                    p.Name.Equals(item.PropertyName, StringComparison.OrdinalIgnoreCase));
                    if (prop != null)
                    {
                        try
                        {
                            item.Value = prop.Value;
                        }
                        catch (Exception ex)
                        {
                            Logger.Log.Error(ex,
                                             msg: $"Ошибка типа значения для дин параметра '{item.PropertyName}' " +
                                             $"при вставке блока '{blName}': тип устанавливаемого значение '{prop.Value.GetType()}', " +
                                             $"а должен быть тип '{item.UnitsType}'");
                        }
                    }
                }
            }

            // jig
            var entJig = new Jigs.BlockInsertJig(br);
            var pr     = ed.Drag(entJig);

            if (pr.Status == PromptStatus.OK)
            {
                var btrBl = (BlockTableRecord)t.GetObject(idBlBtr, OpenMode.ForRead);
                if (btrBl.HasAttributeDefinitions)
                {
                    AddAttributes(br, btrBl, t);
                }
                if (explode)
                {
                    var owner = br.BlockId.GetObject <BlockTableRecord>(OpenMode.ForWrite);
                    using var explodes = new DBObjectCollection();
                    br.Explode(explodes);
                    foreach (Entity ent in explodes)
                    {
                        owner.AppendEntity(ent);
                        t.AddNewlyCreatedDBObject(ent, true);
                        ent.Layer = br.Layer;
                    }

                    br.Erase();
                }
            }
            else
            {
                br.Erase();
                idBlRefInsert = ObjectId.Null;
            }

            t.Commit();

            return(idBlRefInsert);
        }
Beispiel #31
0
        public void _drawGridCartogramma()
        {
            double step = 20d;


            //Polyline3d border = null;

            /*ObjectId surfaceId = CivilSurfaces.SurfaceTools.PromptForTinSurface("\nУкажитье поверхность: ");
             * if (surfaceId.IsNull)
             *  return;
             * Tools.StartTransaction(() =>
             * {
             *  TinSurface surface = surfaceId.GetObjectForRead<CivilSurface>() as TinSurface;
             *  if (surface == null)
             *      return;
             *  var borders = surface.ExtractBorders().Select(l => (Polyline3d)l.Clone());
             *  //borders.SaveToDatebase();
             *  border = borders.First();
             * });*/

            Polyline border;

            if (!ObjectCollector.TrySelectAllowedClassObject(out border))
            {
                return;
            }

            if (border == null)
            {
                return;
            }

            border = border.Id.Open(OpenMode.ForRead).Clone() as Polyline;

            Matrix3d ucs = Tools.GetAcadEditor().CurrentUserCoordinateSystem;

            border.TransformBy(ucs);
            Extents3d bounds = border.Bounds.Value;

            Vector3d hVector = Matrix3d.Identity.CoordinateSystem3d.Xaxis.MultiplyBy((bounds.MaxPoint - bounds.MinPoint).X);
            Vector3d vVector = Matrix3d.Identity.CoordinateSystem3d.Yaxis.MultiplyBy((bounds.MaxPoint - bounds.MinPoint).Y);

            Polyline polygon = border; /*border.ConvertToPolyline();*/

            //((Entity)polygon.Clone()).SaveToDatebase();

            ObjectId btrId = ObjectId.Null;
            ObjectId brId  = ObjectId.Null;

            List <Entity>    rectgs        = null;
            CartogrammLabels labelsFactory = null;

            Action <Point3d> transformProcessor = startPoint =>
            {
                gride         = new SimpleGride(/*bounds.MinPoint*/ startPoint, vVector, hVector, step, step);
                labelsFactory = new CartogrammLabels(gride);

                int rowsCount   = SimpleGride.CalculateCeilingCount(vVector, step);
                int columnCount = SimpleGride.CalculateCeilingCount(hVector, step);

                rectgs = new List <Entity>(rowsCount * columnCount);
                for (int r = 0; r < rowsCount; r++)
                {
                    for (int c = 0; c < columnCount; c++)
                    {
                        Polyline line = gride.CalculateRectagle(r, c, polygon, true);
                        if (line != null)
                        {
                            line.TransformBy(ucs.Inverse());
                            rectgs.Add(line);
                        }

                        /*if (r == 0)
                         * {
                         *  var labels = labelsFactory.CreateTableColumn(c);
                         *  if (labels != null)
                         *      rectgs.AddRange(labels.Select(x => (Polyline)x.GetTransformedCopy(ucs.Inverse())));
                         * }*/
                    }
                }

                labelsFactory.CreateTeble(columnCount);
                for (int i = 0; i < columnCount; i++)
                {
                    labelsFactory.SetValueToField(i, (IgorKL.ACAD3.Model.Helpers.Math.Randoms.RandomGen.NextDouble() - 0.5) * 10000d, labelsFactory.TopRow);
                }

                if (!btrId.IsNull)
                {
                    Tools.StartTransaction(() =>
                    {
                        BlockTableRecord btr = btrId.GetObjectForWrite <BlockTableRecord>();
                        foreach (var id in btr)
                        {
                            Entity ent = id.GetObjectForWrite <DBObject>() as Entity;
                            if (ent != null)
                            {
                                ent.Erase(true);
                            }
                        }
                        BlockReference br = brId.GetObjectForWrite <BlockReference>();
                        br.Erase(true);
                        btr.Erase(true);

                        btrId = AcadBlocks.BlockTools.CreateBlockTableRecord("*U", startPoint.TransformBy(ucs.Inverse()), rectgs.Cast <Entity>(), AnnotativeStates.NotApplicable, false);
                        brId  = AcadBlocks.BlockTools.AppendBlockItem(startPoint.TransformBy(ucs.Inverse()), btrId, null);
                    }
                                           );
                }
            };

            transformProcessor(bounds.MinPoint);

            var points = labelsFactory._getGridElevationPoints(rectgs.Cast <Polyline>()).Select(x => new DBPoint(x));

            points.SaveToDatebase();

            rectgs.AddRange(labelsFactory.Entities.Select(x => x.GetTransformedCopy(ucs.Inverse())));



            btrId = AcadBlocks.BlockTools.CreateBlockTableRecord("*U", bounds.MinPoint.TransformBy(ucs.Inverse()), rectgs.Cast <Entity>(), AnnotativeStates.NotApplicable, false);
            brId  = AcadBlocks.BlockTools.AppendBlockItem(bounds.MinPoint.TransformBy(ucs.Inverse()), btrId, null);



            /*Tools.StartTransaction(() =>
             * {
             *  BlockReference br = brId.GetObjectForWrite<BlockReference>();
             *  CartogrammGride jigGrid = new CartogrammGride(bounds.MinPoint.TransformBy(ucs), br, transformProcessor);
             *  jigGrid.StartJig();
             * });*/


            //rectgs.Cast<Entity>().SaveToDatebase();
        }
        private void FormImage_Fire(object sender, EventArgs e)
        {
            try
            {
                Bitmap bitmap = getBitmapForColorArea((Bitmap)sender);
                using (var lockDoc = _doc.LockDocument())
                {
                    using (var t = _db.TransactionManager.StartTransaction())
                    {
                        // Проверка блока зоны покраски. если нет, то копирование из шаблона с блоками.
                        RandomPaintService.CheckBlockColorAre(_db);

                        clearPreviusBlocks();
                        _idsInsertBlRefColorArea = new List <ObjectId>();

                        // блок шаблона зоны покраски
                        var bt = t.GetObject(_db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        var cs = t.GetObject(_db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                        _idCS = cs.Id;
                        var btrColorArea           = t.GetObject(bt[Settings.Default.BlockColorAreaName], OpenMode.ForRead) as BlockTableRecord;
                        var blRefColorAreaTemplate = new BlockReference(Point3d.Origin, btrColorArea.Id);
                        cs.AppendEntity(blRefColorAreaTemplate);
                        t.AddNewlyCreatedDBObject(blRefColorAreaTemplate, true);
                        _idBlRefColorAreaTemplate = blRefColorAreaTemplate.Id;
                        RandomPaintService.SetDynParamColorAreaBlock(blRefColorAreaTemplate, _colorAreaSize);
                        _idColCopy = new ObjectIdCollection();
                        _idColCopy.Add(_idBlRefColorAreaTemplate);

                        Point3d ptStart = new Point3d(_colorAreaSize.ExtentsColorArea.MinPoint.X, _colorAreaSize.ExtentsColorArea.MaxPoint.Y, 0);
                        _layersColorArea = new Dictionary <Color, ObjectId>();

                        ProgressMeter progressMeter = new ProgressMeter();
                        progressMeter.SetLimit(bitmap.Width * bitmap.Height);
                        progressMeter.Start("Вставка блоков зон покраски");

                        for (int i = 0; i < bitmap.Width * bitmap.Height; i++)
                        {
                            if (HostApplicationServices.Current.UserBreak())
                            {
                                break;
                            }
                            progressMeter.MeterProgress();
                            int     x        = i / bitmap.Height;
                            int     y        = i % bitmap.Height;
                            Point3d position = ptStart.Add(new Vector3d(x * _colorAreaSize.LenghtSpot, -(y + 1) * _colorAreaSize.HeightSpot, 0));
                            insertSpot(position, getLayerId(bitmap.GetPixel(x, y), _layersColorArea));
                        }
                        progressMeter.Stop();
                        blRefColorAreaTemplate.Erase(true);
                        t.Commit();

                        _doc.Editor.Regen();
                        _doc.Editor.WriteMessage("\nГотово");
                    }
                }
            }
            catch (System.Exception ex)
            {
                Logger.Log.Error(ex, "FormImage_Fire()");
            }
        }