Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LWJGL Window Object
package engine;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.GL_TRUE;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.system.MemoryUtil.NULL;
public class Window {
private final String title;
private int width;
private int height;
private long windowHandle;
private boolean resized;
private boolean vSync;
public Window(String windowTitle, int width, int height, boolean vSync) {
this.title = windowTitle;
this.width = width;
this.height = height;
this.vSync = vSync;
this.resized = false;
}
public void init() {
GLFWErrorCallback.createPrint(System.err).set();
if (!glfwInit()) {
throw new IllegalStateException("Unable to initialise GLFW");
}
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
windowHandle = glfwCreateWindow(width, height, title, NULL, NULL);
if (windowHandle == NULL) {
throw new RuntimeException("Failed to create the GLFW Window");
}
//Setup resize callback
glfwSetFramebufferSizeCallback(windowHandle, (windowHandle, width, height) -> {
this.width = width;
this.height = height;
this.setResized(true);
});
glfwSetKeyCallback(windowHandle, (window, key, scancode, action, mods) -> {
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
glfwSetWindowShouldClose(window, true);
}
});
GLFWVidMode vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(
windowHandle,
(vidMode.width() - width) / 2,
(vidMode.height() - height) / 2
);
glfwMakeContextCurrent(windowHandle);
if (isvSync()){
glfwSwapInterval(1);
}
glfwShowWindow(windowHandle);
GL.createCapabilities();
glClearColor(0.3f, 0.4f, 0.2f, 0.1f);
}
public void setClearColor(float r, float g, float b, float alpha) {
glClearColor(r, g, b, alpha);
}
public boolean isKeyPressed(int keyCode) {
return glfwGetKey(windowHandle, keyCode) == GLFW_PRESS;
}
public void setResized(boolean resized) {
this.resized = resized;
}
public boolean requestClose() {
return glfwWindowShouldClose(windowHandle);
}
public boolean isvSync() {
return vSync;
}
public String getTitle() {
return title;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public boolean isResized() {
return resized;
}
public void setvSync(boolean vSync) {
this.vSync = vSync;
}
public void update(){
glfwSwapBuffers(windowHandle);
glfwPollEvents();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.