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
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Text;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.Geometry;
- namespace LinkedObjects
- {
- public class LinkInfoXDataUtil
- {
- private const string OBJECT_LINK_APP = "MyNameSpace.LinkObjects";
- public static void SetLink(Database db,
- ObjectId fromCircleId, ObjectId toCircleId, ObjectId linkLineId)
- {
- ObjectLinkAppExists(db, true);
- using (Transaction tran =
- db.TransactionManager.StartTransaction())
- {
- Entity fromCircle = (Entity)tran.GetObject(
- fromCircleId, OpenMode.ForWrite);
- Entity toCircle = (Entity)tran.GetObject(
- toCircleId, OpenMode.ForWrite);
- Entity line = (Entity)tran.GetObject(
- linkLineId, OpenMode.ForWrite);
- AddFromLinkToCircle(fromCircle, line.Handle.ToString());
- AddToLinkToCircle(toCircle, line.Handle.ToString());
- AddLinksToLine(line,
- fromCircle.Handle.ToString(),
- toCircle.Handle.ToString());
- tran.Commit();
- }
- }
- public static void RemoveLink(Database db, ObjectId linkLineId)
- {
- using (Transaction tran =
- db.TransactionManager.StartTransaction())
- {
- Entity line = (Entity)tran.GetObject(
- linkLineId, OpenMode.ForWrite);
- ObjectId fromCircleId;
- ObjectId toCircleId;
- GetLinkedCirclesFromLine(
- db, tran, line, out fromCircleId, out toCircleId);
- Entity fromCircle = (Entity)tran.GetObject(
- fromCircleId, OpenMode.ForWrite);
- Entity toCircle = (Entity)tran.GetObject(
- toCircleId, OpenMode.ForWrite);
- //Remove line's handle from XData in circles
- RemoveFromLinkFromCircle(fromCircle, line.Handle.ToString());
- RemoveToLinkFromCircle(toCircle, line.Handle.ToString());
- //Clear Xdata from the line
- TypedValue[] vals = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP)
- };
- ResultBuffer buffer = new ResultBuffer(vals);
- line.XData = buffer;
- tran.Commit();
- }
- }
- public static void GetCirleLink(Database db, ObjectId circleId,
- out List<ObjectId> fromLineIds, out List<ObjectId> toLineIds)
- {
- fromLineIds = new List<ObjectId>();
- toLineIds = new List<ObjectId>();
- if (circleId.ObjectClass.DxfName.ToUpper() == "CIRCLE")
- {
- using (Transaction tran =
- circleId.Database.TransactionManager.StartTransaction())
- {
- Entity ent = (Entity)tran.GetObject(
- circleId, OpenMode.ForRead);
- ResultBuffer buffer =
- ent.GetXDataForApplication(OBJECT_LINK_APP);
- if (buffer == null) return;
- TypedValue[] vals = buffer.AsArray();
- if (vals.Length == 3)
- {
- string handles;
- //Get lines started from this circle
- handles = vals[1].Value.ToString();
- if (handles.Length > 0)
- {
- string[] hs = handles.Split('|');
- foreach (string h in hs)
- {
- fromLineIds.Add(HandleToObjectId(db, h));
- }
- }
- //Get lines pointing to this circle
- handles = vals[2].Value.ToString();
- if (handles.Length > 0)
- {
- string[] hs = handles.Split('|');
- foreach (string h in hs)
- {
- toLineIds.Add(HandleToObjectId(db, h));
- }
- }
- }
- else
- {
- //Clear inavlid XData
- TypedValue[] vs = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName,
- OBJECT_LINK_APP)
- };
- ent.UpgradeOpen();
- ent.XData = new ResultBuffer(vs);
- }
- tran.Commit();
- }
- }
- }
- public static void GetLineLink(Database db, ObjectId lineId,
- out ObjectId fromCircleId, out ObjectId toCircleId)
- {
- fromCircleId = ObjectId.Null;
- toCircleId = ObjectId.Null;
- if (lineId.ObjectClass.DxfName.ToUpper() == "LINE")
- {
- using (Transaction tran =
- lineId.Database.TransactionManager.StartTransaction())
- {
- Entity ent = (Entity)tran.GetObject(
- lineId, OpenMode.ForRead);
- ResultBuffer buffer =
- ent.GetXDataForApplication(OBJECT_LINK_APP);
- if (buffer == null) return;
- TypedValue[] vals = buffer.AsArray();
- if (vals.Length == 3)
- {
- string handle;
- //FROM circle
- handle = vals[1].Value.ToString();
- if (handle.Length > 0)
- fromCircleId = HandleToObjectId(db, handle);
- //TO circle
- handle = vals[2].Value.ToString();
- if (handle.Length > 0)
- toCircleId = HandleToObjectId(db, handle);
- }
- tran.Commit();
- }
- }
- }
- public static void GetLinkedCircleCentres(Database db, ObjectId linkLineId,
- out Point3d fromCircleCentre, out Point3d toCircleCentre)
- {
- ObjectId fromCircleId;
- ObjectId toCircleId;
- GetLineLink(db, linkLineId, out fromCircleId, out toCircleId);
- fromCircleCentre = CommonUtil.GetCircleCentre(db, fromCircleId);
- toCircleCentre = CommonUtil.GetCircleCentre(db, toCircleId);
- }
- #region private methoids
- private static bool ObjectLinkAppExists(Database db, bool create)
- {
- bool exists = false;
- using (Transaction tran =
- db.TransactionManager.StartTransaction())
- {
- RegAppTable appTable = (RegAppTable)tran.GetObject(
- db.RegAppTableId, OpenMode.ForRead);
- if (appTable.Has(OBJECT_LINK_APP))
- exists = true;
- else
- {
- if (create)
- {
- RegAppTableRecord appRec = new RegAppTableRecord();
- appRec.Name = OBJECT_LINK_APP;
- appTable.UpgradeOpen();
- appTable.Add(appRec);
- tran.AddNewlyCreatedDBObject(appRec, true);
- exists = true;
- }
- }
- tran.Commit();
- }
- return exists;
- }
- private static ObjectId HandleToObjectId(
- Database db, string handleString)
- {
- ObjectId id = ObjectId.Null;
- id = db.GetObjectId(false,
- new Handle(Int64.Parse(handleString,
- System.Globalization.NumberStyles.AllowHexSpecifier)), 0);
- return id;
- }
- private static void AddFromLinkToCircle(Entity fromEnt, string handle)
- {
- ResultBuffer buffer =
- fromEnt.GetXDataForApplication(OBJECT_LINK_APP);
- TypedValue[] vals;
- string newHandles = "";
- string existingHandles = "";
- string toHandles = "";
- if (buffer != null)
- {
- vals = buffer.AsArray();
- existingHandles = vals[1].Value.ToString();
- toHandles = vals[2].Value.ToString();
- }
- bool exists = false;
- if (existingHandles.Length > 0)
- {
- string[] hs = existingHandles.Split('|');
- foreach (string h in hs)
- {
- if (h.ToUpper() == handle.ToUpper())
- {
- exists = true;
- break;
- }
- }
- if (!exists)
- newHandles = existingHandles + "|" + handle;
- else
- newHandles = existingHandles;
- }
- else
- {
- newHandles = handle;
- }
- vals = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString, newHandles),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString, toHandles)
- };
- fromEnt.XData = new ResultBuffer(vals);
- }
- private static void AddToLinkToCircle(Entity toEnt, string handle)
- {
- ResultBuffer buffer =
- toEnt.GetXDataForApplication(OBJECT_LINK_APP);
- TypedValue[] vals;
- string newHandles = "";
- string existingHandles = "";
- string fromHandles = "";
- if (buffer != null)
- {
- vals = buffer.AsArray();
- existingHandles = vals[2].Value.ToString();
- fromHandles = vals[1].Value.ToString();
- }
- bool exists = false;
- if (existingHandles.Length > 0)
- {
- string[] hs = existingHandles.Split('|');
- foreach (string h in hs)
- {
- if (h.ToUpper() == handle.ToUpper())
- {
- exists = true;
- break;
- }
- }
- if (!exists)
- newHandles = existingHandles + "|" + handle;
- else
- newHandles = existingHandles;
- }
- else
- {
- newHandles = handle;
- }
- vals = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString, fromHandles),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString, newHandles)
- };
- toEnt.XData = new ResultBuffer(vals);
- }
- private static void AddLinksToLine(
- Entity line, string fromHandle, string toHandle)
- {
- TypedValue[] vals = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString, fromHandle),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString, toHandle)
- };
- line.XData = new ResultBuffer(vals);
- }
- private static void GetLinkedCirclesFromLine(
- Database db, Transaction tran, Entity line,
- out ObjectId fromCircleId, out ObjectId toCircleId)
- {
- fromCircleId = ObjectId.Null;
- toCircleId = ObjectId.Null;
- ResultBuffer buffer =
- line.GetXDataForApplication(OBJECT_LINK_APP);
- if (buffer != null)
- {
- TypedValue[] vals = buffer.AsArray();
- string handleString;
- handleString = vals[1].Value.ToString();
- fromCircleId = HandleToObjectId(db, handleString);
- handleString = vals[2].Value.ToString();
- toCircleId = HandleToObjectId(db, handleString);
- }
- }
- private static void RemoveFromLinkFromCircle(
- Entity fromCircle, string lineHandle)
- {
- ResultBuffer buffer =
- fromCircle.GetXDataForApplication(OBJECT_LINK_APP);
- if (buffer == null) return;
- TypedValue[] vals = buffer.AsArray();
- string fromHandles = vals[1].Value.ToString();
- string toHandles = vals[2].Value.ToString();
- if (fromHandles.Length > 0)
- {
- StringBuilder newHandles = new StringBuilder();
- bool removed = false;
- //rebuild the handles string with
- //targeted handle striing being excluded
- string[] hs = fromHandles.Split('|');
- foreach (string h in hs)
- {
- if (h.ToUpper() != lineHandle.ToUpper())
- {
- newHandles.Append(h + "|");
- }
- else
- {
- removed = true;
- }
- }
- if (removed)
- {
- //remove the trailing "|"
- if (newHandles.ToString().EndsWith("|"))
- {
- newHandles.Length = newHandles.Length - 1;
- }
- //recreate XData
- if (newHandles.Length == 0 && toHandles.Length == 0)
- {
- vals = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName,
- OBJECT_LINK_APP)
- };
- }
- else
- {
- vals = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName,
- OBJECT_LINK_APP),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString,
- newHandles.ToString()),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString,
- toHandles)
- };
- }
- fromCircle.XData = new ResultBuffer(vals);
- }
- }
- }
- private static void RemoveToLinkFromCircle(
- Entity toCircle, string lineHandle)
- {
- ResultBuffer buffer =
- toCircle.GetXDataForApplication(OBJECT_LINK_APP);
- if (buffer == null) return;
- TypedValue[] vals = buffer.AsArray();
- string fromHandles = vals[1].Value.ToString();
- string toHandles = vals[2].Value.ToString();
- if (toHandles.Length > 0)
- {
- StringBuilder newHandles = new StringBuilder();
- bool removed = false;
- //rebuild the handles string with
- //targeted handle striing being excluded
- string[] hs = toHandles.Split('|');
- foreach (string h in hs)
- {
- if (h.ToUpper() != lineHandle.ToUpper())
- {
- newHandles.Append(h + "|");
- }
- else
- {
- removed = true;
- }
- }
- if (removed)
- {
- //remove the trailing "|"
- if (newHandles.ToString().EndsWith("|"))
- {
- newHandles.Length = newHandles.Length - 1;
- }
- //recreate XData
- if (newHandles.Length == 0 && fromHandles.Length == 0)
- {
- vals = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName,
- OBJECT_LINK_APP)
- };
- }
- else
- {
- vals = new TypedValue[]
- {
- new TypedValue(
- (Int16)DxfCode.ExtendedDataRegAppName,
- OBJECT_LINK_APP),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString,
- fromHandles),
- new TypedValue(
- (Int16)DxfCode.ExtendedDataAsciiString,
- newHandles.ToString())
- };
- }
- toCircle.XData = new ResultBuffer(vals);
- }
- }
- }
- #endregion
- }
- }
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
- using System;
- using System.Collections.Generic;
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.EditorInput;
- using Autodesk.AutoCAD.Geometry;
- namespace LinkedObjects
- {
- public class CommonUtil
- {
- public static void PrintCancelMessage(string message = "")
- {
- Editor ed =
- Application.DocumentManager.MdiActiveDocument.Editor;
- if (!string.IsNullOrEmpty(message))
- {
- ed.WriteMessage("\n" + message);
- }
- ed.WriteMessage("\n*Cancel*");
- Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
- }
- public static bool PickEntity(Editor ed, Type entType,
- string optionMessage, string rejectMessage, out ObjectId entId)
- {
- entId = ObjectId.Null;
- PromptEntityOptions opt = new PromptEntityOptions(optionMessage);
- opt.SetRejectMessage(rejectMessage);
- opt.AddAllowedClass(entType, true);
- PromptEntityResult res = ed.GetEntity(opt);
- if (res.Status == PromptStatus.OK)
- {
- entId = res.ObjectId;
- return true;
- }
- return false;
- }
- public static ObjectId DrawLineBetweenCircles(
- Database db, ObjectId fromCircleId, ObjectId toCircleId)
- {
- ObjectId lineId = ObjectId.Null;
- using (Transaction tran =
- db.TransactionManager.StartTransaction())
- {
- Circle fromCircle = (Circle)tran.GetObject(
- fromCircleId, OpenMode.ForRead);
- Circle toCircle = (Circle)tran.GetObject(
- toCircleId, OpenMode.ForRead);
- ObjectId modelId =
- SymbolUtilityServices.GetBlockModelSpaceId(db);
- BlockTableRecord model = (BlockTableRecord)tran.GetObject(
- modelId, OpenMode.ForWrite);
- using (Line line =
- new Line(fromCircle.Center, toCircle.Center))
- {
- //Change startpoint/endpoint from
- //circle's center to circle's perimeter
- Point3d pt;
- pt = line.GetPointAtDist(fromCircle.Radius);
- line.StartPoint = pt;
- double dist=line.Length-toCircle.Radius;
- pt = line.GetPointAtDist(dist);
- line.EndPoint = pt;
- line.SetDatabaseDefaults(db);
- lineId = model.AppendEntity(line);
- tran.AddNewlyCreatedDBObject(line, true);
- tran.Commit();
- }
- }
- return lineId;
- }
- public static void EraseEntity(Database db, ObjectId entId)
- {
- using (Transaction tran = db.TransactionManager.StartTransaction())
- {
- Entity ent = (Entity)tran.GetObject(entId, OpenMode.ForWrite);
- ent.Erase(true);
- tran.Commit();
- }
- }
- public static Point3d GetCircleCentre(Database db, ObjectId circleId)
- {
- Point3d pt = new Point3d();
- using (Transaction tran = db.TransactionManager.StartTransaction())
- {
- Circle c = tran.GetObject(circleId, OpenMode.ForRead) as Circle;
- if (c != null)
- pt = c.Center;
- else
- throw new ArgumentException("Entity is not a circle.");
- tran.Commit();
- }
- return pt;
- }
- public static void HighlightEntities(
- Database db, List<ObjectId> entIds, bool highlight)
- {
- using (Transaction tran =
- db.TransactionManager.StartTransaction())
- {
- foreach (var id in entIds)
- {
- Entity ent = (Entity)tran.GetObject(id, OpenMode.ForWrite);
- if (highlight)
- ent.Highlight();
- else
- ent.Unhighlight();
- }
- tran.Commit();
- }
- }
- }
- }
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
Code Snippet
- using System.Collections.Generic;
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.EditorInput;
- using Autodesk.AutoCAD.Geometry;
- using Autodesk.AutoCAD.GraphicsInterface;
- namespace LinkedObjects
- {
- public class LinkedCircleJig : DrawJig
- {
- private Document _dwg;
- private Editor _ed;
- private Database _db;
- private ObjectId _circleId;
- private List<ObjectId> _fromLineIds;
- private List<ObjectId> _toLineIds;
- private Point3d _basePoint;
- private Point3d _currentPoint;
- private Point3d _prevPoint;
- private bool _cancelled = false;
- private Circle _visualCircle = null;
- private List<Line> _fromVisualLines = new List<Line>();
- private List<Line> _toVisualLines = new List<Line>();
- private int _visualColorIndex = 1;
- public LinkedCircleJig(Document dwg, ObjectId circleId)
- {
- _dwg = dwg;
- _ed = dwg.Editor;
- _db = dwg.Database;
- _circleId = circleId;
- LinkInfoXDataUtil.GetCirleLink(
- _db, _circleId, out _fromLineIds, out _toLineIds);
- _basePoint = CommonUtil.GetCircleCentre(_db, circleId);
- }
- public void DragLinkedCircle()
- {
- _cancelled = false;
- try
- {
- CreateVisualEntities();
- _currentPoint = _basePoint;
- _prevPoint = _basePoint;
- HighlightEntities(true);
- _ed.Drag(this);
- if (!_cancelled)
- {
- using (Transaction tran =
- _db.TransactionManager.StartTransaction())
- {
- //Move circle
- Vector3d displacement =
- _basePoint.GetVectorTo(_currentPoint);
- Circle c = (Circle)tran.GetObject(
- _circleId, OpenMode.ForWrite);
- c.TransformBy(
- Matrix3d.Displacement(displacement));
- ObjectId fCircleId;
- ObjectId tCircleId;
- Point3d pt;
- double dist;
- //update FROM lines
- foreach (var id in _fromLineIds)
- {
- Line l = (Line)tran.GetObject(
- id, OpenMode.ForWrite);
- //get its TO circle
- LinkInfoXDataUtil.GetLineLink(
- _db, id, out fCircleId, out tCircleId);
- Circle tCircle = (Circle)tran.GetObject(
- tCircleId, OpenMode.ForRead);
- l.StartPoint = c.Center;
- l.EndPoint = tCircle.Center;
- //Shrink line's length
- pt = l.GetPointAtDist(c.Radius);
- l.StartPoint = pt;
- dist = l.Length - tCircle.Radius;
- pt = l.GetPointAtDist(dist);
- l.EndPoint = pt;
- }
- //Update TO lines
- foreach (var id in _toLineIds)
- {
- Line l = (Line)tran.GetObject(
- id, OpenMode.ForWrite);
- //get its TO circle
- LinkInfoXDataUtil.GetLineLink(
- _db, id, out fCircleId, out tCircleId);
- Circle fCircle = (Circle)tran.GetObject(
- fCircleId, OpenMode.ForRead);
- l.StartPoint = fCircle.Center;
- l.EndPoint = c.Center;
- //Shrink line's length
- pt = l.GetPointAtDist(fCircle.Radius);
- l.StartPoint = pt;
- dist = l.Length - c.Radius;
- pt = l.GetPointAtDist(dist);
- l.EndPoint = pt;
- }
- tran.Commit();
- }
- }
- }
- catch
- {
- throw;
- }
- finally
- {
- HighlightEntities(false);
- DisposeVisualEntities();
- }
- }
- #region Jig method overrides
- protected override bool WorldDraw(WorldDraw draw)
- {
- draw.Geometry.Draw(_visualCircle);
- foreach (var e in _fromVisualLines)
- draw.Geometry.Draw(e);
- foreach (var e in _toVisualLines)
- draw.Geometry.Draw(e);
- return true;
- }
- protected override SamplerStatus Sampler(JigPrompts prompts)
- {
- JigPromptPointOptions jigOpt =
- new JigPromptPointOptions();
- jigOpt.UserInputControls =
- UserInputControls.Accept3dCoordinates |
- UserInputControls.NoZeroResponseAccepted |
- UserInputControls.NoDwgLimitsChecking;
- jigOpt.BasePoint = _basePoint;
- jigOpt.UseBasePoint = true;
- jigOpt.Cursor = CursorType.RubberBand;
- jigOpt.Message = "\nMove the linked circle to picked point: ";
- PromptPointResult res = prompts.AcquirePoint(jigOpt);
- if (res.Status == PromptStatus.Cancel)
- {
- return SamplerStatus.Cancel;
- }
- else
- {
- _currentPoint = res.Value;
- if (_currentPoint == _prevPoint)
- return SamplerStatus.NoChange;
- else
- {
- //Update location of visual circle
- Vector3d displacement =
- _prevPoint.GetVectorTo(_currentPoint);
- _visualCircle.TransformBy(
- Matrix3d.Displacement(displacement));
- //Update each FROM visual line
- foreach (var l in _fromVisualLines)
- {
- l.StartPoint = _currentPoint;
- }
- //Update each TO visual line
- foreach (var l in _toVisualLines)
- {
- l.EndPoint = _currentPoint;
- }
- _prevPoint = _currentPoint;
- return SamplerStatus.OK;
- }
- }
- }
- #endregion
- #region private methods
- private void CreateVisualEntities()
- {
- using (Transaction tran =
- _db.TransactionManager.StartTransaction())
- {
- //Create visual Circle
- Circle c = (Circle)tran.GetObject(
- _circleId, OpenMode.ForRead);
- _visualCircle = c.Clone() as Circle;
- _visualCircle.SetDatabaseDefaults(_db);
- _visualCircle.ColorIndex = _visualColorIndex;
- Point3d fromPt;
- Point3d toPt;
- //Create FROM lines
- foreach (var id in _fromLineIds)
- {
- Line l = (Line)tran.GetObject(id, OpenMode.ForRead);
- Line vLine = l.Clone() as Line;
- vLine.SetDatabaseDefaults(_db);
- vLine.ColorIndex = _visualColorIndex;
- //Stretch the line to FROM/TO circles' centre points
- LinkInfoXDataUtil.GetLinkedCircleCentres(
- _db, id, out fromPt, out toPt);
- vLine.StartPoint = fromPt;
- vLine.EndPoint = toPt;
- _fromVisualLines.Add(vLine);
- }
- //Create TO lines
- foreach (var id in _toLineIds)
- {
- Line l = (Line)tran.GetObject(id, OpenMode.ForRead);
- Line vLine = l.Clone() as Line;
- vLine.SetDatabaseDefaults(_db);
- vLine.ColorIndex = _visualColorIndex;
- //Stretch the line to FROM/TO circles' centre points
- LinkInfoXDataUtil.GetLinkedCircleCentres(
- _db, id, out fromPt, out toPt);
- vLine.StartPoint = fromPt;
- vLine.EndPoint = toPt;
- _toVisualLines.Add(vLine);
- }
- }
- }
- private void HighlightEntities(bool highlight)
- {
- List<ObjectId> ents = new List<ObjectId>();
- ents.Add(_circleId);
- ents.AddRange(_fromLineIds);
- ents.AddRange(_toLineIds);
- CommonUtil.HighlightEntities(_db, ents, highlight);
- }
- private void DisposeVisualEntities()
- {
- if (_visualCircle != null)
- {
- _visualCircle.Dispose();
- _visualCircle = null;
- }
- foreach (var ent in _fromVisualLines)
- ent.Dispose();
- _fromVisualLines.Clear();
- foreach (var ent in _toVisualLines)
- ent.Dispose();
- _toVisualLines.Clear();
- }
- #endregion
- }
- }
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
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.EditorInput;
- namespace LinkedObjects
- {
- public class ObjectLinker
- {
- private Document _dwg;
- private Database _db;
- private Editor _ed;
- public ObjectLinker(Document dwg)
- {
- _dwg = dwg;
- _db = dwg.Database;
- _ed = _dwg.Editor;
- }
- //The method does not check whether there is already
- //an existing linking line between the two circles
- public bool AddLinkBetweenCircles()
- {
- //Pick linking circle
- ObjectId fromCircleId;
- if (!CommonUtil.PickEntity(_ed, typeof(Circle),
- "\nPick a circle (or press any key to exit): ",
- "Not a circle!", out fromCircleId))
- {
- CommonUtil.PrintCancelMessage();
- return false;
- }
- //pick circle to be linked
- ObjectId toCircleId;
- if (!CommonUtil.PickEntity(_ed, typeof(Circle),
- "\nPick a circle (or press any key to exit): ",
- "Not a circle!", out toCircleId))
- {
- CommonUtil.PrintCancelMessage();
- return false;
- }
- //Draw line between the circles
- ObjectId lineId = CommonUtil.DrawLineBetweenCircles(
- _db, fromCircleId, toCircleId);
- //Set link XData
- LinkInfoXDataUtil.SetLink(_db, fromCircleId, toCircleId, lineId);
- _ed.WriteMessage(
- "\nLink between the 2 picked circles has been established.");
- return true;
- }
- public void RemoveLinkBetweenCircles(bool eraseLineEntity)
- {
- //Pick line
- ObjectId lineId;
- if (!CommonUtil.PickEntity(_ed, typeof(Line),
- "\nPick linking line: ", "Not a line!", out lineId))
- {
- CommonUtil.PrintCancelMessage();
- return;
- }
- LinkInfoXDataUtil.RemoveLink(_db, lineId);
- if (eraseLineEntity)
- {
- CommonUtil.EraseEntity(_db, lineId);
- }
- }
- public void MoveCircle()
- {
- //Pick a linked circle
- PromptEntityOptions opt = new
- PromptEntityOptions("\nPick a linked circle:");
- opt.SetRejectMessage("Invalid pick: must be a circle.");
- opt.AddAllowedClass(typeof(Circle), true);
- PromptEntityResult res = _ed.GetEntity(opt);
- if (res.Status == PromptStatus.OK)
- {
- LinkedCircleJig jig = new LinkedCircleJig(_dwg, res.ObjectId);
- jig.DragLinkedCircle();
- }
- }
- }
- }
By now, the only thing left is to create commands for users to do what they want:
Code Snippet
- using System;
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.EditorInput;
- using Autodesk.AutoCAD.Runtime;
- [assembly: CommandClass(typeof(LinkedObjects.MyCommands))]
- namespace LinkedObjects
- {
- public class MyCommands
- {
- private ObjectLinker linker = null;
- [CommandMethod("LinkMyCircles")]
- public void LinkCircles()
- {
- Document dwg = Application.DocumentManager.MdiActiveDocument;
- Editor ed = dwg.Editor;
- if (linker == null) linker = new ObjectLinker(dwg);
- try
- {
- while (true)
- {
- if (!linker.AddLinkBetweenCircles())
- break;
- }
- }
- catch (System.Exception ex)
- {
- CommonUtil.PrintCancelMessage(ex.Message);
- }
- }
- [CommandMethod("MoveMyCircle")]
- public void MoveLinkedCircle()
- {
- Document dwg = Application.DocumentManager.MdiActiveDocument;
- Editor ed = dwg.Editor;
- if (linker == null) linker = new ObjectLinker(dwg);
- try
- {
- linker.MoveCircle();
- }
- catch (System.Exception ex)
- {
- CommonUtil.PrintCancelMessage(ex.Message);
- }
- }
- [CommandMethod("DelinkMyCircle")]
- public void DelinkCircles()
- {
- Document dwg = Application.DocumentManager.MdiActiveDocument;
- Editor ed = dwg.Editor;
- if (linker == null) linker = new ObjectLinker(dwg);
- try
- {
- linker.RemoveLinkBetweenCircles(true);
- }
- catch (System.Exception ex)
- {
- CommonUtil.PrintCancelMessage(ex.Message);
- }
- }
- }
- }
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;
There is a bug in class LinkedCircleJig: following code should be added between line 173 and 174:
_cancel=true;
Great sample normal, thanks.
ReplyDeleteRegards
Kerry
Ooops ..
ReplyDeleteNorman is meant to be normal :)