Изменение размера окна не влияет на содержимое

У меня проблема с изменением размера окна на LWJGL3 и GLFW. Я могу изменить размер окна, однако то, что в него отображается, не зависит от него, скорее всего, это проблема с координатами. Я перечислил свои классы Display и Main.

public static void init() {
    // Setup an error callback. The default implementation
    // will print the error message in System.err.
    GLFWErrorCallback.createPrint(System.err).set();

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

    // Configure GLFW
    glfwDefaultWindowHints(); // optional, the current window hints are already the default
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
    glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable

    // Create the window
    window = glfwCreateWindow(800, 500, "Game Indev", 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, (window, key, scancode, action, mods) -> {
        if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE )
            glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop
    });

    // Get the thread stack and push a new frame
    try ( MemoryStack stack = stackPush() ) {
        IntBuffer pWidth = stack.mallocInt(1); // int*
        IntBuffer pHeight = stack.mallocInt(1); // int*

        // Get the window size passed to glfwCreateWindow
        glfwGetWindowSize(window, pWidth, pHeight);

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

        // Center the window
        glfwSetWindowPos(
                window,
                (vidmode.width() - pWidth.get(0)) / 2,
                (vidmode.height() - pHeight.get(0)) / 2
        );
    } // the stack frame is popped automatically

    // Make the OpenGL context current
    glfwMakeContextCurrent(window);
    // Enable v-sync
    glfwSwapInterval(1);

    // Make the window visible
    glfwShowWindow(window);
}

И мой основной класс здесь:

// The window handle

public static void main(String[] args) {
    System.out.println(Version.getVersion());

    Display.init();

    Loader loader = new Loader();
    Renderer renderer = new Renderer();
    // This line checks the context and capabilities
    GL.createCapabilities();
    float[] vertices = {

            -0.5f, 0.5f, 0f,
            -0.5f, -0.5f, 0f,
            0.5f, -0.5f, 0f,
            0.5f, -0.5f, 0f,
            0.5f, 0.5f, 0f,
            -0.5f, 0.5f, 0f
    };
    RawModel model = loader.loadToVao(vertices);

    // Set the clear color initially
    glClearColor(1.0f, 0.0f, 0.0f, 0.0f);

    /*
    THIS
    IS
    THE
    MAIN
    GAME
    LOGIC
    ---------------------------------------------------------------------------------
     */
    while ( !glfwWindowShouldClose(Display.window) ) {
        GL11.glClearColor(GameState.stateR, GameState.stateG, GameState.stateB, GameState.stateA);
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);

        renderer.renderModel(model);

        glfwSwapBuffers(Display.window); // swap the color buffers


        GameState.getStateInput();
        GameState.renderGameState(loader, renderer);
        glfwPollEvents();

    }

    //End of main loop -----------------------------------------------------------------

    // Free the window callbacks and destroy the window
    glfwFreeCallbacks(Display.window);
    glfwDestroyWindow(Display.window);

    // Terminate GLFW and free the error callback
    glfwTerminate();
    glfwSetErrorCallback(null).free();
}
// --------------------------------------------------------------------------------------------

У меня также есть представление о том, о чем я говорю.

Перед изменением размера После изменения размера Очевидно, я бы хотел, чтобы размер четырехугольника менялся вместе с экраном, чтобы в полноэкранном режиме был большой четырехугольник посередине, а не тот же размер в нижние левые координаты. Как бы я это сделал?


person Ea-r-th    schedule 07.06.2020    source источник


Ответы (1)


Для правильного изменения размера содержимого окна вам необходимо отреагировать на изменение размера окна с помощью:

glfwSetWindowSizeCallback(window, new GLFWWindowSizeCallback() {
        @Override
        public void invoke(long window, int argWidth, int argHeight) {
            resizeWindow(argWidth, argHeight);
        }
});

В resizeWindow (argWidth, argHeight) вам нужно установить область просмотра и пересчитать матрицу проекции (только если вы ее используете).

private void resizeWindow(int argWidth, int argHeight) {
    glViewport(0, 0, argWidth,argHeight);

    adjustProjectionMatrix(width, height); // recalculating projection matrix (only if you are using one)
}

РЕДАКТИРОВАТЬ:

Если вы используете LWJGL 2:

if (Display.wasResized()) {
    GL11.glViewport(0, 0, Display.getWidth(), Display.getHeight());

    adjustProjectionMatrix(Display.getWidth(), Display.getHeight()); // only if you are using one
}
person Tymo Tymo    schedule 07.06.2020
comment
Я не совсем понимаю синтаксис здесь, этот код вызывает множество ошибок, когда помещается в мой собственный, скорее всего, из-за того, что объект GLFWWindowSizeCallback является расширением абстрактного класса или чего-то еще. Как это исправить? Заранее спасибо. @tymo tymo - person Ea-r-th; 07.06.2020
comment
Вы используете LWJGL 2 или 3, потому что это написано в LWJGL 3. GLFWWindowSizeCallback не существует в LWJGL 2. - person Tymo Tymo; 07.06.2020
comment
Хорошо, поэтому я смог получить код, чтобы не выдавать никаких ошибок и запускать программу, однако четырехугольник просто исчезает, когда я изменяю размер окна @tymo tymo - person Ea-r-th; 08.06.2020
comment
Вы используете шейдеры. Может что-то не так с матрицей проекции (ее расчетом). У меня все отлично работает. - person Tymo Tymo; 08.06.2020