`
sogotobj
  • 浏览: 612619 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

opengl超级宝典代码学习2

 
阅读更多

我们需要学习的第二个例子是在第二章的glrect例子。

// Called to draw scene

void RenderScene(void)

{

// Clear the window with current clearing color

glClear(GL_COLOR_BUFFER_BIT);


// Set current drawing color to red

// R G B

glColor3f(1.0f, 0.0f, 0.0f);


// Draw a filled rectangle with current color

glRectf(-25.0f, 25.0f, 25.0f, -25.0f);


// Flush drawing commands

glFlush();

}



///////////////////////////////////////////////////////////

// Setup the rendering state

void SetupRC(void)

{

// Set clear color to blue

glClearColor(0.0f, 0.0f, 1.0f, 1.0f);

}



///////////////////////////////////////////////////////////

// Called by GLUT library when the window has chanaged size

void ChangeSize(int w, int h)

{

GLfloat aspectRatio;


// Prevent a divide by zero

if(h == 0)

h = 1;

// Set Viewport to window dimensions

glViewport(0, 0, w, h);


// Reset coordinate system

glMatrixMode(GL_PROJECTION);

glLoadIdentity();


printf("w = %d::h = %d",w,h);

// Establish clipping volume (left, right, bottom, top, near, far)

aspectRatio = (GLfloat)w / (GLfloat)h;

if (w <= h)

glOrtho (-100.0, 100.0, -100 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0);

else

glOrtho (-100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0, 1.0, -1.0);


glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

}


///////////////////////////////////////////////////////////

// Main program entry point

int main(int argc, char* argv[])

{

glutInit(&argc, argv);

glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

// glutInitWindowSize(800, 600);

glutCreateWindow("GLRect");

glutDisplayFunc(RenderScene);

glutReshapeFunc(ChangeSize);

SetupRC();

glutMainLoop();

return 0;

}

书中对代码解释的非常清楚。这个代码的关键在于当窗口的大小被改变的时候的回调函数ChangeSize的代码。这里h和w分别代表窗口新的高和宽,为了使得我们画的矩形保持正方形,代码如下:

if(w <= h)

glOrtho(-100.0, 100.0, -100 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0);

else

glOrtho(-100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0, 1.0, -1.0);


这里可以看到opengl中实用的坐标系统是中心点坐标是(0,0)的普通笛卡儿坐标系统,和我们在屏幕上的坐标不同,屏幕上是原点在左上角,x是从左到右依次变大,不会出现负值,Y是从上到下依次变大,不会出现负值,但是opengl其实使用三维坐标系统,是符合右手法则的系统,原点在屏幕中心,X是从左到右变大,但是是从负值变到正值,Y是从下到上变大,从负值变成正值,Z垂直于屏幕,从里到外是从负值到正值的,这和大部分计算机的坐标系统不同。

我们使用函数glOrtho定义X和Y坐标的范围,这里X始终是从-100到正100,所以最后显示的正方形的长度始终是窗口的1/4,在高度上,我们设置为50个高,但是这个表示像素,它需要和glOrtho定义的Y坐标做比较来确定像素。

比如w=h的时候,是正方形,

w = 200;h=400的时候,那么矩形的长是50个像素,这个时候,整个opengl视图在Y上的坐标是-200到200,那么正好矩形的高占了整个视图的1/8,也正好是50个像素。

当w>h的时候,以此类推。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics