Search code examples
javac++openglgraphicsjogl

OpenGL load & render png to screen


I'm trying to load a crosshair png I have to a game I'm developing with OpenGL, more precisely JOGL.

The crosshair should be loaded to the center of the screen.

However even after scanning the internet for few hours - haven't found a method to simply render pngs to screen with JOGL, something that I belive is pretty easy.

All the answers I found was regarding textures, and that's not what I'm looking for since I'm not planning to make an object for this - just to show it on screen when needed.

Edit:

After eldo's advice, tried to do the following in the display method:

    gl.glPushMatrix();
    gl.glEnable(GL2.GL_TEXTURE_2D);

    try {
        Texture text = TextureIO.newTexture(getClass().getResourceAsStream("/misc/crosshair.png"),true, "png");
        gl.glTexParameteri( GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_T, GL2.GL_REPEAT );
        gl.glTexParameteri( GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT );
        text.bind(gl);
    } catch (GLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    float sizeX = 20, sizeY = 20, sizeZ = 20;
    gl.glBegin(GL2.GL_QUADS);

    // create crosshair square
    gl.glTexCoord2d(0, 0);
    gl.glVertex3d(0, sizeY, 0);
    gl.glTexCoord2d(1, 0);
    gl.glVertex3d(sizeX, sizeY, 0);
    gl.glTexCoord2d(1, 1);
    gl.glVertex3d(sizeX, sizeY, sizeZ);
    gl.glTexCoord2d(0, 1);
    gl.glVertex3d(0, sizeY, sizeZ);


    gl.glEnd();
    gl.glPopMatrix();

However the result I get is (the other stuff is just walls): enter image description here

Here's the crosshair png: crosshair


Solution

  • You can't just draw an image that easily in middle of your screen, OpenGL wont 'forget' its actual state and render your image as you wish. But in a few steps you can make it able to draw it after you finished rendering all your 3D stuffs.

    gl.glMatrixMode(GL.GL_PROJECTION); //reset the projection matrix
    gl.glLoadIdentity();
    gl.glOrtho(left, right, bottom, top, near, far);//change to orthographic projection
    gl.glMatrixMode(GL.GL_MODELVIEW);// reset the modelview matrix
    gl.glLoadIdentity();
    gl.glDisable(GL.GL_DEPTH_TEST);//disable depth test
    //draw 2D stuff here
    

    After this you can draw a quad in the middle of your screen with a crosshair texture on it.