Search code examples
java2dpngtextureslwjgl

Texture in LWJGL not displaying


I am trying to display a png as a texture in Eclipse using the LWJGL library. I made sure to bind the texture and to set the coordinates BEFORE drawing the vertexes, but the image still isn't displaying. What could be the problem?

package javagame;

import static org.lwjgl.opengl.GL11.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

@SuppressWarnings("unused")
public class ImageLWJGL {
    public static Texture p;

    public static void main(String[] args) {
        createDisplay();
        createGL();

        render();

        cleanUp();

    }

    private static void createDisplay(){        
        try {
            Display.setDisplayMode(new DisplayMode(800,600));
            Display.create();
            Display.setVSyncEnabled(true);

        } catch (LWJGLException e) {
            e.printStackTrace();
        }
    }

    public static void createGL(){
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();               
        glOrtho(0, Display.getWidth(), 0, Display.getHeight(), -1, 1);      

        glMatrixMode(GL_MODELVIEW);     

        glClearColor(0,0,0,1);          
        glDisable(GL_DEPTH_TEST);
        glEnable(GL_TEXTURE_2D);

    }


    private static  void render(){
        while(!Display.isCloseRequested()){

        try {
             p = TextureLoader.getTexture("PNG", 
                            new FileInputStream(new     File("res/wood.png")));
        } catch (IOException e) {

            e.printStackTrace();
        }



        glClear(GL_COLOR_BUFFER_BIT);
        glLoadIdentity();

        glColor3f(0.25f,0.75f,0.5f);        


        p.bind();

        glBegin(GL_QUADS);

        glTexCoord2f(0,0);
        glVertex2f(0,0);                    // (origin, origin)

        glTexCoord2f(0,1);
        glVertex2f(0,p.getHeight());        // (origin, y-axis)-height

        glTexCoord2f(1,1);
        glVertex2f(p.getWidth(),p.getHeight());     // (x-axis, y-axis)

        glTexCoord2f(1,0);
        glVertex2f(p.getWidth(),0);             // (x-axis, origin)-width


        glEnd();

        Display.update();
        }

    }




private static void cleanUp(){
    Display.destroy();

}

}


Solution

  • Your problem is your Ortho Projection Matrix.

    glOrtho(0, Display.getWidth(), 0, Display.getHeight(), -1, 1);    
    

    It goes from 0 to Display Width and 0 to Display Height, but you render your Quad from 0 to 1. So your Quad will be rendered, but to Small, that you can see it.
    To solve the Problem Change the glOrtho to:

    glOrtho(0, 1, 0, 1, -1, 1);