65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 OpenGL 进行变换

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.25/5 (8投票s)

2002年5月2日

CPOL

2分钟阅读

viewsIcon

112635

downloadIcon

3660

本文解释了观察和建模变换。

Sample Image - Trans.jpg

引言

本文解释了两种变换——观察和建模。

观察变换

观察变换类似于定位和瞄准相机。观察变换通过 gluLookAt() 指定。该命令的参数指示相机的放置位置(或眼睛位置)、相机瞄准的方向以及向上方向。这里使用的参数将相机放置在 (0, 0, 5),将相机镜头对准 (0, 0, 0),并将向上向量指定为 (0, 1, 0)。向上向量定义了相机的唯一方向。

在此代码示例中,在可以指定观察变换之前,当前矩阵使用 glLoadIdentity() 设置为单位矩阵。此步骤是必要的,因为大多数变换命令会将当前矩阵乘以指定的矩阵,然后将结果设置为当前矩阵。如果您不通过加载单位矩阵来清除当前矩阵,则会继续将先前的变换矩阵与您提供的新的矩阵组合。在某些情况下,您确实希望执行此类组合,但有时也需要清除矩阵。

建模变换

您使用建模变换来定位和定向模型。例如,您可以旋转、平移或缩放模型——或者执行这些操作的某种组合。glScalef() 是用于建模变换的命令。该命令的参数指定沿三个轴应如何进行缩放。如果所有参数均为 1.0,则该命令无效。在演示应用程序中,多边形在 y 方向上绘制的两倍大。因此,如果多边形的一个角最初位于 (3.0, 3.0, 3.0),则该角最终将被绘制在 (3.0, 6.0, 3.0)。

我之前的 OpenGL 文章 - OpenGL 入门,展示了在窗口中绘制的基本框架。

本文演示项目的 OnPaint() 如下所示

void OnPaint()
{
  //do this if u want to clear the area before showing an image
  this->Invalidate(TRUE);

  // Draw the scene.

  // Get a DC, then make the RC current and
  // associate with this DC
  hdc = ::BeginPaint(hwnd,&ps);

  wglMakeCurrent( hdc, hRC );

  //********Drawing Start****************

  // Define the modelview transformation.

  glMatrixMode( GL_MODELVIEW );
  glLoadIdentity();

  // move the viewpoint out to where we can see everything
  glTranslatef( 0.0f, 0.0f, -5.0f );

  //Specify the polygon vertices in an array
  static GLfloat vertices[] =  {
                 1.0,-0.5,0.5,
                 1.0,0.5,-1.0,
                 0.5,1.0,-1.0,
                 0.5,-1.0,1.0
                           };
  glEnableClientState(GL_VERTEX_ARRAY);//Enable use of array of vertices
  glColor3f(0.0,0.0,0.0);//black color
  glVertexPointer(3,GL_FLOAT,0,vertices);

  glPolygonMode(GL_FRONT,GL_LINE);//Front face as a lined plolygon
  glPolygonMode(GL_BACK,GL_FILL);//back face as a filled polygon
  glLoadIdentity ();/* clear the matrix */

    /* viewing transformation  */
     //camera position , where its pointed ,up direction    
     gluLookAt (vx1,vy1,vz1,vx2,vy2,vz2,vx3,vy3,vz3);

     /*modeling transformation Front Face*/
     glScalef((float)mx,(float)my,(float)mz);
     glBegin(GL_POLYGON);
     for(int i=0;i<4;i++)
       glArrayElement (i);//Plotting using array
     glEnd();

     glDisableClientState(GL_VERTEX_ARRAY);

     glFlush();

//********END**************************

    // we're done with the RC, so
    // deselect it
    // (note: This technique is not recommended!)
    wglMakeCurrent( NULL, NULL );

   ::EndPaint(hwnd,&ps);

}

关于演示应用程序

该演示应用程序允许您指定变换的坐标,并相应地查看图像。只需在建模变换对话框中将 x 坐标更改为 -1,即可查看多边形的背面。

© . All rights reserved.