Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - fixo

Pages: 1 2 [3] 4 5 ... 7
31
Dimensions / Get the geometry from a dimension entity
« on: January 17, 2013, 11:04:00 PM »
Code: [Select]
        // Get the geometry from a dimension entity
        // translated on C# from article by  Augusto Goncalves:
        // http://adndevblog.typepad.com/autocad/2013/01/get-the-geometry-from-a-dimension-entity.html
        [CommandMethod("dgeom", CommandFlags.UsePickSet)]
        public void GetDimensionLinesData()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            Transaction tr = doc.TransactionManager.StartOpenCloseTransaction();

            using (tr)
            {

                Dimension diment = null;

                PromptEntityOptions peo = new PromptEntityOptions("\nSelect a Dimension>>");
                peo.SetRejectMessage("\nSelect Dimension only >>");
                peo.AddAllowedClass(typeof(Dimension), false);
                PromptEntityResult res;
                res = ed.GetEntity(peo);
                if (res.Status != PromptStatus.OK)
                    return;
                Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                if (ent == null)
                    return;
                diment = (Dimension)ent as Dimension;
                if (diment == null)
                {
                    ed.WriteMessage("\nError: selected entity is not a Dimension");
                    return;
                }
                //get current space
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                //get dimension block definition
                BlockTableRecord dimbtr = tr.GetObject(diment.DimBlockId, OpenMode.ForRead) as BlockTableRecord;
                MessageBox.Show(dimbtr.Name);
                BlockTableRecordEnumerator iter = dimbtr.GetEnumerator();
                Entity obj;
                // Iterate every entity stored in the
                // block definition of the dimension.
                while (iter.MoveNext())
                {
                   
                    obj = tr.GetObject((ObjectId)iter.Current, OpenMode.ForRead) as Entity;

                    Line ln = obj as Line;

                    if (ln != null)
                    {

                        // Get the start and end point. 

                        Point3d sp, ep;

                        sp = ln.StartPoint;
                        ep = ln.EndPoint;


                        //     // Transform the start and end point.   

                        //     // Get the transformation matrix.   

                        Matrix3d mat = new Matrix3d();

                        // Get the axis of the dimension entity.

                        Vector3d zAxis = diment.Normal;

                        Vector3d xAxis = zAxis.GetPerpendicularVector();

                        Vector3d yAxis = zAxis.CrossProduct(xAxis);

                        // Build the transformation matrix.   
                       
                        mat = Matrix3d.AlignCoordinateSystem(Point3d.Origin, new Vector3d(1.0, 0.0, 0.0),

                          new Vector3d(0.0, 1.0, 0.0),

                          new Vector3d(0.0, 0.0, 1.0),

                          Point3d.Origin,

                          xAxis, yAxis, zAxis);
                     

                        // To test this matrix create a new line   

                        // using the start and endpoint of the line

                        // from the block definition, and transform   

                        // the line using the calculated transformation matrix.     

                        Line newln = new Line(sp, ep);

                        newln.TransformBy(mat);

                        Point3d nptStart, nptEnd;

                        nptStart = newln.StartPoint;

                        nptEnd = newln.EndPoint;

                        newln.ColorIndex = 4;

                        // Append the new line to the model space and close it.   

                        // The new line should be at the location     

                        // of the dimension entity.     

                       
                        btr.AppendEntity(newln);
                        tr.AddNewlyCreatedDBObject(newln, true);
               
                    }

                    tr.Commit();

                }
            }
        }

32
Blocks / How to place blocks in a rectangular area evenly
« on: January 15, 2013, 09:43:33 PM »
This one is written on C# only
Please, change block name and sizes to your suit

33
Polylines / Create 3d polyline from points
« on: January 12, 2013, 11:03:35 PM »
Code: [Select]
        [CommandMethod("c3p")]
        static public void Create3dPolyline()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

         Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                // Get blocktable and modelspace (for write)
                BlockTable bt =  (BlockTable)tr.GetObject(   db.BlockTableId, OpenMode.ForRead,  false);

                BlockTableRecord btr =(BlockTableRecord)tr.GetObject( bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false );
               
                // Create a 3D polyline with 6 segments (closed)
                Point3d[] pts = new Point3d[]
                        { new Point3d(0,0,0),
                          new Point3d(60,0,0),
                         new Point3d(60,0,60),
                         new Point3d(60,60,60),
                         new Point3d(0,60,60),
                         new Point3d(0,0,60)
                        };
                Point3dCollection points = new Point3dCollection(pts);

                Polyline3d poly = new Polyline3d();
                // First add polyline to model space and transaction
                btr.AppendEntity(poly);

                tr.AddNewlyCreatedDBObject(poly, true);
                // Then add all vertices to polyline from point collection
                foreach (Point3d pt in points)
                {
                    // Now create the vertices

                    PolylineVertex3d vex3d = new PolylineVertex3d(pt);

                    // And add them to the 3dpoly (this adds them to the db also)

                    poly.AppendVertex(vex3d);

                    tr.AddNewlyCreatedDBObject(vex3d, true);
                   
                }
                // Make polyline closed
                poly.Closed = true;
                // Change color
                poly.ColorIndex = 14;
                // Commit transaction
                tr.Commit();

            }
        }

34
 
Code: [Select]
              public static ErrorStatus fixoGetEntity(Transaction tr, Editor ed, RXClass rx, string msg, out ObjectId id)
        {
            ErrorStatus es;
            Entity ent;
            id = ObjectId.Null;
            PromptEntityOptions peo = new PromptEntityOptions(msg);
            peo.SetRejectMessage("\nYou're missing, try again >>");
            peo.AddAllowedClass(typeof(Entity), false);
            PromptEntityResult res;
            res = ed.GetEntity(peo);
            if (res.Status != PromptStatus.OK)
                es = ErrorStatus.PointNotOnEntity;
            id = res.ObjectId;
            if (id == ObjectId.Null)
                es = ErrorStatus.NullObjectId;
            ent = tr.GetObject(id, OpenMode.ForRead, false) as Entity;
            if (ent.GetRXClass() != rx)
            {
                ed.WriteMessage("\n{0}Must be a \"{0}\" type of only!",rx.DxfName);
                es = ErrorStatus.NotThatKindOfClass;
            }
            if (ent == null)
                es = ErrorStatus.NotAnEntity;
            else es = ErrorStatus.OK;
            return es;
        }
         

        // Use function above this way
        [CommandMethod("tef")]
        public static void testSelectFunction()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            ObjectId id = ObjectId.Null;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
               if (fixoGetEntity(tr, ed, RXClass.GetClass(typeof(MText)), "\nSelect MTEXT to edit", out id) == ErrorStatus.OK)
                {
                    ed.WriteMessage("\nObjectId: {0}\n", id);
                    ed.WriteMessage("\nEntity Name: {0}\n", id.ObjectClass.DxfName);
                    // get entity by direct cast
                    Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite);
                    ent.ColorIndex = 121;// do whatever you need with entity here
                    tr.Commit();
                }
            }
        }

35
Polylines / Getting the Midpoint of each Polyline Segment
« on: January 10, 2013, 03:08:32 PM »
        Getting the Midpoint of each Polyline Segment
        based on article by Fenton Webb here:
        http://adndevblog.typepad.com/autocad/2013/01/getting-the-midpoint-of-each-polyline-segment-using-objectarx.html
Code: [Select]
        [CommandMethod("smp")] //OK  //
        public void ShowMidPointOnEachSegment()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = HostApplicationServices.WorkingDatabase;
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("pdmode", (short)34);
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("pdsize", (double)5.0);
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                 BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
             
                    Entity ename;

                    PromptEntityResult retval = ed.GetEntity("\nSelect LW polyline: ");

                    if (retval.Status != PromptStatus.OK)

                        return;

                    Curve curv;

                    ObjectId id;

                    id = retval.ObjectId;

                    ename = tr.GetObject(id, OpenMode.ForWrite) as Entity;

                    curv = ename as Polyline;
                    if (curv == null)
                    {
                        ed.WriteMessage("\nSelected entity is not a LW polyline");
                        return;
                    }
                    if (!curv.IsWriteEnabled)
                        curv.UpgradeOpen();

                    double startParam, endParam;

                    // get the start param, usually it starts at 0 or 1

                    startParam = curv.StartParam;

                    ed.WriteMessage("\nStartParam is: {0:f3}\n", startParam);

                    // get the end param, for a polyline it's the total number of

                    // vertex's -1

                    endParam = curv.EndParam;

                    ed.WriteMessage("\nEndParam is: {0:f3}\n", endParam);

                    // now loop the parameters, adding 1.0 each iteration

                    for (double i = startParam; i < endParam; ++i)
                    {

                        Point3d pt;

                        pt = curv.GetPointAtParameter(i + 0.5);
                        // create points to display result
                        DBPoint dp = new DBPoint(pt);
                        dp.ColorIndex = 1;
                        btr.AppendEntity(dp);

                        tr.AddNewlyCreatedDBObject(dp, true);

                        ed.WriteMessage("\nMid Point: {0:f3},{1:f3},{2:f3}\n", pt[0], pt[1], pt[2]);

                    }
                    tr.Commit();
                }
            }

36
Polylines / Create region from connected arcs and lines
« on: January 10, 2013, 08:23:44 AM »
Code: [Select]
        //Create region from connected arcs and lines
        [CommandMethod("craw")]
        public static void CreateRegionFromConnected()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            DBObjectCollection objs = new DBObjectCollection();

            DBObjectCollection regcoll = new DBObjectCollection();

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

                BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                TypedValue[] tvs = new TypedValue[] { new TypedValue(0, "line,arc") };

                Point3dCollection points = new Point3dCollection();

                SelectionFilter sf = new SelectionFilter(tvs);

                PromptSelectionResult sres = ed.GetSelection(sf);

                if (sres.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\nInvalid selection!");

                    return;
                }

                foreach (SelectedObject selobj in sres.Value)
                {
                    DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForWrite, false) as DBObject;

                    objs.Add(obj);

                }

                regcoll = Region.CreateFromCurves(objs);

                Region reg = regcoll[0] as Region;

                btr.AppendEntity(reg);

                tr.AddNewlyCreatedDBObject(reg, true);
                // you might be want to remove the parent objects here,
                // because of DELOBJ variable did not effect :
                //foreach (DBObject obj in objs)
                //    obj.Erase();  // uncomment this code block if needs

                tr.Commit();
            }
        }

37
Blocks / How to insert multiline attributes
« on: January 09, 2013, 08:07:58 PM »

Code: [Select]
        // based on code example from article by by Gopinath Taget here:
        //  http://adndevblog.typepad.com/autocad/2013/01/how-to-mimic-the-autocad-insert-command-in-arx-without-acedcommand-call.html

        [CommandMethod("testInsertCommand", "doi", CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public static void DoInsert()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;
            // set your block name here
            string blockName = "UserName";

            ObjectId blockId;
            // dictionary to store pairs of tag-string
            Dictionary<string, string> dict = new Dictionary<string, string>();
            //populate dictionary with exact values to your block
            string[,] pairs = new string[,] { { "TAG1", "VALUE 1" },
            { "TAG2", "VALUE 2" },
            { "TAG3", "VALUE 3" },
            { "TAG4",
          "Some text in the default colour...\\P" +
          "{\\C1;Something red}\\P" +
          "{\\C2;Something yellow}\\P" +
          "{\\C3;And} {\\C4;something cyan}" } };

            for (int i=0;i<=pairs.GetUpperBound(0);i++)
                dict.Add(pairs[i,0], pairs[i,1]);
            //------------------------------------------------------------
            //  debug only:
            //  foreach (KeyValuePair<string, string> kvp in dict)
            //    ed.WriteMessage("\n{0}\t{1}\n", kvp.Key, kvp.Value);
            //------------------------------------------------------------

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if (!bt.Has(blockName)) return;
                blockId = bt[blockName];
               
                PromptPointOptions ppo = new PromptPointOptions("\nPlease specify insertion point of block: ");
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
                Point3d basePoint = ppr.Value;
                AddBlockWithAttributes(db, dict, blockId, basePoint);         
                tr.Commit();
                ed.UpdateScreen();
            }

        }


        //Here is the code for addBlockWithAttributes:

        // NOTE: You will have to update the code to properly set the

        // attribute values. The code below sets the value of each

        // attribute from dictionary.

        static public void AddBlockWithAttributes(Database db, Dictionary<string, string> dict, ObjectId blockId, Point3d basePoint)
        {
            try
            {
                Transaction tr = db.TransactionManager.StartTransaction();

                using (tr)
                {
                    //----- Step 1: Allocate a block reference object

                    BlockReference bref = new BlockReference(basePoint, blockId);

                    //----- Step 2: Set up the block reference to the newly

                    //----- created block definition

                    // pBlkRef.BlockTableRecord =blockId ;

                    //---- Give it the current UCS normal.

                    bref.Rotation = 0.0;

                    bref.Normal = new Vector3d(0.0, 0.0, 1.0);

                    //----- Step 3: Open current database's Model Space

                    //----- blockTableRecord

                    BlockTable bt;

                    BlockTableRecord btr;

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

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

                    //----- Append the block reference to the model space

                    //----- block table record

                    ObjectId newEntId;

                    newEntId = btr.AppendEntity(bref);

                    tr.AddNewlyCreatedDBObject(bref, true);

                    //----- Step 4: Open the block definition for read

                    BlockTableRecord blkDef;

                    blkDef = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead);

                    Entity ent;

                    AttributeDefinition attDef;

                    AttributeCollection attColl = bref.AttributeCollection;

                    foreach (ObjectId id in blkDef)
                    {
                        // Commented, you can use 'foreach' instead:
                        // BlockTableRecordEnumerator ienum = blkDef.GetEnumerator();
                        //while (ienum.MoveNext())
                        //{

                        //----- Get the next entity

                        // ent = (Entity)tr.GetObject(ienum.Current, OpenMode.ForRead);// commented
                        ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                        //----- Make sure the entity is an attribute definition

                        //----- and not a constant

                        attDef = ent as AttributeDefinition;

                        if (attDef != null && !attDef.Constant)
                        {

                            //----- We have a non-constant attribute definition

                            //----- so build an attribute entity

                            AttributeReference attRef = new AttributeReference();

                          //  attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);

                            attRef.SetPropertiesFrom(attDef);

                            attRef.Visible = attDef.Visible;

                            //----- Translate attribute by block reference.

                            //----- To be really correct, entire block

                            //----- reference transform should be applied here.

                            basePoint = attDef.Position;

                            basePoint += bref.Position.GetAsVector();

                            attRef.Position = basePoint;

                            attRef.Height = attDef.Height;

                            attRef.Rotation = attDef.Rotation;

                            attRef.Tag = attDef.Tag;

                            attRef.FieldLength = attDef.FieldLength;

                            //----- Database Column value should be displayed

                            //----- INSERT would prompt for this...

                            //------ Update attribute value from dictionary by tag
                            if (attDef.IsMTextAttributeDefinition)
                            {
                                attRef.IsMTextAttribute = true;
                             
                                attRef.TextString = dict[attDef.Tag.ToUpper()];
                                attRef.ForceAnnoAllVisible = true;
                                attRef.UpdateMTextAttribute();
                               
                            }
                            else
                            {
                                attRef.TextString = dict[attDef.Tag.ToUpper()];
                            }
                            //----- Set Alignments

                            attRef.HorizontalMode = attDef.HorizontalMode;

                            attRef.VerticalMode = attDef.VerticalMode;

                            attRef.AdjustAlignment(db);
                            //----- Insert the attribute in the DWG

                            attColl.AppendAttribute(attRef);


                        }
                    }

                    bref.RecordGraphicsModified(true);//    optional
                   
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                // MessageBox.Show(string.Format("Error: {0}\nTrace: {1}", ex.Message, ex.StackTrace));
                Console.WriteLine(string.Format("Error: {0}\nTrace: {1}", ex.Message, ex.StackTrace));
            }
            finally { }
        }

38
Math and Geometry / Create arc by 3 points
« on: January 08, 2013, 07:43:41 PM »
Code: [Select]
        [CommandMethod("CreateArcBy3Points", "cra3p", CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public void CreateArcByThreePoints()
        {
            short osm = (short)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("osmode");
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            // get the points

            Point3d p1, p2, p3;
            PromptPointOptions ppo = new PromptPointOptions("\nFirst point: ");
            PromptPointResult ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p1 = ppr.Value;

            ppo = new PromptPointOptions("\nSecond point: ");
            ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p2 = ppr.Value;

            ppo = new PromptPointOptions("\nThird point: ");
            ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p3 = ppr.Value;

            // create a CircularArc3d
           
            CircularArc3d carc = new CircularArc3d(p1, p2, p3);

            Arc arc = null;

            // now convert the CircularArc3d to an Arc
            Point3d cpt = carc.Center;
            Vector3d normal = carc.Normal;
            Vector3d refVec = carc.ReferenceVector;
            Plane plan = new Plane(cpt, normal);
            double ang = refVec.AngleOnPlane(plan);
            arc = new Arc(cpt, normal, carc.Radius, carc.StartAngle + ang, carc.EndAngle + ang);

            arc.SetDatabaseDefaults();
 
            // dispose CircularArc3d
            carc.Dispose();


            // get the current database

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // get the current space
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    // append arc to space
                    btr.AppendEntity(arc);
                    // add arc to transaction
                    tr.AddNewlyCreatedDBObject(arc, true);
                    tr.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
                }
                finally
                {
                    //do nothing (optional)
                    Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", osm);
                }
            }

        }

39
Dimensions / Change leader annotation point
« on: January 08, 2013, 06:19:14 PM »
Tested on A2010 only, for other release it's may be a different solution
Code: [Select]
      [CommandMethod("ChangeLeaderAnnoPoint", "clap", CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public void MoveLeaderAnno()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            Transaction tr = doc.TransactionManager.StartTransaction();

            using (tr)
            {

                PromptEntityOptions peo = new PromptEntityOptions("\nPlease pick leader >>");
                peo.SetRejectMessage("\nSelect Leader only >>");
                peo.AddAllowedClass(typeof(Leader), false);
                PromptEntityResult res;
                res = ed.GetEntity(peo);
                if (res.Status != PromptStatus.OK)
                    return;
                Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                if (ent == null)
                    return;
                Leader ld = (Leader)ent as Leader;
                if (ld == null) return;

                ld.UpgradeOpen();
                Point3d oldPt = ld.LastVertex;
                ObjectId aid = ld.Annotation;
                Entity anno = tr.GetObject(aid, OpenMode.ForWrite) as Entity;
                if (anno == null) return;

                if (!anno.IsWriteEnabled) anno.UpgradeOpen();
                Point3d newPt;

                PromptPointOptions ppo = new PromptPointOptions("\nNew annotation point");
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;

                if (ppr.Status != PromptStatus.OK) return;
                newPt = ppr.Value;
                ed.WriteMessage("\nNew annotation point: {0}\n", newPt);
                Vector3d offset = newPt - oldPt;

                anno.TransformBy(Matrix3d.Displacement(offset));

                tr.Commit();
            }
        }

40
Hatching / Create associative hatch
« on: January 04, 2013, 07:44:39 PM »
Code: [Select]
        [CommandMethod("CreateAssocHatch","cash", CommandFlags.UsePickSet)]
        public void testCreateAssocHatch()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            ObjectId objId;

            Entity ent;

            PromptEntityResult per = ed.GetEntity(new PromptEntityOptions("\nSelect an entity to be hatched: "));

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

            objId = per.ObjectId;

            try
            {
                Transaction tr = doc.TransactionManager.StartTransaction();

                using (tr)
                {

                    ent = tr.GetObject(objId, OpenMode.ForRead) as Entity;

                    if (ent == null) return;
                 
                    Hatch hat = new Hatch();

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);
                   // to set associative add hatch first
                    btr.AppendEntity(hat);

                    tr.AddNewlyCreatedDBObject(hat, true);

                    hat.PatternAngle = 0.0;

                    hat.PatternScale = 10.0;

                    hat.Associative = true;

                    hat.SetHatchPattern(HatchPatternType.PreDefined, "ANSI32");

                    // append loop to hatch
                    ObjectIdCollection dbObjIds = new ObjectIdCollection();

                    dbObjIds.Add(objId);
                     
                    hat.AppendLoop(HatchLoopTypes.External, dbObjIds);
       
                    hat.Layer = ent.Layer;
 
                    hat.ColorIndex = 256;//bylayer,  may use as per entity colorindex
   
                    hat.HatchStyle = HatchStyle.Normal;
 
                    hat.EvaluateHatch(true);
 

                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("Error: {0}", ex.ToString());
            }
        }

41
Dimensions / Create ordinate dimension
« on: January 03, 2013, 01:13:35 PM »
   http://adndevblog.typepad.com/autocad/2012/09/ordinate-dimension-text-is-incorrect-in-rotated-ucs.html   
   By Philippe Leefsma (translated on C#)]
Code: [Select]
       [CommandMethod("CreateOrdinateDimension","cdom", CommandFlags.Modal | CommandFlags.UsePickSet)]
        public static void testOrdinateDimension()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            ObjectId id = ObjectId.Null;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                PromptPointOptions ppo = new PromptPointOptions("\n  >>  Select point for ordinate dimension >>");

                PromptPointResult ppr = ed.GetPoint(ppo);

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

                double gap = db.Dimtxt * 2;

               Point3d  pt = ppr.Value;

               Point3d tpt = new Point3d(pt.X, pt.Y + gap, pt.Z);

               Matrix3d mx = ed.CurrentUserCoordinateSystem.Inverse();

               Vector3d mXPrev = Vector3d.XAxis;
                // build custom dimension text
               string dstr = string.Format("X = {0:f3}\\PY = {1:f3}", pt.X, pt.Y);// set precision to 3 decimals {:f3}

               OrdinateDimension odim = new OrdinateDimension(false, pt, tpt, dstr, db.Dimstyle);

               double ohrot = odim.HorizontalRotation;
               // get the old Xaxis and transform it to current plane
               Matrix3d mMat = Matrix3d.PlaneToWorld(odim.Normal); //ECS

               mXPrev.TransformBy(mMat); //get the ECS xaxis in the world coordinates

               mXPrev.TransformBy(mx); //transform current xaxis to plane defined by mx

               // transform the dimension entity by the given transformation matrix

               odim.TransformBy(mx);

               // get the xAxis after transformation of the dimension entity

               mMat=   Matrix3d.WorldToPlane(odim.Normal);

               // transform the old axis to the current ECS.

               mXPrev.TransformBy(mMat);

                  // get the angle of the old xaxis with respect to the current xaxis
               
                 double newhrot = - Math.Atan2(mXPrev.X, mXPrev.Y);

                 odim.HorizontalRotation = ohrot + newhrot;

               postToModelSpace(odim);

               tr.AddNewlyCreatedDBObject(odim, true);
   
                    tr.Commit();
                }
            }


        static void postToModelSpace(Entity ent)
        {

            BlockTableRecord btr;

            Database db = HostApplicationServices.WorkingDatabase;

            btr = SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject(OpenMode.ForWrite) as BlockTableRecord;

            btr.AppendEntity(ent);

        }

42
Blocks / How can you copy an entity from Model Space to Paper Space
« on: January 03, 2013, 10:07:28 AM »
         Translated on C# from this web page:
         http://adndevblog.typepad.com/autocad/2013/01/how-can-you-copy-an-entity-from-model-space-to-paper-space-in-objectarx.html
         Citation:
        How can you copy an entity from Model Space to Paper Space in ObjectARX?
        By Gopinath Taget

        To copy entities from Model Space to Paper Space in ObjectARX is actually quite straightforward.
        You can utilize the services of deepCloneObject() function to copy your select entities from Model Space into Paper Space.
        This is useful in situations where for example an older drawing contains a title block and you want to copy that title block into Paper Space.
        The following code defines command called "MS2PS". Simply select entities you want to copy over using a "window" style of selection:


        // This is command 'MS2PS'
Code: [Select]
        [CommandMethod("MS2PS")]
        public void ms2ps()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            Transaction tr = doc.TransactionManager.StartTransaction();

            using (tr)
            {

                PromptPointOptions ppo = new PromptPointOptions("\nFirst corner: ");
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
                PromptCornerOptions pco = new PromptCornerOptions("\nOther corner: ", ppr.Value);
                PromptPointResult pcr = ed.GetCorner(pco);
                if (pcr.Status != PromptStatus.OK) return;
                Point3d p1 = ppr.Value;
                Point3d p2 = pcr.Value;
                if (p1.X == p2.X || p1.Y == p2.Y)
                {
                    ed.WriteMessage("\nInvalid coordinate specification");
                    return;
                }//end getcorner
                PromptSelectionResult res = ed.SelectCrossingWindow(p1, p2);
                if (res.Status != PromptStatus.OK) return;
                SelectionSet sset = res.Value;
                if (sset.Count == 0) return;
                ObjectIdCollection idps = new ObjectIdCollection();
                foreach (SelectedObject obj in sset)
                    idps.Add(obj.ObjectId);
                // Get the BlockTable
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.PaperSpace], OpenMode.ForWrite);
                db.DeepCloneObjects(idps, btr.ObjectId, new IdMapping(), true);

                tr.Commit();
            }
        }

43
Polylines / Get Curve Length
« on: January 03, 2013, 09:17:45 AM »
 
Code: [Select]
       [CommandMethod("getCurveLength", "cul", CommandFlags.Modal | CommandFlags.UsePickSet)]
        public void CurveLength()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            Transaction tr = doc.TransactionManager.StartTransaction();
            double startParam, endParam, length;
            using (tr)
            {

                PromptEntityOptions peo = new PromptEntityOptions("\nSelect Curve >>");
                peo.SetRejectMessage("\nSelect Curve only >>");
                peo.AddAllowedClass(typeof(Curve), false);
                PromptEntityResult res;
                res = ed.GetEntity(peo);
                if (res.Status != PromptStatus.OK)
                    return;
                Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                if (ent == null)
                    return;
                Curve curve = (Curve)ent as Curve;
                if (curve != null)
                {
                    startParam = curve.StartParam;

                    endParam = curve.EndParam;

                    length = curve.GetDistanceAtParameter(endParam) - curve.GetDistanceAtParameter(startParam);

                    ed.WriteMessage("\nLength = {0:f3}\n", length);

                }//end getentity

                tr.Commit();
            }//end using transaction
        }

44
External databases / Read and parse .csv or .txt file
« on: December 29, 2012, 08:16:31 PM »
 
Code: [Select]
       [CommandMethod("ptsRead")]
        public void testReadCSV()
        {   // file name contains separated text
            string filePath = @"C:\Test\points.txt";
            if (!File.Exists(filePath))
            {
                MessageBox.Show("File does not exist");
                return;
            }
            // put appropriate delimiter here
            string sep = ";";
            Point3dCollection pts = new Point3dCollection();
            using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
            {
                while (!reader.EndOfStream)
                {
                    // Call reader.ReadLine() appropriately
                    string textLine = reader.ReadLine();
                    Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\n{0}", textLine);
                    string[] tmp = textLine.Split(new string[] { sep }, StringSplitOptions.RemoveEmptyEntries);
                    if (tmp.Length != 0)
                    {
                        Point3d pt = new Point3d(Convert.ToDouble(tmp[0]), Convert.ToDouble(tmp[1]), Convert.ToDouble(tmp[2]));
                        pts.Add(pt);
                    }
                }
            }

            if (pts == null)
            {
                MessageBox.Show("Cant parse this file");
                return;
            }
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("pdmode", 34);

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("pdsize", 2.0);

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                foreach (Point3d pnt in pts)
                {
                    DBPoint pt = new DBPoint(pnt);

                    pt.SetDatabaseDefaults();

                    pt.ColorIndex = 1;// <-- set any color of point

                    btr.AppendEntity(pt);

                    DBText txt = new DBText();

                    tr.AddNewlyCreatedDBObject(pt, true);

                    txt.SetDatabaseDefaults();

                    txt.Position = pt.Position;

                    txt.TextString = txt.Position.ToString();//<-- add any textstring to suit

                    txt.Justify = AttachmentPoint.BaseLeft;

                    // txt.AlignmentPoint = pt.Position;

                    txt.AdjustAlignment(db);

                    btr.AppendEntity(txt);

                    tr.AddNewlyCreatedDBObject(txt, true);
                }
                tr.Commit();
            }
        }

45
Dimensions / Add text or mtext to leader
« on: December 29, 2012, 06:38:52 PM »
 
Code: [Select]
       [CommandMethod("CopyTextToLeader", "ttl", CommandFlags.Redraw)]
        public void TextToMleader()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;
            // save current DIMBLK variable
            string dblk = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("DIMBLK").ToString();
            try
            {
                PromptEntityOptions peo =
                 new PromptEntityOptions("\nSelect Text / MText: ");
                peo.SetRejectMessage("\nMust be select type of Text or MText.");
                peo.AddAllowedClass(typeof(DBText), false);
                peo.AddAllowedClass(typeof(MText), false);
                PromptEntityResult per = ed.GetEntity(peo);
                if (per.Status != PromptStatus.OK) return;
                ObjectId txtId = per.ObjectId;
                PromptPointOptions opt = new PromptPointOptions("\nSpecify leader arrowhead location: ");
                PromptPointResult res = ed.GetPoint(opt);

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

                Point3d pt = res.Value;

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                    ObjectId blkid = ObjectId.Null;
                    DBObject obj = (DBObject)tr.GetObject(txtId, OpenMode.ForWrite) as DBObject;
                    ed.WriteMessage("\nType\t{0}\n", obj.GetRXClass().DxfName);
                    DBText txtobj = null;
                    MText mtxtobj = null;
                    Point3d tp = new Point3d();
                    if (obj.GetRXClass().DxfName == "TEXT")
                    {
                        txtobj = obj as DBText;
                        if (txtobj == null) return;
                        tp = txtobj.Position;
                    }
                    if (obj.GetRXClass().DxfName == "MTEXT")
                    {
                        mtxtobj = obj as MText;
                        if (mtxtobj == null) return;
                        tp = mtxtobj.Location;
                    }

                    Leader leader = new Leader();
                    // Create the MText annotation
                    MText copymtx = new MText();
                    if (mtxtobj != null)
                    {
                        copymtx = mtxtobj.Clone() as MText;
                    }
                    if (txtobj != null)
                    {
                        copymtx = new MText();
                        copymtx.Location = txtobj.Position;
                        copymtx.Contents = txtobj.TextString;
                    }

                    // Add the new object to current space and the transaction
                    btr.AppendEntity(copymtx);
                    tr.AddNewlyCreatedDBObject(copymtx, true);


                    if (txtobj != null)
                    {
                        leader.TextStyleId = txtobj.TextStyleId;
                    }
                    if (mtxtobj != null)
                    {
                        leader.TextStyleId = mtxtobj.TextStyleId;
                    }

                    // set arrow head block to DOT or use any other
                    if (!bt.Has("_DOT"))
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", "_DOT");

                    }
                    leader.HasArrowHead = true;
                    leader.Dimldrblk = bt["_DOT"];
                    leader.Dimasz = db.Dimtxt * 0.2;
                    leader.AppendVertex(pt);
                    leader.AppendVertex(tp);

                    btr.AppendEntity(leader);
                    tr.AddNewlyCreatedDBObject(leader, true);
                    // attach the annotation after the leader object is added
                    leader.Annotation = copymtx.ObjectId;
                    // evaluate leader
                    leader.EvaluateLeader();
                    // erase prototypes
                    if (mtxtobj != null) mtxtobj.Erase();
                    if (txtobj != null) txtobj.Erase();

                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}\nTrace: {1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                // reset DIMBLK
                if (dblk != "")
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", dblk);
                }
                else
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", ".");
                }
            }
        }

Pages: 1 2 [3] 4 5 ... 7