0

I have an array of unsigned bytes that represent the pixels of the letter q. I would like to write those pixels to an OpenGL texture using glTexImage2D. In the code below I have also added some checks to make sure the pixel data is valid. I checked that the width times the height matched the data length, and even printed the pixels to the terminal. (The code is written in rust, however the GL calls are the same as they would be in any other binding).

// create the array of pixels
let data: &[u8] = &[
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 37, 2, 0, 0, 0, 0, 0, 0, 0, 119,
    248, 252, 241, 92, 223, 130, 0, 0, 0, 84, 253, 108, 8, 36, 202, 248, 130, 0, 0, 0,
    198, 182, 0, 0, 0, 52, 255, 130, 0, 0, 0, 241, 120, 0, 0, 0, 0, 245, 130, 0, 0, 3,
    252, 108, 0, 0, 0, 0, 233, 130, 0, 0, 0, 223, 143, 0, 0, 0, 14, 253, 130, 0, 0, 0,
    144, 234, 20, 0, 0, 126, 255, 130, 0, 0, 0, 23, 219, 223, 142, 173, 194, 231, 130,
    0, 0, 0, 0, 18, 120, 156, 108, 13, 223, 130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 223, 130,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 223, 130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 149, 87, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0,
];

// check that WxH equals the number of pixels
let data_w = 11;
let data_h = 15;
assert_eq!(data_w * data_h, data.len());

// write the pixels to the texture
glBindTexture(GL_TEXTURE_2D, texture);

// initialize the texture
glTexImage2D(
    GL_TEXTURE_2D,
    0,
    GL_RED as _,
    256,
    256,
    0,
    GL_RED,
    GL_UNSIGNED_BYTE,
    ptr::null(),
);

// write the pixels
glTexSubImage2D(
    GL_TEXTURE_2D,
    0,
    0,
    0,
    data_w as _,
    data_h as _,
    GL_RED,
    GL_UNSIGNED_BYTE,
    data.as_ptr() as _,
);

// print the pixels to the terminal
let mut counter = 0;
for _ in 0..data_h {
    for _ in 0..data_w {
        if data[counter] > 100 {
            print!("+");
        } else {
            print!(" ");
        }
        counter += 1;
    }
    println!()
}

The output of the terminal test is:

   ++++ ++
   ++  +++
  ++    ++
  ++    ++
  ++    ++
  ++    ++
  ++   +++
   +++++++
    +++ ++
        ++
        ++
        +

So the issue is clearly not in the pixel data.

Here is how the texture looks like when I render it to the screen: enter image description here

Why doesn't it render properly?

Roy Varon
  • 536
  • 2
  • 5
  • 14

1 Answers1

0

It turns out that OpenGL does some byte-row alignments when writing data to textures. The solution was to add this line before glTexImage2D:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

Link to the: documentation.

Roy Varon
  • 536
  • 2
  • 5
  • 14