You're right—your function for drawing filled polygons (like hexagons, octagons, etc.) using a triangle fan approach has a few issues:
-
Triangle Fan Construction:
For a filled polygon, you need to create a triangle fan: the center point, and then the outer points in order. Your current code tries to insert the center after the first edge, which doesn't work for a fan.
-
Point Buffer Construction:
The points for a triangle fan should be:
- The center point first
- Then all the outer points (one per segment, plus one to close the loop)
-
Count Calculation:
The number of points should be segments + 2 (center + all outer points + repeat of the first outer point to close the fan).
-
Y-Axis Direction:
Your use of hh - ry*sinf(theta) may be intentional (depending on your coordinate system), but usually, it's + for both cos and sin unless your Y axis is inverted.
Fixed Function
Here's a corrected version:
void _polygon(float x, float y, float rx, float ry, int segments, bool filled) {
sgp_push_transform();
sgp_translate(x, y);
float step = (2.0f * PI) / (float)segments;
unsigned int count = 0;
static sgp_vec2 points_buffer[66]; // 1 center + up to 64 segments + 1 to close
if (filled) {
// Center point for triangle fan
points_buffer[count++] = (sgp_vec2){0.0f, 0.0f};
// Outer points
for (int i = 0; i <= segments; ++i) {
float theta = i * step;
sgp_vec2 v = {rx * cosf(theta), ry * sinf(theta)};
points_buffer[count++] = v;
}
sgp_draw_filled_triangles_fan(points_buffer, count);
} else {
// Outline: just the outer points
for (int i = 0; i <= segments; ++i) {
float theta = i * step;
sgp_vec2 v = {rx * cosf(theta), ry * sinf(theta)};
points_buffer[count++] = v;
}
sgp_draw_lines_strip(points_buffer, count);
}
sgp_pop_transform();
}
Key Changes:
- For filled polygons, the center point is first, then all outer points (including the first again to close).
- For outlines, just the outer points (including the first again to close).
- Used
sgp_draw_filled_triangles_fan (assuming your library has this; if not, you may need to implement it or use a similar function).
- Removed the
hw and hh variables, as they were always zero.
If you don't have sgp_draw_filled_triangles_fan:
If your library only has sgp_draw_filled_triangles_strip, you need to manually create triangles for the fan, or (better) implement a fan function.
Summary
- Triangle fan: center point first, then all outer points in order, closing the loop.
- Outline: just the outer points, closing the loop.
Let me know if you need a version that works with a specific drawing function!