簡體   English   中英

OpenGL:如何根據以前的轉換結果進行新的轉換?

[英]OpenGL: How to make new transformations based on the result of former transformations?

我已經閱讀了旋轉這樣的多維數據集的代碼(僅關鍵部分):

static GLfloat theta[] = {0.0,0.0,0.0};
static GLint axis = 2;

void display(void)
{
/* display callback, clear frame buffer and z buffer,
   rotate cube and draw, swap buffers */

 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glRotatef(theta[0], 1.0, 0.0, 0.0);
    glRotatef(theta[1], 0.0, 1.0, 0.0);
    glRotatef(theta[2], 0.0, 0.0, 1.0);

 colorcube();

 glFlush();
    glutSwapBuffers();
}

void spinCube()
{

/* Idle callback, spin cube 2 degrees about selected axis */

    theta[axis] += 2.0;
    if( theta[axis] > 360.0 ) theta[axis] -= 360.0;
    /* display(); */
    glutPostRedisplay();
}

void mouse(int btn, int state, int x, int y)
{

/* mouse callback, selects an axis about which to rotate */

    if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;
    if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis = 1;
    if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;
}

它將變量theta保留在display功能之外,以跟蹤角度的變化。 而且,每當它重新定義轉換矩陣時,看起來新轉換就基於最后一個轉換。

但是,僅旋轉時就是這種情況。 同時考慮旋轉和平移時。 我發現很難使用類似的方法 ,該方法將一些變量保留在外部以跟蹤轉換並每次都重新定義矩陣,因為旋轉和平移不可互換

我的想法之一是使用glPushMatrixglPopMatrix 但是我想知道這是否是處理此類問題的標准方法。

你能幫忙嗎? 謝謝。

是的,這是您要更改模型視圖矩陣時要執行的標准方法,這就是glPushMatrix()glPopMatrix()所做的,將當前模型視圖矩陣保存在矩陣堆棧中。

假設您有第二個對象,一個球體,它的坐標有不同的變化,僅出於論點,在OX軸上平移了-5。

如果你試試:

//for spehere
glTranslatef(-5.0f,0.0f,0.0f):

drawSphere();

//for cube
glTranslatef(-1.0f,0.0f,0.0f)
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);

drawCube();

您實際上將在Ox軸上將立方體轉換為-6.0,而不是-5.0。

為了解決這個問題,您只需要使用glPushMatrix(), glPopMatrix()

//for spehere
glPushMatrix();
glTranslatef(-5.0f,0.0f,0.0f):

drawSphere();
glPopMatrix();

//for cube
glPushMatrix();

glTranslatef(-1.0f,0.0f,0.0f)
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);

drawCube();

glPopMatrix();

這樣,您可以保存原始的Model-View矩陣,以便可以對每個對象應用正確的變換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM