How to create textured triangle

Is it possible to create a textured triangle? I tried to use the new SDL_RenderGeometry function which can “render a list of triangles, optionally using a texture”. I copied the code sample from wiki and added BMP texture. Rendering without texture shows a triangle but when I pass my texture to the functuion it doesn’t show anything. Here is the code:

#include <SDL.h>
#include <iostream>

int main(int argc, char* argv[])
{
    SDL_bool quit = SDL_FALSE;
    SDL_Window* window = SDL_CreateWindow("Triangle Example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, 0);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    SDL_Vertex vert[3];
    SDL_Color c{ 255, 0, 0, 255 };

    SDL_Texture* tex = nullptr;
    SDL_Surface* surf = SDL_LoadBMP("t.bmp");
    if (!surf)
    {
        std::cerr << "Failed to load BMP file!" << "\n";
    }
    tex = SDL_CreateTextureFromSurface(renderer, surf);
    if (!tex)
    {
        std::cerr << "Failed to create texture!" << "\n";
    }

    // center
    vert[0].position.x = 400;
    vert[0].position.y = 150;
    vert[0].color = c;

    // left
    vert[1].position.x = 200;
    vert[1].position.y = 450;
    vert[1].color = c;

    // right 
    vert[2].position.x = 600;
    vert[2].position.y = 450;
    vert[2].color = c;
   
    while (!quit) {
        SDL_Event ev;
        while (SDL_PollEvent(&ev) != 0) {
            switch (ev.type) {
            case SDL_QUIT:
                quit = SDL_TRUE;
                break;
            }
        }
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
        SDL_RenderClear(renderer);

        SDL_RenderGeometry(renderer, NULL, vert, 3, NULL, 0);

        SDL_RenderPresent(renderer);
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

You’re missing texture coordinates.

Try this:

	// center
	vert[ 0 ].position.x = 400;
	vert[ 0 ].position.y = 150;
	vert[ 0 ].tex_coord.x = 0;
	vert[ 0 ].tex_coord.y = 0;
	vert[ 0 ].color = c;

	// left
	vert[ 1 ].position.x = 200;
	vert[ 1 ].position.y = 450;
	vert[ 1 ].tex_coord.x = 0;
	vert[ 1 ].tex_coord.y = 1;
	vert[ 1 ].color = c;

	// right 
	vert[ 2 ].position.x = 600;
	vert[ 2 ].position.y = 450;
	vert[ 2 ].tex_coord.x = 1;
	vert[ 2 ].tex_coord.y = 1;
	vert[ 2 ].color = c;
1 Like

Thank you @slouken !