Borut Flis
Borut Flis

Reputation: 16415

Get position of object in opengl after transforms

I would like to get the coordinates of an object in OpenGL. I draw a quad. And after that I do some transforms like GL11.glTranslatef() and GL11.glRotatef().

GL11.glBegin(GL11.GL_QUADS); // draw independent triangles
GL11.glColor3f(0.0f, 1.0f, 0.0f);
GL11.glVertex3f(-0.2f, 0.0f, -2.0f);    // lower left vertex
GL11.glVertex3f( 0.2f, 0.0f, -2.0f);    // upper vertex
GL11.glVertex3f( 0.2f, 0.4f, -2.0f);    // lower right verte
GL11.glVertex3f( -0.2f, 0.4f, -2.0f);
GL11.glEnd(); 

Is it possible to get the position of the vertices after the transformation?

Upvotes: 4

Views: 5095

Answers (2)

Cris Stringfellow
Cris Stringfellow

Reputation: 3808

Sure. Apply the same transforms (translations and rotations) to a position vector, that holds the position of your object. The result will be the position of your object after the transform. You may need to do some scaling at some point if you want to convert the 3d co-ords to 2d screen co-ords. But this is very much doable. It involves scaling based on the z-depth of the object.

EDIT:

 private final FloatBuffer buffer = EngineUtil.createBuffer( 16 );

      /**
    * @return Current modelview matrix (column-major)
    */
   public Matrix getModelviewMatrix() {
      return getMatrix( GL11.GL_MODELVIEW_MATRIX );
   }

   /**
    * @return Current projection matrix (column-major)
    */
   public Matrix getProjectionMatrix() {
      return getMatrix( GL11.GL_PROJECTION_MATRIX );
   }

   /**
    * Retrieves the specified matrix.
    * @param name Matrix name
    */
   private Matrix getMatrix( int name ) {
      // Retrieve specified matrix buffer
      buffer.rewind();
      GL11.glGetFloat( name, buffer );

      // Convert to array
      final float[] array = new float[ 16 ];
      buffer.get( array );

      // Convert to matrix
      return new Matrix( array );
   }

But you may want to simply use something more complete than LWJGL. Google vecmath, processing, unity. 3D is tricky and it seems there are no real short cuts, so just keep trying, you will get it.

Upvotes: 2

fen
fen

Reputation: 10125

this is not possible... opengl sends your vertex data to the GPU and only on GPU you can get them after the transformation.

to get transformed vertices you have to multiply them by the matrix

for each vertex:
   vertex_transformed = matrix * vertex

some more advanced ways is to use transform feedback and store those transformed vertices into a buffer (but still this buffer will be stored on the GPU).

Upvotes: 0

Related Questions