Search code examples
pythonopenglmatrixpyopenglopengl-compat

Switch axis Y and Z in PyOpenGL


I would like to switch the Y and Z axis orientation in PyOpenGL. I have tried using matrix transformations but I have not been able to do it.

Code:

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(self.zoom, -self.zoom, -self.zoom, self.zoom, -5000, 5000)
glMatrixMode(GL_MODELVIEW)
glClearColor(1, 1, 1, 0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadMatrixf(self.m)

Where:

self.zoom = 150
self.m = [[1, 0, 0, 0],
          [0, 0, 1, 0],
          [0, 1, 0, 0],
          [0, 0, 0, 1]]

Wrong result: enter image description here

Using identity matrix: enter image description here

Expected: enter image description here

Edit: This works:

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(self.zoom, -self.zoom, -self.zoom, self.zoom, -5000, 5000)
        up = 1
        if self.theta == 360:
            up = -1
        gluLookAt(self.x, self.y, self.z, 0, 0, 0, 0, up, 0)
        glMatrixMode(GL_MODELVIEW)
        glClearColor(1, 1, 1, 0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadMatrixf(self.m)

Solution

  • A 2 dimensional vector can be rotated by 90°, by swapping the components and inverting one of the components:

    • Rotate (x, y) left is (-y, x)
    • Rotate (x, y) right is (y, -x)

    What you actually do is to turn the right handed matrix to a left handed matrix. It is a concatenation of a rotation by 90° and mirroring.

    Change the matrix:

    Either

    self.m = [[1, 0,  0, 0],
              [0, 0, -1, 0],
              [0, 1,  0, 0],
              [0, 0,  0, 1]]
    

    or

    self.m = [[1,  0, 0, 0],
              [0,  0, 1, 0],
              [0, -1, 0, 0],
              [0,  0, 0, 1]]
    

    Note, the same can be achieved by a rotation around the x-axis. e.g:

    glLoadIdentity()
    glRotatef(90, 1, 0, 0)
    

    If you've a view matrix and a model matrix, then you've to multiply the modle matrix to the view matrix by glMultMatrix:

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    gluLookAt(self.x, self.y, self.z, 0, 0, 0, 0, up, 0)
    glMultMatrixf(self.m)