Files
cool-game/src/main/java/org/hirw/game/Window.java
2025-08-17 15:11:42 +01:00

103 lines
2.7 KiB
Java

package org.hirw.game;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
import org.lwjgl.Version;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
public class Window {
private int width, height;
private final String title;
private long glfwWindow;
private static Window window = null;
private Window() {
this.width = 1280;
this.height = 720;
this.title = "game";
}
public static Window get() {
if (Window.window == null) {
Window.window = new Window();
}
return Window.window;
}
public void blastOff() {
setup();
loop();
cleanUp();
}
private void logVersion() {
System.out.println("LWJGL Version: " + Version.getVersion());
}
private void setup() {
logVersion();
GLFWErrorCallback.createPrint(System.err).set();
if (!glfwInit()) throw new IllegalStateException("Unable to initialize GLFW");
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
glfwWindow = glfwCreateWindow(this.width, this.height, "Hello World!", NULL, NULL);
if (glfwWindow == NULL) throw new RuntimeException("Failed to create the GLFW window");
// glfwSetKeyCallback(
// glfwWindow,
// (glfwWindow, key, scancode, action, mods) -> {
// if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
// glfwSetWindowShouldClose(glfwWindow, true);
// });
//
// try (MemoryStack stack = stackPush()) {
// IntBuffer pWidth = stack.mallocInt(1);
// IntBuffer pHeight = stack.mallocInt(1);
// glfwGetWindowSize(glfwWindow, pWidth, pHeight);
// GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
// }
glfwSetCursorPosCallback(glfwWindow, Mouse::cursorPositionCallback);
glfwSetMouseButtonCallback(glfwWindow, Mouse::mouseButtonCallback);
glfwSetKeyCallback(glfwWindow, Keyboard::keyCallback);
glfwSetWindowTitle(glfwWindow, this.title);
glfwMakeContextCurrent(glfwWindow);
glfwSwapInterval(1);
glfwShowWindow(glfwWindow);
GL.createCapabilities();
glClearColor(1.0f, 0.0f, 2.0f, 0.0f);
}
private void loop() {
while (!glfwWindowShouldClose(glfwWindow)) {
if (Mouse.isPressed(Mouse.Buttons.LEFT)) {
System.out.println("LEFT CLICKED");
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glfwSwapBuffers(glfwWindow);
glfwPollEvents();
}
}
private void cleanUp() {
glfwFreeCallbacks(glfwWindow);
glfwDestroyWindow(glfwWindow);
glfwTerminate();
glfwSetErrorCallback(null).free();
}
}