drawPolygon / drawSolidPoly doesn't properly support concave polygons

I’m creating my own library inspired by Flash Actionscript (/Javascript) which gives you access to graphics functions like:

  • 1 - moveTo( x, y )
  • 2 - lineTo( x, y )
  • 3 - lineStyle( thickness, color )
  • 4 - beginFill( color )
  • 5 - endFill()

lineTo( x, y ) - adds vert to vector
endFill() - calls drawPolygon

I’ve had a lot of success using these functions for simple shapes, but I I’ve just come across a bug while trying to fill a more complex shape, using only the above functions.

This isn’t the first time the issue has been brought up.

For educational purposes I’m recreating a game of Worms, and using a single polygon to try and render the water using a sine-wave.

It works for basic concave shapes, like an arrowhead, e.g:

m_water.beginFill( 0x0000FF7F ); // rrggbbaa
m_water.moveTo( cx + 100, cy + 0 );
m_water.lineTo( cx + 0, cy + 100 );
m_water.lineTo( cx + 50, cy + 0 );
m_water.lineTo( cx + 0, cy - 100 );
m_water.lineTo( cx + 100, cy + 0 );
m_water.endFill(); // Works for basic arrowhead shape

Using the exact same technique, I have this problem when I try to fill an enclosed sine wave / rect:

I don’t want to force anyone who uses this graphics library to split their dynamic drawing into separate parts, I would expect drawPolygon to correctly fill in any polygon without filling outside the lines.

Remember, this library is for educational purposes, for children some as young as 12, these function needs to work how you would expect it to work.

Is there an easy hack / fix for this which I can add to my graphics library without having to change the usage of these 5 graphics functions, or do I have to post this as an official bug?

Thanks, I really appreciate any help I can get on this.

You probably need to triangulate or decompose your complex polygon.

After some experimentation I found a solution which seems to work well, but I’m sure there must be a simpler / more efficient solution.

I still feel this should be be an official cocos bug since the same function which correctly draws a polygon’s outlines incorrectly fills that exact same polygon without concave support.

If this problem was only limited only to drawSolidPoly it would be an understandable limitation, but this is inconsistent behavior for drawPolygon.

Either way, I made a small example project for anyone else who encounters the same problem.

GraphicsObj.cpp (6.8 KB)
GraphicsObj.h (1.7 KB)
HelloWorld.cpp (1.6 KB)
HelloWorld.h (388 Bytes)

Simply include GraphicsObj.h in your header, define a GraphicsObj variable in your header, call init(), and put your drawing code in update(float).


1 Like