Exemplo n.º 1
1
        static public void CreateTunnel()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            Database db  = doc.Database;

            //===========
            Matrix3d           curUCSMatrix = doc.Editor.CurrentUserCoordinateSystem;
            CoordinateSystem3d curUCS       = curUCSMatrix.CoordinateSystem3d;

            double             TunnelDia = 6.04;
            PromptEntityResult per       = ed.GetEntity("Select polylines");
            ObjectId           oid       = per.ObjectId;

            if (per.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);

                    DBObject objPick = tr.GetObject(oid, OpenMode.ForRead);
                    Entity   objEnt  = objPick as Entity;
                    string   sLayer  = objEnt.Layer.ToString();

                    ObjectIdCollection oDBO = CADops.SelectAllPolyline(sLayer);

                    List <string> data = new List <string>();
                    foreach (ObjectId id in oDBO)
                    {
                        //get 3d polyline
                        Polyline3d poly3d = tr.GetObject(id, OpenMode.ForRead) as Polyline3d;

                        //get points on 3d polyline
                        List <Point3d> pts0 = CADops.GetPointsFrom3dPolyline(poly3d, doc);
                        List <Point3d> pts  = pts0.Distinct(new PointComparer(3)).ToList();

                        //get vectors on points
                        List <Vector3d> vectorAlongPath = new List <Vector3d>();
                        List <Vector3d> vectors         = CADops.getVectors(pts, doc, ref vectorAlongPath);

                        List <LoftProfile> loftProfiles = new List <LoftProfile>();
                        for (int i = 0; i < pts.Count(); i = i + 4)
                        {
                            Point3d pt = pts[i];
                            //ed.WriteMessage($"TUN_CreateTBM => {pt.X}, {pt.Y}, {pt.Z}; ");

                            Vector3d v   = vectors[i].GetNormal() * TunnelDia / 2;
                            Matrix3d mat = Matrix3d.Displacement(v);
                            Point3d  npt = pt.TransformBy(mat);

                            //create a 2d line in XY plane
                            Line ln = new Line(npt, pt);

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

                            double ang = ln.Angle; //vectors[i].GetAngleTo(curUCS.Xaxis);
                                                   //ed.WriteMessage($"angle {ang}\n");

                            Region acRegion = new Region();
                            try
                            {
                                using (Circle acCirc = new Circle())
                                {
                                    acCirc.Center = new Point3d(pt.X, pt.Y, pt.Z);
                                    acCirc.Radius = TunnelDia / 2;

                                    acCirc.TransformBy(Matrix3d.Rotation(Angle.angToRad(90), curUCS.Xaxis, acCirc.Center));
                                    acCirc.TransformBy(Matrix3d.Rotation(ang, curUCS.Zaxis, acCirc.Center));

                                    // Add the new object to the block table record and the transaction
                                    btr.AppendEntity(acCirc);
                                    tr.AddNewlyCreatedDBObject(acCirc, true);

                                    DBObjectCollection acDBObjColl = new DBObjectCollection();
                                    acDBObjColl.Add(acCirc);
                                    DBObjectCollection myRegionColl = new DBObjectCollection();
                                    myRegionColl = Region.CreateFromCurves(acDBObjColl);
                                    Region acRegion1 = myRegionColl[0] as Region;
                                    // Add the new object to the block table record and the transaction
                                    btr.AppendEntity(acRegion1);
                                    tr.AddNewlyCreatedDBObject(acRegion1, true);
                                    LoftProfile lp1 = new LoftProfile(acRegion1);
                                    loftProfiles.Add(lp1);
                                }
                            }
                            catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(ex.ToString()); }
                        }

                        LoftProfile[] lps = new LoftProfile[loftProfiles.Count()];
                        for (int i = 0; i < loftProfiles.Count(); i++)
                        {
                            lps[i] = loftProfiles[i];
                        }

                        try
                        {
                            // =========== create loft solid
                            Solid3d sol = new Solid3d();
                            sol.SetDatabaseDefaults();
                            LoftOptions lpOptions = new LoftOptions();
                            //LoftProfile lpGuide = new LoftProfile(acLine);//create loft profile
                            //LoftProfile[] guideToLoft = new LoftProfile[1] { lpGuide };
                            //sol.CreateLoftedSolid(lps, guideToLoft, null, lpOptions);//guide to loft can not be null, this parameter is not optional
                            sol.CreateLoftedSolid(lps, null, null, lpOptions);
                            sol.Layer = sLayer;//assign layer

                            //=============save it into database
                            Autodesk.AutoCAD.DatabaseServices.Entity ent = sol;//this is created for using hyperlink
                            btr.AppendEntity(ent);
                            tr.AddNewlyCreatedDBObject(ent, true);
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(ex.ToString()); }
                    }

                    tr.Commit();
                }
            }
        }
Exemplo n.º 2
0
 public List<Point3d> pointOffset(Point3d point1, Point3d point2,double offset)
 {
     Line line = new Line(point1,point2);
     List<Point3d> returnList = new List<Point3d>();
     DBObjectCollection offsetLine = new DBObjectCollection();
     try
     {
         offsetLine = line.GetOffsetCurves(offset);
     }
     catch
     {
         offsetLine.Add(new Line(point1, point2));
     }
     if(offsetLine.Count == 1)
     {
         Line oLine = offsetLine[0] as Line;
         returnList.Add(oLine.StartPoint);
         returnList.Add(new LineSegment3d(oLine.StartPoint, oLine.EndPoint).MidPoint);
         returnList.Add(oLine.EndPoint);
         line.Dispose();
         oLine.Dispose();
         return returnList;
     }
     else
     {
         line.Dispose();
         return null;
     }
 }
Exemplo n.º 3
0
        private void Create_strz5()
        {
            string blockName = "strz5";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Line ent1 = new Line(new Point3d(-0.043, 0.043, 0), new Point3d(0.043, -0.043, 0));
            ent1.Layer = "0";
            entityCollection.Add(ent1);

            Line ent2 = new Line(new Point3d(0.095, 0, 0), new Point3d(-0.095, 0, 0));
            ent2.Layer = "0";
            entityCollection.Add(ent2);

            Circle ent3 = new Circle(new Point3d(0, 0, 0), new Vector3d(0, 0, 1), 0.015);
            ent3.Layer = "0";
            entityCollection.Add(ent3);

            TryInsertBlockRecord(blockName, entityCollection);
        }
Exemplo n.º 4
0
        private void Create_ACMark()
        {
            LayerManager lm = new LayerManager();
            string layerName = lm.GetACMarkLayerCreateIfDoesntExists();
            string blockName = "ACMark";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Circle ent1 = new Circle(new Point3d(0, 0, 0), new Vector3d(0, 0, 1), 0.2);
            ent1.Layer = layerName;
            ent1.Color = Color.FromColorIndex(ColorMethod.ByColor, 1);
            entityCollection.Add(ent1);

            Line ent2 = new Line(new Point3d(-0.200, -0.200, 0), new Point3d(0.200, 0.200, 0));
            ent2.Layer = layerName;
            ent2.Color = Color.FromColorIndex(ColorMethod.ByColor, 1);
            entityCollection.Add(ent2);

            Line ent3 = new Line(new Point3d(-0.200, 0.200, 0), new Point3d(0.200, -0.200, 0));
            ent3.Layer = layerName;
            ent3.Color = Color.FromColorIndex(ColorMethod.ByColor, 1);
            entityCollection.Add(ent3);

            TryInsertBlockRecord(blockName, entityCollection);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Gets the centroid of the closed planar spline.
 /// </summary>
 /// <param name="spl">The instance to which the method applies.</param>
 /// <returns>The centroid of the spline (WCS coordinates).</returns>
 /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">
 /// eNonPlanarEntity is thrown if the Spline is not planar.</exception>
 /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">
 /// eNotApplicable is thrown if the Spline is not closed.</exception>
 public static Point3d Centroid(this Spline spl)
 {
     if (!spl.IsPlanar)
         throw new AcRx.Exception(AcRx.ErrorStatus.NonPlanarEntity);
     if (spl.Closed != true)
         throw new AcRx.Exception(AcRx.ErrorStatus.NotApplicable);
     using (DBObjectCollection curves = new DBObjectCollection())
     {
         curves.Add(spl);
         using (DBObjectCollection dboc = Region.CreateFromCurves(curves))
         {
             return ((Region)dboc[0]).Centroid();
         }
     }
 }
 public override void Explode(Entity entity, DBObjectCollection entitySet)
 {
    Curve curve = entity as Curve;
    if (curve != null)
    {
       Isoline isoline = new Isoline(curve);
       if (isoline.IsIsoline)
       {
          var lines = isoline.GetLines(curve);
          foreach (var line in lines)
          {
             entitySet.Add(line);
          }
          //isoline.Activate(false); fatal
          Isoline.RemoveXData(entity);
       }
    }
    if (entity is Line)
    {
       entitySet.Add((DBObject)entity.Clone());
       return;
    }
    base.Explode(entity, entitySet);
 }
Exemplo n.º 7
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;
        }
Exemplo n.º 8
0
 /// <summary>
 /// Gets the centroid of the closed planar spline.
 /// </summary>
 /// <param name="spl">The instance to which the method applies.</param>
 /// <returns>The centroid of the spline (WCS coordinates).</returns>
 /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">
 /// eNonPlanarEntity is thrown if the Spline is not planar.</exception>
 /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">
 /// eNotApplicable is thrown if the Spline is not closed.</exception>
 public static Point3d Centroid(this Spline spl)
 {
     if (!spl.IsPlanar)
     {
         throw new AcRx.Exception(AcRx.ErrorStatus.NonPlanarEntity);
     }
     if (spl.Closed != true)
     {
         throw new AcRx.Exception(AcRx.ErrorStatus.NotApplicable);
     }
     using (DBObjectCollection curves = new DBObjectCollection())
     {
         curves.Add(spl);
         using (DBObjectCollection dboc = Region.CreateFromCurves(curves))
         {
             return(((Region)dboc[0]).Centroid());
         }
     }
 }
Exemplo n.º 9
0
        public static ObjectId CreateFromCurve(Curve poly)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                // Open the Block table for read
                BlockTable acBlkTbl;
                acBlkTbl = tr.GetObject(doc.Database.BlockTableId,
                                        OpenMode.ForRead) as BlockTable;

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


                //Curve poly = tr.GetObject(polyId, OpenMode.ForRead) as Curve;
                DBObjectCollection objColl = new DBObjectCollection();
                objColl.Add(poly);

                DBObjectCollection myRegionColl = new DBObjectCollection();
                Autodesk.AutoCAD.DatabaseServices.Region objreg = new Autodesk.AutoCAD.DatabaseServices.Region();
                DBObjectCollection objRegions = new DBObjectCollection();
                try
                {
                    objRegions = Autodesk.AutoCAD.DatabaseServices.Region.CreateFromCurves(objColl);
                    objreg     = objRegions[0] as Autodesk.AutoCAD.DatabaseServices.Region;

                    acBlkTblRec.AppendEntity(objreg);
                    tr.AddNewlyCreatedDBObject(objreg, true);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    // eInvalidInput exception
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Error: unable to create region collection:\n" + ex.Message);
                }

                tr.Commit();
                return(objreg.ObjectId);
            }
        }
Exemplo n.º 10
0
            public ObjectId createTextGroup(ObjectIdCollection texts)
            {
                DBObjectCollection DbTexts = new DBObjectCollection();

                foreach (ObjectId txt in texts)
                {
                    DBText text = tr.openObject(txt, OpenMode.ForWrite) as DBText;
                    text.Erase(true);

                    DBText nTxt = new DBText();
                    nTxt.Justify        = text.Justify;
                    nTxt.Height         = text.Height;
                    nTxt.TextString     = text.TextString;
                    nTxt.Rotation       = text.Rotation;
                    nTxt.AlignmentPoint = text.AlignmentPoint;
                    tr.closeObject();
                    DbTexts.Add(nTxt);
                }
                return(tr.addGroup(GUID, DbTexts, false));
            }
Exemplo n.º 11
0
        public DBObjectCollection GetBlockTableRecordSpaceCollection(Document acDoc, Transaction acTrans)
        {
            Database           acCurDb            = acDoc.Database;
            BlockTable         acBlkTbl           = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
            DBObjectCollection acBlkTblRecSpcColl = new DBObjectCollection();

            foreach (ObjectId acObj in acBlkTbl)
            {
                DBObject acDbObj = acTrans.GetObject(acObj, OpenMode.ForRead);
                if (acDbObj is BlockTableRecord)
                {
                    BlockTableRecord acBlkTblRec = (BlockTableRecord)acDbObj;
                    if (acBlkTblRec.IsLayout)
                    {
                        acBlkTblRecSpcColl.Add(acBlkTblRec);
                    }
                }
            }
            return(acBlkTblRecSpcColl);
        }
Exemplo n.º 12
0
        public static DBObjectCollection GetCurrentDatabaseLayerEntities(string layerKey)
        {
            var db       = Application.DocumentManager.MdiActiveDocument.Database;
            var entities = new DBObjectCollection();

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                var lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead);

                if (!lt.Has(layerKey))
                {
                    return(entities);
                }

                var blockTable = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                var modelSpace = (BlockTableRecord)trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                foreach (ObjectId id in modelSpace)
                {
                    // if the id is not a valid,ignore.
                    if (!id.IsValid)
                    {
                        continue;
                    }

                    var entity = trans.GetObject(id, OpenMode.ForRead) as Entity;
                    if (entity == null)
                    {
                        continue;
                    }
                    if (entity.Layer == layerKey)
                    {
                        entities.Add(entity);
                    }
                }

                trans.Commit();
            }

            return(entities);
        }
Exemplo n.º 13
0
        private DBObjectCollection SquareOfLines(double size)
        {
            // A function to generate a set of entities for our block

            DBObjectCollection ents = new DBObjectCollection();

            Point3d[] pts =
            { new Point3d(-size,     -size, 0),
              new Point3d(size,  -size, 0),
              new Point3d(size,  size,  0),
              new Point3d(-size, size, 0) };
            int max = pts.GetUpperBound(0);

            for (int i = 0; i <= max; i++)
            {
                int  j  = (i == max ? 0 : i + 1);
                Line ln = new Line(pts[i], pts[j]);
                ents.Add(ln);
            }
            return(ents);
        }
Exemplo n.º 14
0
        public static void SolidJig()
        {
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = ed.Document.Database;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    JigPline          jig = new JigPline();
                    Point3dCollection pts;
                    PromptResult      res = jig.DragMe(out pts);
                    if (res.Status == PromptStatus.OK)
                    {
                        BlockTableRecord   btr   = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                        Polyline3d         pLine = new Polyline3d(Poly3dType.SimplePoly, pts, true);
                        DBObjectCollection dbObj = new DBObjectCollection();
                        dbObj.Add(pLine);
                        Region region = Region.CreateFromCurves(dbObj)[0] as Region;
                        btr.AppendEntity(region);
                        tr.AddNewlyCreatedDBObject(region, true);
                        Solid3d solid = new Solid3d();
                        btr.AppendEntity(solid);
                        tr.AddNewlyCreatedDBObject(solid, true);
                        JigSolid solJig = new JigSolid(solid, ed.CurrentUserCoordinateSystem, region, pts[0]);
                        btr.AppendEntity(pLine);
                        tr.AddNewlyCreatedDBObject(pLine, true);
                        res = ed.Drag(solJig);
                        switch (res.Status)
                        {
                        case PromptStatus.OK:

                            break;
                        }
                    }
                    tr.Commit();
                }
            }
            catch { }
        }
Exemplo n.º 15
0
        private DBObjectCollection GetSelection(FilterType[] tps)
        {
            Document               doc              = Application.DocumentManager.MdiActiveDocument;
            Database               db               = doc.Database;
            Editor                 ed               = doc.Editor;
            Entity                 entity           = null;
            DBObjectCollection     entityCollection = new DBObjectCollection();
            PromptSelectionOptions selops           = new PromptSelectionOptions();

            //建立选择的过滤器内容
            TypedValue[] filList = new TypedValue[tps.Length + 2];
            filList[0] = new TypedValue((int)DxfCode.Operator, "<or");
            filList[tps.Length + 1] = new TypedValue((int)DxfCode.Operator, ">or");
            for (int i = 0; i < tps.Length; i++)
            {
                filList[i + 1] = new TypedValue((int)DxfCode.Start, tps[i].ToString());
            }

            //建立过滤器
            SelectionFilter       filter = new SelectionFilter(filList);
            PromptSelectionResult ents   = ed.GetSelection(selops, filter);

            if (ents.Status == PromptStatus.OK)
            {
                using (Transaction transaction = db.TransactionManager.StartTransaction())
                {
                    SelectionSet SS = ents.Value;
                    foreach (ObjectId id in SS.GetObjectIds())
                    {
                        entity = (Entity)transaction.GetObject(id, OpenMode.ForWrite, true);
                        if (entity != null)
                        {
                            entityCollection.Add(entity);
                        }
                    }
                    transaction.Commit();
                }
            }
            return(entityCollection);
        }
Exemplo n.º 16
0
        public static DBObjectCollection IntersectSurf(Autodesk.AutoCAD.DatabaseServices.Surface surf1, Autodesk.AutoCAD.DatabaseServices.Surface surf2)
        {
            Brep surfBrep1 = new Brep(surf1);
            Brep surfBrep2 = new Brep(surf2);
            SurfaceSurfaceIntersector ssi = new SurfaceSurfaceIntersector();

            DBObjectCollection dboCol = new DBObjectCollection();

            foreach (Autodesk.AutoCAD.BoundaryRepresentation.Face fc1 in surfBrep1.Faces)
            {
                ExternalBoundedSurface[]          ebSurfs1 = fc1.GetSurfaceAsTrimmedNurbs();
                Autodesk.AutoCAD.Geometry.Surface sur1     = ebSurfs1[0];
                foreach (Autodesk.AutoCAD.BoundaryRepresentation.Face fc2 in surfBrep2.Faces)
                {
                    ExternalBoundedSurface[]          ebSurfs2 = fc2.GetSurfaceAsTrimmedNurbs();
                    Autodesk.AutoCAD.Geometry.Surface sur2     = ebSurfs2[0];

                    ssi.Set(sur1, sur2);
                    if (ssi.NumResults < 1)
                    {
                        break;
                    }

                    for (int i = 0; i < ssi.NumResults; i++)
                    {
                        Curve3d c3d = ssi.IntersectCurve(i, true);
                        Curve   crv = GenCurve(c3d);
                        crv.SetDatabaseDefaults();
                        crv.Color = Color.FromRgb(255, 255, 255);
                        dboCol.Add(crv);

                        ////adding for now need instead to conver to single Spline
                        //BlockTableRecord btr = (BlockTableRecord)(trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite));
                        //btr.AppendEntity(crv);
                        //trans.AddNewlyCreatedDBObject(crv, true);
                    }
                }
            }
            return(dboCol);
        }
Exemplo n.º 17
0
        public static void ExplodeSolid()
        {
            Database workingDatabase = HostApplicationServices.WorkingDatabase;
            Editor   editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            try
            {
                //LicenseManager.CheckValid("FULL");
                TypedValue[] array = new TypedValue[]
                {
                    new TypedValue(0, "3DSOLID")
                };
                PromptSelectionOptions promptSelectionOptions = new PromptSelectionOptions();
                promptSelectionOptions.MessageForAdding = ("Select 3d solids");
                PromptSelectionResult selection = editor.GetSelection(promptSelectionOptions, new SelectionFilter(array));
                if (selection.Status == (PromptStatus)5100)
                {
                    ObjectId[]         objectIds          = selection.Value.GetObjectIds();
                    DBObjectCollection dBObjectCollection = new DBObjectCollection();
                    using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                    {
                        for (int i = 0; i < objectIds.Length; i++)
                        {
                            dBObjectCollection.Add(transaction.GetObject(objectIds[i], (OpenMode)0));
                        }
                    }
                    DBObjectCollection dBObjectCollection2 = new DBObjectCollection();
                    Tesselation.smethod_0(dBObjectCollection, ref dBObjectCollection2);
                    editor.WriteMessage("\nElements: " + dBObjectCollection2.Count);
                }
            }
            catch (System.Exception ex)
            {
                editor.WriteMessage("\nException during traversal: {0}", new object[]
                {
                    ex.ToString()
                });
            }
        }
Exemplo n.º 18
0
        public static Region CreateRegion1(Polyline pl)
        {
            DBObjectCollection dbc = new DBObjectCollection();

            if (pl != null)
            {
                dbc.Add(pl);
            }
            else
            {
                return(null);
            }
            try
            {
                DBObjectCollection res = Autodesk.AutoCAD.DatabaseServices.Region.CreateFromCurves(dbc);
                return((Region)res[0]);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 19
0
        private DBObjectCollection SquareOfLines(double size)
        {
            DBObjectCollection ents = new DBObjectCollection();

            AcadGeo.Point3d[] pts =
            {
                new AcadGeo.Point3d(-size, -size, 0),
                new AcadGeo.Point3d(size,  -size, 0),
                new AcadGeo.Point3d(size,  size,  0),
                new AcadGeo.Point3d(-size, size, 0)
            };

            int max = pts.GetUpperBound(0);

            for (int i = 0; i <= max; i++)
            {
                int  j  = (i == max ? 0 : i + 1);
                Line ln = new Line(pts[i], pts[j]);
                ents.Add(ln);
            }
            return(ents);
        }
Exemplo n.º 20
0
        public override void Explode(Entity e, DBObjectCollection objs)
        {
            double radius = 0.0;

            if (e is DBObject)
            {
                radius = PipeDrawOverrule.PipeRadiusForObject(e);
            }

            if (radius > 0.0)
            {
                Circle circle = e as Circle;

                if (circle != null)
                {
                    // Needed to avoid ill-formed swept surface

                    if (circle.Radius > radius)
                    {
                        // Draw a pipe around the cirle

                        Vector3d normal =
                            (circle.Center - circle.StartPoint).
                            CrossProduct(circle.Normal);
                        Circle clr =
                            new Circle(
                                circle.StartPoint, normal, radius
                                );
                        SweptSurface pipe = new SweptSurface();
                        pipe.CreateSweptSurface(clr, circle, sweepOpts);
                        clr.Dispose();
                        objs.Add(pipe);
                    }
                    return;
                }
            }
            base.Explode(e, objs);
        }
Exemplo n.º 21
0
        internal static void smethod_0(DBObjectCollection dbobjectCollection_0, ref DBObjectCollection dbobjectCollection_1)
        {
            Editor arg_0F_0 = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            foreach (DBObject dBObject in dbobjectCollection_0)
            {
                Entity             entity             = (Entity)dBObject;
                DBObjectCollection dBObjectCollection = new DBObjectCollection();
                try
                {
                    entity.Explode(dBObjectCollection);
                    Tesselation.smethod_0(dBObjectCollection, ref dbobjectCollection_1);
                }
                catch
                {
                    dbobjectCollection_1.Add(dBObject);
                }
                finally
                {
                    dBObject.Dispose();
                }
            }
        }
Exemplo n.º 22
0
        public static DBObjectCollection GetBlockTableRecordSpaceCollection(Document acDoc)
        {
            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                BlockTable         acBlkTbl           = (BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);
                DBObjectCollection acBlkTblRecSpcColl = new DBObjectCollection();
                foreach (ObjectId acObj in acBlkTbl)
                {
                    DBObject acDbObj = acTrans.GetObject(acObj, OpenMode.ForRead);
                    if (acDbObj is BlockTableRecord)
                    {
                        BlockTableRecord acBlkTblRec = (BlockTableRecord)acDbObj;
                        if (acBlkTblRec.Name.Contains("Space"))
                        {
                            acBlkTblRecSpcColl.Add(acBlkTblRec);
                        }
                    }
                }
                return(acBlkTblRecSpcColl);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// 选择所有对象
        /// </summary>
        /// <returns></returns>
        public static DBObjectCollection selectAll()
        {
            Entity                entity;
            DBObjectCollection    EntityCollection = new DBObjectCollection();
            PromptSelectionResult ents             = ed.SelectAll();

            if (ents.Status == PromptStatus.OK)
            {
                using (Transaction trans = db.TransactionManager.StartTransaction()){
                    SelectionSet ss = ents.Value;
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        entity = trans.GetObject(id, OpenMode.ForWrite, true) as Entity;
                        if (entity != null)
                        {
                            EntityCollection.Add(entity);
                        }
                    }
                    trans.Commit();
                }
            }
            return(EntityCollection);
        }
Exemplo n.º 24
0
        public virtual DBObjectCollection DrawRings(Shrinkage shrinkage, double StartDepth, double Step)
        {
            DBObjectCollection collection = new DBObjectCollection();

            bool   next         = true;
            double currentDepth = StartDepth;

            while (next)
            {
                Circle acCirc = DrawShape(currentDepth, shrinkage) as Circle;
                if (acCirc != null)
                {
                    collection.Add(acCirc);
                }
                else
                {
                    next = false;
                }

                currentDepth = currentDepth + Step;
            }

            return(collection);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 过滤选择在窗口区域中的对象
        /// </summary>
        /// <param name="pt1">窗口角点1</param>
        /// <param name="pt2">窗口角点2</param>
        /// <param name="tps">类型过滤集合</param>
        /// <returns></returns>
        public static DBObjectCollection SelectCrossingWindow(Point3d pt1, Point3d pt2, FilterType[] tps)
        {
            Database db     = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            Editor   ed     = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Entity   entity = null;

            // 建立选择的过滤器内容
            TypedValue[] filList = new TypedValue[tps.Length + 2];
            filList[0] = new TypedValue((int)DxfCode.Operator, "<or");
            filList[tps.Length + 1] = new TypedValue((int)DxfCode.Operator, "or>");
            for (int i = 0; i < tps.Length; i++)
            {
                filList[i + 1] = new TypedValue((int)DxfCode.Start, tps[i].ToString());
            }
            SelectionFilter       filter           = new SelectionFilter(filList);
            DBObjectCollection    EntityCollection = new DBObjectCollection();
            PromptSelectionResult ents             = ed.SelectCrossingWindow(pt1, pt2, filter);

            if (ents.Status == PromptStatus.OK)
            {
                using (Transaction transaction = db.TransactionManager.StartTransaction())
                {
                    SelectionSet ss = ents.Value;
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        entity = transaction.GetObject(id, OpenMode.ForWrite, true) as Entity;
                        if (entity != null)
                        {
                            EntityCollection.Add(entity);
                        }
                    }
                    transaction.Commit();
                }
            }
            return(EntityCollection);
        }
Exemplo n.º 26
0
        public DBObjectCollection GetEntityCollection(PromptSelectionResult ents)
        {
            Database           db               = HostApplicationServices.WorkingDatabase;
            Entity             entity           = null;
            DBObjectCollection EntityCollection = new DBObjectCollection();

            if (ents.Status == PromptStatus.OK)
            {
                using (Transaction transaction = db.TransactionManager.StartTransaction())
                {
                    SelectionSet ss = ents.Value;
                    foreach (ObjectId id in ss.GetObjectIds())
                    {
                        entity = transaction.GetObject(id, OpenMode.ForWrite, true) as Entity;
                        if (entity != null)
                        {
                            EntityCollection.Add(entity);
                        }
                    }
                    transaction.Commit();
                }
            }
            return(EntityCollection);
        }
Exemplo n.º 27
0
        // draw the 3-D drawing
        // nFlag: dimension control
        private void DrawSolidProfile(Plate pl, Point3d p0, int nFlag)
        {
            // Create Container for the curve, the region (face)
            DBObjectCollection curves = new DBObjectCollection();
            // - Collection for the regions
            DBObjectCollection regions = new DBObjectCollection();

            // Solid3d objects
            Solid3d plateSolid = new Solid3d();
            Solid3d rectHole   = new Solid3d();            // Rectangular Hole in the Center

            Point3d[] pt = new Point3d[26];                // geometry helpers
            Line[]    ln = new Line[26];                   // database objects

            // create points
            pt[0]  = p0;
            pt[1]  = new Point3d(p0.X + (pl.dW - pl.R1), p0.Y, p0.Z);
            pt[2]  = new Point3d(p0.X + pl.dW, pl.R1, p0.Z);
            pt[3]  = new Point3d(pt[1].X, pt[2].Y, p0.Z);
            pt[4]  = new Point3d(pt[3].X, pt[3].Y + pl.L9, p0.Z);
            pt[5]  = new Point3d(pt[4].X + pl.L2, pt[4].Y + pl.L8, p0.Z);
            pt[6]  = new Point3d(pt[5].X, pt[5].Y + pl.L7, p0.Z);
            pt[7]  = new Point3d(pt[4].X, pt[6].Y + pl.L6, p0.Z);
            pt[8]  = new Point3d(pt[7].X, pt[7].Y + pl.L5, p0.Z);
            pt[9]  = new Point3d(p0.X + pl.L3, pt[8].Y + pl.L4, p0.Z);
            pt[10] = new Point3d(p0.X, pt[9].Y, p0.Z);

            // symmetry - create points on negative x-axis
            int k = 9;

            for (int i = 11; i < 20; i++)
            {
                pt[i] = new Point3d(-pt[k].X, pt[k].Y, pt[k].Z);
                k--;
            }

            // create lines and store them into the database
            for (int i = 0; i < 20; i++)
            {
                if (i != 1 & i != 18)
                {
                    ln[i]            = new Line(pt[i], pt[(i + 1)]);
                    ln[i].ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(ln[i]);
                }
                else if (i == 1)
                {
                    double st_angle0  = 270 * (Math.PI / 180);
                    double end_angle0 = 0;

                    Arc a0 = new Arc(pt[3], pl.R1, st_angle0, end_angle0);
                    a0.ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(a0);
                }
                else if (i == 18)
                {
                    double st_angle1  = 180 * (Math.PI / 180);
                    double end_angle1 = 270 * (Math.PI / 180);

                    Arc a1 = new Arc(pt[17], pl.R1, st_angle1, end_angle1);
                    a1.ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(a1);
                }
                else
                {
                    continue;
                }
            }

            // Create the Region from the curves
            regions = Region.CreateFromCurves(curves);
            plateSolid.ColorIndex = pl.nColor[CONTOUR];

            // Create the plate without the hole
            plateSolid.Extrude((Region)regions[0], pl.dT, 0.0);

            // draw points for centre hole
            curves.Clear();

            pt[20] = new Point3d(p0.X + pl.R2, pt[3].Y + pl.R2, 0.0);
            pt[21] = new Point3d(pt[20].X, pt[7].Y - pl.R2, 0.0);
            pt[22] = new Point3d(-pt[20].X, pt[7].Y - pl.R2, 0.0);
            pt[23] = new Point3d(-(p0.X + pl.R2), pt[3].Y + pl.R2, 0.0);
            pt[24] = new Point3d(p0.X, pt[20].Y, 0.0);
            pt[25] = new Point3d(p0.X, pt[21].Y, 0.0);

            // draw lines for centre hole
            for (int i = 20; i < 24; i++)
            {
                if (i != 21 & i != 23)
                {
                    ln[i]            = new Line(pt[i], pt[(i + 1)]);
                    ln[i].ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(ln[i]);
                }
                else if (i == 21)
                {
                    double st_angle2  = 0;
                    double end_angle2 = 180 * (Math.PI / 180);

                    Arc a2 = new Arc(pt[25], pl.R2, st_angle2, end_angle2);
                    a2.ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(a2);
                }
                else if (i == 23)
                {
                    double st_angle3  = 180 * (Math.PI / 180);
                    double end_angle3 = 0;

                    Arc a3 = new Arc(pt[24], pl.R2, st_angle3, end_angle3);
                    a3.ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(a3);
                }
                else
                {
                    continue;
                }
            }

            // Create the Region from the curves (Rectangular Hole)
            regions = Region.CreateFromCurves(curves);
            rectHole.Extrude((Region)regions[0], pl.dT, 0.0);
            rectHole.ColorIndex = pl.nColor[HIDDEN];

            // Substract the Hole Solid from the Rectangle
            plateSolid.BooleanOperation(BooleanOperationType.BoolSubtract, rectHole);

            // Add Solids into the Database
            AcTrans.Add(plateSolid);
        }
Exemplo n.º 28
0
        public static DBObjectCollection GetFirstRow(FilterType[] filter)
        {
            Document               doc              = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database               db               = doc.Database;
            Editor                 ed               = doc.Editor;
            Entity                 entity           = null;
            DBObjectCollection     entityCollection = new DBObjectCollection();
            PromptSelectionOptions selops           = new PromptSelectionOptions();

            //建立选择的过滤器内容
            TypedValue[] filList = new TypedValue[filter.Length + 2];
            filList[0] = new TypedValue((int)DxfCode.Operator, "<or");
            filList[filter.Length + 1] = new TypedValue((int)DxfCode.Operator, "or>");
            for (int i = 0; i < filter.Length; i++)
            {
                filList[i + 1] = new TypedValue((int)DxfCode.Start, filter[i].ToString());
            }
            //建立过滤器
            SelectionFilter f = new SelectionFilter(filList);
            //按照过滤器进行选择
            PromptSelectionResult ents = ed.GetSelection(selops, f);

            if (ents.Status == PromptStatus.OK)
            {
                using (Transaction transaction = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        SelectionSet SS = ents.Value;
                        foreach (ObjectId id in SS.GetObjectIds())
                        {
                            entity = (Entity)transaction.GetObject(id, OpenMode.ForWrite, true);
                            if (entity != null)
                            {
                                entityCollection.Add(entity);
                                DBText ddd = entity as DBText;
                                //ed.WriteMessage(ddd.TextString + entity.ObjectId.ToString() + "\n");
                            }
                        }
                        transaction.Commit();
                    }
                    catch
                    {
                        ed.WriteMessage("Error ");
                    }
                    finally
                    {
                        transaction.Dispose();
                    }
                }
            }
            //目前entityCollection中的文字是按照ObjectId的大小排序的,如果出现Id大的在Id小的左边,就出现写入文字错位。
            //对entityCollection中的文字进行排序,按照Point.X从大到小(后面导入文字时使用的foreach在本程序体现出来的是倒序)的顺序排序。防止写入文字是错位。
            DBObjectCollection entityCollection1 = new DBObjectCollection();
            DBText             k1    = null;
            DBText             k2    = null;
            Entity             temp1 = null;

            for (int ii = 0; ii < entityCollection.Count - 1; ii++)
            {
                for (int jj = 0; jj < entityCollection.Count - 1 - ii; jj++)
                {
                    k1 = entityCollection[jj] as DBText;
                    k2 = entityCollection[jj + 1] as DBText;
                    if (k1.Position.X < k2.Position.X)
                    {
                        temp1 = entityCollection[jj + 1] as Entity;
                        entityCollection[jj + 1] = entityCollection[jj];
                        entityCollection[jj]     = temp1;
                    }
                }
            }
            return(entityCollection);
        }
Exemplo n.º 29
0
        public void zselect()
        {
            //Excel.Application app;
            //Excel.Workbook wbk;
            //Excel.Worksheet wsh;
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            ed.WriteMessage("请选取矩形\n");
            //Autodesk.AutoCAD.Interop.AcadApplication AcadApp = (Autodesk.AutoCAD.Interop.AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
            //Autodesk.AutoCAD.Interop.AcadDocument acaddoc = AcadApp.ActiveDocument;
            Entity entity = null;

            FilterType[] filter = new FilterType[1];
            //选取矩形之过滤条件
            filter[0] = FilterType.LWPolyline;
            //设置矩形框选中的表格的直线之过滤条件
            TypedValue[] tv = new TypedValue[1];
            tv.SetValue(new TypedValue((int)DxfCode.Start, "Line,LWPolyline"), 0);
            SelectionFilter sf = new SelectionFilter(tv);

            //设置矩形框选中的表格中文字之过滤条件
            TypedValue[] tv1 = new TypedValue[1];
            tv1.SetValue(new TypedValue((int)DxfCode.Start, "Text"), 0);
            SelectionFilter sf1 = new SelectionFilter(tv1);

            //形框选中的表格
            try
            {
                Dictionary <ObjectId, Entity> rectangleDic = GetRectangle(filter);
                //获取选中了的矩形
                Dictionary <ObjectId, Entity> .ValueCollection valcollect = rectangleDic.Values;
                DBObjectCollection rectangleCollection = new DBObjectCollection();
                //为每个矩形框中的内容生成表格
                List <midTable> tables = new List <midTable>();
                foreach (Entity ent in valcollect)
                {
                    rectangleCollection.Add(ent);
                }
                int count = rectangleCollection.Count;
                //可同时计算多个矩形框选中的表格
                for (int i = 0; i < count; i++)
                {
                    #region 获取计算表格单元格
                    int j = i + 1;
                    ed.WriteMessage("\n第" + j + "个矩形选择:\n");
                    Polyline          pl  = rectangleCollection[i] as Polyline;
                    Point3dCollection p3d = new Point3dCollection();
                    //ed.WriteMessage("\n1:" + pl.GetPoint3dAt(0).X + "  " + pl.GetPoint3dAt(0).Y);
                    //ed.WriteMessage("\n2:" + pl.GetPoint3dAt(1).X + "  " + pl.GetPoint3dAt(1).Y);
                    //ed.WriteMessage("\n3:" + pl.GetPoint3dAt(2).X + "  " + pl.GetPoint3dAt(2).Y);
                    //ed.WriteMessage("\n4:" + pl.GetPoint3dAt(3).X + "  " + pl.GetPoint3dAt(3).Y);
                    p3d.Add(pl.GetPoint3dAt(0));
                    p3d.Add(pl.GetPoint3dAt(1));
                    p3d.Add(pl.GetPoint3dAt(2));
                    p3d.Add(pl.GetPoint3dAt(3));
                    //获取选中的矩形框选选中的直线
                    DBObjectCollection    lineCollection = new DBObjectCollection();
                    PromptSelectionResult ents           = ed.SelectCrossingPolygon(p3d, sf);
                    if (ents.Status == PromptStatus.OK)
                    {
                        using (Transaction transaction = db.TransactionManager.StartTransaction())
                        {
                            SelectionSet SS = ents.Value;
                            foreach (ObjectId id in SS.GetObjectIds())
                            {
                                entity = (Entity)transaction.GetObject(id, OpenMode.ForRead, true);
                                //SelectCrossingPolygon()会把框选用的矩形也包含
                                //要把这个矩形排除掉
                                bool isContain = rectangleDic.ContainsKey(id);
                                if (entity != null && !isContain)
                                {
                                    lineCollection.Add(entity);
                                    //ed.WriteMessage(entity.GetRXClass().DxfName + "\n");
                                }
                            }
                            //ed.WriteMessage(lineCollection.Count.ToString());
                            transaction.Commit();
                        }
                    }
                    else
                    {
                        ed.WriteMessage("什么都没选到。");
                    }
                    List <Curve> HorizonLine  = new List <Curve>();
                    List <Curve> VerticalLine = new List <Curve>();
                    foreach (Curve cur in lineCollection)
                    {
                        if (cur.StartPoint.X == cur.EndPoint.X)
                        {
                            VerticalLine.Add(cur);
                        }
                        else if (cur.StartPoint.Y == cur.EndPoint.Y)
                        {
                            HorizonLine.Add(cur);
                        }
                        else
                        {
                            ed.WriteMessage("表格里有斜线!" + "\n");
                            break;
                        }
                    }
                    //水平线从上往下按Y坐标由大到小排序
                    HorizonLine.Sort(new HorizontalLinePointComparer());
                    //垂直线从左往右按X坐标由小到大排序
                    VerticalLine.Sort(new VerticalLinePointComparer());
                    //ed.WriteMessage("\n水平线:\n-------------------\n");
                    //for (int a = 0; a < HorizonLine.Count;a++ )
                    //{
                    //    Curve cur = HorizonLine[a] as Curve;
                    //    ed.WriteMessage(cur.GetType().ToString());
                    //    ed.WriteMessage("  Y坐标为:" + cur.StartPoint.Y + "\n");
                    //}
                    //ed.WriteMessage("\n垂直线:\n-------------------\n");
                    //for (int b = 0; b < VerticalLine.Count; b++)
                    //{
                    //    Curve cur = VerticalLine[b] as Curve;
                    //    ed.WriteMessage(cur.GetType().ToString());
                    //    ed.WriteMessage("  X坐标为:" + cur.StartPoint.X + "\n");
                    //}
                    //划分单元格
                    //记录所有直线的交点
                    //交点的记录格式为 “1-1,[]”,1-1表示第一行第一列,[0]为X的坐标值,[1]为Y的坐标值
                    string pointName = null;
                    Dictionary <string, double[]> IntersectionPoints = new Dictionary <string, double[]>();
                    int horizonCount  = HorizonLine.Count;
                    int verticalCount = VerticalLine.Count;
                    for (int m = 0; m < horizonCount; m++)
                    {
                        for (int n = 0; n < verticalCount; n++)
                        {
                            pointName = String.Format("{0}-{1}", m + 1, n + 1);
                            double[]          intersectionpoint = new double[2];
                            Point3dCollection p = new Point3dCollection();
                            HorizonLine[m].IntersectWith(VerticalLine[n], Intersect.OnBothOperands, p, 0, 0);
                            if (p.Count == 1)
                            {
                                intersectionpoint[0] = p[0].X;
                                intersectionpoint[1] = p[0].Y;
                                IntersectionPoints.Add(pointName, intersectionpoint);
                            }
                        }
                    }
                    //foreach (string s in IntersectionPoints.Keys)
                    //{
                    //    ed.WriteMessage("\nName:" + s + " 交点坐标X:" + IntersectionPoints[s][0] + " 交点坐标Y:" + IntersectionPoints[s][1]);
                    //}
                    #endregion

                    #region 获取文字并填入单元格
                    //获取选中的矩形框选选中的文字
                    DBObjectCollection    textCollection = new DBObjectCollection();
                    PromptSelectionResult ents1          = ed.SelectCrossingPolygon(p3d, sf1);
                    if (ents1.Status == PromptStatus.OK)
                    {
                        using (Transaction transaction = db.TransactionManager.StartTransaction())
                        {
                            SelectionSet SS = ents1.Value;
                            foreach (ObjectId id in SS.GetObjectIds())
                            {
                                entity = (Entity)transaction.GetObject(id, OpenMode.ForRead, true);
                                if (entity != null)
                                {
                                    textCollection.Add(entity);
                                    ed.WriteMessage("\n" + entity.GetRXClass().DxfName);
                                }
                            }
                            ed.WriteMessage("\n" + textCollection.Count.ToString());
                            transaction.Commit();
                        }
                    }
                    //保存选中数据的数组object[pointName,text]
                    object[,] table = new object[HorizonLine.Count + 1, VerticalLine.Count + 1];
                    string tablename = "table" + j;
                    //为每个文字找到对应的单元格,如果有多个文字在一个单元格范围内,则合并
                    //合并的操作在写EXCEL单元格的时候进行,加空格Append在原有文字的后面
                    //通过Text.AlignmentPoint来定位
                    foreach (Entity ent_text in textCollection)
                    {
                        DBText db_text    = ent_text as DBText;
                        string pointName1 = "";
                        string x_text     = "";
                        string y_text     = "";
                        int    x_index    = 0;
                        int    y_index    = 0;
                        //先查找AlignmentPoint.X在"List<Curve> HorizonLine"中行的位置
                        for (int aa = 0; aa < HorizonLine.Count; aa++)
                        {
                            if (db_text.AlignmentPoint.Y > HorizonLine[aa].StartPoint.Y)
                            {
                                y_text  = (aa + 1).ToString();
                                y_index = aa;
                                break;
                            }
                            else
                            {
                                if (aa == (HorizonLine.Count - 1))
                                {
                                    y_text  = (aa + 2).ToString();
                                    y_index = aa + 1;
                                }
                            }
                        }
                        //再查找AlignmentPoint.X在"List<Curve> VerticalLine"中列的位置
                        for (int bb = 0; bb < VerticalLine.Count; bb++)
                        {
                            if (db_text.AlignmentPoint.X < VerticalLine[bb].StartPoint.X)
                            {
                                x_text  = (bb + 1).ToString();
                                x_index = bb;
                                break;
                            }
                            else
                            {
                                if (bb == (VerticalLine.Count - 1))
                                {
                                    x_text  = (bb + 2).ToString();
                                    x_index = bb + 1;
                                }
                            }
                        }
                        pointName1 = y_text + "-" + x_text;
                        //如果单元格内有多个文字,则将其内容拼在一起
                        table[y_index, x_index] += db_text.TextString;
                        //ed.WriteMessage("\n" + db_text.TextString + " 位置为" + pointName1);
                    }

                    #endregion

                    #region  将数据写入midTable

                    midTable midtable = new midTable();
                    midtable.Name = tablename;
                    midtable.data = table;
                    tables.Add(midtable);

                    #endregion
                }

                //写入Access数据库
                xl2cad_wps.AccessDataBase.WriteDB(tables);
                //提示读取数据完毕,点击确定后跳到EXCEL导入数据
                MessageBox.Show("选定的数据读取完毕,点击确定导入Excel");
                //xl2cad_wps.AccessDataBase.ReadDB

                #region 将数据写入Excel

                //app = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("ket.Application");
                //wbk = app.ActiveWorkbook;
                //wsh = (Worksheet)wbk.ActiveSheet;
                ////使excel程序跳到在最前面,需要添加引用“Microsoft.VisualBasic”
                //Microsoft.VisualBasic.Interaction.AppActivate(app.Caption);
                string         fileName1 = "";
                SaveFileDialog saveFile  = new SaveFileDialog();
                saveFile.Filter = ("Excel 文件(*.xls)|*.xls");//指定文件后缀名为Excel 文件。
                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    fileName1 = saveFile.FileName;
                    if (System.IO.File.Exists(fileName1))
                    {
                        System.IO.File.Delete(fileName1);       //如果文件存在删除文件。
                    }
                    int index = fileName1.LastIndexOf("//");    //获取最后一个/的索引
                    fileName1 = fileName1.Substring(index + 1); //获取excel名称(新建表的路径相对于SaveFileDialog的路径)
                }
                foreach (midTable table in tables)
                {
                    xl2cad_wps.AccessDataBase.ReadDB(table.Name, fileName1);
                }

                #endregion
            }
            catch (System.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message);
            }
            finally
            {
                System.GC.Collect();
            }
        }
Exemplo n.º 30
0
        public static void CreateCompositeRegions()
        {
            // 获取当前文档和数据库
            Document acDoc   = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            // 启动事务
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以读模式打开 Block 表
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;
                // 以写模式打开 Block 表记录 Model 空间
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForWrite) as BlockTableRecord;
                // 在内存建两个圆
                Circle acCirc1 = new Circle();
                acCirc1.Center = new Point3d(4, 4, 0);
                acCirc1.Radius = 2;
                Circle acCirc2 = new Circle();
                acCirc2.Center = new Point3d(4, 4, 0);
                acCirc2.Radius = 1;
                // 将圆添加到对象数组
                DBObjectCollection acDBObjColl = new DBObjectCollection();
                acDBObjColl.Add(acCirc1);
                acDBObjColl.Add(acCirc2);

                // 基于每个闭环计算面域
                DBObjectCollection myRegionColl = new DBObjectCollection();
                myRegionColl = Region.CreateFromCurves(acDBObjColl);
                Region acRegion1 = myRegionColl[0] as Region;
                Region acRegion2 = myRegionColl[1] as Region;

                acDoc.Editor.WriteMessage("r1{0},r2{1}", acRegion1.Area, acRegion2.Area);
                // 从面域 2 减去面域 1
                if (acRegion1.Area > acRegion2.Area)
                {
                    // 从较大面域中减去较小面域
                    acRegion1.BooleanOperation(BooleanOperationType.BoolSubtract,
                                               acRegion2);
                    acRegion2.Dispose();
                    // 将最终的面域添加到数据库
                    acBlkTblRec.AppendEntity(acRegion1);
                    acTrans.AddNewlyCreatedDBObject(acRegion1, true);
                }
                else
                {
                    // 从较大面域中减去较小面域
                    acRegion2.BooleanOperation(BooleanOperationType.BoolSubtract,
                                               acRegion1);
                    acRegion1.Dispose();
                    // 将最终的面域添加到数据库
                    acBlkTblRec.AppendEntity(acRegion2);
                    acTrans.AddNewlyCreatedDBObject(acRegion2, true);
                }
                // 销毁内存中的两个圆对象
                acCirc1.Dispose();
                acCirc2.Dispose();
                // 将新对象保存到数据库
                acTrans.Commit();
            }
        }
Exemplo n.º 31
0
 //
 // Fonction de tracé des lignes entre les points pour afficher les blocks
 //
 private DBObjectCollection RacksOfLines(int height, int deep)
 {
     // A function to generate a set of entities for our block
     var ents = new DBObjectCollection();
     Point3d[] pts = {
                             new Point3d(0, 0, 0),
                             new Point3d(0, height, 0),
                             new Point3d(deep, height, 0),
                             new Point3d(deep, 0, 0)
                     };
     // first square
     const byte red = 255;
     const byte green = 255;
     const byte blue = 255;
     for (int i = 0; i <= 3; i++)
     {
         int j = (i == 3 ? 0 : i + 1);
         var ln = new Line(pts[i], pts[j]) { Color = Color.FromRgb(red, green, blue) };
         ents.Add(ln);
     }
     return ents;
 }
Exemplo n.º 32
0
        static public void Mcopy()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // Select the objects to copy
            PromptSelectionOptions psopt = new PromptSelectionOptions();

            psopt.MessageForAdding   = "\nSelect objects : ";
            psopt.AllowDuplicates    = false;
            psopt.AllowSubSelections = false;
            PromptSelectionResult psres = ed.GetSelection(psopt);

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

            SelectionSet selset = psres.Value;
            //ObjectIdCollection oidcoll = new ObjectIdCollection(psres.Value.GetObjectIds

            // Get copy distance from user by two points
            PromptPointOptions ppopt_source = new PromptPointOptions("\n Pick source point : ");

            ppopt_source.AllowArbitraryInput = true;
            ppopt_source.AllowNone           = false;
            PromptPointResult ppres_source = ed.GetPoint(ppopt_source);
            //ed.WriteMessage("\nSource point = " + ppres_source);
            Point3d            pts        = ppres_source.Value;
            PromptPointOptions ppopt_dest = new PromptPointOptions("\n Pick destination point : ");

            ppopt_dest.AllowArbitraryInput = true;
            ppopt_dest.AllowNone           = false;
            PromptPointResult ppres_dest = ed.GetPoint(ppopt_dest);
            //ed.WriteMessage("\nSource point = " + ppres_dest);
            Point3d ptd = ppres_dest.Value;

            // Convert two points to a vector
            Vector3d vec  = (ptd - pts);
            double   vlen = vec.Length;

            ed.WriteMessage("\nVector3d : " + vec + ">> Length : " + vlen);

            using (Transaction tx = db.TransactionManager.StartTransaction())
            {
                DBObjectCollection dbocoll = new DBObjectCollection();

                // Iterate in selection set & cast in db.obj.collection
                foreach (SelectedObject selobj in selset)
                {
                    if (selobj == null)
                    {
                        ed.WriteMessage("\nNull obj detected > ID : " + selobj.ObjectId);
                    }

                    Entity ent = tx.GetObject(selobj.ObjectId, OpenMode.ForRead) as Entity;

                    dbocoll.Add(ent);
                    //ed.WriteMessage("\nObjId original : " + selobj.ObjectId);
                }

                // Copy objects in obj collection
                IterateCopy(dbocoll, vec);
                tx.Commit();

                // Ask for repetition number
                PromptIntegerOptions piopt = new PromptIntegerOptions("\nMultiply Copy : ");
                piopt.DefaultValue  = 1;
                piopt.AllowZero     = false;
                piopt.AllowNone     = true;
                piopt.AllowNegative = false;
                PromptIntegerResult pires = ed.GetInteger(piopt);
                int i_pires = pires.Value;

                // Repeat copy
                if (i_pires > 1)
                {
                    for (int i = i_pires; i >= 2; i--)
                    {
                        ed.WriteMessage("\n int i : " + i);

                        Vector3d vec_new = vec * i;
                        ed.WriteMessage("\nnew vector length = " + vec_new.Length);

                        IterateCopy(dbocoll, vec_new);
                    }
                }
            }
        }
Exemplo n.º 33
0
        public static void CreateRectangular3DArray()
        {
            // 获取当前文档和数据库,启动事务
            var acDoc   = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            var acCurDb = acDoc.Database;

            using (var acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // 以读模式打开块表
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;

                // 以写模式打开块表记录模型空间
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForWrite) as BlockTableRecord;

                // 创建圆,圆心(2,2,0),半径0.5
                var acCirc = new Circle();
                acCirc.Center = new Point3d(2, 2, 0);
                acCirc.Radius = 0.5;

                // 将新对象添加到块表记录和事务
                acBlkTblRec.AppendEntity(acCirc);
                acTrans.AddNewlyCreatedDBObject(acCirc, true);

                // 创建4行4列3层的矩形阵列
                var nRows    = 4;
                var nColumns = 4;
                var nLevels  = 3;

                // 设置行、列、层3个方向的偏移量及阵列基角
                double dRowOffset    = 1;
                double dColumnOffset = 1;
                double dLevelsOffset = 4;
                double dArrayAng     = 0;

                // 获取当前UCS坐标系X轴的角度
                var curUCSMatrix = acDoc.Editor.CurrentUserCoordinateSystem;
                var curUCS       = curUCSMatrix.CoordinateSystem3d;
                var acVec2dAng   = new Vector2d(curUCS.Xaxis.X,
                                                curUCS.Xaxis.Y);

                // 如果UCS被旋转了,相应地调整阵列角度
                dArrayAng = dArrayAng + acVec2dAng.Angle;

                // 使用对象界限的左上角作为阵列基点
                var acExts          = acCirc.Bounds.GetValueOrDefault();
                var acPt2dArrayBase = new Point2d(acExts.MinPoint.X,
                                                  acExts.MaxPoint.Y);

                // 跟踪为每列创建的对象
                var acDBObjCollCols = new DBObjectCollection();
                acDBObjCollCols.Add(acCirc);

                // 创建首列对象
                var nColumnsCount = 1;
                while (nColumns > nColumnsCount)
                {
                    var acEntClone = acCirc.Clone() as Entity;
                    acDBObjCollCols.Add(acEntClone);

                    // 给复制的对象计算新位置
                    var acPt2dTo = PolarPoints(acPt2dArrayBase,
                                               dArrayAng,
                                               dColumnOffset * nColumnsCount);

                    var acVec2d = acPt2dArrayBase.GetVectorTo(acPt2dTo);
                    var acVec3d = new Vector3d(acVec2d.X, acVec2d.Y, 0);
                    acEntClone.TransformBy(Matrix3d.Displacement(acVec3d));

                    acBlkTblRec.AppendEntity(acEntClone);
                    acTrans.AddNewlyCreatedDBObject(acEntClone, true);

                    nColumnsCount = nColumnsCount + 1;
                }

                // 90度的弧度值
                var dAng = 1.5708;

                // 跟踪每行和列中创建的对象
                var acDBObjCollLvls = new DBObjectCollection();

                foreach (DBObject acObj in acDBObjCollCols)
                {
                    acDBObjCollLvls.Add(acObj);
                }

                // 创建每行对象
                foreach (Entity acEnt in acDBObjCollCols)
                {
                    var nRowsCount = 1;

                    while (nRows > nRowsCount)
                    {
                        var acEntClone = acEnt.Clone() as Entity;
                        acDBObjCollLvls.Add(acEntClone);

                        // 给复制的对象计算新位置
                        var acPt2dTo = PolarPoints(acPt2dArrayBase,
                                                   dArrayAng + dAng,
                                                   dRowOffset * nRowsCount);

                        var acVec2d = acPt2dArrayBase.GetVectorTo(acPt2dTo);
                        var acVec3d = new Vector3d(acVec2d.X, acVec2d.Y, 0);
                        acEntClone.TransformBy(Matrix3d.Displacement(acVec3d));

                        acBlkTblRec.AppendEntity(acEntClone);
                        acTrans.AddNewlyCreatedDBObject(acEntClone, true);

                        nRowsCount = nRowsCount + 1;
                    }
                }

                // 创建3D阵列的层
                foreach (Entity acEnt in acDBObjCollLvls)
                {
                    var nLvlsCount = 1;

                    while (nLevels > nLvlsCount)
                    {
                        var acEntClone = acEnt.Clone() as Entity;

                        var acVec3d = new Vector3d(0, 0, dLevelsOffset * nLvlsCount);
                        acEntClone.TransformBy(Matrix3d.Displacement(acVec3d));

                        acBlkTblRec.AppendEntity(acEntClone);
                        acTrans.AddNewlyCreatedDBObject(acEntClone, true);

                        nLvlsCount = nLvlsCount + 1;
                    }
                }

                // 提交事务
                acTrans.Commit();
            }
        }
        private void paint_Click(object sender, EventArgs e)
        {
            this.Hide();
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (DocumentLock doclock = acDoc.LockDocument())
            {
                using (Transaction trans = acCurDb.TransactionManager.StartTransaction())
                {

                    PromptPointResult pPtRes;
                    PromptPointOptions pPtOpts = new PromptPointOptions("");
                    pPtOpts.Message = "\nВведи точку: ";
                    pPtRes = acDoc.Editor.GetPoint(pPtOpts);
                    // pPtRes.Value - точка типа Point3D
                    Data.table_x = pPtRes.Value.X - 185;
                    Data.table_y = pPtRes.Value.Y;

                    BlockTableRecord btr;
                    BlockTable bt;
                    DBObjectCollection ObjColl = new DBObjectCollection();

                    //ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x, Data.table_y, 0)));

                    //Вставили шапку таблицы.
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x + 185, Data.table_y, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y - 15, 0), new Point3d(Data.table_x + 185, Data.table_y - 15, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x, Data.table_y - 15, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 185, Data.table_y, 0), new Point3d(Data.table_x + 185, Data.table_y - 15, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 20, Data.table_y, 0), new Point3d(Data.table_x + 20, Data.table_y - 15, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 130, Data.table_y, 0), new Point3d(Data.table_x + 130, Data.table_y - 15, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 140, Data.table_y, 0), new Point3d(Data.table_x + 140, Data.table_y - 15, 0)));

                    #region Текст в шапке
                    MText objText = new MText();
                    objText.SetDatabaseDefaults();
                    objText.Location = new Point3d(Data.table_x + 2, Data.table_y - 1, 0);
                    objText.Contents = "Поз.\nОбозна-\nчение";
                    objText.TextStyleId = acCurDb.Textstyle;
                    objText.TextHeight = 3;
                    objText.Height = 15;
                    objText.Width = 20;
                    ObjColl.Add(objText);

                    MText objText1 = new MText();
                    objText1.SetDatabaseDefaults();
                    objText1.TextStyleId = acCurDb.Textstyle;
                    objText1.TextHeight = 3;
                    objText1.Location = new Point3d(Data.table_x + 65, Data.table_y - 6, 0);
                    objText1.Contents = "Наименование";
                    objText1.Height = 15;
                    objText1.Width = 110;
                    ObjColl.Add(objText1);

                    MText objText2 = new MText();
                    objText2.SetDatabaseDefaults();
                    objText2.TextStyleId = acCurDb.Textstyle;
                    objText2.TextHeight = 3;
                    objText2.Location = new Point3d(Data.table_x + 132, Data.table_y - 6, 0);
                    objText2.Contents = "Кол.";
                    objText2.Height = 15;
                    objText2.Width = 10;
                    ObjColl.Add(objText2);

                    MText objText3 = new MText();
                    objText3.SetDatabaseDefaults();
                    objText3.TextStyleId = acCurDb.Textstyle;
                    objText3.TextHeight = 3;
                    objText3.Location = new Point3d(Data.table_x + 143, Data.table_y - 6, 0);
                    objText3.Contents = "Примечание";
                    objText3.Height = 15;
                    objText3.Width = 45;
                    ObjColl.Add(objText3);

                    #endregion

                    Data.table_y = Data.table_y - 8;
                    double table_xx = Data.table_x, table_yy = Data.table_y - 20;

                    #region Вставляем строки таблицы
                    for (int j = 0; j < dataGridView1.Rows.Count - 1; j++)
                    {
                        Data.table_y = Data.table_y - 7;

                        ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x, Data.table_y - 7, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 20, Data.table_y, 0), new Point3d(Data.table_x + 20, Data.table_y - 7, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 130, Data.table_y, 0), new Point3d(Data.table_x + 130, Data.table_y - 7, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 140, Data.table_y, 0), new Point3d(Data.table_x + 140, Data.table_y - 7, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 185, Data.table_y, 0), new Point3d(Data.table_x + 185, Data.table_y - 7, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y - 7, 0), new Point3d(Data.table_x + 185, Data.table_y - 7, 0)));

                        DBText acText6 = new DBText();
                        acText6.SetDatabaseDefaults();
                        acText6.Height = 3;
                        acText6.Position = new Point3d(Data.table_x + 2, Data.table_y - 5, 0);
                        acText6.TextString = dataGridView1.Rows[j].Cells["Обозначение"].Value.ToString();
                        ObjColl.Add(acText6);

                        DBText acText7 = new DBText();
                        acText7.SetDatabaseDefaults();
                        acText7.Height = 3;
                        acText7.Position = new Point3d(Data.table_x + 21, Data.table_y - 5, 0);
                        acText7.TextString = dataGridView1.Rows[j].Cells["Наименование"].Value.ToString();
                        ObjColl.Add(acText7);

                        DBText acText8 = new DBText();
                        acText8.SetDatabaseDefaults();
                        acText8.Height = 3;
                        acText8.Position = new Point3d(Data.table_x + 132, Data.table_y - 5, 0);
                        acText8.TextString = dataGridView1.Rows[j].Cells["Кол"].Value.ToString();
                        ObjColl.Add(acText8);

                        DBText acText9 = new DBText();
                        acText9.SetDatabaseDefaults();
                        acText9.Height = 3;
                        acText9.Position = new Point3d(Data.table_x + 141, Data.table_y - 5, 0);
                        acText9.TextString = dataGridView1.Rows[j].Cells["Примечание"].Value.ToString();
                        ObjColl.Add(acText9);
                    }
                    #endregion

                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y - 7, 0), new Point3d(Data.table_x + 185, Data.table_y - 7, 0)));

                    Database wbd = HostApplicationServices.WorkingDatabase;

                    bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
                    btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    foreach (Entity ent in ObjColl)
                    {
                        btr.AppendEntity(ent);
                        trans.AddNewlyCreatedDBObject(ent, true);
                    }
                    trans.Commit();
                    trans.Dispose();
                }
            }
            this.Show();
        }
Exemplo n.º 35
0
 /// <summary>
 /// Creates a new Polyline that is the result of projecting the polyline parallel to 'direction' onto 'plane' and returns it.
 /// </summary>
 /// <param name="pline">The polyline (any type) to project.</param>
 /// <param name="plane">The plane onto which the curve is to be projected.</param>
 /// <param name="direction">Direction (in WCS coordinates) of the projection.</param>
 /// <returns>The projected Polyline.</returns>
 internal static Polyline ProjectPolyline(Curve pline, Plane plane, Vector3d direction)
 {
     if (!(pline is Polyline) && !(pline is Polyline2d) && !(pline is Polyline3d))
         return null;
     plane = new Plane(Point3d.Origin.OrthoProject(plane), direction);
     using (DBObjectCollection oldCol = new DBObjectCollection())
     using (DBObjectCollection newCol = new DBObjectCollection())
     {
         pline.Explode(oldCol);
         foreach (DBObject obj in oldCol)
         {
             Curve crv = obj as Curve;
             if (crv != null)
             {
                 Curve flat = crv.GetProjectedCurve(plane, direction);
                 newCol.Add(flat);
             }
             obj.Dispose();
         }
         PolylineSegmentCollection psc = new PolylineSegmentCollection();
         for (int i = 0; i < newCol.Count; i++)
         {
             if (newCol[i] is Ellipse)
             {
                 psc.AddRange(new PolylineSegmentCollection((Ellipse)newCol[i]));
                 continue;
             }
             Curve crv = (Curve)newCol[i];
             Point3d start = crv.StartPoint;
             Point3d end = crv.EndPoint;
             double bulge = 0.0;
             if (crv is Arc)
             {
                 Arc arc = (Arc)crv;
                 double angle = arc.Center.GetVectorTo(start).GetAngleTo(arc.Center.GetVectorTo(end), arc.Normal);
                 bulge = Math.Tan(angle / 4.0);
             }
             psc.Add(new PolylineSegment(start.Convert2d(plane), end.Convert2d(plane), bulge));
         }
         foreach (DBObject o in newCol) o.Dispose();
         Polyline projectedPline = psc.Join(new Tolerance(1e-9, 1e-9))[0].ToPolyline();
         projectedPline.Normal = direction;
         projectedPline.Elevation =
             plane.PointOnPlane.TransformBy(Matrix3d.WorldToPlane(new Plane(Point3d.Origin, direction))).Z;
         if (!pline.StartPoint.Project(plane, direction).IsEqualTo(projectedPline.StartPoint, new Tolerance(1e-9, 1e-9)))
         {
             projectedPline.Normal = direction = direction.Negate();
             projectedPline.Elevation =
                 plane.PointOnPlane.TransformBy(Matrix3d.WorldToPlane(new Plane(Point3d.Origin, direction))).Z;
         }
         return projectedPline;
     }
 }
        private void DrawVRCTable(Point3d pt, int ListIndex)
        {
            Document myDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            DocumentLock myLock = myDoc.LockDocument();
            Database acCurDb = myDoc.Database;
            Editor ed = myDoc.Editor;
            List<Line> lines = new List<Line>();
            DBObjectCollection ObjColl = new DBObjectCollection();
            double x0 = pt.X, y0 = pt.Y - 10 * K, z0 = pt.Z;
            #region Objects
            lines.Add(new Line(new Point3d(x0, y0, z0), new Point3d(x0, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0, y0, z0), new Point3d(x0 + 185 * K, y0, z0)));
            lines.Add(new Line(new Point3d(x0, y0 - 15 * K, z0), new Point3d(x0 + 185 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 15 * K, y0, z0), new Point3d(x0 + 15 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 155 * K, y0, z0), new Point3d(x0 + 155 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 185 * K, y0, z0), new Point3d(x0 + 185 * K, y0 - 15 * K, z0)));
            MText Header = new MyText(new Point3d(x0 + 92.5 * K, pt.Y - 5 * K, z0), "Ведомость рабочих чертежей", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text1 = new MyText(new Point3d(x0 + 7.5 * K, y0 - 7.5 * K, z0), "Лист", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text2 = new MyText(new Point3d(x0 + 85 * K, y0 - 7.5 * K, z0), "Наименование", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text3 = new MyText(new Point3d(x0 + 170 * K, y0 - 7.5 * K, z0), "Примечание", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText[,] texts = new MText[WDIList.Count, 3];
            for (int v = 0; v < WDIList.Count; v++)
            {
                texts[v, 0] = new MText();
                texts[v, 1] = new MText();
                texts[v, 2] = new MText();
            }
            double realH = y0 - 15 * K;
            int i = 0, thisRows = 0, thisRows2 = 0, rowsCount = 0; //счетчик  thisRows - в столбце Наименований, thisRows2 - примечаний
            double h = 0, hm;
            i = ListIndex;
            h += (P1.Y - pt.Y) + 25 * K;
            if (185 * K + pt.X <= P2.X + 185 * K) //если есть место для колонки
            {
                if (185 * K + pt.X < P2.X) //колонка левее штампа
                    hm = P1.Y - P3.Y;
                else hm = P1.Y - P3.Y - 55 * K;

                while (h < hm && i < WDIList.Count)
                {
                    texts[i, 0] = new MyText(new Point3d(x0 + 7.5 * K, realH - 3 * K, z0), WDIList[i].PNum, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                    texts[i, 1] = new MyText(new Point3d(x0 + (15 + 2.5) * K, realH - 3 * K, z0), WDIList[i].Name, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                    thisRows = (int)RowCount(texts[i, 1], 135);
                    texts[i, 1].LineSpaceDistance = 8;
                    texts[i, 2] = new MyText(new Point3d(x0 + (155 + 1) * K, realH - 3 * K, z0), WDIList[i].Note, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                    thisRows2 = (int)RowCount(texts[i, 2], 28);
                    texts[i, 2].LineSpaceDistance = 8;
                    thisRows = Math.Max(thisRows, thisRows2);
                    if (h + thisRows * 8 * K > hm) break;
                    ObjColl.Add(texts[i, 0]);
                    ObjColl.Add(texts[i, 1]);
                    ObjColl.Add(texts[i, 2]);

                    for (int x = 0; x < thisRows; x++)
                    {
                        lines.Add(new Line(new Point3d(x0, realH - 8 * K, z0), new Point3d(x0 + 185 * K, realH - 8 * K, z0)));
                        realH -= 8 * K;
                    }
                    rowsCount += thisRows;
                    h += thisRows * 8 * K;
                    i++;
                }

                lines.Add(new Line(new Point3d(x0, y0 - 15 * K, z0), new Point3d(x0, y0 - K * (15 + 8 * rowsCount), z0)));
                lines.Add(new Line(new Point3d(x0 + 15 * K, y0 - 15 * K, z0), new Point3d(x0 + 15 * K, y0 - K * (15 + 8 * rowsCount), z0)));
                lines.Add(new Line(new Point3d(x0 + 155 * K, y0 - 15 * K, z0), new Point3d(x0 + 155 * K, y0 - K * (15 + 8 * rowsCount), z0)));
                lines.Add(new Line(new Point3d(x0 + 185 * K, y0 - 15 * K, z0), new Point3d(x0 + 185 * K, y0 - K * (15 + 8 * rowsCount), z0)));

            #endregion
                BlockTableRecord btr;
                BlockTable bt;
                //DBObjectCollection ObjColl = new DBObjectCollection(); //коллекция объектов
                #region AddObjects to collection
                ObjColl.Add(Text1); ObjColl.Add(Text2); ObjColl.Add(Text3); ObjColl.Add(Header);
                //for (int m=0; m<i; m++)
                //foreach (MText m in texts) ObjColl.Add(m);
                foreach (Line l in lines) ObjColl.Add(l);
                #endregion

                Database wbd = HostApplicationServices.WorkingDatabase;
                wbd.LineWeightDisplay = true;
                Transaction trans = wbd.TransactionManager.StartTransaction();
                bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
                btr = (BlockTableRecord)trans.GetObject(wbd.CurrentSpaceId, OpenMode.ForWrite);
                foreach (Entity ent in ObjColl)
                {
                    btr.AppendEntity(ent);
                    trans.AddNewlyCreatedDBObject(ent, true);
                }
                trans.Commit();
                trans.Dispose();

                if (i < WDIList.Count)
                    DrawVRCTable(new Point3d(pt.X + 186 * K, pt.Y, pt.Z), i);
            }
            else if (i < WDIList.Count && PageW >= 185)//места для колонки нет - создаем новый лист
            {
                DrawBorders(new Point3d(P1.X + (-10 + PageW) * K, P1.Y + (5 - PageH) * K, P1.Z));
                DrawVRCTable(P1, i);
            }
            else MessageBox.Show("Лист слишком узок для таблицы");
        }
Exemplo n.º 37
0
        private void Create_opis21()
        {
            string blockName = "opis-21";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Circle ent1 = new Circle(new Point3d(0, 0, 0), new Vector3d(0, 0, 1), 0.2);
            ent1.Color = Color.FromColorIndex(ColorMethod.ByColor, 7);
            entityCollection.Add(ent1);

            List<AttributeDefinition> attDefCollection = new List<AttributeDefinition>();

            AttributeDefinition attDef1 = new AttributeDefinition();
            attDef1.Position = new Point3d(-0.117, -0.085, 0);
            attDef1.Tag = "NN";
            attDef1.Prompt = "numer_preta";
            attDef1.TextString = "nic";
            attDef1.Height = 0.17;
            attDef1.WidthFactor = 0.8;
            attDef1.Justify = AttachmentPoint.MiddleCenter;
            attDef1.Layer = "0";

            AttributeDefinition attDef2 = new AttributeDefinition();
            attDef2.Tag = "OPIS1";
            attDef2.Prompt = "opis_preta1";
            attDef2.TextString = "nic";
            attDef2.Height = 0.125;
            attDef2.WidthFactor = 1;
            attDef2.Justify = AttachmentPoint.MiddleLeft;
            attDef2.HorizontalMode = TextHorizontalMode.TextLeft;
            attDef2.Layer = "0";
            attDef2.AlignmentPoint = new Point3d(0.276, 0, 0);

            Transaction trans = db.TransactionManager.StartTransaction();
            using (trans)
            {
                TextStyleTable tst = trans.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;

                if (!tst.Has("SIMPLEX8"))
                {
                    System.Windows.Forms.MessageBox.Show("W pliku nie ma definicji stylu tekstu!", "Error",
                        System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                else
                {
                    ObjectId textStyleId;
                    textStyleId = tst["SIMPLEX8"];
                    attDef1.TextStyleId = textStyleId;
                    attDef2.TextStyleId = textStyleId;
                }
            }

            attDefCollection.Add(attDef1);
            attDefCollection.Add(attDef2);
            TryInsertBlockRecord(blockName, entityCollection, attDefCollection);
        }
Exemplo n.º 38
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
            {
                return(false);
            }

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                //  using (Solid3d cube = new Solid3d())
                //{
                try
                {
                    //cube.CreateBox(0.5, 0.5, 0.5);
                    _firstdraw = _firstdraw + 1;


                    if (cube != null)
                    {
                        //int i = 20000;
                        bool chk = false;
                        //cube.TransformBy(
                        //  Matrix3d.Displacement(
                        //     _resizeLocation - Point3d.Origin
                        //  )
                        //  );

                        // Draw the cursor

                        draw.SubEntityTraits.Color = ColorIndex;
                        cube.WorldDraw(draw);
                        vRot = leftHand.GetVectorTo(rightHand);; // new Point3d(-3, 4, 0).GetVectorTo(new Point3d(-3, -4, 0)); //rightHand.GetVectorTo(leftHand);

                        System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(0.2).TotalMilliseconds);

                        //chk = (leftHand.Z < leftHip.Z);

                        //while (true)
                        //{
                        //  if (chk)
                        //    break;
                        //Point3d pt1 = rightHand - leftHand;
                        cube.TransformBy(Matrix3d.Rotation(0.1, vRot, Point3d.Origin));
                        //}

                        /*if (chk)
                         * {
                         *  cube.TransformBy(Matrix3d.Rotation(1.046, vRot, leftHand));
                         *  System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(2).TotalMilliseconds);
                         * }  */

                        //cube.TransformBy(Matrix3d.Rotation(0.5236, vRot, leftHand));
                    }

                    // if(_changeaxis)

                    //            vRot = rightHand.GetVectorTo(leftHand);
                    //          cube.TransformBy(Matrix3d.Rotation(0.5236,vRot,leftHand));

                    //   if (leftHand.Z > leftHip.Z)
                    //     _isRotate = false;
                }
                catch (System.Exception ex)
                {
                    _doc.Editor.WriteMessage(
                        "\nException: {0} - {1}", ex.Message, ex.InnerException
                        );
                }
                finally
                {
                    draw.SubEntityTraits.Color = origCol;
                }
                // }
                return(true);
            }

            if (_isRotate)
            {
                cube.WorldDraw(draw);
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                        )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int  n         = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                                _profSide, GetAllButLast(_vertices, n++), out sol
                                );

                            _created.Add(sol);
                            sol       = null;
                            succeeded = true;
                        }
                        catch { }
                    }while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            cursor.CreateBox(_profSide, _profSide, _profSide);

                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                    Matrix3d.Displacement(lastPt - Point3d.Origin)
                                    );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 4; // ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return(true);
        }
Exemplo n.º 39
0
        public static DBObject Create(this Grevit.Types.Slab s, Transaction tr)
        {
            try
            {
                BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead);
                BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                // Polyline acPoly = new Polyline();
                //acPoly.SetDatabaseDefaults();

                //int i = 0;

                DBObjectCollection objColl = new DBObjectCollection();
                Point3dCollection ptcol = new Point3dCollection();
                foreach (Grevit.Types.Loop loop in s.surface.profile)
                {
                    foreach (Grevit.Types.Component p in loop.outline)
                        ptcol = p.To3dPointCollection();


                    //Curve3dCollection collt = parse3dCurve(p);
                    //acPoly.AppendVertex(new PolylineVertex3d(new Point3d(p.x, p.y, p.z)));
                    //acPoly.AddVertexAt(i, new Point2d(p.x, p.y), 0, 0, 0);
                    //i++;

                    //foreach (Curve3d curve in collt)
                    //{ 
                    //    objColl.Add(Autodesk.AutoCAD.DatabaseServices.Curve.CreateFromGeCurve(curve));
                    //}
                }

                Polyline3d face = new Polyline3d(Poly3dType.SimplePoly, ptcol, true);
                objColl.Add(face);
                //Polyline3d face = new Polyline3d();
                //ETC...
                // or from your settings
                // Polyline3d face = new Polyline3d(Poly3dType.SimplePoly, vertices, true);





                DBObjectCollection myRegionColl = new DBObjectCollection();
                // create a single region
                Autodesk.AutoCAD.DatabaseServices.Region objreg = new Autodesk.AutoCAD.DatabaseServices.Region();
                DBObjectCollection objRegions = new DBObjectCollection();
                try
                {
                    objRegions = Autodesk.AutoCAD.DatabaseServices.Region.CreateFromCurves(objColl);
                    objreg = objRegions[0] as Autodesk.AutoCAD.DatabaseServices.Region;

                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    // eInvalidInput exception
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Error: unable to create region collection:\n" + ex.Message);

                }






                //acPoly.Closed = true;
                //ms.AppendEntity(acPoly);
                //tr.AddNewlyCreatedDBObject(acPoly, true);

                //atrix3d mm = Matrix3d.Displacement(new Vector3d(0, 0, r.outline[0].z));
                //acPoly.TransformBy(mm);


                //Autodesk.Aec.Geometry.Profile myProfile = Autodesk.Aec.Geometry.Profile.CreateFromEntity(acPoly, ed.CurrentUserCoordinateSystem);

                //Slab slab = new Slab();
                //slab.SetDatabaseDefaults(db);
                //slab.SetToStandard(db);         
                //slab.Location = new Point3d(0, 0, 0);

                //slab.SetBaseProfile(myProfile, Matrix3d.Identity);

                //DBObjectCollection col = acPoly.GetOffsetCurves(0);


                //DBObjectCollection res = Region.CreateFromCurves(coll);

                //Region reg = res[0] as Region;

                Solid3d solid = new Solid3d();
                solid.Extrude(objreg, s.height, s.slope);


                LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead);
                if (s.TypeOrLayer != "") { if (lt.Has(s.TypeOrLayer)) solid.LayerId = lt[s.TypeOrLayer]; }
                //if (ss.Has(r.family, tr)) slab.StyleId = ss.GetAt(r.family);


                ms.AppendEntity(solid);
                tr.AddNewlyCreatedDBObject(solid, true);
                return solid;
            }

            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
            }

            return null;
        }
        //Рисуем таблицу щитка.
        private void b_paint_Click(object sender, EventArgs e)
        {
            this.Hide();
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (DocumentLock doclock = acDoc.LockDocument())
            {
                using (Transaction trans = acCurDb.TransactionManager.StartTransaction())
                {

                    PromptPointResult pPtRes;
                    PromptPointOptions pPtOpts = new PromptPointOptions("");
                    pPtOpts.Message = "\nВведи точку: ";
                    pPtRes = acDoc.Editor.GetPoint(pPtOpts);
                    // pPtRes.Value - точка типа Point3D
                    Data.table_x = pPtRes.Value.X;
                    Data.table_y = pPtRes.Value.Y;

                    BlockTableRecord btr;
                    BlockTable bt;
                    DBObjectCollection ObjColl = new DBObjectCollection();

                    //ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x, Data.table_y, 0)));

                    //Вставили шапку таблицы.
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x + 285, Data.table_y, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y - 50, 0), new Point3d(Data.table_x + 285, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 101, Data.table_y - 15, 0), new Point3d(Data.table_x + 285, Data.table_y - 15, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y, 0), new Point3d(Data.table_x, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 25, Data.table_y, 0), new Point3d(Data.table_x + 25, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 58, Data.table_y, 0), new Point3d(Data.table_x + 58, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 63, Data.table_y, 0), new Point3d(Data.table_x + 63, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 96, Data.table_y, 0), new Point3d(Data.table_x + 96, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 101, Data.table_y, 0), new Point3d(Data.table_x + 101, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 106, Data.table_y - 15, 0), new Point3d(Data.table_x + 106, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 123, Data.table_y - 15, 0), new Point3d(Data.table_x + 123, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 136, Data.table_y - 15, 0), new Point3d(Data.table_x + 136, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 161, Data.table_y - 15, 0), new Point3d(Data.table_x + 161, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 174, Data.table_y, 0), new Point3d(Data.table_x + 174, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 197, Data.table_y - 15, 0), new Point3d(Data.table_x + 197, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 210, Data.table_y, 0), new Point3d(Data.table_x + 210, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 226, Data.table_y - 15, 0), new Point3d(Data.table_x + 226, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 238, Data.table_y - 15, 0), new Point3d(Data.table_x + 238, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 250, Data.table_y - 15, 0), new Point3d(Data.table_x + 250, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 285, Data.table_y, 0), new Point3d(Data.table_x + 285, Data.table_y - 50, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x + 239, Data.table_y - 32, 0), new Point3d(Data.table_x + 249, Data.table_y - 32, 0)));

                    #region Текст в шапке
                    MText objText = new MText();
                    objText.SetDatabaseDefaults();
                    objText.Location = new Point3d(Data.table_x + 2, Data.table_y - 1, 0);
                    objText.Contents = "Распреде-\nлительное устройство";
                    objText.TextStyleId = acCurDb.Textstyle;
                    objText.TextHeight = 3;
                    objText.Height = 50;
                    objText.Width = 25;
                    ObjColl.Add(objText);

                    MText objText1 = new MText();
                    objText1.SetDatabaseDefaults();
                    objText1.TextStyleId = acCurDb.Textstyle;
                    objText1.TextHeight = 3;
                    objText1.Location = new Point3d(Data.table_x + 27, Data.table_y - 1, 0);
                    objText1.Contents = "Аппарат отходящей линии /ввода/, обозначение, тип, Iном, A, расцепитель или плавкая вставка, А.";
                    objText1.Height = 50;
                    objText1.Width = 31;
                    ObjColl.Add(objText1);

                    MText objText2 = new MText();
                    objText2.SetDatabaseDefaults();
                    objText2.TextStyleId = acCurDb.Textstyle;
                    objText2.TextHeight = 3;
                    objText2.Location = new Point3d(Data.table_x + 65, Data.table_y - 1, 0);
                    objText2.Contents = "Пусковой аппарат, обозначение, тип, Iном, A, расцепитель или плавкая вставка А, уставка теплового реле А.";
                    objText2.Height = 50;
                    objText2.Width = 31;
                    ObjColl.Add(objText2);

                    MText objText3 = new MText();
                    objText3.SetDatabaseDefaults();
                    objText3.TextStyleId = acCurDb.Textstyle;
                    objText3.TextHeight = 3;
                    objText3.Location = new Point3d(Data.table_x + 108, Data.table_y - 18, 0);
                    objText3.Contents = "Обозна-\nчение";
                    objText3.Height = 35;
                    objText3.Width = 17;
                    ObjColl.Add(objText3);

                    MText objText4 = new MText();
                    objText4.SetDatabaseDefaults();
                    objText4.TextStyleId = acCurDb.Textstyle;
                    objText4.TextHeight = 3;
                    objText4.Location = new Point3d(Data.table_x + 125, Data.table_y - 18, 0);
                    objText4.Contents = "Марка";
                    objText4.Height = 35;
                    objText4.Width = 13;
                    ObjColl.Add(objText4);

                    MText objText5 = new MText();
                    objText5.SetDatabaseDefaults();
                    objText5.TextStyleId = acCurDb.Textstyle;
                    objText5.TextHeight = 3;
                    objText5.Location = new Point3d(Data.table_x + 138, Data.table_y - 18, 0);
                    objText5.Contents = "Количество, число жил и сечение";
                    objText5.Height = 35;
                    objText5.Width = 25;
                    ObjColl.Add(objText5);

                    MText objText6 = new MText();
                    objText6.SetDatabaseDefaults();
                    objText6.TextStyleId = acCurDb.Textstyle;
                    objText6.TextHeight = 3;
                    objText6.Location = new Point3d(Data.table_x + 162, Data.table_y - 18, 0);
                    objText6.Contents = "Длина, м.";
                    objText6.Height = 35;
                    objText6.Width = 13;
                    ObjColl.Add(objText6);

                    MText objText7 = new MText();
                    objText7.SetDatabaseDefaults();
                    objText7.TextStyleId = acCurDb.Textstyle;
                    objText7.TextHeight = 3;
                    objText7.Location = new Point3d(Data.table_x + 175, Data.table_y - 18, 0);
                    objText7.Contents = "Обозначение на плане";
                    objText7.Height = 35;
                    objText7.Width = 23;
                    ObjColl.Add(objText7);

                    MText objText8 = new MText();
                    objText8.SetDatabaseDefaults();
                    objText8.TextStyleId = acCurDb.Textstyle;
                    objText8.TextHeight = 3;
                    objText8.Location = new Point3d(Data.table_x + 198, Data.table_y - 18, 0);
                    objText8.Contents = "Длина, м.";
                    objText8.Height = 35;
                    objText8.Width = 13;
                    ObjColl.Add(objText8);

                    MText objText9 = new MText();
                    objText9.SetDatabaseDefaults();
                    objText9.TextStyleId = acCurDb.Textstyle;
                    objText9.TextHeight = 3;
                    objText9.Location = new Point3d(Data.table_x + 212, Data.table_y - 18, 0);
                    objText9.Contents = "Обозна-\nчение";
                    objText9.Height = 35;
                    objText9.Width = 16;
                    ObjColl.Add(objText9);

                    MText objText10 = new MText();
                    objText10.SetDatabaseDefaults();
                    objText10.TextStyleId = acCurDb.Textstyle;
                    objText10.TextHeight = 3;
                    objText10.Location = new Point3d(Data.table_x + 227, Data.table_y - 18, 0);
                    objText10.Contents = "Pуст. или Pном., КВт";
                    objText10.Height = 35;
                    objText10.Width = 12;
                    ObjColl.Add(objText10);

                    MText objText11 = new MText();
                    objText11.SetDatabaseDefaults();
                    objText11.TextStyleId = acCurDb.Textstyle;
                    objText11.TextHeight = 3;
                    objText11.Location = new Point3d(Data.table_x + 239, Data.table_y - 18, 0);
                    objText11.Contents = "Iрасч. или Iном. Iпуск., А.";
                    objText11.Height = 35;
                    objText11.Width = 12;
                    ObjColl.Add(objText11);

                    MText objText12 = new MText();
                    objText12.SetDatabaseDefaults();
                    objText12.TextStyleId = acCurDb.Textstyle;
                    objText12.TextHeight = 3;
                    objText12.Location = new Point3d(Data.table_x + 252, Data.table_y - 18, 0);
                    objText12.Contents = "Наименование, тип, обозначение чертежа, принципиальной схемы.";
                    objText12.Height = 35;
                    objText12.Width = 35;
                    ObjColl.Add(objText12);

                    DBText acText = new DBText();
                    acText.SetDatabaseDefaults();
                    acText.Position = new Point3d(Data.table_x + 62, Data.table_y - 48, 0);
                    acText.Height = 3;
                    acText.TextString = "Участок сети 1";
                    acText.Rotation = 1.570796; //Это 90 градусов в радианах.
                    ObjColl.Add(acText);

                    DBText acText1 = new DBText();
                    acText1.SetDatabaseDefaults();
                    acText1.Rotation = 1.570796;
                    acText1.Height = 3;
                    acText1.Position = new Point3d(Data.table_x + 100, Data.table_y - 48, 0);
                    acText1.TextString = "Участок сети 2";
                    ObjColl.Add(acText1);

                    DBText acText2 = new DBText();
                    acText2.SetDatabaseDefaults();
                    acText2.Rotation = 1.570796;
                    acText2.Height = 3;
                    acText2.Position = new Point3d(Data.table_x + 105, Data.table_y - 48, 0);
                    acText2.TextString = "Участок сети";
                    ObjColl.Add(acText2);

                    DBText acText3 = new DBText();
                    acText3.SetDatabaseDefaults();
                    acText3.Height = 3;
                    acText3.Position = new Point3d(Data.table_x + 123, Data.table_y - 8, 0);
                    acText3.TextString = "Кабель, провод";
                    ObjColl.Add(acText3);
                    //acText.WidthFactor = 0.5;

                    DBText acText4 = new DBText();
                    acText4.SetDatabaseDefaults();
                    acText4.Height = 3;
                    acText4.Position = new Point3d(Data.table_x + 185, Data.table_y - 8, 0);
                    acText4.TextString = "Труба";
                    ObjColl.Add(acText4);

                    DBText acText5 = new DBText();
                    acText5.SetDatabaseDefaults();
                    acText5.Height = 3;
                    acText5.Position = new Point3d(Data.table_x + 230, Data.table_y - 8, 0);
                    acText5.TextString = "Электроприемник";
                    ObjColl.Add(acText5);
                    #endregion

                    Data.table_y = Data.table_y - 30;
                    double table_xx = Data.table_x, table_yy = Data.table_y - 20;

                    #region Вставляем строки таблицы
                    for (int j = 0; j < dataGridView1.Rows.Count - 1; j++)
                    {
                        Data.table_y = Data.table_y - 20;

                        if (dataGridView1.Rows[j].Cells["Ветвь"].Value.ToString() == "Главная линия")
                        {
                            Line l_gl = new Line(new Point3d(Data.table_x + 25, Data.table_y - 20, 0), new Point3d(Data.table_x + 210, Data.table_y - 20, 0));
                            l_gl.LineWeight = LineWeight.LineWeight050;
                            l_gl.ColorIndex = 4;
                            ObjColl.Add(l_gl);
                        }

                        if (dataGridView1.Rows[j].Cells["Ветвь"].Value.ToString() == "Ответвление")
                        {
                            Line l_gl = new Line(new Point3d(Data.table_x + 62, Data.table_y, 0), new Point3d(Data.table_x + 60, Data.table_y - 2, 0));
                            l_gl.LineWeight = LineWeight.LineWeight050;
                            l_gl.ColorIndex = 4;
                            ObjColl.Add(l_gl);

                            Line l_gl1 = new Line(new Point3d(Data.table_x + 60, Data.table_y - 2, 0), new Point3d(Data.table_x + 60, Data.table_y - 20, 0));
                            l_gl1.LineWeight = LineWeight.LineWeight050;
                            l_gl1.ColorIndex = 4;
                            ObjColl.Add(l_gl1);

                            Line l_gl2 = new Line(new Point3d(Data.table_x + 60, Data.table_y - 20, 0), new Point3d(Data.table_x + 210, Data.table_y - 20, 0));
                            l_gl2.LineWeight = LineWeight.LineWeight050;
                            l_gl2.ColorIndex = 4;
                            ObjColl.Add(l_gl2);
                        }

                        if (dataGridView1.Rows[j].Cells["Род тока"].Value.ToString() == "1")
                        {
                            ObjColl.Add(new Line(new Point3d(Data.table_x + 51, Data.table_y - 17.5, 0), new Point3d(Data.table_x + 49, Data.table_y - 22.5, 0)));
                        }

                        if (dataGridView1.Rows[j].Cells["Род тока"].Value.ToString() == "3")
                        {
                            ObjColl.Add(new Line(new Point3d(Data.table_x + 51, Data.table_y - 17.5, 0), new Point3d(Data.table_x + 49, Data.table_y - 22.5, 0)));
                            ObjColl.Add(new Line(new Point3d(Data.table_x + 52, Data.table_y - 17.5, 0), new Point3d(Data.table_x + 50, Data.table_y - 22.5, 0)));
                            ObjColl.Add(new Line(new Point3d(Data.table_x + 50, Data.table_y - 17.5, 0), new Point3d(Data.table_x + 48, Data.table_y - 22.5, 0)));
                        }

                        ObjColl.Add(new Line(new Point3d(Data.table_x + 25, Data.table_y, 0), new Point3d(Data.table_x + 25, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 58, Data.table_y, 0), new Point3d(Data.table_x + 58, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 63, Data.table_y, 0), new Point3d(Data.table_x + 63, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 96, Data.table_y, 0), new Point3d(Data.table_x + 96, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 101, Data.table_y, 0), new Point3d(Data.table_x + 101, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 106, Data.table_y, 0), new Point3d(Data.table_x + 106, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 123, Data.table_y, 0), new Point3d(Data.table_x + 123, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 136, Data.table_y, 0), new Point3d(Data.table_x + 136, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 161, Data.table_y, 0), new Point3d(Data.table_x + 161, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 174, Data.table_y, 0), new Point3d(Data.table_x + 174, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 197, Data.table_y, 0), new Point3d(Data.table_x + 197, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 210, Data.table_y, 0), new Point3d(Data.table_x + 210, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 226, Data.table_y, 0), new Point3d(Data.table_x + 226, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 238, Data.table_y, 0), new Point3d(Data.table_x + 238, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 250, Data.table_y, 0), new Point3d(Data.table_x + 250, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 285, Data.table_y, 0), new Point3d(Data.table_x + 285, Data.table_y - 20, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 101, Data.table_y - 10, 0), new Point3d(Data.table_x + 210, Data.table_y - 10, 0)));
                        ObjColl.Add(new Line(new Point3d(Data.table_x + 210, Data.table_y - 20, 0), new Point3d(Data.table_x + 285, Data.table_y - 20, 0)));

                        DBText acText6 = new DBText();
                        acText6.SetDatabaseDefaults();
                        acText6.Height = 3;
                        acText6.Position = new Point3d(Data.table_x + 27, Data.table_y - 14, 0);
                        acText6.TextString = dataGridView1.Rows[j].Cells["Аппарат"].Value.ToString();
                        ObjColl.Add(acText6);

                        DBText acText7 = new DBText();
                        acText7.SetDatabaseDefaults();
                        acText7.Height = 3;
                        acText7.Position = new Point3d(Data.table_x + 27, Data.table_y - 18, 0);
                        acText7.TextString = dataGridView1.Rows[j].Cells["Ток"].Value.ToString();
                        ObjColl.Add(acText7);

                        DBText acText8 = new DBText();
                        acText8.SetDatabaseDefaults();
                        acText8.Height = 3;
                        acText8.Position = new Point3d(Data.table_x + 60, Data.table_y - 18, 0);
                        acText8.TextString = dataGridView1.Rows[j].Cells["Фаза"].Value.ToString();
                        ObjColl.Add(acText8);

                        DBText acText9 = new DBText();
                        acText9.SetDatabaseDefaults();
                        acText9.Height = 3;
                        acText9.Position = new Point3d(Data.table_x + 65, Data.table_y - 18, 0);
                        acText9.TextString = dataGridView1.Rows[j].Cells["Пусковой аппарат 1"].Value.ToString();
                        ObjColl.Add(acText9);

                        DBText acText10 = new DBText();
                        acText10.SetDatabaseDefaults();
                        acText10.Height = 3;
                        acText10.Position = new Point3d(Data.table_x + 65, Data.table_y - 14, 0);
                        acText10.TextString = dataGridView1.Rows[j].Cells["Пусковой аппарат 2"].Value.ToString();
                        ObjColl.Add(acText10);

                        DBText acText11 = new DBText();
                        acText11.SetDatabaseDefaults();
                        acText11.Height = 3;
                        acText11.Position = new Point3d(Data.table_x + 65, Data.table_y - 10, 0);
                        acText11.TextString = dataGridView1.Rows[j].Cells["Пусковой аппарат 3"].Value.ToString();
                        ObjColl.Add(acText11);

                        DBText acText12 = new DBText();
                        acText12.SetDatabaseDefaults();
                        acText12.Height = 3;
                        acText12.Position = new Point3d(Data.table_x + 108, Data.table_y - 8, 0);
                        acText12.TextString = dataGridView1.Rows[j].Cells["Обозначение 1"].Value.ToString();
                        ObjColl.Add(acText12);

                        DBText acText13 = new DBText();
                        acText13.SetDatabaseDefaults();
                        acText13.Height = 3;
                        acText13.Position = new Point3d(Data.table_x + 125, Data.table_y - 8, 0);
                        acText13.TextString = dataGridView1.Rows[j].Cells["Марка 1"].Value.ToString();
                        ObjColl.Add(acText13);

                        DBText acText14 = new DBText();
                        acText14.SetDatabaseDefaults();
                        acText14.Height = 3;
                        acText14.Position = new Point3d(Data.table_x + 138, Data.table_y - 8, 0);
                        acText14.TextString = dataGridView1.Rows[j].Cells["Жилы 1"].Value.ToString() + "x" + dataGridView1.Rows[j].Cells["Сечение 1"].Value.ToString();
                        ObjColl.Add(acText14);

                        DBText acText15 = new DBText();
                        acText15.SetDatabaseDefaults();
                        acText15.Height = 3;
                        acText15.Position = new Point3d(Data.table_x + 163, Data.table_y - 8, 0);
                        acText15.TextString = dataGridView1.Rows[j].Cells["Длина 1"].Value.ToString();
                        ObjColl.Add(acText15);

                        DBText acText16 = new DBText();
                        acText16.SetDatabaseDefaults();
                        acText16.Height = 3;
                        acText16.Position = new Point3d(Data.table_x + 108, Data.table_y - 18, 0);
                        acText16.TextString = dataGridView1.Rows[j].Cells["Обозначение 2"].Value.ToString();
                        ObjColl.Add(acText16);

                        DBText acText17 = new DBText();
                        acText17.SetDatabaseDefaults();
                        acText17.Height = 3;
                        acText17.Position = new Point3d(Data.table_x + 125, Data.table_y - 18, 0);
                        acText17.TextString = dataGridView1.Rows[j].Cells["Марка 2"].Value.ToString();
                        ObjColl.Add(acText17);

                        DBText acText18 = new DBText();
                        acText18.SetDatabaseDefaults();
                        acText18.Height = 3;
                        acText18.Position = new Point3d(Data.table_x + 138, Data.table_y - 18, 0);
                        if (dataGridView1.Rows[j].Cells["Жилы 2"].Value.ToString() + "x" + dataGridView1.Rows[j].Cells["Сечение 2"].Value.ToString() != "x")
                            acText18.TextString = dataGridView1.Rows[j].Cells["Жилы 2"].Value.ToString() + "x" + dataGridView1.Rows[j].Cells["Сечение 2"].Value.ToString();
                        else
                            acText18.TextString = "";
                        ObjColl.Add(acText18);

                        DBText acText19 = new DBText();
                        acText19.SetDatabaseDefaults();
                        acText19.Height = 3;
                        acText19.Position = new Point3d(Data.table_x + 163, Data.table_y - 18, 0);
                        acText19.TextString = dataGridView1.Rows[j].Cells["Длина 2"].Value.ToString();
                        ObjColl.Add(acText19);

                        DBText acText20 = new DBText();
                        acText20.SetDatabaseDefaults();
                        acText20.Height = 3;
                        acText20.Position = new Point3d(Data.table_x + 212, Data.table_y - 12, 0);
                        acText20.TextString = dataGridView1.Rows[j].Cells["Обознач. прием."].Value.ToString();
                        ObjColl.Add(acText20);

                        DBText acText21 = new DBText();
                        acText21.SetDatabaseDefaults();
                        acText21.Height = 3;
                        acText21.Position = new Point3d(Data.table_x + 228, Data.table_y - 12, 0);
                        acText21.TextString = dataGridView1.Rows[j].Cells["P"].Value.ToString();
                        ObjColl.Add(acText21);

                        DBText acText22 = new DBText();
                        acText22.SetDatabaseDefaults();
                        acText22.Height = 3;
                        acText22.Position = new Point3d(Data.table_x + 240, Data.table_y - 12, 0);
                        acText22.TextString = dataGridView1.Rows[j].Cells["I"].Value.ToString();
                        ObjColl.Add(acText22);

                        DBText acText23 = new DBText();
                        acText23.SetDatabaseDefaults();
                        acText23.Height = 3;
                        acText23.Position = new Point3d(Data.table_x + 252, Data.table_y - 12, 0);
                        acText23.TextString = dataGridView1.Rows[j].Cells["Наим. прием."].Value.ToString();
                        ObjColl.Add(acText23);

                        DBText acText24 = new DBText();
                        acText24.SetDatabaseDefaults();
                        acText24.Height = 3;
                        acText24.Position = new Point3d(Data.table_x + 103, Data.table_y - 8, 0);
                        acText24.TextString = "1";
                        ObjColl.Add(acText24);

                        DBText acText25 = new DBText();
                        acText25.SetDatabaseDefaults();
                        acText25.Height = 3;
                        acText25.Position = new Point3d(Data.table_x + 103, Data.table_y - 18, 0);
                        acText25.TextString = "2";
                        ObjColl.Add(acText25);
                    }
                    #endregion

                    Line l_ver = new Line(new Point3d(table_xx + 25, table_yy - 20, 0), new Point3d(table_xx + 25, Data.table_y - 26.5, 0));
                    l_ver.LineWeight = LineWeight.LineWeight050;
                    l_ver.ColorIndex = 4;
                    ObjColl.Add(l_ver);

                    Line l_ver1 = new Line(new Point3d(Data.table_x + 22.5, Data.table_y - 26.5, 0), new Point3d(Data.table_x + 27.5, Data.table_y - 26.5, 0));
                    l_ver1.LineWeight = LineWeight.LineWeight100;
                    l_ver1.ColorIndex = 4;
                    ObjColl.Add(l_ver1);

                    ObjColl.Add(new Line(new Point3d(Data.table_x, table_yy, 0), new Point3d(Data.table_x, Data.table_y - 20, 0)));
                    ObjColl.Add(new Line(new Point3d(Data.table_x, Data.table_y - 20, 0), new Point3d(Data.table_x + 63, Data.table_y - 20, 0)));

                    Database wbd = HostApplicationServices.WorkingDatabase;

                    bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
                    btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    foreach (Entity ent in ObjColl)
                    {
                        btr.AppendEntity(ent);
                        trans.AddNewlyCreatedDBObject(ent, true);
                    }
                    trans.Commit();
                    trans.Dispose();
                }
            }
            this.Show();
        }
Exemplo n.º 41
0
            public ObjectId createTextGroup(ObjectIdCollection texts)
            {
                DBObjectCollection DbTexts = new DBObjectCollection();
                foreach (ObjectId txt in texts)
                {
                    DBText text = tr.openObject(txt, OpenMode.ForWrite) as DBText;
                    text.Erase(true);

                    DBText nTxt = new DBText();
                    nTxt.Justify = text.Justify;
                    nTxt.Height = text.Height;
                    nTxt.TextString = text.TextString;
                    nTxt.Rotation = text.Rotation;
                    nTxt.AlignmentPoint = text.AlignmentPoint;
                    tr.closeObject();
                    DbTexts.Add(nTxt);
                }
                return tr.addGroup(GUID, DbTexts,false);
            }
Exemplo n.º 42
0
        private void Create_symbol1()
        {
            string blockName = "symbol1";
            DBObjectCollection entityCollection = new DBObjectCollection();
            Line ent1 = new Line(new Point3d(0, 0.12, 0), new Point3d(0, -0.12, 0));
            ent1.Layer = "0";
            entityCollection.Add(ent1);

            Point3dCollection verties = new Point3dCollection();
            verties.Add(new Point3d(0, 0, 0));
            verties.Add(new Point3d(0.077, 0.064, 0));
            verties.Add(new Point3d(0.077, -0.064, 0));
            verties.Add(new Point3d(0, 0, 0));
            Polyline2d ent2 = new Polyline2d(Poly2dType.SimplePoly, verties, 0, false, 0, 0,
                new DoubleCollection(new double[] { 0, 0, 0, 0 }));
            ent2.Layer = "0";
            entityCollection.Add(ent2);

            TryInsertBlockRecord(blockName, entityCollection);
        }
Exemplo n.º 43
0
        public static void AccessSpace()
        {

            AcadApp.Document acDoc = AcadApp.Application.DocumentManager.MdiActiveDocument;

            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                BlockTableRecord acBlkTblRec;

                // Request which table record to open询问打开哪条表记录(空间)

                PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");

                pKeyOpts.Message = "\nEnter whichspace to create the line in ";

                pKeyOpts.Keywords.Add("Model");

                pKeyOpts.Keywords.Add("Paper");

                pKeyOpts.Keywords.Add("Current");

                pKeyOpts.AllowNone = false;

                pKeyOpts.AppendKeywordsToMessage = true;

                PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

                if (pKeyRes.StringResult == "Model")                    //从Block表获取Model空间的ObjectID
                {

                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                }

                else if (pKeyRes.StringResult == "Paper")              //从Block表获取Paper空间的ObjectID
                {

                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.PaperSpace], OpenMode.ForWrite) as BlockTableRecord;
                }
                else
                {
                    //从数据库获取当前空间的ObjectID
                    acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                }


                ////设置图形中所有点对象的样式

                acCurDb.Pdmode = 34;

                acCurDb.Pdsize = 1;

                //******************************
                // Create an in memory circle在内存创建一个圆

                using (Circle acCirc = new Circle())
                {

                    acCirc.Center = new Point3d(2, 2, 0);

                    acCirc.Radius = 5;

                    // Adds the circle to an object array将圆添加到对象数组

                    DBObjectCollection acDBObjColl = new DBObjectCollection();

                    acDBObjColl.Add(acCirc);

                    // Calculate the regions based oneach closed loop

                    //基于每个闭环计算面域

                    DBObjectCollection myRegionColl = new DBObjectCollection();

                    myRegionColl = Region.CreateFromCurves(acDBObjColl);

                    Region acRegion = myRegionColl[0] as Region;

                    acBlkTblRec.AppendEntity(acRegion);

                    acTrans.AddNewlyCreatedDBObject(acRegion, true);

                    acCirc.ColorIndex = 1;
                    acBlkTblRec.AppendEntity(acCirc);

                    acTrans.AddNewlyCreatedDBObject(acCirc, true);

                    // Dispose of the in memory circlenot appended to the database

                    //处置内存中的圆,不添加到数据库;

                }

                acTrans.Commit();

            }

        }
        private void DrawLDTable(Point3d pt)
        {
            Document myDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            DocumentLock myLock = myDoc.LockDocument();
            Database acCurDb = myDoc.Database;
            Editor ed = myDoc.Editor;
            List<Line> lines = new List<Line>();
            double x0 = pt.X, y0 = pt.Y - 10 * K, z0 = pt.Z;
            //double height = y0 - k * 55;
            #region Objects
            lines.Add(new Line(new Point3d(x0, y0, z0), new Point3d(x0, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0, y0, z0), new Point3d(x0 + 185 * K, y0, z0)));
            lines.Add(new Line(new Point3d(x0, y0 - 15 * K, z0), new Point3d(x0 + 185 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 60 * K, y0, z0), new Point3d(x0 + 60 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 155 * K, y0, z0), new Point3d(x0 + 155 * K, y0 - 15 * K, z0)));
            lines.Add(new Line(new Point3d(x0 + 185 * K, y0, z0), new Point3d(x0 + 185 * K, y0 - 15 * K, z0)));
            MText Header = new MyText(new Point3d(x0 + 92.5 * K, pt.Y - 5 * K, z0), "Ведомость прилагаемых документов", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text1 = new MyText(new Point3d(x0 + 30 * K, y0 - 7.5 * K, z0), "Обозначение", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text2 = new MyText(new Point3d(x0 + 107.5 * K, y0 - 7.5 * K, z0), "Наименование", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text3 = new MyText(new Point3d(x0 + 170 * K, y0 - 7.5 * K, z0), "Примечание", K * 4, acCurDb, AttachmentPoint.MiddleCenter);
            MText[,] texts = new MText[LDIList.Count, 3];
            double realH = y0 - 15 * K;
            int i = 0, thisRows = 0, thisRows2 = 0, rowsCount = 0; //счетчик  thisRows - в столбце Наименований, thisRows2 - примечаний

            //считаем кол-во строк
            for (i = 0; i < LDIList.Count; i++)
            {
                texts[i, 0] = new MyText(new Point3d(x0 + 30 * K, realH - 3 * K, z0), LDIList[i].Label, 3 * K, acCurDb, AttachmentPoint.TopCenter);
                texts[i, 1] = new MyText(new Point3d(x0 + (60 + 2.5) * K, realH - 3 * K, z0), LDIList[i].Name, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                thisRows = (int)RowCount(texts[i, 1], 90);
                texts[i, 1].LineSpaceDistance = 8;
                texts[i, 2] = new MyText(new Point3d(x0 + (155 + 1) * K, realH - 3 * K, z0), LDIList[i].Note, 3 * K, acCurDb, AttachmentPoint.TopLeft);
                thisRows2 = (int)RowCount(texts[i, 2], 28);
                texts[i, 2].LineSpaceDistance = 8;
                thisRows = Math.Max(thisRows, thisRows2);
                for (int x = 0; x < thisRows; x++)
                {
                    lines.Add(new Line(new Point3d(x0, realH - 8 * K, z0), new Point3d(x0 + 185 * K, realH - 8 * K, z0)));
                    realH -= 8 * K;
                }
                rowsCount += thisRows;
            }
            lines.Add(new Line(new Point3d(x0, y0 - 15 * K, z0), new Point3d(x0, y0 - K * (15 + 8 * rowsCount), z0)));
            lines.Add(new Line(new Point3d(x0 + 60 * K, y0 - 15 * K, z0), new Point3d(x0 + 60 * K, y0 - K * (15 + 8 * rowsCount), z0)));
            lines.Add(new Line(new Point3d(x0 + 155 * K, y0 - 15 * K, z0), new Point3d(x0 + 155 * K, y0 - K * (15 + 8 * rowsCount), z0)));
            lines.Add(new Line(new Point3d(x0 + 185 * K, y0 - 15 * K, z0), new Point3d(x0 + 185 * K, y0 - K * (15 + 8 * rowsCount), z0)));

            #endregion
            BlockTableRecord btr;
            BlockTable bt;
            DBObjectCollection ObjColl = new DBObjectCollection(); //коллекция объектов
            #region AddObjects to collection
            ObjColl.Add(Text1); ObjColl.Add(Text2); ObjColl.Add(Text3); ObjColl.Add(Header);
            foreach (MText m in texts) ObjColl.Add(m);
            foreach (Line l in lines) ObjColl.Add(l);
            #endregion

            Database wbd = HostApplicationServices.WorkingDatabase;
            wbd.LineWeightDisplay = true;
            Transaction trans = wbd.TransactionManager.StartTransaction();
            bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
            btr = (BlockTableRecord)trans.GetObject(wbd.CurrentSpaceId, OpenMode.ForWrite);
            foreach (Entity ent in ObjColl)
            {
                btr.AppendEntity(ent);
                trans.AddNewlyCreatedDBObject(ent, true);
            }
            trans.Commit();
            trans.Dispose();
        }
Exemplo n.º 45
0
        static public void MatchPropReverse()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            PromptSelectionResult psres = ed.SelectImplied();

            // if there is no selected obj prior this command
            if (psres.Status == PromptStatus.Error)
            {
                // Select objects
                PromptSelectionOptions psopt = new PromptSelectionOptions();
                psopt.MessageForAdding   = "\nSelect objects : ";
                psopt.AllowDuplicates    = false;
                psopt.AllowSubSelections = false;
                psres = ed.GetSelection(psopt);
            }
            // if there is an obj selected prior this command
            else
            {
                ed.SetImpliedSelection(new ObjectId[0]);
            }

            // if the user has not cancelled this operation
            if (psres.Status == PromptStatus.OK)
            {
                using (Transaction tx = db.TransactionManager.StartTransaction())
                {
                    //BlockTable bt = tx.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    //BlockTableRecord btrec = tx.GetObject(bt[BlockTableRecord.ModelSpace],OpenMode.ForWrite) as BlockTableRecord;

                    LayerTable       laytab    = tx.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                    LayerTableRecord laytabrec = null;

                    DBObjectCollection dbocoll = new DBObjectCollection();
                    //ObjectId[] oids = psres.Value.GetObjectIds();
                    SelectionSet selset = psres.Value;

                    foreach (SelectedObject selobj in selset)
                    {
                        if (selobj == null)
                        {
                            ed.WriteMessage("\nNull obj detected > ID : " + selobj.ObjectId);
                        }

                        Entity ent = tx.GetObject(selobj.ObjectId, OpenMode.ForWrite) as Entity;

                        dbocoll.Add(ent);
                        //ed.WriteMessage("\nObjId original : " + selobj.ObjectId);
                    }

                    // Select donor obj v2
                    PromptEntityResult per_d = ed.GetEntity("\nSelect source object : ");
                    if (per_d.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    Entity en_d = tx.GetObject(per_d.ObjectId, OpenMode.ForRead) as Entity;


                    // Get donor obj properties
                    string     en_lyr = en_d.Layer;
                    int        en_clr = en_d.ColorIndex;
                    string     en_lt  = en_d.Linetype;
                    LineWeight en_lw  = en_d.LineWeight;
                    ed.WriteMessage("\nDonor layer/color/linetype/lineweight is : " + en_lyr + en_clr + "/" + en_lt + "/" + en_lw + "/n");

                    // Casting properties to selection set
                    foreach (Entity en in dbocoll)
                    {
                        en.Layer      = en_lyr;
                        en.ColorIndex = en_clr;
                        en.Linetype   = en_lt;
                        en.LineWeight = en_lw;
                    }
                    ed.Regen();
                    tx.Commit();
                }
            }
        }
        //рисует рамки листа и передает координаты правого нижнего угла функции рисования штампа
        /// <summary>
        /// Функция отрисовки листа
        /// </summary>
        /// <param name="pt3d">Координата левого нижнего угла</param>
        private void DrawBorders(Point3d pt3d)
        {
            PageH = double.Parse(pHeight.Text);
            PageW = double.Parse(pWidth.Text);
            double height = PageH, width = PageW, k = double.Parse(koebox.Text); K = k;
            Document myDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            DocumentLock myLock = myDoc.LockDocument();
            Database acCurDb = myDoc.Database;
            double x0 = pt3d.X, y0 = pt3d.Y, z0 = pt3d.Z, a = PageA;
            height *= k; width *= k;
            //if (orientcbx.Text != "альбомная") { double x = height; height = width; width = x; }
            A = PageA;
            Line left = new Line(new Point3d(x0, y0 + height, z0), new Point3d(x0, y0, z0));
            Line leftin = new Line(new Point3d(x0 + 20 * k, y0 + height - 5 * k, z0), new Point3d(x0 + 20 * k, y0 + a * k, z0));
            leftin.LineWeight = LineWeight.LineWeight030;
            Line right = new Line(new Point3d(x0 + width, y0 + height, z0), new Point3d(x0 + width, y0, z0));
            Line rightin = new Line(new Point3d(x0 + width - 5 * k, y0 + height - 5 * k, z0), new Point3d(x0 + width - 5 * k, y0 + a * k, z0));
            rightin.LineWeight = LineWeight.LineWeight030;
            Line top = new Line(new Point3d(x0, y0 + height, z0), new Point3d(x0 + width, y0 + height, z0));
            Line topin = new Line(new Point3d(x0 + 20 * k, y0 + height - 5 * k, z0), new Point3d(x0 + width - 5 * k, y0 + height - 5 * k, z0));
            topin.LineWeight = LineWeight.LineWeight030;
            Line bottom = new Line(new Point3d(x0, y0, z0), new Point3d(x0 + width, y0, z0));
            Line bottomin = new Line(new Point3d(x0 + 20 * k, y0 + a * k, z0), new Point3d(x0 + width - 5 * k, y0 + a * k, z0));
            bottomin.LineWeight = LineWeight.LineWeight030;
            Line line1 = new Line(new Point3d(x0 + 8 * k, y0 + a * k, z0), new Point3d(x0 + 20 * k, y0 + a * k, z0));
            line1.LineWeight = LineWeight.LineWeight030;
            Line line2 = new Line(new Point3d(x0 + 8 * k, y0 + (a + 25) * k, z0), new Point3d(x0 + 20 * k, y0 + (a + 25) * k, z0));
            line2.LineWeight = LineWeight.LineWeight030;
            Line line3 = new Line(new Point3d(x0 + 8 * k, y0 + (a + 60) * k, z0), new Point3d(x0 + 20 * k, y0 + (a + 60) * k, z0));
            line3.LineWeight = LineWeight.LineWeight030;
            Line line4 = new Line(new Point3d(x0 + 8 * k, y0 + (a + 85) * k, z0), new Point3d(x0 + 20 * k, y0 + (a + 85) * k, z0));
            line4.LineWeight = LineWeight.LineWeight030;
            Line line5 = new Line(new Point3d(x0 + 8 * k, y0 + a * k, z0), new Point3d(x0 + 8 * k, y0 + (a + 85) * k, z0));
            line5.LineWeight = LineWeight.LineWeight030;
            Line line6 = new Line(new Point3d(x0 + 13 * k, y0 + a * k, z0), new Point3d(x0 + 13 * k, y0 + (a + 85) * k, z0));
            line6.LineWeight = LineWeight.LineWeight030;
            MText Text1 = new MyText(new Point3d(x0 + 10.5 * k, y0 + (12.5 + a) * k, z0), "Инв. № подл.", k * (5 - 2.3), acCurDb, AttachmentPoint.MiddleCenter, 90);
            MText Text2 = new MyText(new Point3d(x0 + 10.5 * k, y0 + (42.5 + a) * k, z0), "Подп. и дата", k * (5 - 2.3), acCurDb, AttachmentPoint.MiddleCenter, 90);
            MText Text3 = new MyText(new Point3d(x0 + 10.5 * k, y0 + (72.5 + a) * k, z0), "Взам. инв. №", k * (5 - 2.3), acCurDb, AttachmentPoint.MiddleCenter, 90);
            MText Text4 = new MyText(new Point3d(x0 + 2.5 * k, y0 + (86 + a) * k, z0), "Согласовано", k * (5 - 2.3), acCurDb, AttachmentPoint.MiddleLeft, 90);
            MText Text5 = new MyText(new Point3d(x0 + (width - 85) * k, y0 + a / 2 * k, z0), "Копировал", k * 3, acCurDb, AttachmentPoint.MiddleCenter);
            MText Text6 = new MyText(new Point3d(x0 + (width - 25) * k, y0 + a / 2 * k, z0), "Формат   " + formatcbx.Text, k * 3, acCurDb, AttachmentPoint.MiddleCenter);

            DBObjectCollection ObjColl = new DBObjectCollection();
            ObjColl.Add(left); ObjColl.Add(leftin); ObjColl.Add(right); ObjColl.Add(rightin);
            ObjColl.Add(top); ObjColl.Add(topin); ObjColl.Add(bottom); ObjColl.Add(bottomin);
            ObjColl.Add(line1); ObjColl.Add(line2); ObjColl.Add(line3); ObjColl.Add(line4); ObjColl.Add(line5); ObjColl.Add(line6);
            ObjColl.Add(Text1); ObjColl.Add(Text2); ObjColl.Add(Text3); ObjColl.Add(Text4); ObjColl.Add(Text5); ObjColl.Add(Text6);
            ObjColl.Add(new Line(new Point3d(x0, y0 + (a + 85) * k, z0), new Point3d(x0 + 20 * k, y0 + (a + 85) * k, z0)));
            ObjColl.Add(new Line(new Point3d(x0 + 5 * k, y0 + (a + 105) * k, z0), new Point3d(x0 + 20 * k, y0 + (a + 105) * k, z0)));
            ObjColl.Add(new Line(new Point3d(x0 + 5 * k, y0 + (a + 125) * k, z0), new Point3d(x0 + 20 * k, y0 + (a + 125) * k, z0)));
            ObjColl.Add(new Line(new Point3d(x0 + 5 * k, y0 + (a + 140) * k, z0), new Point3d(x0 + 20 * k, y0 + (a + 140) * k, z0)));
            ObjColl.Add(new Line(new Point3d(x0, y0 + (a + 150) * k, z0), new Point3d(x0 + 20 * k, y0 + (a + 150) * k, z0)));
            ObjColl.Add(new Line(new Point3d(x0 + 5 * k, y0 + (a + 85) * k, z0), new Point3d(x0 + 5 * k, y0 + (a + 150) * k, z0)));
            ObjColl.Add(new Line(new Point3d(x0 + 10 * k, y0 + (a + 85) * k, z0), new Point3d(x0 + 10 * k, y0 + (a + 150) * k, z0)));
            ObjColl.Add(new Line(new Point3d(x0 + 15 * k, y0 + (a + 85) * k, z0), new Point3d(x0 + 15 * k, y0 + (a + 150) * k, z0)));

            Database wbd = HostApplicationServices.WorkingDatabase;
            BlockTableRecord btr;
            BlockTable bt;
            Transaction trans = wbd.TransactionManager.StartTransaction();
            bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
            btr = (BlockTableRecord)trans.GetObject(wbd.CurrentSpaceId, OpenMode.ForWrite);
            foreach (Entity ent in ObjColl)
            {
                btr.AppendEntity(ent);
                trans.AddNewlyCreatedDBObject(ent, true);
            }
            trans.Commit();
            trans.Dispose();
            DrawStampLines(new Point3d(x0 + width - 5 * k, y0 + a * k, z0), k);
            //необходимые координаты
            Point3d InnerLeftTop = new Point3d(x0 + 20 * k, y0 + height - 5 * k, z0); P1 = InnerLeftTop;
            Point3d InnerLeftBottom = new Point3d(x0 + 20 * k, y0 + a * k, z0); P3 = InnerLeftBottom;
            Point3d StampLeftTop = new Point3d(x0 + width - 190 * k, y0 + (a + 55) * k, z0); P2 = StampLeftTop;
        }
Exemplo n.º 47
0
        /// <summary>
        /// Sorts a DBObjectCollection so that the order of its items corresponds 
        /// to the position of these items along the axis parameter. 
        /// </summary>
        /// <param name="entities">Entities that will be sorted.</param>
        /// <param name="axis">Axis along which the entities will be sorted.</param>
        /// <param name="sortParameter">Defines what point in the object's GeometricExtents will be used to sort.</param>
        /// <remarks>The entity's position is obtained from the GeometricExtents and uses what the sortParameter indicates.</remarks>
        public static DBObjectCollection SortEntities(DBObjectCollection entities, Axis axis, SortParameter sortParameter)
        {
            DBObject[] entitiesArray = new DBObject[entities.Count];
            double[] positions = new double[entities.Count];

            for (int i = 0; i < entities.Count; i++)
            {
                Entity entity = (Entity)entities[i];
                entitiesArray[i] = entity;

                switch (axis)
                {
                    case Axis.X:
                        switch (sortParameter)
                        {
                            case SortParameter.MinPoint:
                                positions[i] = entity.GeometricExtents.MinPoint.X;
                                break;
                            case SortParameter.CenterPoint:
                                positions[i] = (entity.GeometricExtents.MinPoint.X + entity.GeometricExtents.MaxPoint.X) / 2;
                                break;
                            case SortParameter.MaxPoint:
                                positions[i] = entity.GeometricExtents.MinPoint.X;
                                break;
                            default:
                                break;
                        }
                        break;
                    case Axis.Y:
                        switch (sortParameter)
                        {
                            case SortParameter.MinPoint:
                                positions[i] = entity.GeometricExtents.MinPoint.Y;
                                break;
                            case SortParameter.CenterPoint:
                                positions[i] = (entity.GeometricExtents.MinPoint.Y + entity.GeometricExtents.MaxPoint.Y) / 2;
                                break;
                            case SortParameter.MaxPoint:
                                positions[i] = entity.GeometricExtents.MinPoint.Y;
                                break;
                            default:
                                break;
                        }
                        break;
                    case Axis.Z:
                        switch (sortParameter)
                        {
                            case SortParameter.MinPoint:
                                positions[i] = entity.GeometricExtents.MinPoint.Z;
                                break;
                            case SortParameter.CenterPoint:
                                positions[i] = (entity.GeometricExtents.MinPoint.Z + entity.GeometricExtents.MaxPoint.Z) / 2;
                                break;
                            case SortParameter.MaxPoint:
                                positions[i] = entity.GeometricExtents.MinPoint.Z;
                                break;
                            default:
                                break;
                        }
                        break;
                }
            }

            Array.Sort(positions, entitiesArray);

            DBObjectCollection sortedEntities = new DBObjectCollection();
            for (int i = 0; i < entitiesArray.Length; i++)
            {
                sortedEntities.Add(entitiesArray[i]);
            }

            return sortedEntities;
        }
Exemplo n.º 48
0
        public bool TryCreateContourLinesBlock(string blockName)
        {
            int barAmount = firstBarLine.StartPoint.NumberOfBarsToPoint(lastBarLine.StartPoint,
                spanStep.Value);
            string text = GetCountourLinesText(barAmount, barDiameter.Value, spanStep.Value);

            DBObjectCollection entityCollection = new DBObjectCollection();
            Line l1 = CreateFirstBarLine();
            Line l2 = CreateBarLine(lastBarLine.StartPoint, lastBarLine.EndPoint);
            Line l3 = CreateBarLine(firstBarLine.StartPoint, lastBarLine.EndPoint);
            Point3d textOrigin = GetTextOrigin(l3);
            MText mText = GetMText(text, textOrigin);
            entityCollection.Add(l1);
            entityCollection.Add(l2);
            entityCollection.Add(l3);
            entityCollection.Add(mText);
            return bdm.TryInsertBlockRecord(blockName, entityCollection);
        }
        public void GetIntersectionsRiver()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Transaction tr = db.TransactionManager.StartTransaction();

            #region For Word
            string filepath = "D:\\intersections_rivers.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость пересечений"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                         new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Наимен. водотока")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Пикетное положение пересечения")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Ширина водотока в межень")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Глуб. водотока")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 3 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Горизонт воды")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим."))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 });
            #endregion

                    while (true)
                    {

                        //using (tr)
                        //{
                        try
                        {
                            #region Поиск пересечений
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline  >>");
                            peo.SetRejectMessage("\nМожно только polyline >>");
                            peo.AddAllowedClass(typeof(Polyline), false);
                            PromptEntityResult res;
                            res = ed.GetEntity(peo);
                            if (res.Status != PromptStatus.OK)
                            {
                                break;
                            }
                            DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                            if (ent == null) return;

                            PromptPointResult pPtRes;
                            PromptPointOptions pPtOpts = new PromptPointOptions("");
                            // Prompt for the start point
                            pPtOpts.Message = "\nВведи начало: ";
                            pPtRes = doc.Editor.GetPoint(pPtOpts);

                            PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                            PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);

                            //zoom
                            /*PromptEntityResult per = ed.GetEntity(peo);

                            if (per.Status != PromptStatus.OK)
                                return;*/

                            // Extract its extents

                            Extents3d ext;

                            Transaction trans = db.TransactionManager.StartTransaction();
                            using (trans)
                            {
                                Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                                ext = enti.GeometricExtents;
                                trans.Commit();
                            }

                            ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse());

                            ZoomWin(ed, ext.MinPoint, ext.MaxPoint);
                            //

                            //Polyline poly = (Polyline)ent as Polyline;
                            Curve curv = ent as Curve;

                            DBObjectCollection pcurves = new DBObjectCollection();

                            curv.Explode(pcurves);
                            TypedValue[] values = new TypedValue[]
                     {
                        new TypedValue(0, "lwpolyline")
                        //might be added layer name to select curve:
                        //, new TypedValue(8, "mylayer")
                     };
                            SelectionFilter filter = new SelectionFilter(values);

                            Point3dCollection fence = new Point3dCollection();

                            double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                            // number of divisions along polyline to create fence selection
                            double step = leng / 256;// set number of steps to your suit

                            int num = Convert.ToInt32(leng / step);

                            for (int i = 0; i < num; i++)
                            {
                                Point3d pp = curv.GetPointAtDist(step * i);

                                fence.Add(curv.GetClosestPointTo(pp, false));
                            }

                            PromptSelectionResult selres = ed.SelectFence(fence, filter);

                            if (selres.Status != PromptStatus.OK) return;
                            Point3dCollection intpts = new Point3dCollection();

                            DBObjectCollection qcurves = new DBObjectCollection();
                            //ed.WriteMessage("\nCheck");
                            foreach (SelectedObject selobj in selres.Value)
                            {
                                DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                                if (selobj.ObjectId != curv.ObjectId)
                                {
                                    DBObjectCollection icurves = new DBObjectCollection();
                                    Curve icurv = obj as Curve;
                                    icurv.Explode(icurves);
                                    foreach (DBObject dbo in icurves)
                                    {
                                        if (!qcurves.Contains(dbo))
                                            qcurves.Add(dbo);
                                    }
                                }

                            }
                            //ed.WriteMessage("\n{0}", qcurves.Count);

                            int j = 0;
                            Point3dCollection polypts = new Point3dCollection();

                            for (int i = 0; i < pcurves.Count; ++i)
                            {
                                for (j = 0; j < qcurves.Count; ++j)
                                {
                                    Curve curve1 = pcurves[i] as Curve;

                                    Curve curve2 = qcurves[j] as Curve;

                                    Point3dCollection pts = new Point3dCollection();

                                    curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);

                                    foreach (Point3d pt in pts)
                                    {
                                        if (!polypts.Contains(pt))
                                            polypts.Add(pt);
                                    }
                                }
                            }
                            #endregion

                            try
                            {
                                using (Transaction tran = db.TransactionManager.StartTransaction())
                                {
                                    Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                    table.AppendChild(new TableRow(
                                        new TableCell(
                                            new TableCellProperties(
                                                new GridSpan() { Val = 9 }),
                                                new Paragraph(
                                                    new ParagraphProperties(
                                                        new ParagraphMarkRunProperties(new Bold()),
                                                        new Justification() { Val = JustificationValues.Center }),
                                                        new Run(new RunProperties(
                                                            new Bold()),
                                                            new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" +
                                                                ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" +
                                                                ((100 * getpikRes.Value + pline.Length) % 100).ToString("F")))))));
                                }
                            }
                            catch { ed.WriteMessage("\nError."); }

                            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional
                            // for debug only
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count));

                            if (polypts.Count == 0)
                            {
                                try
                                {
                                    using (Transaction tran = db.TransactionManager.StartTransaction())
                                    {
                                        Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                        table.AppendChild(new TableRow(
                                            new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 9 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text("На данном участке трассы пересечения отсутствуют"))))));
                                    }
                                }
                                catch { ed.WriteMessage("\nError."); }
                            }
                            else
                            {
                                //List<double> pik = new List<double>(polypts.Count);
                                double[] pik = new double[polypts.Count];
                                int numInter = 0;

                                foreach (Point3d inspt in polypts)
                                {
                                    double dist = 0;
                                    dist = 100 * getpikRes.Value;

                                    // test for visulization only
                                    /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                                    circ.ColorIndex = 1;
                                    btr.AppendEntity(circ);
                                    tr.AddNewlyCreatedDBObject(circ, true);*/

                                    Point3d curr = pPtRes.Value, next = pPtRes.Value;
                                    try
                                    {
                                        using (Transaction tran = db.TransactionManager.StartTransaction())
                                        {
                                            Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                            if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                                for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                            else
                                                for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                        }
                                    }
                                    catch
                                    {
                                        ed.WriteMessage("\nInvalid polyline.");
                                    }
                                    pik[numInter] = dist;
                                    numInter++;
                                    //ed.WriteMessage(" {0:0.00}\n", dist);
                                }

                                //pik.Sort();

                                Array.Sort(pik);

                                for (int i = 0; i < polypts.Count; i++)
                                {
                                    tr1 = new TableRow(
                                        new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 2 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run()))
                                        );
                                    table.AppendChild(tr1);
                                }
                            }

                        }
                        catch
                        {
                            ed.WriteMessage("\nError");
                        }
                        //}
                    }

                    tr.Commit();

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
Exemplo n.º 50
0
 private DBObjectCollection SquareOfLines(double height, double width, double deep, int type)
 {
     // A function to generate a set of entities for our block
     var ents = new DBObjectCollection();
     Point3d[] pts = {
                             new Point3d(0, 0, 0),
                             new Point3d(0, 0, width),
                             new Point3d(height, 0, width),
                             new Point3d(height, 0, 0),
                             new Point3d(0, deep, 0),
                             new Point3d(0, deep, width),
                             new Point3d(height, deep, width),
                             new Point3d(height, deep, 0)
                         };
     // first square
     byte red = 0, green, blue = 0;
     switch (type)
     {
         case 1:
             red = 255; green = 150; break;
         case 2:
             green = 255; break;
         case 3:
             green = 255; blue = 255; break;
         default:
             red = 255; green = 255; blue = 255;
             break;
     }
     Line ln;
     for (int i = 0; i <= 3; i++)
     {
         int j = (i == 3 ? 0 : i + 1);
         ln = new Line(pts[i], pts[j]) { Color = Color.FromRgb(red, green, blue) };
         ents.Add(ln);
     }
     // second square
     for (int i = 4; i <= 7; i++)
     {
         int j = (i == 7 ? 4 : i + 1);
         ln = new Line(pts[i], pts[j]) { Color = Color.FromRgb(red, green, blue) };
         ents.Add(ln);
     }
     // Complete cube
     for (int i = 0; i <= 3; i++)
     {
         int j = i + 4;
         ln = new Line(pts[i], pts[j]) { Color = Color.FromRgb(red, green, blue) };
         ents.Add(ln);
     }
     return ents;
 }
Exemplo n.º 51
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
            {
                return(false);
            }

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                using (Solid3d cube = new Solid3d())
                {
                    try
                    {
                        if (switchm == 1)
                        {
                            cube.CreateFrustum(_profSide, _profSide, _profSide, 0.0);
                        }
                        else if (switchm == 0)
                        {
                            cube.CreateBox(_profSide, _profSide, _profSide);
                        }


                        if (cube != null)
                        {
                            cube.TransformBy(
                                Matrix3d.Displacement(
                                    _resizeLocation - Point3d.Origin
                                    )
                                );

                            // Draw the cursor

                            draw.SubEntityTraits.Color = ColorIndex;
                            cube.WorldDraw(draw);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _doc.Editor.WriteMessage(
                            "\nException: {0} - {1}", ex.Message, ex.InnerException
                            );
                    }
                    finally
                    {
                        draw.SubEntityTraits.Color = origCol;
                    }
                }



                return(true);
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                        )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int  n         = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                                _profSide, GetAllButLast(_vertices, n++), out sol
                                );

                            _created.Add(sol);
                            sol       = null;
                            succeeded = true;
                        }
                        catch { }
                    }while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            if (switchm == 1)
                            {
                                cursor.CreateFrustum(_profSide, _profSide, _profSide, 0.0);
                            }
                            else if (switchm == 0)
                            {
                                cursor.CreateBox(_profSide, _profSide, _profSide);
                            }
                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                    Matrix3d.Displacement(lastPt - Point3d.Origin)
                                    );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 4;     // ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return(true);
        }
Exemplo n.º 52
0
        /**
         * @brief   Metodo que descompone una enitdad AUTOCAD en sub-entidades cuando es posible. Replica el comportamiento del comando
         *          DESCOMPONER / EXPLODE de AutoCAD. Las unidades básicas que devuelve son puntos y lineas. Descompone recursivamente
         *          las entidades hasta dejarlas representadas como puntos, lineas y arcos.
         *
         * @param   ent         Entidad que debe ser descompuesta
         * @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.
         *
         * @return              Devuelve una colección de entidades bajo la clase DBObjectCollection.
         **/
        private static DBObjectCollection ObtenerPuntosyLineas(Entity ent, BlockTable acBlkTbl, BlockTableRecord acBlkTblRec, Transaction t)
        {
            DBObjectCollection retorno = new DBObjectCollection();
            DBObjectCollection procesar = new DBObjectCollection();

            ent.Explode(procesar);

            while (procesar.Count != 0)
            {
                Entity obj = (Entity) procesar[0];
                acBlkTblRec.AppendEntity(obj);
                t.AddNewlyCreatedDBObject(obj, true);
                dwgf.objetosArtificiales.Add(obj.ObjectId);

                if (obj.ObjectId.ObjectClass.DxfName == "POINT" || obj.ObjectId.ObjectClass.DxfName == "LINE")
                {
                    if (retorno.Contains(obj) == false)
                    {
                        retorno.Add(obj);
                    }
                }
                if (obj.ObjectId.ObjectClass.DxfName == "ARC")
                {
                   // Completar con el proceso para los arcos.
                    if (retorno.Contains(obj) == false)
                    {
                        retorno.Add(obj);
                    }
                }
                if (obj.ObjectId.ObjectClass.DxfName == "LWPOLYLINE")
                {
                   DBObjectCollection aux = new DBObjectCollection();
                   obj.Explode(aux);
                   foreach (DBObject aux2 in aux)
                   {
                       procesar.Add(aux2);
                   }
                }
                procesar.Remove(obj);
            }

            return retorno;
        }
Exemplo n.º 53
0
            public static DBObjectCollection PolylineFromRegion(
                Region reg
                )
            {
                // We will return a collection of entities
                // (should include closed Polylines and other
                // closed curves, such as Circles)

                DBObjectCollection res =
                    new DBObjectCollection();

                // Explode Region -> collection of Curves / Regions

                DBObjectCollection cvs =
                    new DBObjectCollection();

                reg.Explode(cvs);

                // Create a plane to convert 3D coords
                // into Region coord system

                Plane pl =
                    new Plane(new Point3d(0, 0, 0), reg.Normal);

                using (pl)
                {
                    bool finished = false;

                    while (!finished && cvs.Count > 0)
                    {
                        // Count the Curves and the non-Curves, and find
                        // the index of the first Curve in the collection

                        int cvCnt = 0, nonCvCnt = 0, fstCvIdx = -1;

                        for (int i = 0; i < cvs.Count; i++)
                        {
                            Curve tmpCv = cvs[i] as Curve;
                            if (tmpCv == null)
                            {
                                nonCvCnt++;
                            }
                            else
                            {
                                // Closed curves can go straight into the
                                // results collection, and aren't added
                                // to the Curve count

                                if (tmpCv.Closed)
                                {
                                    res.Add(tmpCv);
                                    cvs.Remove(tmpCv);
                                    // Decrement, so we don't miss an item
                                    i--;
                                }
                                else
                                {
                                    cvCnt++;
                                    if (fstCvIdx == -1)
                                    {
                                        fstCvIdx = i;
                                    }
                                }
                            }
                        }

                        if (fstCvIdx >= 0)
                        {
                            // For the initial segment take the first
                            // Curve in the collection

                            Curve fstCv = (Curve)cvs[fstCvIdx];

                            // The resulting Polyline

                            Polyline p = new Polyline();

                            // Set common entity properties from the Region

                            p.SetPropertiesFrom(reg);

                            // Add the first two vertices, but only set the
                            // bulge on the first (the second will be set
                            // retroactively from the second segment)

                            // We also assume the first segment is counter-
                            // clockwise (the default for arcs), as we're
                            // not swapping the order of the vertices to
                            // make them fit the Polyline's order

                            p.AddVertexAt(
                                p.NumberOfVertices,
                                fstCv.StartPoint.Convert2d(pl),
                                BulgeFromCurve(fstCv, false), 0, 0
                                );

                            p.AddVertexAt(
                                p.NumberOfVertices,
                                fstCv.EndPoint.Convert2d(pl),
                                0, 0, 0
                                );

                            cvs.Remove(fstCv);

                            // The next point to look for

                            Point3d nextPt = fstCv.EndPoint;

                            // We no longer need the curve

                            fstCv.Dispose();

                            // Find the line that is connected to
                            // the next point

                            // If for some reason the lines returned were not
                            // connected, we could loop endlessly.
                            // So we store the previous curve count and assume
                            // that if this count has not been decreased by
                            // looping completely through the segments once,
                            // then we should not continue to loop.
                            // Hopefully this will never happen, as the curves
                            // should form a closed loop, but anyway...

                            // Set the previous count as artificially high,
                            // so that we loop once, at least.

                            int prevCnt = cvs.Count + 1;
                            while (cvs.Count > nonCvCnt && cvs.Count < prevCnt)
                            {
                                prevCnt = cvs.Count;
                                foreach (DBObject obj in cvs)
                                {
                                    Curve cv = obj as Curve;

                                    if (cv != null)
                                    {
                                        // If one end of the curve connects with the
                                        // point we're looking for...

                                        if (cv.StartPoint == nextPt ||
                                            cv.EndPoint == nextPt)
                                        {
                                            // Calculate the bulge for the curve and
                                            // set it on the previous vertex

                                            double bulge =
                                                BulgeFromCurve(cv, cv.EndPoint == nextPt);
                                            if (bulge != 0.0)
                                            {
                                                p.SetBulgeAt(p.NumberOfVertices - 1, bulge);
                                            }

                                            // Reverse the points, if needed

                                            if (cv.StartPoint == nextPt)
                                            {
                                                nextPt = cv.EndPoint;
                                            }
                                            else
                                            {
                                                // cv.EndPoint == nextPt
                                                nextPt = cv.StartPoint;
                                            }

                                            // Add out new vertex (bulge will be set next
                                            // time through, as needed)

                                            p.AddVertexAt(
                                                p.NumberOfVertices,
                                                nextPt.Convert2d(pl),
                                                0, 0, 0
                                                );

                                            // Remove our curve from the list, which
                                            // decrements the count, of course

                                            cvs.Remove(cv);
                                            cv.Dispose();

                                            break;
                                        }
                                    }
                                }
                            }

                            // Once we have added all the Polyline's vertices,
                            // transform it to the original region's plane

                            p.TransformBy(Matrix3d.PlaneToWorld(pl));
                            res.Add(p);

                            if (cvs.Count == nonCvCnt)
                            {
                                finished = true;
                            }
                        }

                        // If there are any Regions in the collection,
                        // recurse to explode and add their geometry

                        if (nonCvCnt > 0 && cvs.Count > 0)
                        {
                            foreach (DBObject obj in cvs)
                            {
                                Region subReg = obj as Region;
                                if (subReg != null)
                                {
                                    DBObjectCollection subRes =
                                        PolylineFromRegion(subReg);

                                    foreach (DBObject o in subRes)
                                    {
                                        res.Add(o);
                                    }

                                    cvs.Remove(subReg);
                                    subReg.Dispose();
                                }
                            }
                        }
                        if (cvs.Count == 0)
                        {
                            finished = true;
                        }
                    }
                }
                return(res);
            }
        private void button12_Click(object sender, EventArgs e)
        {
            this.Hide();

            string textM = "";
            double pointX = 0, pointY = 0;

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (DocumentLock doclock = acDoc.LockDocument())
            {
                // Старт транзакции
                using (Transaction trans = acCurDb.TransactionManager.StartTransaction())
                {
                    // Запрос выбора объектов в области чертежа
                    PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection();

                    // Если статус запроса равен OK, объекты выбраны
                    if (acSSPrompt.Status == PromptStatus.OK)
                    {
                        SelectionSet acSSet = acSSPrompt.Value;
                        // Перебор объектов в наборе
                        foreach (SelectedObject acSSObj in acSSet)
                        {
                            // Проверка, нужно убедиться в правильности полученного объекта
                            if (acSSObj != null)
                            {
                                // Открытие объекта для чтения
                                Line acEnt = trans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Line;
                                if (acEnt != null)
                                {

                                    int indS = Data.pathPoints.FindIndex(item => item == acEnt.StartPoint);
                                    int indE = Data.pathPoints.FindIndex(item => item == acEnt.EndPoint);

                                    pointX = acEnt.StartPoint.X;
                                    pointY = acEnt.StartPoint.Y;

                                    List<string> tmp = new List<string>();
                                    tmp = Data.pathName[indS];

                                    foreach (String str in tmp)
                                    {
                                        if (Data.pathName[indE].Contains(str))
                                            textM = String.Concat(textM, "/", str);
                                    }

                                }
                            }
                        }
                    }

                    BlockTableRecord btr;
                    BlockTable bt;
                    DBObjectCollection ObjColl = new DBObjectCollection();
                    MText objText = new MText();
                    objText.SetDatabaseDefaults();
                    objText.Location = new Point3d(pointX, pointY + 5, 0);
                    objText.Contents = textM;
                    objText.TextStyleId = acCurDb.Textstyle;
                    objText.TextHeight = 3;
                    objText.Height = 25;
                    objText.Width = 25;
                    ObjColl.Add(objText);

                    Database wbd = HostApplicationServices.WorkingDatabase;

                    bt = (BlockTable)trans.GetObject(wbd.BlockTableId, OpenMode.ForRead);
                    btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    foreach (Entity ent in ObjColl)
                    {
                        btr.AppendEntity(ent);
                        trans.AddNewlyCreatedDBObject(ent, true);
                    }
                    trans.Commit();
                    trans.Dispose();
                }
            }

            this.Show();
        }