gpt4 book ai didi

c++ - Qt OpenGL DrawElements 不绘制第二个三角形

转载 作者:行者123 更新时间:2023-11-28 06:30:57 24 4
gpt4 key购买 nike

现在我正在按照 Jamie King Qt OpenGL 教程学习 OpenGL。 (他们很好)。

在其中一个教程中,我遵循它但无法使用 DrawElemets 绘制两个顶点缓冲区三角形。它适用于 GLDrawArrays

请帮忙

提前致谢。

GLWidget.h

#ifndef _GL_WIDGET_H_
#define _GL_WIDGET_H_

#include <QtOpenGL\QGLWidget>

class GLWidget : public QGLWidget
{
public:

GLWidget();
virtual ~GLWidget();

protected:
void initializeGL();
void paintGL();
};
#endif

GLWidget.cpp
#include <gl\glew.h>
#include "globals.h"

#include "GLWidget.h"

using namespace std;

#define SIZE 1.0f


GLWidget::GLWidget()
{

}

GLWidget::~GLWidget()
{

}

// GLWindow Initialize function.
void GLWidget::initializeGL()
{


// Initializing GLEW.
GLenum err = glewInit();

// Checking if the glew loads fine.
if(err != GLEW_OK)
{
cerr<<"Cannot initialize GLEW: "<<err<<endl;
}

// Vertex Buffer storage space.
GLuint vertBufferID;
GLuint vertIndicesID;

// Vertex array.
GLfloat verts[] =
{
// First traingle.
+0.0f, +0.0f, // 0
+1.0f, +1.0f, // 1
-1.0, +1.0, // 2
-1.0, -1.0, // 3
+1.0, -1.0, // 4
};

// Creating the vertex buffer
glGenBuffers(1, &vertBufferID);

// binding the buffer.
glBindBuffer(GL_ARRAY_BUFFER, vertBufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), &verts, GL_STATIC_DRAW);

// Enalbing the position attribute of the vertex.
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

// Creating the vertex indices buffer.
GLushort indices[] = { 0, 1, 2, 0, 3, 4};
glGenBuffers(1, &vertIndicesID);

// binding the buffer.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertIndicesID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertIndicesID), indices, GL_STATIC_DRAW);
}

// GLWindow Paint Function.
void GLWidget::paintGL()
{

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Defining the viewport.
glViewport(0, 0, width(), height());

// Drawing the Triangle.
//glDrawArrays(GL_TRIANGLES, 0, 6);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
}

最佳答案

上传索引缓冲区时:

glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertIndicesID), indices, GL_STATIC_DRAW);

您正在获取错误变量的大小。那应该是:

glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);


不确定你是否知道这一点,你没有指定步幅:

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

应该是

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);

步长是两个顶点在顶点缓冲区中相隔的字节数。如果你告诉它它们相距 0,那么你基本上总是渲染相同的顶点。 (完全不确定您是如何绘制第一个三角形的)。

Update: Turns out 0 is a valid argument for the stride. The OpenGL reference says this:

Specifies the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0.

关于c++ - Qt OpenGL DrawElements 不绘制第二个三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com