Example usage for org.lwjgl.opengl GL createCapabilities

List of usage examples for org.lwjgl.opengl GL createCapabilities

Introduction

In this page you can find the example usage for org.lwjgl.opengl GL createCapabilities.

Prototype

public static GLCapabilities createCapabilities() 

Source Link

Document

Creates a new GLCapabilities instance for the OpenGL context that is current in the current thread.

Usage

From source file:net.caseif.cubic.gl.GraphicsMain.java

License:Open Source License

private void initGL() {
    GL.createCapabilities();
    glClearColor(0.67f, 0.77f, 0.95f, 1f);
}

From source file:net.wolf.wljglplayground.PlayRenderer.java

License:Open Source License

public void init() {
    glfwMakeContextCurrent(window);//w  ww.  ja va 2  s .  c om

    GL.createCapabilities();

    debugProc = GLUtil.setupDebugMessageCallback();

    String glVersionString = glGetString(GL_VERSION);
    LOG.info(glVersionString);

    glfwSwapInterval(0);

    glEnable(GL_DEPTH_TEST);
    glViewport(0, 0, width, height);

    scene.initScene(width, height);
}

From source file:net._5tingr4y.openrpg.lwjgl.OpenGLHandler.java

License:Open Source License

public void setupOpenGL() {
    Log.info(this, "OpenGL setup started");

    glfwSetErrorCallback(errorCallback = GLFWErrorCallback.createPrint(System.err));

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

    //configure window
    glfwDefaultWindowHints(); //make sure we have the default window hints (should already be, just to be sure)
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); //window will stay hidden after creation
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); //window will not be resizable

    long monitor = fullscreen ? glfwGetPrimaryMonitor() : NULL;
    window = glfwCreateWindow(width, height, "OpenRPG", monitor, NULL);

    if (window == NULL)
        throw new RuntimeException("Failed to create the GLFW window");

    //get the resolution of the primary monitor
    GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

    if (!fullscreen) {
        glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
    }//from w w  w . j  a v a 2s. c  o m

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

    //enable v-sync
    glfwSwapInterval(1);

    //make the window visible
    glfwShowWindow(window);

    // 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 GLCapabilities instance and makes the OpenGL
    // bindings available for use.
    GL.createCapabilities();

    //set the clear color
    GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    initialized = true;
    Log.info(this, "OpenGL setup finished");
}

From source file:opengl.demo.OpenGLDemo.java

public void loop() {
    GL.createCapabilities();
    glClearColor(0f, 0f, 0f, 1f);//from   ww  w  .j ava  2s.  c o  m
    while (GLFW.glfwWindowShouldClose(window) == GL_FALSE) {
        glClear(GL_COLOR_BUFFER_BIT);

        drawGrid();
        glColor3f(1.0f, 1.0f, 0.0f);
        drawTriangle();
        glPushMatrix();
        theta++;
        glRotatef(theta, 0, 0, 1);
        glTranslatef(0.5f, 0f, 0f);
        glScalef(0.5f, 0.5f, 0.5f);
        glColor3f(0.0f, 0.0f, 1.0f);
        drawTriangle();

        // White MOON
        glRotatef(5 * theta, 0, 0, 1);
        glTranslatef(0.5f, 0.0f, 0.0f);
        glScalef(0.5f, 0.5f, 0.5f);
        glColor3f(1.0f, 1.0f, 1.0f);
        drawTriangle();

        glPopMatrix();

        GLFW.glfwSwapBuffers(window);
        GLFW.glfwPollEvents();
    }
}

From source file:opengl.test.OpenGL.java

public OpenGL() {
    GLFW.glfwSetErrorCallback(errorCallback);
    if (GLFW.glfwInit() != GLFW.GLFW_TRUE) {
        throw new RuntimeException("Khong the khoi tao glfw");
    }/*from  ww  w . j  a v  a 2  s  .c o m*/

    GLFW.glfwDefaultWindowHints();
    GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 3);// su dung opengl phien ban 3.2 --> GLSL phien bn 1.50
    GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 2);
    GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_PROFILE, GLFW.GLFW_OPENGL_CORE_PROFILE);
    GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_FORWARD_COMPAT, GLFW.GLFW_TRUE);

    this.windowID = GLFW.glfwCreateWindow(this.width, this.height, this.title, MemoryUtil.NULL,
            MemoryUtil.NULL);
    if (this.windowID == MemoryUtil.NULL) {
        throw new RuntimeException("Khong the tao window");
    }

    GLFW.glfwMakeContextCurrent(windowID);
    GL.createCapabilities();
    GLFW.glfwSwapInterval(1);

    this.keyCallback = new GLFWKeyCallback() {
        @Override
        public void invoke(long arg0, int arg1, int arg2, int arg3, int arg4) {
            if (arg1 == GLFW.GLFW_KEY_ESCAPE && arg3 != GLFW.GLFW_RELEASE) {
                GLFW.glfwSetWindowShouldClose(windowID, GL11.GL_TRUE);
            }
            OpenGL.this.keyCallback(arg0, arg1, arg2, arg3, arg4);
        }
    };
    this.windowSizeCallback = new GLFWWindowSizeCallback() {
        @Override
        public void invoke(long arg0, int arg1, int arg2) {
            GL11.glViewport(0, 0, arg1, arg2);// view port 0,0 goc tre, arg1, arg2 goc duoi cung !
        }

    };
    this.cursorPosCallback = new GLFWCursorPosCallback() {
        @Override
        public void invoke(long arg0, double arg1, double arg2) {
            OpenGL.this.cursorCallback(arg0, arg1, arg2);
        }

    };
    GLFW.glfwSetWindowSizeCallback(windowID, windowSizeCallback);
    GLFW.glfwSetKeyCallback(windowID, keyCallback);
    GLFW.glfwSetCursorPosCallback(windowID, cursorPosCallback);
    try {
        this.init();
        this.loop();
    } catch (InterruptedException ex) {
        throw new RuntimeException("Loop !!!1");
    }

}

From source file:org.jogl.api.screen.Window.java

License:Apache License

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 GLCapabilities instance and makes the OpenGL
    // bindings available for use.
    GLCapabilities capabilities = GL.createCapabilities();

    // Set the clear color
    screen.init();/*from w  w w . j  ava 2 s .  com*/

    // Run the rendering loop until the user has attempted to close
    // the window or has pressed the ESCAPE key.
    long before = System.currentTimeMillis() - 1;
    while (glfwWindowShouldClose(windowID) == GLFW_FALSE) {
        float time = (System.currentTimeMillis() - before) / 1000f;
        before = System.currentTimeMillis() - 1;
        screen.update(time);
        screen.draw();

        keyboard.update();
        mouse.update();

        glfwSwapBuffers(windowID);
        glfwPollEvents();
    }

    screen.deinit();
}

From source file:org.jwjgl.samples.Introduction.java

License:Open Source License

/**
 * The main function will create a 640x480 window and renders a rotating
 * triangle until the window gets closed.
 *
 * @param args the command line arguments
 *//*from   ww  w  .j  a  va  2  s . c o  m*/
public static void main(String[] args) {
    long window;

    /* Set the error callback */
    glfwSetErrorCallback(errorCallback);

    /* Initialize GLFW */
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize GLFW");
    }

    /* Create window */
    window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
    if (window == NULL) {
        glfwTerminate();
        throw new RuntimeException("Failed to create the GLFW window");
    }

    /* Center the window on screen */
    GLFWVidMode vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    glfwSetWindowPos(window, (vidMode.width() - 640) / 2, (vidMode.height() - 480) / 2);

    /* Create OpenGL context */
    glfwMakeContextCurrent(window);
    GL.createCapabilities();

    /* Enable vertical synchronization */
    glfwSwapInterval(1);

    /* Set the key callback */
    glfwSetKeyCallback(window, keyCallback);

    /* Declare buffers for using inside the loop */
    IntBuffer width = BufferUtils.createIntBuffer(1);
    IntBuffer height = BufferUtils.createIntBuffer(1);

    /* Loop until window gets closed */
    while (!glfwWindowShouldClose(window)) {
        float ratio;

        /* Get width and height to calcualte the ratio */
        glfwGetFramebufferSize(window, width, height);
        ratio = width.get() / (float) height.get();

        /* Rewind buffers for next get */
        width.rewind();
        height.rewind();

        /* Set viewport and clear screen */
        glViewport(0, 0, width.get(), height.get());
        glClear(GL_COLOR_BUFFER_BIT);

        /* Set ortographic projection */
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(-ratio, ratio, -1f, 1f, 1f, -1f);
        glMatrixMode(GL_MODELVIEW);

        /* Rotate matrix */
        glLoadIdentity();
        glRotatef((float) glfwGetTime() * 50f, 0f, 0f, 1f);

        /* Render triangle */
        glBegin(GL_TRIANGLES);
        glColor3f(1f, 0f, 0f);
        glVertex3f(-0.6f, -0.4f, 0f);
        glColor3f(0f, 1f, 0f);
        glVertex3f(0.6f, -0.4f, 0f);
        glColor3f(0f, 0f, 1f);
        glVertex3f(0f, 0.6f, 0f);
        glEnd();

        /* Swap buffers and poll Events */
        glfwSwapBuffers(window);
        glfwPollEvents();

        /* Flip buffers for next loop */
        width.flip();
        height.flip();
    }

    /* Release window and its callbacks */
    glfwDestroyWindow(window);
    keyCallback.free();

    /* Terminate GLFW and release the error callback */
    glfwTerminate();
    errorCallback.free();
}

From source file:org.lwjgl.demo.game.SpaceGame.java

License:Open Source License

private void init() throws IOException {
    if (!glfwInit())
        throw new IllegalStateException("Unable to initialize GLFW");

    glfwDefaultWindowHints();/*from   w ww .j  ava2  s  .  co m*/
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);

    long monitor = glfwGetPrimaryMonitor();
    GLFWVidMode vidmode = glfwGetVideoMode(monitor);
    if (!windowed) {
        width = vidmode.width();
        height = vidmode.height();
    }
    window = glfwCreateWindow(width, height, "Little Space Shooter Game", !windowed ? monitor : 0L, NULL);
    if (window == NULL) {
        throw new AssertionError("Failed to create the GLFW window");
    }
    glfwSetCursor(window, glfwCreateStandardCursor(GLFW_CROSSHAIR_CURSOR));

    glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() {
        public void invoke(long window, int width, int height) {
            if (width > 0 && height > 0 && (SpaceGame.this.width != width || SpaceGame.this.height != height)) {
                SpaceGame.this.width = width;
                SpaceGame.this.height = height;
            }
        }
    });

    System.out.println("Press W/S to move forward/backward");
    System.out.println("Press L.Ctrl/Spacebar to move down/up");
    System.out.println("Press A/D to strafe left/right");
    System.out.println("Press Q/E to roll left/right");
    System.out.println("Hold the left mouse button to shoot");
    System.out.println("Hold the right mouse button to rotate towards the mouse cursor");
    glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
        public void invoke(long window, int key, int scancode, int action, int mods) {
            if (key == GLFW_KEY_UNKNOWN)
                return;
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
                glfwSetWindowShouldClose(window, true);
            }
            if (action == GLFW_PRESS || action == GLFW_REPEAT) {
                keyDown[key] = true;
            } else {
                keyDown[key] = false;
            }
        }
    });
    glfwSetCursorPosCallback(window, cpCallback = new GLFWCursorPosCallback() {
        public void invoke(long window, double xpos, double ypos) {
            float normX = (float) ((xpos - width / 2.0) / width * 2.0);
            float normY = (float) ((ypos - height / 2.0) / height * 2.0);
            SpaceGame.this.mouseX = Math.max(-width / 2.0f, Math.min(width / 2.0f, normX));
            SpaceGame.this.mouseY = Math.max(-height / 2.0f, Math.min(height / 2.0f, normY));
        }
    });
    glfwSetMouseButtonCallback(window, mbCallback = new GLFWMouseButtonCallback() {
        public void invoke(long window, int button, int action, int mods) {
            if (button == GLFW_MOUSE_BUTTON_LEFT) {
                if (action == GLFW_PRESS)
                    leftMouseDown = true;
                else if (action == GLFW_RELEASE)
                    leftMouseDown = false;
            } else if (button == GLFW_MOUSE_BUTTON_RIGHT) {
                if (action == GLFW_PRESS)
                    rightMouseDown = true;
                else if (action == GLFW_RELEASE)
                    rightMouseDown = false;
            }
        }
    });
    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);
    glfwShowWindow(window);

    IntBuffer framebufferSize = BufferUtils.createIntBuffer(2);
    nglfwGetFramebufferSize(window, memAddress(framebufferSize), memAddress(framebufferSize) + 4);
    width = framebufferSize.get(0);
    height = framebufferSize.get(1);
    caps = GL.createCapabilities();
    if (!caps.OpenGL20) {
        throw new AssertionError("This demo requires OpenGL 2.0.");
    }
    debugProc = GLUtil.setupDebugMessageCallback();

    /* Create all needed GL resources */
    createCubemapTexture();
    createFullScreenQuad();
    createCubemapProgram();
    createShipProgram();
    createParticleProgram();
    createShip();
    createAsteroid();
    createShotProgram();
    createSphere();

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}

From source file:org.lwjgl.demo.glfw.Events.java

License:Open Source License

private static void demo() {
    if (Platform.get() == Platform.WINDOWS) {
        if (User32.Functions.SetThreadDpiAwarenessContext != NULL) {
            SetThreadDpiAwarenessContext(IsValidDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)
                    ? DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
                    : DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
        }/*from   w ww .  ja  v  a2s  .c  o m*/
    }

    int WIDTH = 640;
    int HEIGHT = 480;

    try (MemoryStack s = stackPush()) {
        IntBuffer pi = s.mallocInt(1);
        IntBuffer pj = s.mallocInt(1);

        FloatBuffer px = s.mallocFloat(1);
        FloatBuffer py = s.mallocFloat(1);

        long primaryMonitor = glfwGetPrimaryMonitor();

        PointerBuffer monitors = Objects.requireNonNull(glfwGetMonitors());
        for (int i = 0; i < monitors.remaining(); i++) {
            long monitor = monitors.get(i);

            System.out.format("%nMonitor %d:%n----------%n", i);
            System.out.format("\tName: %s%s%n", glfwGetMonitorName(monitor),
                    primaryMonitor == monitor ? " (primary)" : "");

            glfwGetMonitorPhysicalSize(monitor, pi, pj);
            int widthMM = pi.get(0);
            int heightMM = pj.get(0);

            glfwGetMonitorPos(monitor, pi, pj);
            int xpos = pi.get(0);
            int ypos = pj.get(0);

            glfwGetMonitorContentScale(monitor, px, py);
            float xscale = px.get(0);
            float yscale = py.get(0);

            if (primaryMonitor == monitor && Platform.get() != Platform.MACOSX) {
                WIDTH = round(WIDTH * xscale);
                HEIGHT = round(HEIGHT * yscale);
            }

            double MM_TO_INCH = 0.0393701;

            GLFWVidMode mode = Objects.requireNonNull(glfwGetVideoMode(monitor));
            System.out.format("\tCurrent mode    : %d x %d @ %d Hz (%s, R%dG%dB%d)%n", mode.width(),
                    mode.height(), mode.refreshRate(), ratio(mode.width(), mode.height()), mode.redBits(),
                    mode.greenBits(), mode.blueBits());
            System.out.format("\tContent scale   : %f x %f%n", xscale, yscale);
            if (xscale != 1.0f || yscale != 1.0f) {
                System.out.format("\tContent size    : %d x %d%n", round(mode.width() / xscale),
                        round(mode.height() / yscale));
            }
            System.out.format("\tPhysical size   : %dmm x %dmm (%d\", %d ppi)%n", widthMM, heightMM,
                    round(Math.sqrt(widthMM * widthMM + heightMM * heightMM) * MM_TO_INCH), // inches
                    round(mode.width() / (widthMM * MM_TO_INCH)) // dpi
            );
            System.out.format("\tVirtual position: %d, %d%n", xpos, ypos);
        }
    }

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);

    long window = glfwCreateWindow(WIDTH, HEIGHT, "GLFW Event Demo", NULL, NULL);
    if (window == NULL) {
        throw new IllegalStateException("Failed to create GLFW window.");
    }

    System.out.format("%nWindow opened:%n--------------%n");
    try (MemoryStack s = stackPush()) {
        IntBuffer pi = s.mallocInt(1);
        IntBuffer pj = s.mallocInt(1);
        IntBuffer pk = s.mallocInt(1);
        IntBuffer pl = s.mallocInt(1);

        FloatBuffer px = s.mallocFloat(1);
        FloatBuffer py = s.mallocFloat(1);

        glfwGetWindowSize(window, pi, pj);
        System.out.format("\tSize: %d x %d%n", pi.get(0), pj.get(0));
        glfwGetWindowFrameSize(window, pi, pj, pk, pl);
        System.out.format("\tFrame size: %d, %d, %d, %d%n", pi.get(0), pj.get(0), pk.get(0), pl.get(0));
        glfwGetWindowContentScale(window, px, py);
        System.out.format("\tContent scale: %f x %f%n", px.get(0), py.get(0));
        glfwGetFramebufferSize(window, pi, pj);
        System.out.format("\tFramebuffer size: %d x %d%n", pi.get(0), pj.get(0));
        glfwGetWindowPos(window, pi, pj);
        System.out.format("\tPosition: %d, %d%n%n", pi.get(0), pj.get(0));
    }

    IntBuffer w = memAllocInt(1);
    IntBuffer h = memAllocInt(1);
    IntBuffer comp = memAllocInt(1);

    long cursor;

    // Cursor
    {
        ByteBuffer png;
        try {
            png = ioResourceToByteBuffer("demo/cursor.png", 1024);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        ByteBuffer pixels = Objects.requireNonNull(stbi_load_from_memory(png, w, h, comp, 0));
        try (GLFWImage img = GLFWImage.malloc().set(w.get(0), h.get(0), pixels)) {
            cursor = glfwCreateCursor(img, 0, 8);
            glfwSetCursor(window, cursor);
        } finally {
            stbi_image_free(pixels);
        }
    }

    // Icons
    {
        ByteBuffer icon16;
        ByteBuffer icon32;
        try {
            icon16 = ioResourceToByteBuffer("lwjgl16.png", 2048);
            icon32 = ioResourceToByteBuffer("lwjgl32.png", 4096);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        try (GLFWImage.Buffer icons = GLFWImage.malloc(2)) {
            ByteBuffer pixels16 = Objects.requireNonNull(stbi_load_from_memory(icon16, w, h, comp, 4));
            icons.position(0).width(w.get(0)).height(h.get(0)).pixels(pixels16);

            ByteBuffer pixels32 = Objects.requireNonNull(stbi_load_from_memory(icon32, w, h, comp, 4));
            icons.position(1).width(w.get(0)).height(h.get(0)).pixels(pixels32);

            icons.position(0);
            glfwSetWindowIcon(window, icons);

            stbi_image_free(pixels32);
            stbi_image_free(pixels16);
        }
    }

    memFree(comp);
    memFree(h);
    memFree(w);

    glfwSetMonitorCallback((monitor, event) -> printEvent("Monitor", "%s", monitor,
            event == GLFW_CONNECTED ? "connected" : "disconnected"));
    glfwSetJoystickCallback((joy, event) -> printEvent("Joystick", "%s %s", joy, glfwGetJoystickName(joy),
            event == GLFW_CONNECTED ? "connected" : "disconnected"));

    glfwSetWindowPosCallback(window,
            (windowHnd, xpos, ypos) -> printEvent("moved to %d, %d", windowHnd, xpos, ypos));
    glfwSetWindowSizeCallback(window,
            (windowHnd, width, height) -> printEvent("resized to %d x %d", windowHnd, width, height));
    glfwSetWindowCloseCallback(window, windowHnd -> printEvent("closed", windowHnd));
    glfwSetWindowRefreshCallback(window, windowHnd -> printEvent("refreshed", windowHnd));
    glfwSetWindowFocusCallback(window,
            (windowHnd, focused) -> printEvent(focused ? "gained focus" : "lost focus", windowHnd));
    glfwSetWindowIconifyCallback(window,
            (windowHnd, iconified) -> printEvent(iconified ? "iconified" : "restored", windowHnd));
    glfwSetWindowMaximizeCallback(window,
            (windowHnd, maximized) -> printEvent(maximized ? "maximized" : "restored", windowHnd));
    glfwSetWindowContentScaleCallback(window, (windowHnd, xscale,
            yscale) -> printEvent("content scale changed to %d x %d", windowHnd, xscale, yscale));

    glfwSetFramebufferSizeCallback(window, (windowHnd, width,
            height) -> printEvent("framebuffer resized to %d x %d", windowHnd, width, height));

    glfwSetKeyCallback(window, (windowHnd, key, scancode, action, mods) -> {
        String state;
        switch (action) {
        case GLFW_RELEASE:
            state = "released";
            break;
        case GLFW_PRESS:
            state = "pressed";
            break;
        case GLFW_REPEAT:
            state = "repeated";
            break;
        default:
            throw new IllegalArgumentException(String.format("Unsupported key action: 0x%X", action));
        }

        printEvent("key %s[%s - %d] was %s", windowHnd, getModState(mods), KEY_CODES.get(key), scancode, state);

        if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
            glfwSetWindowShouldClose(windowHnd, true);
        }
    });
    glfwSetCharCallback(window,
            (windowHnd, codepoint) -> printEvent("char %s", windowHnd, Character.toString((char) codepoint)));
    glfwSetCharModsCallback(window, (windowHnd, codepoint, mods) -> printEvent("char mods %s%s", windowHnd,
            getModState(mods), Character.toString((char) codepoint)));
    glfwSetMouseButtonCallback(window, (windowHnd, button, action, mods) -> {
        String state;
        switch (action) {
        case GLFW_RELEASE:
            state = "released";
            break;
        case GLFW_PRESS:
            state = "pressed";
            break;
        default:
            throw new IllegalArgumentException(String.format("Unsupported mouse button action: 0x%X", action));
        }
        printEvent("mouse button %s[0x%X] was %s", windowHnd, getModState(mods), button, state);
    });
    glfwSetCursorPosCallback(window,
            (windowHnd, xpos, ypos) -> printEvent("cursor moved to %f, %f", windowHnd, xpos, ypos));
    glfwSetCursorEnterCallback(window,
            (windowHnd, entered) -> printEvent("cursor %s", windowHnd, entered ? "entered" : "left"));
    glfwSetScrollCallback(window,
            (windowHnd, xoffset, yoffset) -> printEvent("scroll by %f, %f", windowHnd, xoffset, yoffset));
    glfwSetDropCallback(window, (windowHnd, count, names) -> {
        printEvent("drop %d file%s", windowHnd, count, count == 1 ? "" : "s");

        for (int i = 0; i < count; i++) {
            System.out.format("\t%d: %s%n", i + 1, GLFWDropCallback.getName(names, i));
        }
    });

    glfwMakeContextCurrent(window);
    GL.createCapabilities();

    glfwShowWindow(window);
    glfwSwapInterval(1);

    glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
    while (!glfwWindowShouldClose(window)) {
        glfwWaitEvents();

        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(window);
    }

    glfwFreeCallbacks(window);
    Objects.requireNonNull(glfwSetJoystickCallback(null)).free();
    Objects.requireNonNull(glfwSetMonitorCallback(null)).free();

    glfwDestroyCursor(cursor);
    glfwDestroyWindow(window);
}

From source file:org.lwjgl.demo.glfw.Gears.java

License:Open Source License

private void init() {
    GLFWErrorCallback.createPrint().set();
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize glfw");
    }//ww w  .  j a  v a2  s  .  co  m

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
    if (Platform.get() == Platform.MACOSX) {
        glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE);
    }

    int WIDTH = 300;
    int HEIGHT = 300;

    long window = glfwCreateWindow(WIDTH, HEIGHT, "GLFW Gears Demo", NULL, NULL);
    if (window == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }

    /*
      // This code did the equivalent of glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE) before GLFW 3.3
    if ( Platform.get() == Platform.MACOSX ) {
       long cocoaWindow = glfwGetCocoaWindow(window);
            
       long objc_msgSend = ObjCRuntime.getLibrary().getFunctionAddress("objc_msgSend");
       long contentView = invokePPP(objc_msgSend, cocoaWindow, sel_getUid("contentView"));
            
       invokePPV(objc_msgSend, contentView, sel_getUid("setWantsBestResolutionOpenGLSurface:"), false);
            
       boolean bool = invokePPZ(objc_msgSend, contentView, sel_getUid("wantsBestResolutionOpenGLSurface"));
       System.out.println("wantsBestResolutionOpenGLSurface = " + bool);
    }
    */

    glfwSetWindowSizeLimits(window, WIDTH, HEIGHT, GLFW_DONT_CARE, GLFW_DONT_CARE);
    //glfwSetWindowAspectRatio(window, 1, 1);

    long monitor = glfwGetPrimaryMonitor();

    GLFWVidMode vidmode = Objects.requireNonNull(glfwGetVideoMode(monitor));
    // Center window
    glfwSetWindowPos(window, (vidmode.width() - WIDTH) / 2, (vidmode.height() - HEIGHT) / 2);

    glfwSetKeyCallback(window, (windowHnd, key, scancode, action, mods) -> {
        if (action != GLFW_RELEASE) {
            return;
        }

        switch (key) {
        case GLFW_KEY_ESCAPE:
            glfwSetWindowShouldClose(windowHnd, true);
            break;
        case GLFW_KEY_A:
            glfwRequestWindowAttention(windowHnd);
            break;
        case GLFW_KEY_F:
            if (glfwGetWindowMonitor(windowHnd) == NULL) {
                try (MemoryStack s = stackPush()) {
                    IntBuffer a = s.ints(0);
                    IntBuffer b = s.ints(0);

                    glfwGetWindowPos(windowHnd, a, b);
                    xpos = a.get(0);
                    ypos = b.get(0);

                    glfwGetWindowSize(windowHnd, a, b);
                    width = a.get(0);
                    height = b.get(0);
                }
                glfwSetWindowMonitor(windowHnd, monitor, 0, 0, vidmode.width(), vidmode.height(),
                        vidmode.refreshRate());
                glfwSwapInterval(1);
            }
            break;
        case GLFW_KEY_G:
            glfwSetInputMode(windowHnd, GLFW_CURSOR,
                    glfwGetInputMode(windowHnd, GLFW_CURSOR) == GLFW_CURSOR_NORMAL ? GLFW_CURSOR_DISABLED
                            : GLFW_CURSOR_NORMAL);
            break;
        case GLFW_KEY_O:
            glfwSetWindowOpacity(window, glfwGetWindowOpacity(window) == 1.0f ? 0.5f : 1.0f);
            break;
        case GLFW_KEY_R:
            glfwSetWindowAttrib(windowHnd, GLFW_RESIZABLE, 1 - glfwGetWindowAttrib(windowHnd, GLFW_RESIZABLE));
            break;
        case GLFW_KEY_U:
            glfwSetWindowAttrib(windowHnd, GLFW_DECORATED, 1 - glfwGetWindowAttrib(windowHnd, GLFW_DECORATED));
            break;
        case GLFW_KEY_W:
            if (glfwGetWindowMonitor(windowHnd) != NULL) {
                glfwSetWindowMonitor(windowHnd, NULL, xpos, ypos, width, height, 0);
            }
            break;
        }
    });

    glfwSetFramebufferSizeCallback(window, Gears::framebufferSizeChanged);

    glfwSetWindowRefreshCallback(window, windowHnd -> {
        renderLoop();
        glfwSwapBuffers(windowHnd);
    });

    glfwMakeContextCurrent(window);
    GL.createCapabilities();
    debugProc = GLUtil.setupDebugMessageCallback();

    glfwSwapInterval(1);
    glfwShowWindow(window);

    glfwInvoke(window, null, Gears::framebufferSizeChanged);

    this.window = window;
}