OpenGL gluLookat not working with shaders on

一世执手 提交于 2020-02-05 13:57:08

问题


When i want to use gluLookat and have the shaders on it doesnt move the "camera" when i turn the shaders off it works correctly.

Is there something missing in my shaders, i cant figure out what.

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(0.8, 0.8, 0.8, 0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0.5,0,1,0.5,0,0,0,1,0);
    glColor3f(0, 0, 0);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glDrawArrays(GL_LINES, 6, 6);
    glDrawArrays(GL_TRIANGLES, 12,6);
    glDrawArrays(GL_LINES, 18, 4);
    glDrawArrays(GL_TRIANGLES, 22, 6);
    glColor3f(1, 0.7, 0);
    glDrawArrays(GL_TRIANGLES, 28, 6);
    glFlush();
}

Vertex Shader:

#version 450 core  // 420, 330 core , compatibility
in vec4 position

out vec4 Color;
void main()
{ 
 gl_Position = position;
}

Fragment Shader:

#version 450 core  // 420, 330 core , compatibility
in vec4 Color;
layout(location=0) out vec4 fColor;
void main() 
{
 fColor = vec4(0,0,0,0); 
}

Move the "camera" to where i want it to be with shaders on


回答1:


When you use a shader program, then the vertex coordinate attributes are not magically processed, by the current matrices. The shader program has to do the transformations of the vertex coordinates.


You've 2 possibilities, either you use a compatibility profile context and use a lower glsl version (e.g. 1.10).

Then you can use the built in uniform gl_ModelViewProjectionMatrix (see GLSL 1.10 secification) and the fixed function matrix stack will work:

#version 110
attribute vec4 position

// varying vec4 Color;

void main()
{ 
     // ...  

     gl_Position = gl_ModelViewProjectionMatrix * position;
}

But note this is deprecated since decades. See Fixed Function Pipeline and Legacy OpenGL.


I recommend to use a library like OpenGL Mathematics to calculate the view matrix by lookAt() and a uniform variable:

#version 450 core  // 420, 330 core , compatibility
in vec4 position

// out vec4 Color;

layout(location = 7) uniform mat4 view_matrix;

void main()
{ 
    gl_Position = view_matrix * position;
}
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

// [...]
{
    // [...]

    glUseProgram(program);

    glm::mat4 view = glm::lookAt(
        glm::vec3(0.5f,0.0f,1.0f), glm::Vec3(0.5f,0.0f,0.0f), glm::Vec3(0.0f,1.0f,0.0f));
    glUniformMatrix4fv(7, 1, GL_FALSE, glm::value_ptr(view);

    // [...]
}

The uniform location is set explicite by a Layout qualifier (location = 7).
glUniformMatrix4fv sets the value of the uniform at the specified location in the default uniform block. This has to be done after the progroam was installed by glUseProgram.



来源:https://stackoverflow.com/questions/56090164/opengl-glulookat-not-working-with-shaders-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!