I'm currently writing a 3D shader for a computer program, and I've run into a bit of a problem I'm hoping someone can help me with.
The shader is designed to generate an N-sided shape in 2D space. The 3D program that drives the shader essentially passes you a set of x, y coordinates (centred around 0, 0) and expects you to output the appropriate colour. I've already written the portion of the shader that generates these shapes, which works well enough. What I'm having problems with is adding "curvature" to the sides of these shapes, essentially blending between a perfect circle and an N-sided polygon.
The way the shader currently works is as follows:
1) I figure out the angle of a single segment of the N-sided shape:
segmentAngle = (math.pi * 2) / numberOfSides
1) I break down the problem into a single right angle triangle, which uses the following equations:
pAngle = abs((math.atan2(y, x) % segmentAngle) - (segmentAngle / 2)) pDist1 = math.sqrt((x * x) + (y * y))
2) I calculate the distance from the origin of the N-sided shape to the edge, traversing through the coordinates the shader has been given:
pDist2 = (math.cos(segmentAngle / 2) * radius) / math.cos(pAngle)
where radius is typically 0.5. Then, if pDist1 is > pDist2, the shader returns one colour, otherwise it returns another. This allows me to successfully draw N-sided shapes with any number of sides.
Here's where things get tricky... I also need an option that "blends" between the N-sided shape and a perfect circle (which has the same radius as the N-sided shape). Originally I thought I could do this by simply modifying pDist2 as follows:
pDist2 = ((radius - pDist2) * curvature) + pDist2)
where curvature is a value between 0 and 1 (representing 0% to 100%). This doesn't work at all, instead I get a weird wavy edge which I believe has something to do with my angles and the difference between pDist2 and the radius of a circle. In theory, it should work assuming pAngle is pointing at the exact centre of one side of the polygon, but as it approaches a corner things seem to get more and more distorted.
How can I fix this? It seems like there should be some reasonably simple formula for correcting pDist2 based on the difference between pAngle and (segmentAngle / 2), but I can't seem to figure out what that should be.