我在使用OpenGL连接茶壶时遇到问题

时间:2016-12-13 21:54:52

标签: opengl

代码的输出如下所示:

如何让茶壶看起来像这样?:

我一直在尝试添加gluPerspectiveglViewport命令,但它不起作用。

#include<windows.h>
#include<stdio.h>
#include<GL/gl.h>
#include<GL/freeglut.h>


void DrawScene(void);

void DrawSceneAxes(void);

void InitOpenGL(void);

void ReshapeWindow(int width, int height);

int mainWindow;

int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutInitWindowPosition(150,150);
mainWindow = glutCreateWindow("Transformacje czajnikowe");
if(mainWindow == 0){
    puts("Can't create window!\n");
    exit(-1);
}
glutSetWindow(mainWindow);

glutDisplayFunc(DrawScene);
glutReshapeFunc(ReshapeWindow);

InitOpenGL();

glEnable(GL_DEPTH_TEST);

glutMainLoop();

return(0);
}


void DrawScene(void)
{

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

DrawSceneAxes();

glutSwapBuffers();

}


void DrawSceneAxes(void)
{
typedef float pt3d[3];


pt3d x_beg = { -10.0f, 0.0f, 0.0f };
pt3d x_end = {  10.0f, 0.0f, 0.0f };


pt3d y_beg = { 0.0f, -10.0f, 0.0f };
pt3d y_end = { 0.0f,  10.0f, 0.0f };


pt3d z_beg = { 0.0f, 0.0f, -10.0f };
pt3d z_end = { 0.0f, 0.0f,  10.0f };


glBegin(GL_LINES);

    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex3fv(x_beg);
    glVertex3fv(x_end);


    glColor3f(0.0f, 1.0f, 0.0f);
    glVertex3fv(y_beg);
    glVertex3fv(y_end);


    glColor3f(0.0f, 0.0f, 1.0f);
    glVertex3fv(z_beg);
    glVertex3fv(z_end);
glEnd();

glutWireTeapot(4.0);
}


void InitOpenGL(void)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}


void ReshapeWindow(int width, int height)
{
//printf("w: %d\n", width);
//printf("h: %d\n", height);
GLdouble nRange = 15.0f;
if(height == 0)
{
    height = 1;
} 

if(width == 0)
{
    width = 1;
}

glViewport(0, 0, width, height);

glMatrixMode(GL_PROJECTION); 

glLoadIdentity();

if(width <= height)
    glOrtho(-nRange, nRange, -nRange*((GLdouble)height / width), nRange*((GLdouble)height / width), -1.0f, 1.0f);  
 else
    glOrtho(-nRange*((GLdouble)width / height), nRange*((GLdouble)width / height), -nRange, nRange, -1.0f, 1.0f);

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();
}

1 个答案:

答案 0 :(得分:0)

您可以从第glViewport(0, 0, width, height);

开始执行此操作
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

if (width <= height)
    glOrtho(-nRange, nRange, -nRange*((GLdouble)height / width), nRange*((GLdouble)height / width), -100.0f, 100.0f);
else
    glOrtho(-nRange*((GLdouble)width / height), nRange*((GLdouble)width / height), -nRange, nRange, -100.0f, 100.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

这将为您提供正交投影(看起来像2D侧视图 - 没有深度)。请注意,glOrtho的最后两个参数从1更改为100

你可以改为使用这样的东西:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1, 1, -1*((GLdouble)height / width), 1*((GLdouble)height / width), 1, nRange);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -10);

这将为您提供透视投影(看起来像3D侧视图)。

旁注:您应该阅读一些关于OpenGL矩阵的教程,如GL_MODELVIEW和GL_PROJECTION - 它们扮演的角色以及如何操作它们

干杯