2016-07-29 185 views
0

當我試着畫出我的網,我得到了這樣的事情:3D網格投影到二維平面

that

但是,當我轉動我的網格,它是這樣的:

this

這是應該的:

This

這裏是我的代碼:

// Generate MVP matrix. 
glm::mat4 Projection = glm::perspective(glm::radians(45.0f), 
             4.0f/3.0f, 0.1f, 100.0f); 
glm::mat4 View = glm::lookAt(glm::vec3(4,0,4), 
          glm::vec3(0,0,0), 
          glm::vec3(0,0,1)); 
glm::mat4 Model = glm::mat4(1.0f); 
glm::mat4 mvp = Projection * View * Model; 
GLint matrixId = glGetUniformLocation(shader.getProgramId(), "MVP"); 

// Generate VBO and VAO. 
float triangleVertices[] = { 
    -0.5f, -0.5f, 0.0f, 1.0f, 
    0.5f, 0.5f, 0.0f, 1.0f, 
    0.5f, -0.5f, 0.0f, 1.0f, 
    1.0f, 1.0f, 0.0f, 1.0f, 
    1.0f, -1.0f, 0.0f, 1.0f, 
    1.0f, -1.0f, 1.0f, 1.0f, 
}; 
uint un_vertecesNum = sizeof(triangleVertices); 
GLuint vbo; 
glGenBuffers(1, &triangleBufferObject); 
GLuint vao; 
glGenVertexArrays(1, &vao); 
glBindVertexArray(vao); 
glBindBuffer(GL_ARRAY_BUFFER, vbo); 
glBufferData(GL_ARRAY_BUFFER, vertecesNum, 
      triangleVertices, GL_STATIC_DRAW); 
glBindBuffer(GL_ARRAY_BUFFER, 0); 

// Begin main loop. 
// Event handling here (Look for code below) 
glClearColor(0.0,0.0,0.0,0.0); 
glClear(GL_COLOR_BUFFER_BIT); 
shader.Use(); 
glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]); 

// Mesh display stuff. 
glBindBuffer(GL_ARRAY_BUFFER, vbo); 
glEnableVertexAttribArray(0); 
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); 
glDrawArrays(GL_TRIANGLES, 0, un_vertecesNum); 
glDisableVertexAttribArray(0); 
glBindBuffer(GL_ARRAY_BUFFER, 0); 

shader.UnUse(); 
SDL_GL_SwapWindow(win); 
// End main loop. 

這裏的事件處理,我怎麼轉動我的目:

SDL_Event event; 
while (SDL_PollEvent(&event)) 
{ 
    switch(event.type) 
    { 
    case SDL_KEYDOWN: 
     switch(event.key.keysym.sym) 
     { 
      case SDLK_a: 
       Model = glm::rotate(Model, 0.1f, 
         glm::vec3(0.0f, 1.0f, 0.0f)); 
      case SDLK_d: 
       Model = glm::rotate(Model, 0.1f, 
         glm::vec3(0.0f, -1.0f, 0.0f)); 
       break; 
     } 
     break; 
    } 
} 
mvp = Projection * View * Model; 

韋爾着色器:

#version 130 
uniform mat4 MVP; 
attribute vec4 coord4d; 
void main(void) 
{ 
    vec4 temp = vec4(coord4d); 
    gl_Position = temp*(MVP); 
} 

破片着色器:

#version 130 
void main(void) 
{ 
    gl_FragColor[0] = gl_FragCoord.x/640.0; 
    gl_FragColor[1] = 0.2; 
    gl_FragColor[2] = gl_FragCoord.y/480.0; 
    gl_FragColor[3] = 1.0f; 
} 

這是蘇珊怎麼看,如果你不知道這樣的:

img1 img1

我試圖谷歌,讀一些關於它的「典型錯誤「頁面或在stackoverflow找到,但沒有。

+1

垂直着色器不應該是「MVP * temp」嗎? – 2016-07-29 09:26:48

+2

@willywonkadailyblah是對的。另外,你可以簡單地寫'gl_Position = MVP * coord4d;'而不用'temp'變量。 –

+0

我的上帝......解決辦法很簡單。 @willywonkadailyblah,請在回答中寫下您的評論,以便我可以將其標記爲正確。 –

回答

2

頂點着色器應該是MVP * temp,而不是相反。就像在現實世界中一樣,在GLSL矩陣向量乘法是不可交換的(這將是您正在尋找的「典型錯誤」)