Simplified version, not tested for special types of intersections.
After splitting Create Region is added to show results.
[CommandMethod("SPAI")]
public static void SplitPolylineAtIntersection()
{
Document doc = null;
Database db = null;
Editor ed = null;
try
{
doc = AcadApp.DocumentManager.MdiActiveDocument;
if (doc == null)
throw new System.Exception("No MdiActiveDocument");
db = doc.Database;
ed = doc.Editor;
var plPeo = new PromptEntityOptions("Select Poly");
var per = ed.GetEntity(plPeo);
if (per.Status != PromptStatus.OK)
return;
var plId = per.ObjectId;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
var ms = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);
var pl = tr.GetObject(plId, OpenMode.ForRead) as Polyline;
var plSegs = new DBObjectCollection();
pl.Explode(plSegs);
//Test each Poly Segment for intersection with the other segments.
//These segments will be splitted at the intersections and tested again
int i = -1;
while (++i < plSegs.Count)
{
var segi = plSegs[i] as Curve;
if (segi == null) continue;
int j = -1;
while (++j < plSegs.Count)
{
if (j == i) continue;
var segj = plSegs[j] as Curve;
if (segj == null) continue;
//Test Segment[i] against Segment[j]
Point3dCollection intsPnts = new Point3dCollection();
segi.IntersectWith(segj, Intersect.OnBothOperands, intsPnts, IntPtr.Zero, IntPtr.Zero);
if (intsPnts.Count > 0)
{
var splCurves = segi.GetSplitCurves(intsPnts);
if (splCurves.Count > 1) //don't add curves splitted at the start or end
{
foreach (DBObject splCurve in splCurves)
{
plSegs.Add(splCurve);
//for testing purposes add segments to database
ms.AppendEntity((Entity)splCurve);
tr.AddNewlyCreatedDBObject(splCurve, true);
}
plSegs[i] = null;
break; //exit while j, next i
}
}
}
}
pl.UpgradeOpen();
pl.Erase();
//for testing purposes add remaning segments to database
// add the not splitted segments to the Database
foreach (DBObject plseg in plSegs)
{
if (plseg == null) continue;
if (plseg.ObjectId.IsNull)
{
ms.AppendEntity((Entity)plseg);
tr.AddNewlyCreatedDBObject(plseg, true);
}
}
//Create regions from splitted segments
// then create closed polylines from these regions
var regions=Region.CreateFromCurves(plSegs);
//for testing purposes add regions to database
foreach (DBObject region in regions)
{
ms.AppendEntity((Entity)region);
tr.AddNewlyCreatedDBObject(region, true);
}
tr.Commit();
}
}
catch (System.Exception ex)
{
if (ed != null)
ed.WriteMessage("\n Error in SplitPolylineAtIntersection: {0}", ex.Message);
}
}
