GetClientRect(m_Hwnd,&rct); intm_view_width = rct.right- rct.left; intm_view_height = rct.bottom - rct.top; glViewport(0,0,m_view_width,m_view_height); float nearz =5.0; float farz =80000;
float AspectRatio =float(m_view_height)/ float(m_view_width); float ViewAngleH =90 * (PI / 180);//90度
float ViewAngleV = atan(tan(ViewAngleH/2) * AspectRatio)* 2; glMatrixMode(GL_PROJECTION); glLoadIdentity(); GLfloatm[16];
::ZeroMemory(m,16*sizeof(float));
//////m[8],m[9]=0表示对称视椎体即gluPerspective/////////// m[0] = 1.0 /tan(ViewAngleV / 2); m[5] = m[0]*AspectRatio;
m[10] = -(farz +nearz) / (farz - nearz); m[11] = -1;
m[14] = - 2 * farz *nearz / (farz - nearz); glMultMatrixf(m);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); }
void OpenGlCom::draw() {
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix();
glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glBegin(GL_TRIANGLE_FAN);
glTranslatef(0, 0,10.0f);//往视点方向平移10单位显示更大 glColor3f(0.8f, 0.8f, 0.6f); glVertex3f(0,0,-20); glVertex3f(30,20,-40); glVertex3f(40,10,-30); glPopMatrix(); }
我们看看在gluPerspective图形有什么变化呢 将ReSize()改成: {
RECTrct ;
GetClientRect(m_Hwnd,&rct); intm_view_width = rct.right- rct.left; intm_view_height = rct.bottom - rct.top; glViewport(0,0,m_view_width,m_view_height); glMatrixMode(GL_PROJECTION); glLoadIdentity();
floatfAspect = float(m_view_width) / float(m_view_height); gluPerspective(90.0,fAspect, 5.0, 80000.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); }
接下来,再试试看glFrustum()实现的效果:
将ReSize()改成: {
RECTrct ;
GetClientRect(m_Hwnd,&rct); intm_view_width = rct.right- rct.left; intm_view_height = rct.bottom - rct.top; glViewport(0,0,m_view_width,m_view_height); glMatrixMode(GL_PROJECTION); glLoadIdentity();
GLdouble left =-nearz*tan(ViewAngleV/2); GLdouble right =nearz*tan(ViewAngleV/2); GLdouble bottom =-nearz*tan(ViewAngleH/2); GLdouble top =nearz*tan(ViewAngleH/2);
glFrustum(left,right,bottom,top,nearz,farz); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); }
从三幅图中可以看出图形位置是一样的,这就验证了我们的矩阵是正确的!