【问题标题】:Correct Use of glVertexAttribPointer?正确使用 glVertexAttribPointer?
【发布时间】:2021-02-02 04:30:51
【问题描述】:

我最近决定开始学习 OpenGL,并给自己买了一本关于 OpenGL Core 3.3 的书。这本书通常是关于 C++ 的。

所以,在找了一会儿之后,我找到了一个我更擅长的语言的库,它提供了几乎相同的功能:lwjgl

我按照书上的步骤,将 C++ 语法翻译成 java 语法,直到它真正开始绘制为止。

无论我对代码进行什么更改,JVM 都会一直崩溃。经过调试,我发现当我调用glVertexAttribPointerglDrawArrays 时,JVM 崩溃了。

我对 OpenGL 很陌生,我假设这个问题对于更有经验的人来说听起来很愚蠢,但是:我需要对这段代码进行哪些更改?

        

        float[] vertices = {
                -0.5f, -0.5f, -0.0f,    
                0.5f, 0.5f, 0.0f,
                0.0f,0.5f,0.0f
        };
        FloatBuffer b = BufferUtils.createFloatBuffer(9);
        b.put(vertices);
        int VBO = glGenBuffers();
        int VAO = glGenVertexArrays();
        log.info("VBO:" + VBO + "VAO: " + VAO);
        // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
        glBindVertexArray(VAO);

            
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 12,  0);
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
        glBindVertexArray(0);       

            

        // Run the rendering loop until the user has attempted to close
        // the window or has pressed the ESCAPE key.
        while (!glfwWindowShouldClose(window))
            {
                // input
                // -----

                // render
                // ------
                glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
                glClear(GL_COLOR_BUFFER_BIT);

                // draw our first triangle
                glUseProgram(shaderProgram);
                glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
                glDrawArrays(GL_TRIANGLES, 0, 3);
                 glBindVertexArray(0); // no need to unbind it every time 
         
                // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
                // -------------------------------------------------------------------------------
                glfwSwapBuffers(window);
                glfwPollEvents();
            }

如果您需要更多信息/需要查看我的更多代码,我将非常感谢您提供的任何帮助,请告诉我。提前致谢

【问题讨论】:

    标签: java opengl lwjgl vao


    【解决方案1】:

    在指定顶点属性之前,您必须将顶点缓冲区对象绑定到目标GL_ARRAY_BUFFER

    glBindBuffer(GL_ARRAY_BUFFER, VBO); 
    glVertexAttribPointer(0, 3, GL_FLOAT, false, 12,  0);
    

    glVertexAttribPointer被调用时,当前绑定到ARRAY_BUFFER目标的缓冲区对象与属性(索引)相关联,并且对缓冲区对象的引用存储在@的状态向量中987654322@.

    【讨论】:

    • 谢谢,解决了!我很困惑,因为我将 C++ 代码直接翻译成 Java,而这本书是今年的,所以我想知道为什么它不起作用……原来我只是弄错了顺序!再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多