带着色器的OpenGL:正方形看起来像矩形

时间:2015-11-18 09:18:41

标签: opengl shader

我发现了一些文章提供了以下代码来纠正方块的外观:

  glViewport( 0, 0, nWinWidth, nWinHeight );
  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();
  double aspectRatio = (double) nWinWidth / (double) nWinHeight;

  glOrtho( aspectRatio, -aspectRatio, -1.0f, 1.0f, 1.0f, -1.0f );
  glMatrixMode( GL_MODELVIEW );
  glLoadIdentity();

这个旧代码是否只适用于立即模式OpenGL?

我使用简单着色器绘制正方形(目前看起来像一个矩形)。

使用现代OpenGL执行此操作的正确方法是什么?我现在只玩MVP矩阵和旋转 - 这对我来说都很新鲜。上述修正是否需要在该代码中执行(例如见下文)

  // PROJECTION - should aspect ration be corrected in here??
  glm::mat4 Projection = glm::perspective(45.0f, 1.0f, 0.1f, 100.0f);

  // VIEW
  glm::mat4 View = glm::mat4(1.0);

  dist = -5.0f;

  View = glm::translate( View, glm::vec3( 0.0f, 0.0f, dist ) );

  // MODEL
  glm::mat4 Model = glm::mat4(1.0);

  // Scale by factor 0.5
  //Model = glm::scale(glm::mat4(1.0f),glm::vec3(0.5f));

  if( GetTickCount() - dwLastTicks > 10 )
  {
    dwLastTicks = GetTickCount();
    rot += 0.01f;

    if( rot >= 360.0f )
      rot = 0;
  }

  Model = glm::rotate( Model, rot, glm::vec3( 0.0f, 1.0f, 1.0f ) ); // where x, y, z is axis of rotation (e.g. 0 1 0)

  glm::mat4 MVP = Projection * View * Model;

  GLuint transformLoc = glGetUniformLocation( g_ShaderProgram, "transform" );
  glUniformMatrix4fv( transformLoc, 1, GL_FALSE, glm::value_ptr( MVP ) );

1 个答案:

答案 0 :(得分:2)

  

这个旧代码是否只适用于立即模式OpenGL?

实际上,这不会对顶点着色器的结果产生任何影响。

glm::perspective的第二个参数是宽高比:

glm::mat4 Projection = glm::perspective(45.0f, aspectRatio, 0.1f, 100.0f);