2011-03-20 43 views

回答

16

OpenGL使用幾個矩陣來轉換幾何和相關數據。這些矩陣是:

  • 模型變換 - 地點在全局對象的幾何形狀,未投影空間
  • 投影 - 項目整體座標到剪輯空間;你可以把它看成是一種鏡頭
  • 紋理 - 調整之前的紋理座標;主要用於實現紋理投影(即投影紋理,就好像它是投影機中的幻燈片一樣)
  • 顏色 - 調整頂點顏色。很少觸及所有這些矩陣

所有這些矩陣一直在使用。由於他們都遵循相同的規則的OpenGL只有一組矩陣操作函數:glPushMatrixglPopMatrixglLoadIdentityglLoadMatrixglMultMatrixglTranslateglRotateglScaleglOrthoglFrustum

glMatrixMode選擇這些操作對哪個矩陣起作用。假設你想寫一些C++命名空間的包裝,它看起來是這樣的:

namespace OpenGL { 
    // A single template class for easy OpenGL matrix mode association 
    template<GLenum mat> class Matrix 
    { 
    public: 
    void LoadIdentity() const 
     { glMatrixMode(mat); glLoadIdentity(); } 

    void Translate(GLfloat x, GLfloat y, GLfloat z) const 
     { glMatrixMode(mat); glTranslatef(x,y,z); } 
    void Translate(GLdouble x, GLdouble y, GLdouble z) const 
     { glMatrixMode(mat); glTranslated(x,y,z); } 

    void Rotate(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) const 
     { glMatrixMode(mat); glRotatef(angle, x, y, z); } 
    void Rotate(GLdouble angle, GLdouble x, GLdouble y, GLdouble z) const 
     { glMatrixMode(mat); glRotated(angle, x, y, z); } 

    // And all the other matrix manipulation functions 
    // using overloading to select proper OpenGL variant depending on 
    // function parameters, and all the other C++ whiz. 
    // ... 
    }; 

    // 
    const Matrix<GL_MODELVIEW> Modelview; 
    const Matrix<GL_PROJECTION> Projection; 
    const Matrix<GL_TEXTURE> Texture; 
    const Matrix<GL_COLOR>  Color; 
} 

後來在一個C++程序,你可以寫,然後

void draw_something() 
{ 
    OpenGL::Projection::LoadIdentity(); 
    OpenGL::Projection::Frustum(...); 

    OpenGL::Modelview::LoadIdentity(); 
    OpenGL::Modelview::Translate(...); 

    // drawing commands 
} 

不幸的是C++無法模板命名空間,或應用using(或with)的情況下,(其它語言有這個),否則我寫了類似的信息(無效C++)

void draw_something_else() 
{ 
    using namespace OpenGL; 

    with(Projection) { // glMatrixMode(GL_PROJECTION); 
     LoadIdentity(); // glLoadIdentity(); 
     Frustum(...);  // glFrustum(...); 
    } 

    with(Modelview) {  // glMatrixMode(GL_MODELVIEW); 
     LoadIdentity(); // glLoadIdentity(); 
     Translate(...); // glTranslatef(...); 
    } 

} 

我認爲日是最後剪去的(僞)代碼清楚地表明:glMatrixMode是OpenGL的一個with語句。

1

所有的都由OpenGL內部使用,但是否需要更改它們取決於您的應用程序。

您將始終需要設置投影矩陣來確定您的視野和您正在查看的空間範圍。通常你會設置模型視圖矩陣來選擇你的「相機」方向,並在場景中定位對象。

紋理和顏色矩陣不太常用。在我當前的項目中,我使用Texture矩陣來翻轉位圖中的Y.我從未使用過Color矩陣。

3

作爲旁註,矩陣模式(以及矩陣堆棧功能的其餘部分)在OpenGL 3.3及更高版本中不推薦使用。