To use a linked list, or not?
To give you a bit of background on this I'm making a project which draws lines and filled triangles. I then have an abstract Polygon struct that draws different shapes according to its properties. Each polygon needs to contain a set of Points. Up until now I had given each polygon a static array of points. I decided to change it so that each Polygon contains a linked list of points, but I'm not sure if its a good idea. Heres what I have come up with so far on it:
Benefits
- Scalable
- Fast to insert / remove points
Disadvantages
- Memory leak if Polygon object goes out of scope. and points arent freed.
- Before drawing points need to be copied to arrays.
With the first disadvantage. Is there anyway I can do some sort of garbage collection to remove points where their polygon has gone out of scope? Or is there another way to avoid this?
With the second, points on the list need to be copied to arrays so the values can be passed to the relevant drawing functions. Is there a way I could aoid this. Heres the code as an example:
Code:
int DrawPolygon(Uint32 buffer[], Polygon p)
{
// Using a linked list content must be copied across first?
float x[p.size];
float y[p.size];
Point *ptr = p.pt;
int i=0;
while(ptr)
{
x[i] = ptr->x;
y[i] = ptr->y;
i++;
ptr = ptr->next;
}
//if(p.flags & POLYGON_IS_SPLINE)
// return DrawSpline(p);
switch(p.size)
{
case 1:
DrawPixel(buffer, x[0], y[0], p.color);
break;
case 2:
DrawLine(buffer, x[0], y[0], x[1], y[1], p.color);
break;
case 3:
if(p.flags & POLYGON_IS_FILLED)
DrawTriangle(buffer, x[0], y[0], x[1], y[1], x[2], y[2], p.color, 1);
else if(p.flags & POLYGON_IS_CLOSED)
DrawTriangle(buffer, x[0], y[0], x[1], y[1], x[2], y[2], p.color, 0);
else
{
DrawLine(buffer, x[0], y[0], x[1], y[1], p.color);
DrawLine(buffer, x[1], y[1], x[2], y[2], p.color);
}
break;
case 4:
if(p.flags & POLYGON_IS_FILLED)
DrawRhombus(buffer, x[0], y[0], x[1], y[1], x[2], y[2], x[3], y[3], p.color, 1);
else if(p.flags & POLYGON_IS_CLOSED)
DrawRhombus(buffer, x[0], y[0], x[1], y[1], x[2], y[2], x[3], y[3], p.color, 0);
else
{
DrawLine(buffer, x[0], y[0], x[1], y[1], p.color);
DrawLine(buffer, x[1], y[1], x[2], y[2], p.color);
DrawLine(buffer, x[2], y[2], x[3], y[3], p.color);
}
break;
default:
break;
}
return 0;
}