无法使用LWJGL 3和Slick-Util渲染PNG文件

时间:2015-04-05 02:10:49

标签: java image render lwjgl

我试图使用库LWJGL和Slick-Util在java中创建程序。我可以成功创建一个窗口并渲染一个红色矩形,但每当我尝试渲染图像时,它都会给我一个空白的屏幕。有四个java文件,这里是我的代码:

MOBAelex.java:

package com.aelex.mobaelex;

import com.aelex.mobaelex.menu.MenuScreen;

import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;

public class MOBAelex {

    public static Texture playButton;

    private static int ImagesLoaded = 0;

    // We need to strongly reference callback instances.
    private GLFWErrorCallback errorCallback;
    private GLFWKeyCallback   keyCallback;
    private GLFWMouseButtonCallback mouse_button_callback;
    private GLFWCursorPosCallback cursor_pos_callback;

    // The window handle
    private long window;

    private double MouseX;
    private double MouseY;

    private static void LoadImages() {

        try {

            playButton = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("Assets/Pics/Play.png"));
            ImagesLoaded = 1;

        } catch (IOException e) {

            e.printStackTrace();
            ImagesLoaded = 0;

        }

    }

    public void run() {
        System.out.println("Starting MOBAelex");

        init();
        LoadImages();
        loop();

        System.out.println("Now exiting the program");

        // Release window and window callbacks
        glfwDestroyWindow(window);
        keyCallback.release();
        // Terminate GLFW and release the GLFWerrorfun
        glfwTerminate();
        errorCallback.release();
    }

    private void init() {

        System.out.println("Running init");

        // Setup an error callback. The default implementation
        // will print the error message in System.err.

        glfwSetErrorCallback(errorCallback = errorCallbackPrint(System.err));

        System.out.println("Set error callback");

        // Initialize GLFW. Most GLFW functions will not work before doing this.
        if ( glfwInit() != GL11.GL_TRUE )
            throw new IllegalStateException("Unable to initialize GLFW");

        // Configure our window
        glfwDefaultWindowHints(); // optional, the current window hints are already the default
        glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // the window will stay hidden after creation
        glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // the window will be resizable

        System.out.println("comfigured new window");

        int WIDTH = 600;
        int HEIGHT = 600;

        // Create the window
        window = glfwCreateWindow(WIDTH, HEIGHT, "MOBAelex", NULL, NULL);
        if ( window == NULL )
            throw new RuntimeException("Failed to create the GLFW window");

        System.out.println("Created new window");

        // Setup a key callback. It will be called every time a key is pressed, repeated or released.
        glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
            @Override
            public void invoke(long window, int key, int scancode, int action, int mods) {
                if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE )
                    glfwSetWindowShouldClose(window, GL_TRUE); // We will detect this in our rendering loop
            }
        });

        glfwSetCursorPosCallback(window, cursor_pos_callback = new GLFWCursorPosCallback() {
            public void invoke(long window, double xpos, double ypos) {
                MouseX = xpos;
                MouseY = ypos;
            }
        });

        glfwSetMouseButtonCallback(window, mouse_button_callback = new GLFWMouseButtonCallback() {
            public void invoke(long window, int button, int action, int mods) {
                if ( button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE ) {
                    if (MouseX > MenuScreen.Play.X && MouseX < MenuScreen.Play.X + 200 && MouseY > MenuScreen.Play.Y && MouseY < MenuScreen.Play.Y + 100) {
                    MenuScreen.Play.ButtonOn();
                    }
                }
            }
        });

        System.out.println("Setup window close key callback");

        // Get the resolution of the primary monitor
        ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

        System.out.println("Retrieved primary monitor's resolution: " + GLFWvidmode.WIDTH + ":" + GLFWvidmode.HEIGHT);
        System.out.println("Please contact someone if this resolution is wrong");

        // Center our window
        glfwSetWindowPos(
            window,
            (GLFWvidmode.width(vidmode) - WIDTH) / 2,
            (GLFWvidmode.height(vidmode) - HEIGHT) / 2
        );

        System.out.println("Positioned window");

        // Make the OpenGL context current
        glfwMakeContextCurrent(window);

        System.out.println("Made the OpenGL context current");

        // Enable v-sync
        glfwSwapInterval(60);

        System.out.println("Enabled V-Sync");

        // Make the window visible
        glfwShowWindow(window);

        System.out.println("Window now visible");

        // This line is critical for LWJGL's interoperation with GLFW's
        // OpenGL context, or any context that is managed externally.
        // LWJGL detects the context that is current in the current thread,
        // creates the ContextCapabilities instance and makes the OpenGL
        // bindings available for use.
        GLContext.createFromCurrent();

        System.out.println("Created ContextCapabilties instance");
        System.out.println("OpenGL bindings are now available for use within the code");

        // Set the clear color
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    }

    private void loop() {

        if (ImagesLoaded == 1) {

            System.out.println("Textures loaded successfully");

        }
        else if (ImagesLoaded == 0) {

            System.out.println("Textures not loaded properly");
            System.out.println("Now quitting");

            glfwDestroyWindow(window);
            keyCallback.release();

            glfwTerminate();
            errorCallback.release();

        }

        // Run the rendering loop until the user has attempted to <a style="background: none repeat scroll 0% 0% transparent ! important; border: medium none ! important; display: inline-block ! important; text-indent: 0px ! important; float: none ! important; font-weight: bold ! important; height: auto ! important; margin: 0px ! important; min-height: 0px ! important; min-width: 0px ! important; padding: 0px ! important; text-transform: uppercase ! important; text-decoration: underline ! important; vertical-align: baseline ! important; width: auto ! important;" title="Click to Continue > by Provider" in_rurl="http://s.ltmmty.com/click?v=VVM6ODc1NjY6MzI4NTpjbG9zZTpmN2M1ZTlmNTI2Y2UzZjljY2Y1MTViNWE4ZDY5NDJmZDp6LTE3MzctNTMxODUxOTp3d3cubHdqZ2wub3JnOjI1Nzk5ODo2YTAyMjhhMTljZjg2NWU2MGFmMzNlODZjNmNhM2FiYjpjM2Y5MDg0NWRmOTI0YWFiYjY3MDFlM2Y0ZjRlNzE0YToxOmRhdGFfc3MsODYweDE0NDA7ZGF0YV9mYixubzs6NDg4MTQyOA&subid=g-5318519-c269c861ae424a35a05b730fbcbace11-&data_ss=860x1440&data_fb=no&data_tagname=CODE" id="_GPLITA_5" href="#">close<img style="background: none repeat scroll 0% 0% transparent ! important; border: medium none ! important; display: inline-block ! important; text-indent: 0px ! important; float: none ! important; font-weight: bold ! important; height: 10px ! important; margin: 0px 0px 0px 3px ! important; min-height: 0px ! important; min-width: 0px ! important; padding: 0px ! important; text-transform: uppercase ! important; text-decoration: underline ! important; vertical-align: super ! important; width: 10px ! important;" src="http://cdncache-a.akamaihd.net/items/it/img/arrow-10x10.png"></a>
        // the window or has pressed the ESCAPE key.
        while ( glfwWindowShouldClose(window) == GL_FALSE ) {
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

            MenuScreen.Menu();

            glfwSwapBuffers(window); // swap the color buffers
            // Poll for window events. The key callback above will only be
            // invoked during this call.
            glfwPollEvents();
        }
    }

    public static void main(String[] args) {
        new MOBAelex().run();
    }

}

MenuScreen.java:

package com.aelex.mobaelex.menu;

import com.aelex.mobaelex.resources.Buttons;
import com.aelex.mobaelex.MOBAelex;

public class MenuScreen {

    public static Buttons Play = new Buttons();
    private static boolean ButtonRender;

    public static void Menu() {

        Play.X = 0.0f;
        Play.Y = 0.0f;
        Play.Button = MOBAelex.playButton;
        Play.ButtonReaction = "ConnectServer";

        Play.RenderButton();

        ButtonRender = Play.ButtonRendered;

        if (ButtonRender == false) {

            System.out.println("Unable to render playButton!");

        }



    }

}

Buttons.java

package com.aelex.mobaelex.resources;

import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;

import com.aelex.mobaelex.MOBAelex;
import com.aelex.mobaelex.reactions.ButtonReactions;

public class Buttons {

    public float X = 0;
    public float Y = 0;
    private float X2 = 0;
    private float Y2 = 0;

    public Texture Button;

    public String ButtonReaction;

    public boolean ButtonRendered = false;

    public void ButtonOn() {

        if (ButtonReaction.equals("ConnectServer")) {

            System.out.println("Executing button code: " + ButtonReaction);

            ButtonReactions.ConnectServer();

        }

    }

    public void RenderButton() {

        X2 = Button.getTextureWidth()/10000;
        Y2 = Button.getTextureHeight()/10000;

        Color.white.bind();
        Button.bind();

        GL11.glBegin(GL11.GL_QUADS);
        GL11.glVertex2f(X,Y);
        GL11.glVertex2f(X+0.200f,Y);
        GL11.glVertex2f(X+0.200f,Y+0.100f);
        GL11.glVertex2f(X,Y+0.100f);
        GL11.glEnd();

        ButtonRendered = true;

    }

}

ButtonReactions.java

package com.aelex.mobaelex.reactions;

public class ButtonReactions {

    public static void ConnectServer() {

        System.out.println("Successfully connected to Server");

    }

}

这个程序试图使用的Play.png是我用Paint制作的简单图片。它的像素为200x100,全黑。

此外,我尝试将Buttons.java中的Color.white.bind()更改为Color.red.bind(),它导致在窗口中心呈现一个红色矩形,但我想要它在左上角?我不知道如何做到这一点,如果你能回答这个问题那就太棒了。

1 个答案:

答案 0 :(得分:1)

我遇到了same issue;似乎slick-utilslick2d的一部分,已被弃用且不再维护。

您应该使用TWL的PNGDecoder或slick-util3(参见上面的链接)。