opengl gluLookAt函数实现

本文介绍如何使用 C++ 语言实现 OpenGL 中的 gluLookAt 函数,并提供了一个具体的实现示例。通过定义结构体 point 和 Vector 来辅助完成向量运算,包括标准化向量和计算两个向量的叉乘等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数的原型如下:

 gluLookAt(GLdouble eyex,GLdouble eyey,GLdouble eyez,GLdouble centerx,GLdouble centery,GLdouble centerz,GLdouble upx,GLdouble upy,GLdouble upz);

前三个参数的含义是摄像机的位置,四到六个参数是被观察物体的方向,最后面的三个参数是垂直于摄像机向上的向量(也就是摄像机可以扭个角度在同一位置,看同一个地方)

c++实现

#include <iostream>
#include <cstring>
#include <GL/glut.h>
#include <cmath>
using namespace std;

struct point
{
    GLdouble x, y, z;
    point()
    {
        x = y = z = 0;
    }
    point(GLdouble _x, GLdouble _y, GLdouble _z)
    {
        x = _x;
        y = _y;
        z = _z;
    }
};
typedef point Vector;
void Normalize( Vector &V)
{
    GLdouble tmp = sqrt(V.x*V.x + V.y*V.y + V.z*V.z);
    V.x = V.x / tmp;
    V.y = V.y / tmp;
    V.z = V.z / tmp;
}
Vector Cross(Vector a, Vector b)
{
    return Vector(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x);
}
void MyLookAt(GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ)
{
    GLdouble Mat[16];
    memset(Mat, 0, sizeof(Mat));
    Mat[15] = 1;
    Vector forward(centerX - eyeX, centerY - eyeY, centerZ - eyeZ);
    Vector up(upX, upY, upZ);
    Normalize(forward);
    Vector side = Cross(forward, up);
    Normalize(side);
    up = Cross(side, forward);
    Mat[0] = side.x;
    Mat[4] = side.y;
    Mat[8] = side.z;
    Mat[1] = up.x;
    Mat[5] = up.y;
    Mat[9] = up.z;
    Mat[2] = -forward.x;
    Mat[6] = -forward.y;
    Mat[10] = -forward.z;
    cout<<Mat[10]<<" ";
    cout<<endl;
    glLoadMatrixd(Mat);
    glTranslated(-eyeX, -eyeY, -eyeZ);
}
void init(void)
{
    glClearColor(0.0, 0.0, 0.0, 0.0); //背景黑色  
}

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 1.0, 1.0); //画笔白色  

    glLoadIdentity();  //加载单位矩阵  

//  gluLookAt(0, 0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    MyLookAt(0, 0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    glutWireTeapot(2);
    glutSwapBuffers();
}

void reshape(int w, int h)
{
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0, (GLfloat)w / (GLfloat)h, 1.0, 20.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
//  gluLookAt(0, 0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    //  
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(800, 600);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    init();
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值