# How to avoid self-intersection when applying stroke to a curve?

I have several Spline2D objects in my code, each of which has a Position, Velocity, and Acceleration method that returns a vector of the specified quantity at a particular time. I've been using these vectors in order to construct geometry to create gradient strokes for the curves, but I'm having problems with self-intersections at steep curves. As an example, here's one curve where I'm having this occur:

Wireframe: http://twitpic.com/2zplw1/full
Filled: http://twitpic.com/2zpmnt/full

As you can see, on the second bend, the inner portion intersects itself, which causes that ugly artifact. Is there a good algorithm/method to stroke curves without causing that self-intersection?

EDIT: More extreme examples, plus a mock-up of what I'd like to achieve:

Wireframe: http://twitpic.com/2ztwzi/full
Filled: http://twitpic.com/2ztwkt/full
Ideal Outcome (Mock-Up): http://twitpic.com/2ztxa8/full

• Wow, I hadn't even realized the connotation of the title when I wrote it. :) – ThatsGobbles Oct 22 '10 at 15:13

If you're rendering these with the GPU and any modern 3D api (eg. OpenGL/D3D), it looks to me like you can get rid of this with depth testing. If you assign your outside verts to be z=FAR , and your inside verts to be z=NEAR, the depth testing should prevent the overlap from showing. With OpenGL:


// don't forget to clear depth buffer to 1.0f at beginning of frame.
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// enable depth testing.
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

// draw the Spline2D
for each segment in spline
for each vert in segment
if (vert is an outer vert), set vert.z = 1.0, otherwise set vert.z=0.0


Caveat emptor: this won't work if you need translucent strokes.

• Great answer, just what I was thinking, however, you're wrong about it not working for translucent strokes if you allow writing the zbuffer in one pass, then doing the colour in the second. – Richard Fabian Oct 25 '10 at 14:41
• Thanks, my strokes are indeed opaque, so this worked very simply and wonderfully! – ThatsGobbles Oct 29 '10 at 1:26

The "Fix" is going to depend on what you want the resultant output to look like. The problem hasn't reallly been defined well enough here: what's it meant to look like?

I'd suggest you first try making an even more extreme example of the glitch, then using photoshop/paint to fix it you might find inspiration for a solution.

Do you want it to fold up? Overlap with the edge? Pull in until it doesn't overlap?

• Good point, I'll whip up a sharper-turned curve, and an "ideal" curve in Illustrator or Inkscape later today. – ThatsGobbles Oct 22 '10 at 15:16
• Original post edited! – ThatsGobbles Oct 22 '10 at 16:47