Hello. I’m using OpenGL core profile 3.3 for making an SDL2 game in C++
I’ve always used texture coordinates in float format. Never had an issue
Now I want to use a shorter version of my Vertex2D struct, so I want to send texture coords to OpenGL as two unsigned shorts, hoping it will normalize them to (0, 1] floats
The problem is: the rendered sprite is entirely black
What am I doing wrong?
My vertex struct:
using t_uvCoords = std::uint16_t;
struct Vertex2D_PosTexColor
{
Vertex2D_PosTexColor(Vec2 pos, t_uvCoords U, t_uvCoords V, const ColorRGBA& col);
Vec2 position; // -> 2 floats
t_uvCoords u, v;
ColorRGBA color; // -> 4 unsigned chars
};
static_assert(sizeof(Vertex2D_PosTexColor) == 16, "Error: sizeof(Vertex2D_PosTexColor) MUST be exactly 16 bytes!");
My VAO/VBO code:
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
glGenBuffers(m_bufferObjects.size(), m_bufferObjects.data());
glBindBuffer(GL_ARRAY_BUFFER, m_bufferObjects[0]);
const auto stride = static_cast<int>(sizeof(Vertex2D_PosTexColor));
// Position
std::size_t offset = 0U;
glVertexAttribPointer(K_VERTEX2D_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, stride, offsetToVoidPtr(offset));
glEnableVertexAttribArray(K_VERTEX2D_ATTRIB_POSITION);
// Texture coords
offset += sizeof(float) * 2U;
glVertexAttribPointer(K_VERTEX2D_ATTRIB_TEXCOORDS, 2, GL_UNSIGNED_SHORT, GL_TRUE, stride, offsetToVoidPtr(offset));
glEnableVertexAttribArray(K_VERTEX2D_ATTRIB_TEXCOORDS);
// Color
offset += sizeof(t_uvCoords) * 2U;
glVertexAttribPointer(K_VERTEX2D_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, offsetToVoidPtr(offset));
Rendering code:
glBindVertexArray(m_VAO);
glUseProgram(m_material.shader->getProgramName());
// Camera matrix
glUniformMatrix4fv(this->m_projMatrixLoc, 1, GL_FALSE, m_graphics.getCamera2D().getMatrix());
// Texture unit
glUniform1i(this->m_sampler2DLoc, m_material.texture->textureUnit);
// Render everything
glDrawElements(GL_TRIANGLES, m_elementCount, GL_UNSIGNED_SHORT, offsetToVoidPtr(0U));
Vertex shader:
#version 330 core
// Input from the VBO
layout(location = 0) in vec2 a_vertexPos;
layout(location = 1) in vec2 a_vertexTexCoords;
layout(location = 2) in vec4 a_vertexColor;
// Input from uniforms
uniform mat4 u_projection;
// Output to the fragment shader
smooth out vec2 fsTexCoords;
smooth out vec4 fsColor;
void main()
{
vec4 pos = vec4(a_vertexPos.xy, 0.0f, 1.0f);
gl_Position = u_projection * pos;
fsTexCoords = a_vertexTexCoords;
fsColor = a_vertexColor;
}
Fragment shader:
#version 330 core
// Input from the vertex shader
smooth in vec2 fsTexCoords;
smooth in vec4 fsColor;
// Input from uniforms
uniform sampler2D u_texUnit;
// Final fragment color
out vec4 finalColor;
void main()
{
vec4 sampled = texture(u_texUnit, fsTexCoords);
finalColor = fsColor * sampled;
}