OpenGL 使用矩陣變換改變檢視

b_d發表於2019-05-23

前言

在上一篇OpenGL 深度測試基礎上修改main.cpp檔案,完成此demo

程式碼

本篇主要是使用矩陣相關操作,來完成檢視的變換。與之前demo的區別在與,之前通過改變觀察點位置來獲取不同位置物體的檢視。次demo則是直接通過矩陣變換修改物體的位置,來讓觀察者看到不同位置的物體。程式碼如下:


#include "GLMatrixStack.h"
#include "GLFrame.h"
#include "GLFrustum.h"
#include "GLBatch.h"
#include "GLGeometryTransform.h"
#include <math.h>
#include <GLUT/GLUT.h>
#include "GLTools.h"
#include "StopWatch.h"

GLShaderManager  shaderManager;
GLMatrixStack    modelViewMatrix;

//投影矩陣
GLFrustum        viewFrustum;
GLTriangleBatch cylinderBatch;

void changeSize(int w, int h) {
    glViewport(0, 0, w, h);
    //設定透視投影
    viewFrustum.SetPerspective(30.0f, float(w) / float(h), 2.0f, 400.0f);
    
}

void renderScene() {
    //清理緩衝區
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    
    static CStopWatch rotTimer;
    float yRot = rotTimer.GetElapsedSeconds() * 30;
    
    M3DMatrix44f mTranslate, mRotate, mModelView, mModelViewProjection;
    //建立平移矩陣
    m3dTranslationMatrix44(mTranslate,0.0f,0.0f,-8.0f);
    //建立旋轉矩陣
    m3dRotationMatrix44(mRotate, m3dDegToRad(yRot), 0.0f,1.0f,0.0f);
    //模型矩陣 = 旋轉矩陣 * 平移矩陣
    m3dMatrixMultiply44(mModelView, mTranslate, mRotate);
    //模型檢視矩陣 = 檢視矩陣 * 模型矩陣
    m3dMatrixMultiply44(mModelViewProjection, viewFrustum.GetProjectionMatrix(), mModelView);
    
    GLfloat vOrange[] = {1.0f,0.6f,0.0f,1.0f};
    shaderManager.UseStockShader(GLT_SHADER_FLAT,mModelViewProjection,vOrange);
    cylinderBatch.Draw();
    glutSwapBuffers();
    glutPostRedisplay();
}

void setupRC() {
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    shaderManager.InitializeStockShaders();
    glEnable(GL_DEPTH_TEST);
    gltMakeCylinder(cylinderBatch, 0.3f, 0.8f, 0.8f, 100, 1);
    
}

int main(int argc, char* argv[]) {
    
    gltSetWorkingDirectory(argv[0]);
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
    glutInitWindowSize(600, 600);
    glutCreateWindow("dowZhang");
    glutReshapeFunc(changeSize);
    glutDisplayFunc(renderScene);
    
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        return 1;
    }
    
    setupRC();
    
    glutMainLoop();
    
    return 0;
}

複製程式碼

效果如下:

OpenGL 使用矩陣變換改變檢視

相關文章