To my understanding, SDL2's function SDL_RenderGeometry
can render a polygon with any arbitrary number of vertices. Rendering triangles works for me. Attempts to render polygons with 4+ vertices fails.
The following code renders a filled triangle, as expected:
SDL_Vertex vertex_1 = {{10, 10}, {255, 0, 0, 255}, {1, 1}};
SDL_Vertex vertex_2 = {{20, 10}, {255, 0, 0, 255}, {1, 1}};
SDL_Vertex vertex_3 = {{10, 20}, {255, 0, 0, 255}, {1, 1}};
SDL_Vertex vertices[] = {
vertex_1,
vertex_2,
vertex_3
};
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
SDL_RenderGeometry(renderer, nullptr, vertices, 3, NULL, 0);
SDL_RenderPresent(renderer);
However, by simply adding another vertex to render a square, the program fails. Nothing is rendered, and no errors are generated:
SDL_Vertex vertex_1 = {{10, 10}, {255, 0, 0, 255}, {1, 1}};
SDL_Vertex vertex_2 = {{20, 10}, {255, 0, 0, 255}, {1, 1}};
SDL_Vertex vertex_3 = {{20, 20}, {255, 0, 0, 255}, {1, 1}};
SDL_Vertex vertex_4 = {{10, 20}, {255, 0, 0, 255}, {1, 1}};
SDL_Vertex vertices[] = {
vertex_1,
vertex_2,
vertex_3,
vertex_4
};
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
SDL_RenderGeometry(renderer, nullptr, vertices, 4, NULL, 0);
SDL_RenderPresent(renderer);
The question is, what am I doing wrong?
I believe you have got the right intentions but the wrong execution. From my understanding, the problem comes from your use of the SDL_RenderGeometry()
function.
This is because the function draws triangles, which have three points, but you have inputted four points. To fix this, either use 6 points to render two triangles or figure out how indices work.
Indices tell the renderer what order to draw the points in. These can help by reducing duplicate vertices.
An example of how to use this is:
const int indices[] = {
0,1,2
2,3,0
};
SDL_RenderGeometry(renderer, nullptr, vertices, 4, indices, 6);
The indices tell the renderer which index of the vertices array to access.
This new code will use the order stated in the indices array. Please refer to the documentation if you want a deeper understanding of the function SDL_RenderGeometry()
.