Search code examples
c++opengltextures

How to directly input RGB(A) values in textures in C++/OpenGL?


I want to dabble in some procedural textures in an OpenGL project, but nothing seems to work. All I need is to input the RGB and maybe A values into an empty texture, instead of loading it from a file. How do I do this, in actual, practical code?

Edit: There is no main code yet, because I have found nothing that works. The current best guess is this:

void GenerateTexture()
{
    unsigned char image_data[16] = {0, 0, 150, 255, 125, 0, 0, 255, 0, 0, 150, 255, 125, 0, 0, 255};
    glGenTextures(1, &tex_obj);
    glBindTexture(GL_TEXTURE_2D, tex_obj);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
}

... implemented like this:

glBegin (GL_QUADS);
if (*irrelevant for question*){
    glTexCoord2f(0.0,1.0);
    glVertex3f (-0.45-cam.pos.val[0], 0.45-cam.pos.val[1], 0.45-cam.pos.val[2]);
    glTexCoord2f(0.0,0.0);
    glVertex3f (-0.45-cam.pos.val[0], -0.45-cam.pos.val[1], 0.45-cam.pos.val[2]);
    glTexCoord2f(1.0,0.0);
    glVertex3f (0.45-cam.pos.val[0], -0.45-cam.pos.val[1], 0.45-cam.pos.val[2]);
    glTexCoord2f(1.0,1.0);
    glVertex3f (0.45-cam.pos.val[0], 0.45-cam.pos.val[1], 0.45-cam.pos.val[2]);
}
glEnd ();

... but as soon as it is run with more than a 1x1 texture, it just goes clean white.


Solution

  • Create an array of data and load it into a texture image:

    uint8_t image_data[4] = {255, 0, 0, 255}; // red
    GLuint tex_obj;
    glGenTextures(1, &tex_obj);
    glBindTexture(GL_TEXTURE_2D, tex_obj);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);