c++ - Setting up a MVP Matrix in OpenGL -
i'm trying learn basics of opengl, have problem setting transformation matrices. made model, view , projection matrices, have problem sending them vertex shader.
here code:
//set mvp glm::mat4 model = glm::mat4(); glint unimodel = glgetuniformlocation(program, "model"); gluniformmatrix4fv(unimodel, 1, gl_false, glm::value_ptr(model)); glm::mat4 view = glm::lookat( glm::vec3(2.5f, 2.5f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)); glint uniview = glgetuniformlocation(program, "view"); gluniformmatrix4fv(uniview, 1, gl_false, glm::value_ptr(view)); glm::mat4 proj = glm::perspective(45.0f, 800.0f / 600.0f, 1.0f, 10.0f); glint uniproj = glgetuniformlocation(program, "proj"); gluniformmatrix4fv(uniproj, 1, gl_false, glm::value_ptr(proj));
and shader:
layout (location = 0) in vec3 position; uniform mat4 model; uniform mat4 view; uniform mat4 proj; void main() { gl_position = proj * view * model * vec4(position, 1.0); }
i think did wrong setting uniforms, because doesn't draw anything, if set model, view , proj identity. mistyped something, can't find problem.
edit: solved it, problem forgot use gluseprogram()
first.
the first thing check possible return codes, verify shader program has compiled , linked correctly, , make sure uniforms valid, means location value >= 0
.
a binary search glgeterror()
can useful in these instances when don't know it's going wrong.
after compiling shaders, make sure check glgetprogram(gl_link_status,...)
. , finally, must call gluseprogram()
activate shader.
as @vallentin suggests, more efficient pass in precalculated mvp matrix, since not change between app , shader. simplifies code somewhat, application code:
// set mvp matrices glm::mat4 model = glm::mat4(); glm::mat4 view = glm::lookat( glm::vec3(2.5f, 2.5f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 proj = glm::perspective(45.0f, 800.0f / 600.0f, 1.0f, 10.0f); glm::mat4 mvp = proj * view * model; gluseprogram(prog); glint unimvp = glgetuniformlocation(program, "mvp"); gluniformmatrix4fv(unimvp, 1, gl_false, glm::value_ptr(mvp));
and glsl:
// shader code layout (location = 0) in vec3 position; uniform mat4 mvp; void main() { gl_position = mvp * vec4(position, 1.0); }
also, cache uniform locations, since won't change once compiled. save small amount per frame, rather querying them every redraw.
Comments
Post a Comment