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
Related
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.
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();
}
}
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
I need to port something written in Java with LWJGL to a Raspberry. Im using Raspbian and tried oracles java version and some called "openjdk" or something like that.
With both versions I get this Exception:
java.lang.UnsatisfiedLinkError: org.lwjgl.opengl.GLContext.nLoadOpenGLLibrary()V
when creating the "Display".
I already searched for some solution, but they refer to OpenGLES and I did never use OpenGLES nor I found any download to use it.
I have no clue what to do and what information you might need, just comment if you need some more input.
edit:
Well you might want my current sourcecode too:
import java.io.File;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.PixelFormat;
public class Main {
private int fps;
private long lastFPS, lastTime;
Main() {
createWindow();
init2D();
loop();
}
private void init2D() {
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, 500, 400, 0, -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
GL11.glDisable(GL11.GL_DEPTH_TEST);
lastFPS = getTime();
getDelta();
}
private long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
public void updateFPS() {
if (getTime() - lastFPS > 1000) {
Display.setTitle(Integer.toString(fps));
fps = 0;
lastFPS += 1000;
}
fps++;
}
private int getDelta() {
long time = getTime();
int delta = (int) (time - lastTime);
lastTime = time;
return delta;
}
private void loop() {
float rot = 0;
while(!Display.isCloseRequested()&&!Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glLoadIdentity();
int x = Display.getDisplayMode().getWidth()/2;
int y = Display.getDisplayMode().getHeight()/2;
GL11.glTranslated(x, y, 0);
GL11.glRotated(rot, 0, 0, 1);
if(Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
GL11.glColor3f(1, 0, 0);
} else {
GL11.glColor3f(1, 1, 1);
}
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2d(-50, -50);
GL11.glVertex2d(50, -50);
GL11.glVertex2d(50, 50);
GL11.glVertex2d(-50, 50);
GL11.glEnd();
rot+=0.05*getDelta();
Display.update();
updateFPS();
}
}
private void createWindow() {
try {
Display.setDisplayMode(new DisplayMode(500, 400));
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
} // Window is created in this try-catch
try {
Assetloader.load();
} catch (Exception e) {
} // Load Assets
}
public static void main(String args[]) {
System.setProperty("org.lwjgl.librarypath", new File("native").getAbsolutePath());
new Main();
}
}
Raspberry Pi's only support OpenGL ES 2.0 and they're isn't any way around that.
OpenGL ES has no immediate mode rendering (glBegin, glVertex, glColor). You'll have to load your geometry into VBO's and render that way.
You'll also need to write basic shaders and pass your projection and modelview matrices in via glUniformMatrix.
Immediate mode rendering is pretty much only available on the desktop, iPhone's, Android's and Blackberry's use only OpenGL ES and pretty much any game console will use an API very similiar to OpenGL ES.
Bottom line: You'll need to ditch the immediate mode rendering and learn to use the ES spec.
These links should help...
http://www.khronos.org/registry/gles/specs/2.0/es_full_spec_2.0.25.pdf
http://www.khronos.org/files/opengles_shading_language.pdf
Is there a way for me to get the X and Y values of a window in java? I read that I'll have to use runtime, since java can't mess directly, however I am not so sure of how to do this. Can anyone point me some links/tips on how to get this?
To get the x and y position of "any other unrelated application" you're going to have to query the OS and that means likely using either JNI, JNA or some other scripting utility such as AutoIt (if Windows). I recommend either JNA or the scripting utility since both are much easier to use than JNI (in my limited experience), but to use them you'll need to download some code and integrate it with your Java application.
EDIT 1
I'm no JNA expert, but I do fiddle around with it some, and this is what I got to get the window coordinates for some named window:
import java.util.Arrays;
import com.sun.jna.*;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.win32.*;
public class GetWindowRect {
public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class,
W32APIOptions.DEFAULT_OPTIONS);
HWND FindWindow(String lpClassName, String lpWindowName);
int GetWindowRect(HWND handle, int[] rect);
}
public static int[] getRect(String windowName) throws WindowNotFoundException,
GetWindowRectException {
HWND hwnd = User32.INSTANCE.FindWindow(null, windowName);
if (hwnd == null) {
throw new WindowNotFoundException("", windowName);
}
int[] rect = {0, 0, 0, 0};
int result = User32.INSTANCE.GetWindowRect(hwnd, rect);
if (result == 0) {
throw new GetWindowRectException(windowName);
}
return rect;
}
#SuppressWarnings("serial")
public static class WindowNotFoundException extends Exception {
public WindowNotFoundException(String className, String windowName) {
super(String.format("Window null for className: %s; windowName: %s",
className, windowName));
}
}
#SuppressWarnings("serial")
public static class GetWindowRectException extends Exception {
public GetWindowRectException(String windowName) {
super("Window Rect not found for " + windowName);
}
}
public static void main(String[] args) {
String windowName = "Document - WordPad";
int[] rect;
try {
rect = GetWindowRect.getRect(windowName);
System.out.printf("The corner locations for the window \"%s\" are %s",
windowName, Arrays.toString(rect));
} catch (GetWindowRect.WindowNotFoundException e) {
e.printStackTrace();
} catch (GetWindowRect.GetWindowRectException e) {
e.printStackTrace();
}
}
}
Of course for this to work, the JNA libraries would need to be downloaded and placed on the Java classpath or in your IDE's build path.
This is easy to do with the help of the end user. Just get them to click on a point in a screen shot.
E.G.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
/** Getting a point of interest on the screen.
Requires the MotivatedEndUser API - sold separately. */
class GetScreenPoint {
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
final Dimension screenSize = Toolkit.getDefaultToolkit().
getScreenSize();
final BufferedImage screen = robot.createScreenCapture(
new Rectangle(screenSize));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel screenLabel = new JLabel(new ImageIcon(screen));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension(
(int)(screenSize.getWidth()/2),
(int)(screenSize.getHeight()/2)));
final Point pointOfInterest = new Point();
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel pointLabel = new JLabel(
"Click on any point in the screen shot!");
panel.add(pointLabel, BorderLayout.SOUTH);
screenLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
pointOfInterest.setLocation(me.getPoint());
pointLabel.setText(
"Point: " +
pointOfInterest.getX() +
"x" +
pointOfInterest.getY());
}
});
JOptionPane.showMessageDialog(null, panel);
System.out.println("Point of interest: " + pointOfInterest);
}
});
}
}
Typical output
Point of interest: java.awt.Point[x=342,y=43]
Press any key to continue . . .
A little late to the party here but will add this to potentially save others a little time. If you are using a more recent version of JNA then WindowUtils.getAllWindows() will make this much easier to accomplish.
I am using the most recent stable versions as of this post from the following maven locations:
JNA Platform - net.java.dev.jna:jna-platform:5.2.0
JNA Core - net.java.dev.jna:jna:5.2.0
Java 8 Lambda (Edit: rect is a placeholder and will need to be final or effectively final to work in a lambda)
//Find IntelliJ IDEA Window
//import java.awt.Rectangle;
final Rectangle rect = new Rectangle(0, 0, 0, 0); //needs to be final or effectively final for lambda
WindowUtils.getAllWindows(true).forEach(desktopWindow -> {
if (desktopWindow.getTitle().contains("IDEA")) {
rect.setRect(desktopWindow.getLocAndSize());
}
});
Other Java
//Find IntelliJ IDEA Window
Rectangle rect = null;
for (DesktopWindow desktopWindow : WindowUtils.getAllWindows(true)) {
if (desktopWindow.getTitle().contains("IDEA")) {
rect = desktopWindow.getLocAndSize();
}
}
Then within a JPanel you can draw a captured image to fit (Will stretch image if different aspect ratios).
//import java.awt.Robot;
g2d.drawImage(new Robot().createScreenCapture(rect), 0, 0, getWidth(), getHeight(), this);