LWJGL 3: window doesn't show up - java

I downloaded LWJGL 3 today, and found out that it was almost completly rewritten. I looked up a tutorial on how to create a window, but I still have problems creating a window.
The code runs without problems: no errors in the console, but the window isn't displayed!
I hope you can help me, I searched a lot for LWJGL 3 tutorials, but they seem pretty old, so I decided to ask my question here.
Here's my code:
//EDIT: Changed my code so everything runs in one thread but it still doesn' t work. Even System.out.println() doesn't work. No console output is displayed!
//IMPORTANT: I just realized that this may be a bug in GLFW (I'm working on Linux) !
package net.newworld.test;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.Version;
import org.lwjgl.glfw.GLFWVidMode;
public class Main {
private static long window;
private static int width = 1280;
private static int height = 800;
private static void init() {
glfwInit();
System.out.println("Initializing LWJGL...");
System.out.println("LWJGL Version: "+ Version.getVersion());
glfwWindowHint(GLFW_VISIBLE, GL_FALSE); //Set window visible after creation
window = glfwCreateWindow(width, height, "New World", 0, 0);
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); //Get primary monitor
glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2); //Set window position
glfwMakeContextCurrent(window); //Make OpenGL contect current
glfwShowWindow(window); //Show window
}
public static void main(String[] args) {
init();
}
}

The problem might be that you forgot to add the window proc loop (which is blocking)
public static void main(String[] args) {
init();
while (!glfwWindowShouldClose(window)) {
glfwWaitEvents();
}
}

Related

glfwGetPrimaryMonitor() NullPointerException

I'm learning how to make a Java game with ThinMatrix's LWJGL 2 tutorials that I'm adapting to LWJGL 3. Anyway, I can't get the game to detect my monitors. This was working fine just a few days ago on the exact same system with the exact same hardware.
I have tried installing the drivers for them, uninstalling the drivers, and uninstalling the monitors completely from Device Manager. Nothing works. If you need any more information just let me know!
Here is my source code:
Main.java:
package engineTest;
import static org.lwjgl.glfw.GLFW.*;
import static renderEngine.displayManager.*;
public class Main {
public static void main(String[] args) {
window = glfwCreateWindow(WIDTH, HEIGHT, "Farm Game", glfwGetPrimaryMonitor(), 0);
while(!glfwWindowShouldClose(window)) {
updateDisplay();
}
glfwDestroyWindow(window);
}
}
displayManager.java
package renderEngine;
import static org.lwjgl.glfw.GLFW.*;
import org.lwjgl.opengl.GL11;
public class displayManager {
public static int WIDTH = 1280;
public static int HEIGHT = 720;
private static int FPS_CAP = 120;
public static long window;
public static void createDisplay() {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GL11.glViewport(0, 0, WIDTH, HEIGHT);
}
public static void updateDisplay() {
glfwPollEvents();
glfwSwapBuffers(FPS_CAP);
}
public static void closeDisplay() {
glfwDestroyWindow(window);
}
}
Here is the error output.
Exception in thread "main" java.lang.NullPointerException
at org.lwjgl.system.Checks.check(Checks.java:99)
at org.lwjgl.glfw.GLFW.glfwWindowShouldClose(GLFW.java:1874)
at engineTest.Main.main(Main.java:13)
Edit
I have been trying to debug the NullPointerException, and I know what is causing it. The problem is I don't know how to fix it. Sorry, I'm pretty new to Java.
You have to call glfwInit() before you can use any other glfw method. Since this is missing, glfwCreateWindow always returns a nullptr.

How to properly update a transparent swing overlay?

I used transparent click-through overlay based on the answer (that uses jna to enable click-through)
https://stackoverflow.com/a/28772306/1093872.
However the actual visible overlay is always behind one step, ie. when a repaint() gets called on the component, the update that should have been shown in the previous update is shown.
At first I suspected memory inconsistency issue because of the different thread. But I also tried the sure-to-be-correct approach using SwingWorker, and still faced the same problem.
AWTUtilities.setWindowOpaque(w, false); seems to be causing the problem in some way, because after I comment that out or set it to true, the problem disappears, but unfortunately the window is also not transparent (obviously).
I suspect the problem might be something related to double-buffering (the buffer is not swapped after painting only before next paint), but I don't really know. I also tried calling setDoubleBuffered(false) and setDoubleBuffered(true) on the component, but that does not change anything.
Also I realized that the problem isn't related to the jna part, because after removing that, the problem remains exactly the same.
Note that the index printing occurs at the same time as the drawing, so I know the paintComponent gets called in time, but the visible update only happens on the next call to it.
Any ideas on what can be the cause, and how to fix this?
import com.sun.awt.AWTUtilities;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import javax.swing.*;
import java.awt.*;
public class OverlayUpdateTest {
private static MyJComponent myJComponent;
public static void main(String[] args) {
setupOverlayWindow();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
myJComponent.increaseIndex();
myJComponent.repaint();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
private static void setupOverlayWindow() {
Window w = new Window(null);
myJComponent = new MyJComponent();
w.add(myJComponent);
w.pack();
w.setLocationRelativeTo(null);
w.setVisible(true);
w.setAlwaysOnTop(true);
/**
* This sets the background of the window to be transparent.
*/
AWTUtilities.setWindowOpaque(w, false);
setTransparent(w);
}
private static void setTransparent(Component w) {
WinDef.HWND hwnd = getHWnd(w);
int wl = User32.INSTANCE.GetWindowLong(hwnd, WinUser.GWL_EXSTYLE);
wl = wl | WinUser.WS_EX_LAYERED | WinUser.WS_EX_TRANSPARENT;
User32.INSTANCE.SetWindowLong(hwnd, WinUser.GWL_EXSTYLE, wl);
}
/**
* Get the window handle from the OS
*/
private static WinDef.HWND getHWnd(Component w) {
WinDef.HWND hwnd = new WinDef.HWND();
hwnd.setPointer(Native.getComponentPointer(w));
return hwnd;
}
private static class MyJComponent extends JComponent {
private int index = 0;
/**
* This will draw a black cross on screen.
*/
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, getHeight() / 2 - 10, getWidth(), 20);
g.fillRect(getWidth() / 2 - 10, 0, 20, getHeight());
g.setColor(Color.RED);
g.drawString("i: " + index, 10, getFont().getSize() + 10);
System.out.println("i: " + index);
}
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
void increaseIndex() {
index++;
}
}
}
After much trial and error I found a working solution...
Changing Window w = new Window(null); to Window w = new JWindow(); solved the problem. I don't know why, but I'm happy with it.

java.lang.NoClassDefFoundError in LWJGL when attempting to run in Eclipse

So I'm a moderately novice programmer, but after toiling over this error for a while, I can't find a solution. I'm making a puzzle game, and for some reason, it just refuses to run now. I always get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.lwjgl.system.Library
at org.lwjgl.system.MemoryAccess.<clinit>(MemoryAccess.java:22)
at org.lwjgl.system.Pointer.<clinit>(Pointer.java:24)
at org.lwjgl.glfw.GLFW.<clinit>(GLFW.java:594)
at Graphics.LaunchWindow.run(LaunchWindow.java:32)
at Graphics.LaunchWindow.main(LaunchWindow.java:96)
Eclipse tells me that none of my code has errors within it, and reinstalling LWJGL doesn't work (I tried both the stable 3.0.0b build 64 and the nightly 3.0.0 build 22). I have seen other similar questions taking about making sure the lwjgl.jar is in the class path, but I've made sure multiple times. Also, if it matters, I have lwjgl_util.jar and slick_util.jar in the class path as well, and even though they are outdated compared to lwjgl 3, removing them from the class path makes no difference.
package Graphics;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import Controls.KeyParser;
import Controls.KeyboardInput;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
public class LaunchWindow {
private GLFWErrorCallback errorCallback;
private GLFWKeyCallback keyCallback;
public int width = 1024;
public int height = 600;
public String title = "Duplicity";
public long fullscreen = NULL;
public long window;
public void run() {
try {
init();
loop();
glfwDestroyWindow(window);
keyCallback.release();
} finally {
glfwTerminate();
errorCallback.release();
}
}
private void init() {
glfwSetErrorCallback(errorCallback = GLFWErrorCallback.createPrint(System.err));
KeyboardInput.initiate();
if ( glfwInit() != GLFW_TRUE )
throw new IllegalStateException("Unable to initialize GLFW");
if(fullscreen == NULL){
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
}
window = glfwCreateWindow(width, height, title, fullscreen, NULL);
if (window == NULL)
throw new RuntimeException("Failed to create the GLFW window");
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, GLFW_TRUE);
}
});
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwShowWindow(window);
keyCallback = GLFWKeyCallback.create(KeyboardInput::glfw_key_callback);
keyCallback.set(window);
/* mouseButtonCallback = GLFWMouseButtonCallback.create(Mouse::glfw_mouse_button_callback);
mouseButtonCallback.set(window);
cursorPosCallback = GLFWCursorPosCallback.create(Mouse::glfw_cursor_pos_callback);
cursorPosCallback.set(window); */
GL.createCapabilities();
}
public void loop() {
GL.createCapabilities();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
while ( glfwWindowShouldClose(window) == GLFW_FALSE ) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
new KeyParser().checkKeyState();
}
}
public static void main(String[] args) {
new LaunchWindow().run();
}
}
Incorrect system library path can be one reason for this error, but this can also be caused by system library incompatibility (on Linux). Code included in LWJGL 3 requires GLIBC version 2.14 or higher. If your system (e.g. Linux) is older (like Debian Wheezy, for example), your GLIBC version will be older than the required one.
If that's the case you'll need to install a newer GLIBC version, or upgrade your system (e.g. to Debian Jessie).
HTH,
M

Failure to load lwjgl

I finished setting up lwjgl and tried to run the example from the website, but then, I keep getting this error (I changed the name of the class):
Exception in thread "main" java.lang.UnsatisfiedLinkError: Failed to load the native library: lwjgl32
at org.lwjgl.LWJGLUtil.loadLibrarySystem(LWJGLUtil.java:338)
at org.lwjgl.Sys$1.run(Sys.java:36)
at java.security.AccessController.doPrivileged(Native Method)
at org.lwjgl.Sys.<clinit>(Sys.java:33)
at mehavenowebsite.DoStuff.run(DoStuff.java:24)
at mehavenowebsite.DoStuff.main(DoStuff.java:114)
I set up lwjgl correctly, and I added the natives, so I have no idea what's going on. I am using eclipse luna, with lwjgl 3. Does anyone know what's going on? Thanks.
EDIT: code:
package mehavenowebsite;
import org.lwjgl.Sys;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import java.nio.ByteBuffer;
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 DoStuff {
// We need to strongly reference callback instances.
private GLFWErrorCallback errorCallback;
private GLFWKeyCallback keyCallback;
// The window handle
private long window;
public void run() {
System.out.println("Hello LWJGL " + Sys.getVersion() + "!");
try {
init();
loop();
// Release window and window callbacks
glfwDestroyWindow(window);
keyCallback.release();
} finally {
// Terminate GLFW and release the GLFWerrorfun
glfwTerminate();
errorCallback.release();
}
}
private void init() {
// Setup an error callback. The default implementation
// will print the error message in System.err.
glfwSetErrorCallback(errorCallback = errorCallbackPrint(System.err));
// 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
int WIDTH = 300;
int HEIGHT = 300;
// Create the window
window = glfwCreateWindow(WIDTH, HEIGHT, "Hello World!", NULL, NULL);
if ( window == NULL )
throw new RuntimeException("Failed to create the GLFW 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
}
});
// Get the resolution of the primary monitor
ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
// Center our window
glfwSetWindowPos(
window,
(GLFWvidmode.width(vidmode) - WIDTH) / 2,
(GLFWvidmode.height(vidmode) - HEIGHT) / 2
);
// Make the OpenGL context current
glfwMakeContextCurrent(window);
// Enable v-sync
glfwSwapInterval(1);
// Make the window visible
glfwShowWindow(window);
}
private void loop() {
// 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();
// Set the clear color
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
// Run the rendering loop until the user has attempted to close
// 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
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 DoStuff().run();
}
}
Did you add the library the "Eclipse way"?
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7

JOGL creating window using NEWT - examples?

I have been looking at using JOGL to create some things and have been looking through what documentation I can find.
Brief tutorials they all mention how using the JOGL version of canvas can have performance issues and instead you should use NEWT. However each and every tutorial / FAQ then goes on to use the canvas! Or simply specify a few tiny snippets of methods to create a window using NEWT but which (on my machine at least) I cannot get to correctly run.
Does anyone have a good source of examples of how to correctly implement creating and rendering to a window in JOGL using the NEWT method? I'm not even sure how it functions compared to the Canvas so an explanation of the differences between the two and a typical layout of methods to create / manage / render to a window would be ideal.
Just a little lost and cannot find anything useful. Hope someone's come across something before!
This tutorial helped me a lot, see chapter 3.9 - Yet Another Tutorial on JOGL.
Also documentation is useful. Take a look at the attached example, please.
JOGL2NewtDemo.java
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import com.jogamp.newt.event.WindowAdapter;
import com.jogamp.newt.event.WindowEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;
/**
* A program that draws with JOGL in a NEWT GLWindow.
*
*/
public class JOGL2NewtDemo {
private static String TITLE = "JOGL 2 with NEWT"; // window's title
private static final int WINDOW_WIDTH = 640; // width of the drawable
private static final int WINDOW_HEIGHT = 480; // height of the drawable
private static final int FPS = 60; // animator's target frames per second
static {
GLProfile.initSingleton(); // The method allows JOGL to prepare some Linux-specific locking optimizations
}
/**
* The entry main() method.
*/
public static void main(String[] args) {
// Get the default OpenGL profile, reflecting the best for your running platform
GLProfile glp = GLProfile.getDefault();
// Specifies a set of OpenGL capabilities, based on your profile.
GLCapabilities caps = new GLCapabilities(glp);
// Create the OpenGL rendering canvas
GLWindow window = GLWindow.create(caps);
// Create a animator that drives canvas' display() at the specified FPS.
final FPSAnimator animator = new FPSAnimator(window, FPS, true);
window.addWindowListener(new WindowAdapter() {
#Override
public void windowDestroyNotify(WindowEvent arg0) {
// Use a dedicate thread to run the stop() to ensure that the
// animator stops before program exits.
new Thread() {
#Override
public void run() {
if (animator.isStarted())
animator.stop(); // stop the animator loop
System.exit(0);
}
}.start();
}
});
window.addGLEventListener(new JOGL2Renderer());
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setTitle(TITLE);
window.setVisible(true);
animator.start(); // start the animator loop
}
}
JOGL2Renderer.java
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
/**
* Class handles the OpenGL events to render graphics.
*
*/
public class JOGL2Renderer implements GLEventListener {
private double theta = 0.0f; // rotational angle
/**
* Called back by the drawable to render OpenGL graphics
*/
#Override
public void display(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2(); // get the OpenGL graphics context
gl.glClear(GL.GL_COLOR_BUFFER_BIT); // clear background
gl.glLoadIdentity(); // reset the model-view matrix
// Rendering code - draw a triangle
float sine = (float)Math.sin(theta);
float cosine = (float)Math.cos(theta);
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor3f(1, 0, 0);
gl.glVertex2d(-cosine, -cosine);
gl.glColor3f(0, 1, 0);
gl.glVertex2d(0, cosine);
gl.glColor3f(0, 0, 1);
gl.glVertex2d(sine, -sine);
gl.glEnd();
update();
}
/**
* Update the rotation angle after each frame refresh
*/
private void update() {
theta += 0.01;
}
/*... Other methods leave blank ...*/
}
take a look at JOGL's junit tests, they cover large parts of the NEWT API.

Categories