c++ - 为什么我的三角形画在窗口的左下侧

标签 c++ macos opengl graphics

我尝试学习 OpenGL 只是为了消磨时间,只是对计算机图形学感到好奇。我正在关注 Youtube channel FreeCodeCamp.org this 上的速成类(class)教程。

以下是基本创建窗口和绘制一些图元的代码。 (使用C++和OpenGL)

#include<iostream>
#include<glad/glad.h>
#include<GLFW/glfw3.h>

// Vertex Shader source code
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
"   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
//Fragment Shader source code
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
"   FragColor = vec4(0.8f, 0.3f, 0.02f, 1.0f);\n"
"}\n\0";



int main()
{
    // Initialize GLFW
    glfwInit();

    // Tell GLFW what version of OpenGL we are using 
    // In this case we are using OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    // Tell GLFW we are using the CORE profile
    // So that means we only have the modern functions
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //important for macOS users because i dont know it just is
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    // Create a GLFWwindow object of 800 by 800 pixels, naming it "YoutubeOpenGL"
    GLFWwindow* window = glfwCreateWindow(800, 800, "YoutubeOpenGL", NULL, NULL);
    // Error check if the window fails to create
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window and fuck this shit" << std::endl;
        glfwTerminate();
        return -1;
    }
    // Introduce the window into the current context
    glfwMakeContextCurrent(window);

    //Load GLAD so it configures OpenGL
    gladLoadGL();
    // Specify the viewport of OpenGL in the Window
    // In this case the viewport goes from x = 0, y = 0, to x = 800, y = 800
    glViewport(0, 0, 800, 800);



    // Create Vertex Shader Object and get its reference
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    // Attach Vertex Shader source to the Vertex Shader Object
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    // Compile the Vertex Shader into machine code
    glCompileShader(vertexShader);

    // Create Fragment Shader Object and get its reference
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    // Attach Fragment Shader source to the Fragment Shader Object
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    // Compile the Vertex Shader into machine code
    glCompileShader(fragmentShader);

    // Create Shader Program Object and get its reference
    GLuint shaderProgram = glCreateProgram();
    // Attach the Vertex and Fragment Shaders to the Shader Program
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    // Wrap-up/Link all the shaders together into the Shader Program
    glLinkProgram(shaderProgram);

    // Delete the now useless Vertex and Fragment Shader objects
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);



    // Vertices coordinates
    GLfloat vertices[] =
    {
        -0.5f, -0.5f * float(sqrt(3)) / 3, 0.0f, // Lower left corner
        0.5f, -0.5f * float(sqrt(3)) / 3, 0.0f, // Lower right corner
        0.0f, 0.5f * float(sqrt(3)) * 2 / 3, 0.0f, // Upper corner
    };

    // Create reference containers for the Vartex Array Object and the Vertex Buffer Object
    GLuint VAO[1], VBO[1];

    // Generate the VAO and VBO with only 1 object each
    glGenVertexArrays(1, VAO);
    glGenBuffers(1, VBO);

    // Make the VAO the current Vertex Array Object by binding it
    glBindVertexArray(VAO[0]);

    // Bind the VBO specifying it's a GL_ARRAY_BUFFER
    glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
    // Introduce the vertices into the VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Configure the Vertex Attribute so that OpenGL knows how to read the VBO
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    // Enable the Vertex Attribute so that OpenGL knows to use it
    glEnableVertexAttribArray(0);

    // Bind both the VBO and VAO to 0 so that we don't accidentally modify the VAO and VBO we created
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);



    // Main while loop
    while (!glfwWindowShouldClose(window))
    {
        // Specify the color of the background
        glClearColor(0.07f, 0.13f, 0.17f, 1.0f);
        // Clean the back buffer and assign the new color to it
        glClear(GL_COLOR_BUFFER_BIT);
        // Tell OpenGL which Shader Program we want to use
        glUseProgram(shaderProgram);
        // Bind the VAO so OpenGL knows to use it
        glBindVertexArray(VAO[0]);
        // Draw the triangle using the GL_TRIANGLES primitive
        glDrawArrays(GL_TRIANGLES, 0, 3);
        // Swap the back buffer with the front buffer
        glfwSwapBuffers(window);
        // Take care of all GLFW events
        glfwPollEvents();
    }



    // Delete all the objects we've created
    glDeleteVertexArrays(1, VAO);
    glDeleteBuffers(1, VBO);
    glDeleteProgram(shaderProgram);
    // Delete window before ending the program
    glfwDestroyWindow(window);
    // Terminate GLFW before ending the program
    glfwTerminate();
    return 0;
}

但结果我得到了这个作为输出 image

我认为代码是在中心绘制三角形。

另外,我使用的是 Macbook Air M1

以下是我用来构建应用程序的task.json文件

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: clang++ build active file",
            "command": "/usr/bin/clang++",
            "args": [
                "-std=c++17",
                "-fcolor-diagnostics",
                "-Wall",
                "-fansi-escape-codes",
                "-g",
                "-I${workspaceFolder}/dependencies/include",
                "-L${workspaceFolder}/dependencies/library",
                "${workspaceFolder}/*.cpp",
                "${workspaceFolder}/glad.c",
                "${workspaceFolder}/dependencies/library/libglfw.3.3.dylib",
                "-o",
                "${workspaceFolder}/app",
                "-framework",
                "OpenGL",
                "-framework",
                "Cocoa",
                "-framework",
                "IOKit",
                "-framework",
                "CoreVideo",
                "-framework",
                "CoreFoundation",
                "-Wno-deprecated"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "compiler: /usr/bin/clang++"
        }
    ]
}

我尝试阅读代码并在线搜索它,但我想我什至不知道要搜索什么,因为我对 OpenGL 很陌生,并且不知道某些关键字,因为我无法最佳地搜索它。

最佳答案

如果您的显示器进行了缩放,则帧缓冲区大小与窗口大小不同。使用 glfwGetFramebufferSize 获取帧缓冲区大小并根据帧缓冲区大小设置视口(viewport)。

int fbSizeX, fbSizeY;
glfwGetFramebufferSize(window, &fbSizeX, &fbSizeY);
glViewport(0, 0, fbSizeX, fbSizeY);

关于c++ - 为什么我的三角形画在窗口的左下侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76541033/

相关文章:

opengl - 如何让鼠标光标在 opengl/glut 中消失?

c++ - 什么是基于 >MACHINE< 的好 PPC 用于为顺序处理器分析代码

c++ - 弱指针分配失败

c++ - 与类型同名的变量 - 哪个编译器是正确的?

c++ - 使用概念化方法显式实例化类

macos - Mac 上的 wkhtmltopdf - 它是如何执行的?

c - 架构 x86_64 (clang) 的 undefined symbol

c++ - OpenGL:glRotatef 旋转什么?

c++ - 如何使用 glm::lookAt() 旋转对象?

c++ - 在一定距离后获得 catmull rom 样条曲线的点?