2026年7月9日 星期四

Glad and GLFW in Ubuntu

 1. Check previous article to install GLFW


2. Download Glad(https://glad.dav1d.de)

C/C++, OpenGL, gl(Version 3.3) --> Generate --> Download Zip file


3. File tree

├── glad.c

├── include/

│   ├── KHR/

│   │   └── khrplatform.h

│   └── glad/

│       └── glad.h

└── Hello_Window.cpp


4. Hello_World.cpp(A Sample code)

------------------------------------------------------------------------

#include <glad/glad.h>

#include <GLFW/glfw3.h>

#include <iostream>


void framebuffer_size_callback(GLFWwindow* window, int width, int height) {

    glViewport(0, 0, width, height);

}


// Process escape key to close the window

void processInput(GLFWwindow *window) {

    if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {

        glfwSetWindowShouldClose(window, true);

    }

}


int main() {

    // 1. Initialize GLFW

    if (!glfwInit()) {

        std::cerr << "Failed to initialize GLFW" << std::endl;

        return -1;

    }


    // 2. Configure GLFW (Targeting OpenGL 3.3 Core Profile)

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__

    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Required for macOS

#endif


    // 3. Create the window object

    GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL Hello World", NULL, NULL);

    if (window == NULL) {

        std::cerr << "Failed to create GLFW window" << std::endl;

        glfwTerminate();

        return -1;

    }

    glfwMakeContextCurrent(window);

    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);


    // 4. Initialize GLAD before calling any OpenGL functions

    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {

        std::cerr << "Failed to initialize GLAD" << std::endl;

        return -1;

    }


    // 5. The Render Loop

    while (!glfwWindowShouldClose(window)) {

        // Input handling

        processInput(window);


        // Rendering commands (Clear screen with a dark greenish-blue color)

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

        glClear(GL_COLOR_BUFFER_BIT);


        // Swap buffers and poll window events

        glfwSwapBuffers(window);

        glfwPollEvents();

    }


    // 6. Clean up resources

    glfwTerminate();

    return 0;

}

------------------------------------------------------------------------


5. Build code

g++ Hello_World.cpp glad.c -I./include -lglfw -lGL -ldl -o Hello_Window



沒有留言:

張貼留言