Saturday, August 11, 2012

Creating Linked Entities with DrawJig

In AutoCAD discussion group's .NET forum, an user asked how to create linked objects (see here). I suggested that Jig, TransientGraphics and/or Overrule could be considered as the solution. I was thinking then to give it a try myself, but did not have time to actually write some code. However, this topic kept hanging on somewhere in my mind: what would I do if I were facing this task? So, I finally squeeze some time to sit down doing something with it, hence this post.

Let assume some requirement of this task, which may not be the same as the question raised in the AutoCAD discussion group. Say, user wants to use AutoCAD to draw a simple diagram, a kind of flow chart, which includes circles and lines. Let's also assume that a circle can be linked to one or more other circles by lines.

Drawing circles and lines would be very simple with AutoCAD. But what if user wants to move a drawn circle in the flow chart that is linked to other circles? It would be ideal that all lines that link to this moving circle from other circles and all lines that link to other circles from this moving circle would follow the move. So to user, it looks like the lines and circles are physically linked.

Now we can see that the only thing we need to deal with is when user want to change the existing flow chart by moving a node, represented by a circle, around, but still keep the links between nodes, represented by lines. To me, it sounds a lot like a jig. So, I decided to give jig a try.

Now I saw these tasks ahead of me:
  • Make a circle be aware of which line is connected to it from other circle and which line is connected to other circle from itself;
  • A line is used to connect only 2 circles, and knows which 2 circles it is connected.
  • Create a custom "MOVE" command for user to move circles in the flow chart
  • To make things simple, if user wants to change link between circles, he/she simply remove the link and recreate the link between any 2 circles
I decided to attach XData to the circles and linking lines to let the circles and lines be aware of which circles/lines it is linked to/from. Therefore my coding begins with an XData manipulation utility class. Here is it:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Autodesk.AutoCAD.DatabaseServices;
  5. using Autodesk.AutoCAD.Geometry;
  6.  
  7. namespace LinkedObjects
  8. {
  9.     public class LinkInfoXDataUtil
  10.     {
  11.         private const string OBJECT_LINK_APP = "MyNameSpace.LinkObjects";
  12.  
  13.         public static void SetLink(Database db,
  14.             ObjectId fromCircleId, ObjectId toCircleId, ObjectId linkLineId)
  15.         {
  16.             ObjectLinkAppExists(db, true);
  17.  
  18.             using (Transaction tran =
  19.                 db.TransactionManager.StartTransaction())
  20.             {
  21.                 Entity fromCircle = (Entity)tran.GetObject(
  22.                     fromCircleId, OpenMode.ForWrite);
  23.                 Entity toCircle = (Entity)tran.GetObject(
  24.                     toCircleId, OpenMode.ForWrite);
  25.                 Entity line = (Entity)tran.GetObject(
  26.                     linkLineId, OpenMode.ForWrite);
  27.  
  28.                 AddFromLinkToCircle(fromCircle, line.Handle.ToString());
  29.                 AddToLinkToCircle(toCircle, line.Handle.ToString());
  30.                 AddLinksToLine(line,
  31.                     fromCircle.Handle.ToString(),
  32.                     toCircle.Handle.ToString());
  33.  
  34.                 tran.Commit();
  35.             }
  36.         }
  37.  
  38.         public static void RemoveLink(Database db, ObjectId linkLineId)
  39.         {
  40.             using (Transaction tran =
  41.                 db.TransactionManager.StartTransaction())
  42.             {
  43.                 Entity line = (Entity)tran.GetObject(
  44.                     linkLineId, OpenMode.ForWrite);
  45.  
  46.                 ObjectId fromCircleId;
  47.                 ObjectId toCircleId;
  48.                 GetLinkedCirclesFromLine(
  49.                     db, tran, line, out fromCircleId, out toCircleId);
  50.  
  51.                 Entity fromCircle = (Entity)tran.GetObject(
  52.                     fromCircleId, OpenMode.ForWrite);
  53.                 Entity toCircle = (Entity)tran.GetObject(
  54.                     toCircleId, OpenMode.ForWrite);
  55.  
  56.                 //Remove line's handle from XData in circles
  57.                 RemoveFromLinkFromCircle(fromCircle, line.Handle.ToString());
  58.                 RemoveToLinkFromCircle(toCircle, line.Handle.ToString());
  59.  
  60.                 //Clear Xdata from the line
  61.                 TypedValue[] vals = new TypedValue[]
  62.                 {
  63.                     new TypedValue(
  64.                         (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP)
  65.                 };
  66.                 ResultBuffer buffer = new ResultBuffer(vals);
  67.                 line.XData = buffer;
  68.  
  69.                 tran.Commit();
  70.             }
  71.         }
  72.  
  73.         public static void GetCirleLink(Database db, ObjectId circleId,
  74.             out List<ObjectId> fromLineIds, out List<ObjectId> toLineIds)
  75.         {
  76.             fromLineIds = new List<ObjectId>();
  77.             toLineIds = new List<ObjectId>();
  78.  
  79.             if (circleId.ObjectClass.DxfName.ToUpper() == "CIRCLE")
  80.             {
  81.                 using (Transaction tran =
  82.                     circleId.Database.TransactionManager.StartTransaction())
  83.                 {
  84.                     Entity ent = (Entity)tran.GetObject(
  85.                         circleId, OpenMode.ForRead);
  86.  
  87.                     ResultBuffer buffer =
  88.                         ent.GetXDataForApplication(OBJECT_LINK_APP);
  89.                     if (buffer == null) return;
  90.  
  91.                     TypedValue[] vals = buffer.AsArray();
  92.                     if (vals.Length == 3)
  93.                     {
  94.                         string handles;
  95.  
  96.                         //Get lines started from this circle
  97.                         handles = vals[1].Value.ToString();
  98.                         if (handles.Length > 0)
  99.                         {
  100.                             string[] hs = handles.Split('|');
  101.                             foreach (string h in hs)
  102.                             {
  103.                                 fromLineIds.Add(HandleToObjectId(db, h));
  104.                             }
  105.                         }
  106.  
  107.                         //Get lines pointing to this circle
  108.                         handles = vals[2].Value.ToString();
  109.                         if (handles.Length > 0)
  110.                         {
  111.                             string[] hs = handles.Split('|');
  112.                             foreach (string h in hs)
  113.                             {
  114.                                 toLineIds.Add(HandleToObjectId(db, h));
  115.                             }
  116.                         }
  117.                     }
  118.                     else
  119.                     {
  120.                         //Clear inavlid XData
  121.                         TypedValue[] vs = new TypedValue[]
  122.                         {
  123.                             new TypedValue(
  124.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  125.                                 OBJECT_LINK_APP)
  126.                         };
  127.                         ent.UpgradeOpen();
  128.                         ent.XData = new ResultBuffer(vs);
  129.                     }
  130.  
  131.                     tran.Commit();
  132.                 }
  133.             }
  134.         }
  135.  
  136.         public static void GetLineLink(Database db, ObjectId lineId,
  137.             out ObjectId fromCircleId, out ObjectId toCircleId)
  138.         {
  139.             fromCircleId = ObjectId.Null;
  140.             toCircleId = ObjectId.Null;
  141.  
  142.             if (lineId.ObjectClass.DxfName.ToUpper() == "LINE")
  143.             {
  144.                 using (Transaction tran =
  145.                     lineId.Database.TransactionManager.StartTransaction())
  146.                 {
  147.                     Entity ent = (Entity)tran.GetObject(
  148.                         lineId, OpenMode.ForRead);
  149.                     ResultBuffer buffer =
  150.                         ent.GetXDataForApplication(OBJECT_LINK_APP);
  151.                     if (buffer == null) return;
  152.  
  153.                     TypedValue[] vals = buffer.AsArray();
  154.                     if (vals.Length == 3)
  155.                     {
  156.                         string handle;
  157.  
  158.                         //FROM circle
  159.                         handle = vals[1].Value.ToString();
  160.                         if (handle.Length > 0)
  161.                             fromCircleId = HandleToObjectId(db, handle);
  162.  
  163.                         //TO circle
  164.                         handle = vals[2].Value.ToString();
  165.                         if (handle.Length > 0)
  166.                             toCircleId = HandleToObjectId(db, handle);
  167.                     }
  168.  
  169.                     tran.Commit();
  170.                 }
  171.             }
  172.         }
  173.  
  174.         public static void GetLinkedCircleCentres(Database db, ObjectId linkLineId,
  175.             out Point3d fromCircleCentre, out Point3d toCircleCentre)
  176.         {
  177.             ObjectId fromCircleId;
  178.             ObjectId toCircleId;
  179.  
  180.             GetLineLink(db, linkLineId, out fromCircleId, out toCircleId);
  181.  
  182.             fromCircleCentre = CommonUtil.GetCircleCentre(db, fromCircleId);
  183.             toCircleCentre = CommonUtil.GetCircleCentre(db, toCircleId);
  184.         }
  185.  
  186.         #region private methoids
  187.  
  188.         private static bool ObjectLinkAppExists(Database db, bool create)
  189.         {
  190.             bool exists = false;
  191.             using (Transaction tran =
  192.                 db.TransactionManager.StartTransaction())
  193.             {
  194.                 RegAppTable appTable = (RegAppTable)tran.GetObject(
  195.                     db.RegAppTableId, OpenMode.ForRead);
  196.  
  197.                 if (appTable.Has(OBJECT_LINK_APP))
  198.                     exists = true;
  199.                 else
  200.                 {
  201.                     if (create)
  202.                     {
  203.                         RegAppTableRecord appRec = new RegAppTableRecord();
  204.                         appRec.Name = OBJECT_LINK_APP;
  205.                         appTable.UpgradeOpen();
  206.                         appTable.Add(appRec);
  207.                         tran.AddNewlyCreatedDBObject(appRec, true);
  208.                         exists = true;
  209.                     }
  210.                 }
  211.  
  212.                 tran.Commit();
  213.             }
  214.  
  215.                 return exists;
  216.         }
  217.  
  218.         private static ObjectId HandleToObjectId(
  219.             Database db, string handleString)
  220.         {
  221.             ObjectId id = ObjectId.Null;
  222.  
  223.             id = db.GetObjectId(false,
  224.                 new Handle(Int64.Parse(handleString,
  225.                     System.Globalization.NumberStyles.AllowHexSpecifier)), 0);
  226.  
  227.             return id;
  228.         }
  229.  
  230.         private static void AddFromLinkToCircle(Entity fromEnt, string handle)
  231.         {
  232.             ResultBuffer buffer =
  233.                 fromEnt.GetXDataForApplication(OBJECT_LINK_APP);
  234.             TypedValue[] vals;
  235.  
  236.             string newHandles = "";
  237.             string existingHandles = "";
  238.             string toHandles = "";
  239.  
  240.             if (buffer != null)
  241.             {
  242.                 vals = buffer.AsArray();
  243.                 existingHandles = vals[1].Value.ToString();
  244.                 toHandles = vals[2].Value.ToString();
  245.             }
  246.  
  247.             bool exists = false;
  248.             if (existingHandles.Length > 0)
  249.             {
  250.                 string[] hs = existingHandles.Split('|');
  251.                 foreach (string h in hs)
  252.                 {
  253.                     if (h.ToUpper() == handle.ToUpper())
  254.                     {
  255.                         exists = true;
  256.                         break;
  257.                     }
  258.                 }
  259.  
  260.                 if (!exists)
  261.                     newHandles = existingHandles + "|" + handle;
  262.                 else
  263.                     newHandles = existingHandles;
  264.             }
  265.             else
  266.             {
  267.                 newHandles = handle;
  268.             }
  269.  
  270.             vals = new TypedValue[]
  271.             {
  272.                 new TypedValue(
  273.                     (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
  274.                 new TypedValue(
  275.                     (Int16)DxfCode.ExtendedDataAsciiString, newHandles),
  276.                 new TypedValue(
  277.                     (Int16)DxfCode.ExtendedDataAsciiString, toHandles)
  278.             };
  279.  
  280.             fromEnt.XData = new ResultBuffer(vals);
  281.         }
  282.  
  283.         private static void AddToLinkToCircle(Entity toEnt, string handle)
  284.         {
  285.             ResultBuffer buffer =
  286.                 toEnt.GetXDataForApplication(OBJECT_LINK_APP);
  287.             TypedValue[] vals;
  288.  
  289.             string newHandles = "";
  290.             string existingHandles = "";
  291.             string fromHandles = "";
  292.  
  293.             if (buffer != null)
  294.             {
  295.                 vals = buffer.AsArray();
  296.  
  297.                 existingHandles = vals[2].Value.ToString();
  298.                 fromHandles = vals[1].Value.ToString();
  299.             }
  300.  
  301.             bool exists = false;
  302.             if (existingHandles.Length > 0)
  303.             {
  304.                 string[] hs = existingHandles.Split('|');
  305.                 foreach (string h in hs)
  306.                 {
  307.                     if (h.ToUpper() == handle.ToUpper())
  308.                     {
  309.                         exists = true;
  310.                         break;
  311.                     }
  312.                 }
  313.  
  314.                 if (!exists)
  315.                     newHandles = existingHandles + "|" + handle;
  316.                 else
  317.                     newHandles = existingHandles;
  318.             }
  319.             else
  320.             {
  321.                 newHandles = handle;
  322.             }
  323.  
  324.             vals = new TypedValue[]
  325.             {
  326.                 new TypedValue(
  327.                     (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
  328.                 new TypedValue(
  329.                     (Int16)DxfCode.ExtendedDataAsciiString, fromHandles),
  330.                 new TypedValue(
  331.                     (Int16)DxfCode.ExtendedDataAsciiString, newHandles)
  332.             };
  333.  
  334.             toEnt.XData = new ResultBuffer(vals);
  335.         }
  336.  
  337.         private static void AddLinksToLine(
  338.             Entity line, string fromHandle, string toHandle)
  339.         {
  340.             TypedValue[] vals = new TypedValue[]
  341.             {
  342.                 new TypedValue(
  343.                     (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
  344.                 new TypedValue(
  345.                     (Int16)DxfCode.ExtendedDataAsciiString, fromHandle),
  346.                 new TypedValue(
  347.                     (Int16)DxfCode.ExtendedDataAsciiString, toHandle)
  348.             };
  349.  
  350.             line.XData = new ResultBuffer(vals);
  351.         }
  352.  
  353.         private static void GetLinkedCirclesFromLine(
  354.             Database db, Transaction tran, Entity line,
  355.             out ObjectId fromCircleId, out ObjectId toCircleId)
  356.         {
  357.             fromCircleId = ObjectId.Null;
  358.             toCircleId = ObjectId.Null;
  359.  
  360.             ResultBuffer buffer =
  361.                 line.GetXDataForApplication(OBJECT_LINK_APP);
  362.             if (buffer != null)
  363.             {
  364.                 TypedValue[] vals = buffer.AsArray();
  365.  
  366.                 string handleString;
  367.  
  368.                 handleString = vals[1].Value.ToString();
  369.                 fromCircleId = HandleToObjectId(db, handleString);
  370.  
  371.                 handleString = vals[2].Value.ToString();
  372.                 toCircleId = HandleToObjectId(db, handleString);
  373.             }
  374.         }
  375.  
  376.         private static void RemoveFromLinkFromCircle(
  377.             Entity fromCircle, string lineHandle)
  378.         {
  379.             ResultBuffer buffer =
  380.                 fromCircle.GetXDataForApplication(OBJECT_LINK_APP);
  381.             if (buffer == null) return;
  382.  
  383.             TypedValue[] vals = buffer.AsArray();
  384.             string fromHandles = vals[1].Value.ToString();
  385.             string toHandles = vals[2].Value.ToString();
  386.             if (fromHandles.Length > 0)
  387.             {
  388.                 StringBuilder newHandles = new StringBuilder();
  389.                 bool removed = false;
  390.  
  391.                 //rebuild the handles string with
  392.                 //targeted handle striing being excluded
  393.                 string[] hs = fromHandles.Split('|');
  394.                 foreach (string h in hs)
  395.                 {
  396.                     if (h.ToUpper() != lineHandle.ToUpper())
  397.                     {
  398.                         newHandles.Append(h + "|");
  399.                     }
  400.                     else
  401.                     {
  402.                         removed = true;
  403.                     }
  404.                 }
  405.  
  406.                 if (removed)
  407.                 {
  408.                     //remove the trailing "|"
  409.                     if (newHandles.ToString().EndsWith("|"))
  410.                     {
  411.                         newHandles.Length = newHandles.Length - 1;
  412.                     }
  413.  
  414.                     //recreate XData
  415.                     if (newHandles.Length == 0 && toHandles.Length == 0)
  416.                     {
  417.                         vals = new TypedValue[]
  418.                             {
  419.                                 new TypedValue(
  420.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  421.                                 OBJECT_LINK_APP)
  422.                             };
  423.                     }
  424.                     else
  425.                     {
  426.                         vals = new TypedValue[]
  427.                         {
  428.                             new TypedValue(
  429.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  430.                                 OBJECT_LINK_APP),
  431.                             new TypedValue(
  432.                                 (Int16)DxfCode.ExtendedDataAsciiString,
  433.                                 newHandles.ToString()),
  434.                             new TypedValue(
  435.                                 (Int16)DxfCode.ExtendedDataAsciiString,
  436.                                 toHandles)
  437.                         };
  438.                     }
  439.  
  440.                     fromCircle.XData = new ResultBuffer(vals);
  441.                 }
  442.             }
  443.         }
  444.  
  445.         private static void RemoveToLinkFromCircle(
  446.             Entity toCircle, string lineHandle)
  447.         {
  448.             ResultBuffer buffer =
  449.                 toCircle.GetXDataForApplication(OBJECT_LINK_APP);
  450.             if (buffer == null) return;
  451.  
  452.             TypedValue[] vals = buffer.AsArray();
  453.             string fromHandles = vals[1].Value.ToString();
  454.             string toHandles = vals[2].Value.ToString();
  455.             if (toHandles.Length > 0)
  456.             {
  457.                 StringBuilder newHandles = new StringBuilder();
  458.                 bool removed = false;
  459.  
  460.                 //rebuild the handles string with
  461.                 //targeted handle striing being excluded
  462.                 string[] hs = toHandles.Split('|');
  463.                 foreach (string h in hs)
  464.                 {
  465.                     if (h.ToUpper() != lineHandle.ToUpper())
  466.                     {
  467.                         newHandles.Append(h + "|");
  468.                     }
  469.                     else
  470.                     {
  471.                         removed = true;
  472.                     }
  473.                 }
  474.  
  475.                 if (removed)
  476.                 {
  477.                     //remove the trailing "|"
  478.                     if (newHandles.ToString().EndsWith("|"))
  479.                     {
  480.                         newHandles.Length = newHandles.Length - 1;
  481.                     }
  482.  
  483.                     //recreate XData
  484.                     if (newHandles.Length == 0 && fromHandles.Length == 0)
  485.                     {
  486.                         vals = new TypedValue[]
  487.                             {
  488.                                 new TypedValue(
  489.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  490.                                 OBJECT_LINK_APP)
  491.                             };
  492.                     }
  493.                     else
  494.                     {
  495.                         vals = new TypedValue[]
  496.                         {
  497.                             new TypedValue(
  498.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  499.                                 OBJECT_LINK_APP),
  500.                             new TypedValue(
  501.                                 (Int16)DxfCode.ExtendedDataAsciiString,
  502.                                 fromHandles),
  503.                             new TypedValue(
  504.                                 (Int16)DxfCode.ExtendedDataAsciiString,
  505.                                 newHandles.ToString())
  506.                         };
  507.                     }
  508.  
  509.                     toCircle.XData = new ResultBuffer(vals);
  510.                 }
  511.             }
  512.         }
  513.  
  514.         #endregion
  515.     }
  516. }

In order to organize my code in a bit cleaner structure, I place most generic AutoCAD operation used in this project in an AutoCAD utility class CommonUtil:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using Autodesk.AutoCAD.ApplicationServices;
  4. using Autodesk.AutoCAD.DatabaseServices;
  5. using Autodesk.AutoCAD.EditorInput;
  6. using Autodesk.AutoCAD.Geometry;
  7.  
  8. namespace LinkedObjects
  9. {
  10.     public class CommonUtil
  11.     {
  12.         public static void PrintCancelMessage(string message = "")
  13.         {
  14.             Editor ed =
  15.                 Application.DocumentManager.MdiActiveDocument.Editor;
  16.  
  17.             if (!string.IsNullOrEmpty(message))
  18.             {
  19.                 ed.WriteMessage("\n" + message);
  20.             }
  21.             ed.WriteMessage("\n*Cancel*");
  22.             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
  23.         }
  24.  
  25.         public static bool PickEntity(Editor ed, Type entType,
  26.             string optionMessage, string rejectMessage, out ObjectId entId)
  27.         {
  28.             entId = ObjectId.Null;
  29.  
  30.             PromptEntityOptions opt = new PromptEntityOptions(optionMessage);
  31.             opt.SetRejectMessage(rejectMessage);
  32.             opt.AddAllowedClass(entType, true);
  33.  
  34.             PromptEntityResult res = ed.GetEntity(opt);
  35.             if (res.Status == PromptStatus.OK)
  36.             {
  37.                 entId = res.ObjectId;
  38.                 return true;
  39.             }
  40.  
  41.             return false;
  42.         }
  43.  
  44.         public static ObjectId DrawLineBetweenCircles(
  45.             Database db, ObjectId fromCircleId, ObjectId toCircleId)
  46.         {
  47.             ObjectId lineId = ObjectId.Null;
  48.  
  49.             using (Transaction tran =
  50.                 db.TransactionManager.StartTransaction())
  51.             {
  52.                 Circle fromCircle = (Circle)tran.GetObject(
  53.                     fromCircleId, OpenMode.ForRead);
  54.                 Circle toCircle = (Circle)tran.GetObject(
  55.                     toCircleId, OpenMode.ForRead);
  56.  
  57.                 ObjectId modelId =
  58.                     SymbolUtilityServices.GetBlockModelSpaceId(db);
  59.                 BlockTableRecord model = (BlockTableRecord)tran.GetObject(
  60.                     modelId, OpenMode.ForWrite);
  61.  
  62.                 using (Line line =
  63.                     new Line(fromCircle.Center, toCircle.Center))
  64.                 {
  65.                     //Change startpoint/endpoint from
  66.                     //circle's center to circle's perimeter
  67.                     Point3d pt;
  68.  
  69.                     pt = line.GetPointAtDist(fromCircle.Radius);
  70.                     line.StartPoint = pt;
  71.  
  72.                     double dist=line.Length-toCircle.Radius;
  73.                     pt = line.GetPointAtDist(dist);
  74.                     line.EndPoint = pt;
  75.  
  76.                     line.SetDatabaseDefaults(db);
  77.  
  78.                     lineId = model.AppendEntity(line);
  79.                     tran.AddNewlyCreatedDBObject(line, true);
  80.  
  81.                     tran.Commit();
  82.                 }
  83.             }
  84.  
  85.             return lineId;
  86.         }
  87.  
  88.         public static void EraseEntity(Database db, ObjectId entId)
  89.         {
  90.             using (Transaction tran = db.TransactionManager.StartTransaction())
  91.             {
  92.                 Entity ent = (Entity)tran.GetObject(entId, OpenMode.ForWrite);
  93.                 ent.Erase(true);
  94.  
  95.                 tran.Commit();
  96.             }
  97.         }
  98.  
  99.         public static Point3d GetCircleCentre(Database db, ObjectId circleId)
  100.         {
  101.             Point3d pt = new Point3d();
  102.  
  103.             using (Transaction tran = db.TransactionManager.StartTransaction())
  104.             {
  105.                 Circle c = tran.GetObject(circleId, OpenMode.ForRead) as Circle;
  106.                 if (c != null)
  107.                     pt = c.Center;
  108.                 else
  109.                     throw new ArgumentException("Entity is not a circle.");
  110.  
  111.                 tran.Commit();
  112.             }
  113.  
  114.             return pt;
  115.         }
  116.  
  117.         public static void HighlightEntities(
  118.             Database db, List<ObjectId> entIds, bool highlight)
  119.         {
  120.             using (Transaction tran =
  121.                 db.TransactionManager.StartTransaction())
  122.             {
  123.                 foreach (var id in entIds)
  124.                 {
  125.                     Entity ent = (Entity)tran.GetObject(id, OpenMode.ForWrite);
  126.  
  127.                     if (highlight)
  128.                         ent.Highlight();
  129.                     else
  130.                         ent.Unhighlight();
  131.                 }
  132.  
  133.                 tran.Commit();
  134.             }
  135.         }
  136.     }
  137. }

With all required Xdata and AutoCAD manipulation tool available, I was ready to create the Jig. Here are what I wanted to achieve:
  • When user picks the circle to move, the circle and all lines linking from/to it would be highlighted
  • When user moves mouse cursor, a set of ghost circle and the lines move with the mouse cursor
  • After user picks the moving destination point, the select circle is moved to user selected point, and all lines that link from/to this circle will be modified of their start/end points, so that they would start/end properly with the moved circle and still linked to/from other circles
Here is the Jig class:

Code Snippet
  1. using System.Collections.Generic;
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.DatabaseServices;
  4. using Autodesk.AutoCAD.EditorInput;
  5. using Autodesk.AutoCAD.Geometry;
  6. using Autodesk.AutoCAD.GraphicsInterface;
  7.  
  8. namespace LinkedObjects
  9. {
  10.     public class LinkedCircleJig : DrawJig
  11.     {
  12.         private Document _dwg;
  13.         private Editor _ed;
  14.         private Database _db;
  15.         private ObjectId _circleId;
  16.         private List<ObjectId> _fromLineIds;
  17.         private List<ObjectId> _toLineIds;
  18.         private Point3d _basePoint;
  19.         private Point3d _currentPoint;
  20.         private Point3d _prevPoint;
  21.         private bool _cancelled = false;
  22.  
  23.         private Circle _visualCircle = null;
  24.         private List<Line> _fromVisualLines = new List<Line>();
  25.         private List<Line> _toVisualLines = new List<Line>();
  26.         private int _visualColorIndex = 1;
  27.  
  28.         public LinkedCircleJig(Document dwg, ObjectId circleId)
  29.         {
  30.             _dwg = dwg;
  31.             _ed = dwg.Editor;
  32.             _db = dwg.Database;
  33.  
  34.             _circleId = circleId;
  35.             LinkInfoXDataUtil.GetCirleLink(
  36.                 _db, _circleId, out _fromLineIds, out _toLineIds);
  37.  
  38.             _basePoint = CommonUtil.GetCircleCentre(_db, circleId);
  39.         }
  40.  
  41.         public void DragLinkedCircle()
  42.         {
  43.             _cancelled = false;
  44.  
  45.             try
  46.             {
  47.                 CreateVisualEntities();
  48.  
  49.                 _currentPoint = _basePoint;
  50.                 _prevPoint = _basePoint;
  51.  
  52.                 HighlightEntities(true);
  53.  
  54.                 _ed.Drag(this);
  55.  
  56.                 if (!_cancelled)
  57.                 {
  58.                     using (Transaction tran =
  59.                         _db.TransactionManager.StartTransaction())
  60.                     {
  61.                         //Move circle
  62.                         Vector3d displacement =
  63.                         _basePoint.GetVectorTo(_currentPoint);
  64.  
  65.                         Circle c = (Circle)tran.GetObject(
  66.                             _circleId, OpenMode.ForWrite);
  67.                         c.TransformBy(
  68.                             Matrix3d.Displacement(displacement));
  69.  
  70.                         ObjectId fCircleId;
  71.                         ObjectId tCircleId;
  72.                         
  73.                         Point3d pt;
  74.                         double dist;
  75.  
  76.                         //update FROM lines
  77.                         foreach (var id in _fromLineIds)
  78.                         {
  79.                             Line l = (Line)tran.GetObject(
  80.                                 id, OpenMode.ForWrite);
  81.  
  82.                             //get its TO circle
  83.                             LinkInfoXDataUtil.GetLineLink(
  84.                                 _db, id, out fCircleId, out tCircleId);
  85.  
  86.                             Circle tCircle = (Circle)tran.GetObject(
  87.                                 tCircleId, OpenMode.ForRead);
  88.  
  89.                             l.StartPoint = c.Center;
  90.                             l.EndPoint = tCircle.Center;
  91.  
  92.                             //Shrink line's length
  93.                             pt = l.GetPointAtDist(c.Radius);
  94.                             l.StartPoint = pt;
  95.  
  96.                             dist = l.Length - tCircle.Radius;
  97.                             pt = l.GetPointAtDist(dist);
  98.                             l.EndPoint = pt;
  99.                         }
  100.  
  101.                         //Update TO lines
  102.                         foreach (var id in _toLineIds)
  103.                         {
  104.                             Line l = (Line)tran.GetObject(
  105.                                 id, OpenMode.ForWrite);
  106.  
  107.                             //get its TO circle
  108.                             LinkInfoXDataUtil.GetLineLink(
  109.                                 _db, id, out fCircleId, out tCircleId);
  110.  
  111.                             Circle fCircle = (Circle)tran.GetObject(
  112.                                 fCircleId, OpenMode.ForRead);
  113.  
  114.                             l.StartPoint = fCircle.Center;
  115.                             l.EndPoint = c.Center;
  116.  
  117.                             //Shrink line's length
  118.                             pt = l.GetPointAtDist(fCircle.Radius);
  119.                             l.StartPoint = pt;
  120.  
  121.                             dist = l.Length - c.Radius;
  122.                             pt = l.GetPointAtDist(dist);
  123.                             l.EndPoint = pt;
  124.                         }
  125.  
  126.                         tran.Commit();
  127.                     }
  128.                 }
  129.             }
  130.             catch
  131.             {
  132.                 throw;
  133.             }
  134.             finally
  135.             {
  136.                 HighlightEntities(false);
  137.                 DisposeVisualEntities();
  138.             }
  139.         }
  140.  
  141.         #region Jig method overrides
  142.         
  143.         protected override bool WorldDraw(WorldDraw draw)
  144.         {
  145.             draw.Geometry.Draw(_visualCircle);
  146.  
  147.             foreach (var e in _fromVisualLines)
  148.                 draw.Geometry.Draw(e);
  149.  
  150.             foreach (var e in _toVisualLines)
  151.                 draw.Geometry.Draw(e);
  152.  
  153.             return true;
  154.         }
  155.  
  156.         protected override SamplerStatus Sampler(JigPrompts prompts)
  157.         {
  158.             JigPromptPointOptions jigOpt =
  159.                 new JigPromptPointOptions();
  160.  
  161.             jigOpt.UserInputControls =
  162.                 UserInputControls.Accept3dCoordinates |
  163.                 UserInputControls.NoZeroResponseAccepted |
  164.                 UserInputControls.NoDwgLimitsChecking;
  165.             jigOpt.BasePoint = _basePoint;
  166.             jigOpt.UseBasePoint = true;
  167.             jigOpt.Cursor = CursorType.RubberBand;
  168.             jigOpt.Message = "\nMove the linked circle to picked point: ";
  169.  
  170.             PromptPointResult res = prompts.AcquirePoint(jigOpt);
  171.  
  172.             if (res.Status == PromptStatus.Cancel)
  173.             {
  174.                 return SamplerStatus.Cancel;
  175.             }
  176.             else
  177.             {
  178.                 _currentPoint = res.Value;
  179.  
  180.                 if (_currentPoint == _prevPoint)
  181.                     return SamplerStatus.NoChange;
  182.                 else
  183.                 {
  184.                     //Update location of visual circle
  185.                     Vector3d displacement =
  186.                         _prevPoint.GetVectorTo(_currentPoint);
  187.  
  188.                     _visualCircle.TransformBy(
  189.                         Matrix3d.Displacement(displacement));
  190.  
  191.                     //Update each FROM visual line
  192.                     foreach (var l in _fromVisualLines)
  193.                     {
  194.                         l.StartPoint = _currentPoint;
  195.                     }
  196.  
  197.                     //Update each TO visual line
  198.                     foreach (var l in _toVisualLines)
  199.                     {
  200.                         l.EndPoint = _currentPoint;
  201.                     }
  202.  
  203.                     _prevPoint = _currentPoint;
  204.                     return SamplerStatus.OK;
  205.                 }
  206.             }
  207.         }
  208.  
  209.         #endregion
  210.  
  211.         #region private methods
  212.  
  213.         private void CreateVisualEntities()
  214.         {
  215.             using (Transaction tran =
  216.                 _db.TransactionManager.StartTransaction())
  217.             {
  218.                 //Create visual Circle
  219.                 Circle c = (Circle)tran.GetObject(
  220.                     _circleId, OpenMode.ForRead);
  221.                 _visualCircle = c.Clone() as Circle;
  222.                 _visualCircle.SetDatabaseDefaults(_db);
  223.                 _visualCircle.ColorIndex = _visualColorIndex;
  224.  
  225.                 Point3d fromPt;
  226.                 Point3d toPt;
  227.  
  228.                 //Create FROM lines
  229.                 foreach (var id in _fromLineIds)
  230.                 {
  231.                     Line l = (Line)tran.GetObject(id, OpenMode.ForRead);
  232.  
  233.                     Line vLine = l.Clone() as Line;
  234.                     vLine.SetDatabaseDefaults(_db);
  235.                     vLine.ColorIndex = _visualColorIndex;
  236.  
  237.                     //Stretch the line to FROM/TO circles' centre points
  238.                     LinkInfoXDataUtil.GetLinkedCircleCentres(
  239.                         _db, id, out fromPt, out toPt);
  240.  
  241.                     vLine.StartPoint = fromPt;
  242.                     vLine.EndPoint = toPt;
  243.  
  244.                     _fromVisualLines.Add(vLine);
  245.                 }
  246.  
  247.                 //Create TO lines
  248.                 foreach (var id in _toLineIds)
  249.                 {
  250.                     Line l = (Line)tran.GetObject(id, OpenMode.ForRead);
  251.  
  252.                     Line vLine = l.Clone() as Line;
  253.                     vLine.SetDatabaseDefaults(_db);
  254.                     vLine.ColorIndex = _visualColorIndex;
  255.  
  256.                     //Stretch the line to FROM/TO circles' centre points
  257.                     LinkInfoXDataUtil.GetLinkedCircleCentres(
  258.                         _db, id, out fromPt, out toPt);
  259.  
  260.                     vLine.StartPoint = fromPt;
  261.                     vLine.EndPoint = toPt;
  262.  
  263.                     _toVisualLines.Add(vLine);
  264.                 }
  265.             }
  266.         }
  267.  
  268.         private void HighlightEntities(bool highlight)
  269.         {
  270.             List<ObjectId> ents = new List<ObjectId>();
  271.             ents.Add(_circleId);
  272.             ents.AddRange(_fromLineIds);
  273.             ents.AddRange(_toLineIds);
  274.  
  275.             CommonUtil.HighlightEntities(_db, ents, highlight);
  276.         }
  277.  
  278.         private void DisposeVisualEntities()
  279.         {
  280.             if (_visualCircle != null)
  281.             {
  282.                 _visualCircle.Dispose();
  283.                 _visualCircle = null;
  284.             }
  285.  
  286.             foreach (var ent in _fromVisualLines)
  287.                 ent.Dispose();
  288.  
  289.             _fromVisualLines.Clear();
  290.  
  291.             foreach (var ent in _toVisualLines)
  292.                 ent.Dispose();
  293.  
  294.             _toVisualLines.Clear();
  295.         }
  296.  
  297.         #endregion
  298.     }
  299. }

Finally, with all the required functionality available in the classes, it is time to put them together, which leads to another class ObjectLinker:

Code Snippet
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.DatabaseServices;
  3. using Autodesk.AutoCAD.EditorInput;
  4.  
  5. namespace LinkedObjects
  6. {
  7.     public class ObjectLinker
  8.     {
  9.         private Document _dwg;
  10.         private Database _db;
  11.         private Editor _ed;
  12.  
  13.         public ObjectLinker(Document dwg)
  14.         {
  15.             _dwg = dwg;
  16.             _db = dwg.Database;
  17.             _ed = _dwg.Editor;
  18.         }
  19.  
  20.         //The method does not check whether there is already
  21.         //an existing linking line between the two circles
  22.         public bool AddLinkBetweenCircles()
  23.         {
  24.             //Pick linking circle
  25.             ObjectId fromCircleId;
  26.             if (!CommonUtil.PickEntity(_ed, typeof(Circle),
  27.                 "\nPick a circle (or press any key to exit): ",
  28.                 "Not a circle!", out fromCircleId))
  29.             {
  30.                 CommonUtil.PrintCancelMessage();
  31.                 return false;
  32.             }
  33.  
  34.             //pick circle to be linked
  35.             ObjectId toCircleId;
  36.             if (!CommonUtil.PickEntity(_ed, typeof(Circle),
  37.                 "\nPick a circle (or press any key to exit): ",
  38.                 "Not a circle!", out toCircleId))
  39.             {
  40.                 CommonUtil.PrintCancelMessage();
  41.                 return false;
  42.             }
  43.  
  44.             //Draw line between the circles
  45.             ObjectId lineId = CommonUtil.DrawLineBetweenCircles(
  46.                 _db, fromCircleId, toCircleId);
  47.  
  48.             //Set link XData
  49.             LinkInfoXDataUtil.SetLink(_db, fromCircleId, toCircleId, lineId);
  50.  
  51.             _ed.WriteMessage(
  52.                 "\nLink between the 2 picked circles has been established.");
  53.  
  54.             return true;
  55.         }
  56.  
  57.         public void RemoveLinkBetweenCircles(bool eraseLineEntity)
  58.         {
  59.             //Pick line
  60.             ObjectId lineId;
  61.             if (!CommonUtil.PickEntity(_ed, typeof(Line),
  62.                 "\nPick linking line: ", "Not a line!", out lineId))
  63.             {
  64.                 CommonUtil.PrintCancelMessage();
  65.                 return;
  66.             }
  67.  
  68.             LinkInfoXDataUtil.RemoveLink(_db, lineId);
  69.  
  70.             if (eraseLineEntity)
  71.             {
  72.                 CommonUtil.EraseEntity(_db, lineId);
  73.             }
  74.         }
  75.  
  76.         public void MoveCircle()
  77.         {
  78.             //Pick a linked circle
  79.             PromptEntityOptions opt = new
  80.                 PromptEntityOptions("\nPick a linked circle:");
  81.             opt.SetRejectMessage("Invalid pick: must be a circle.");
  82.             opt.AddAllowedClass(typeof(Circle), true);
  83.             PromptEntityResult res = _ed.GetEntity(opt);
  84.             if (res.Status == PromptStatus.OK)
  85.             {
  86.                 LinkedCircleJig jig = new LinkedCircleJig(_dwg, res.ObjectId);
  87.                 jig.DragLinkedCircle();
  88.             }
  89.         }
  90.     }
  91. }

By now, the only thing left is to create commands for users to do what they want:

Code Snippet
  1. using System;
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.DatabaseServices;
  4. using Autodesk.AutoCAD.EditorInput;
  5. using Autodesk.AutoCAD.Runtime;
  6.  
  7. [assembly: CommandClass(typeof(LinkedObjects.MyCommands))]
  8.  
  9. namespace LinkedObjects
  10. {
  11.     public class MyCommands
  12.     {
  13.         private ObjectLinker linker = null;
  14.  
  15.         [CommandMethod("LinkMyCircles")]
  16.         public void LinkCircles()
  17.         {
  18.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  19.             Editor ed = dwg.Editor;
  20.  
  21.             if (linker == null) linker = new ObjectLinker(dwg);
  22.  
  23.             try
  24.             {
  25.                 while (true)
  26.                 {
  27.                     if (!linker.AddLinkBetweenCircles())
  28.                         break;
  29.                 }
  30.             }
  31.             catch (System.Exception ex)
  32.             {
  33.                 CommonUtil.PrintCancelMessage(ex.Message);
  34.             }
  35.         }
  36.  
  37.         [CommandMethod("MoveMyCircle")]
  38.         public void MoveLinkedCircle()
  39.         {
  40.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  41.             Editor ed = dwg.Editor;
  42.  
  43.             if (linker == null) linker = new ObjectLinker(dwg);
  44.  
  45.             try
  46.             {
  47.                 linker.MoveCircle();
  48.             }
  49.             catch (System.Exception ex)
  50.             {
  51.                 CommonUtil.PrintCancelMessage(ex.Message);
  52.             }
  53.         }
  54.  
  55.         [CommandMethod("DelinkMyCircle")]
  56.         public void DelinkCircles()
  57.         {
  58.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  59.             Editor ed = dwg.Editor;
  60.  
  61.             if (linker == null) linker = new ObjectLinker(dwg);
  62.  
  63.             try
  64.             {
  65.                 linker.RemoveLinkBetweenCircles(true);
  66.             }
  67.             catch (System.Exception ex)
  68.             {
  69.                 CommonUtil.PrintCancelMessage(ex.Message);
  70.             }
  71.         }
  72.     }
  73. }

This a quite long post with a lot of code in order to demonstrate a workable operation. I did not try my best effort to make the code more as concise as it could be. As usual, I created a video clip here to show the code in action.
Some points of interest:
  • I could have used a polyline to link 2 circles, so that I can make a segment of the polyline to look like an arrow to indicate the direction of the link. I could have also used DrawableOverrule to make the linking like to show an arrow
  • As I commented in the code, I did not check a link between 2 circles has already existed before adding link
  • It is obvious that standard AutoCAD editing commands, such as MOVE/RORATE/STRETCH...could easily destroy the links visually. Here is when ObjectOverrule could help. One of my previous post here can be used to prevent linked circles/lines from being changed. I might post an update to this post to incorporate the ObjectOverrule into this project later, if I can manage some time available.

Bug Fix Update:

There is a bug in class LinkedCircleJig: following code should be added between line 173 and 174:

_cancel=true;

2 comments:

Anonymous said...

Great sample normal, thanks.
Regards
Kerry

Anonymous said...

Ooops ..
Norman is meant to be normal :)

Followers

About Me

My photo
After graduating from university, I worked as civil engineer for more than 10 years. It was AutoCAD use that led me to the path of computer programming. Although I now do more generic business software development, such as enterprise system, timesheet, billing, web services..., AutoCAD related programming is always interesting me and I still get AutoCAD programming tasks assigned to me from time to time. So, AutoCAD goes, I go.