Home > Mobile >  Do I pass the wrong data to glTexImage2D?
Do I pass the wrong data to glTexImage2D?

Time:05-17

I'm trying to make an OpenGL texture by populating a pixel buffer with data from a baked font. I'm taking each value from the font array and making a bitmap essentially. The problem is when I'm displaying the full texture I get noise. However by creating an 8x8 texture of one glyph the texture is displayed correctly.

The pixel buffer is 8bit monochrome, so I pass GL_ALPHA as buffer format. I tried using 32bpp GL_RGBA format as well and it yields the same result.

DebugFont
LoadBakedFont(void)
{
    glEnable(GL_BLEND);
    glEnable(GL_TEXTURE_2D);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    unsigned char baked_font[128][8] = {} //In my source code this is not empty :)

    unsigned char *pixels = (unsigned char*)malloc(sizeof(unsigned char) * 128 * 8 * 8);
    memset(pixels, 0, sizeof(unsigned char) * 128 * 8 * 8);
    
    int counter = 0;
    for(int i = 0; i < 128;   i)
    {
        for(int j = 0; j < 8;   j)
        {
            for(int k = 0; k < 8;   k)
            {
                unsigned char val = (baked_font[i][j] >> k & 1);
                pixels[counter  ] = val == 1 ? 0xff : 0x00;
            }
        }
    }
    
    //Renders the exlamation mark perfectly
    for(int y = 0; y < 8;   y)
    {
        for(int x = 0; x < 8;   x)
        {
            unsigned char *test = pixels   (0x21 * 64);
            if(test[y * 8   x])
                printf("@");
            else
                printf(".");
        }
        printf("\n");
    }

//POD struct
    DebugFont font;
    
    glGenTextures(1, &font.tex);
    glBindTexture(GL_TEXTURE_2D, font.tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 8 * 128, 8, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
    glBindTexture(GL_TEXTURE_2D, 0);                        
    
    free(pixels);
    return font;
}

void
DrawTexture(DebugFont font)
{
    glBindTexture(GL_TEXTURE_2D, font.tex);
    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f);   glVertex2f(0,0);
    glTexCoord2f(1.0f, 0.0f);   glVertex2f(8 * 128,0);
    glTexCoord2f(1.0f, 1.0f);   glVertex2f(8 * 128, 8);
    glTexCoord2f(0.0f, 1.0f);   glVertex2f(0, 8);
    glEnd();
    glBindTexture(GL_TEXTURE_2D, 0);
}

Random noise?

Exclamation Mark

CodePudding user response:

The way you arrange the data makes sense for a tall 8x1024 image where each 8x8 makes up a character.

But you load it as a 1024x8 image instead, putting all the pixels in the wrong places.

  • Related