OpenGL生成三角网格

时间:2017-12-09 18:50:03

标签: c++ arrays opengl mesh opengl-4

我是OpenGl的初学者,我试图在OpenGL中绘制一个像this一样的三角形网格,我的问题是它不是绘图而我看不清楚原因。此外,如果我打印顶点数组,x和y坐标对于所有顶点保持相同。 x坐标和z坐标都应位于+1和-1之间。 m_meshResolution = 1时坐标似乎是正确的,但不是。我认为有一种更简单的方法可以尝试这样做,所以欢迎所有的建议。

int size = m_meshResolution * m_meshResolution * 2 * 3 * 3;
float* positions = new float[size]();

double triangleWidth = 2 / m_meshResolution;
float startX = -1.0f;
float startZ = 1.0f;
float x1 = 0;
float x2 = 0;
float z1 = 0;
float z2 = 0;
int index = 0;
//For each row
for (int r = 0; r < m_meshResolution; r++) {
    //For each column
    for (int c = 0; c < m_meshResolution; c++) {
        x1 = startX + c*divider;
        x2 = startX + (c+1)*divider;
        z1 = startZ - r*divider;
        z2 = startZ -(r+1)*divider;
        //Generate one triangle
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z1;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z2;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z1;
        //Generate other triangle
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z1;
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z2;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z2;
    }

//Set buffers
glGenBuffers(1, &m_positionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);

glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, false/*normalized*/, 0/*stride*/, 0/*offset*/);
glEnableVertexAttribArray(0);

//Draw
glBindVertexArray(m_vao);
glDrawArrays(GL_TRIANGLES, 0, m_meshResolution*m_meshResolution*2*3);

1 个答案:

答案 0 :(得分:3)

positions是一个指针,sizeof(positions)返回4或8个字节,它取决于体系结构,但glBufferData的第二个参数告诉我们

  

尺寸          指定缓冲区对象的新数据存储的大小(以字节为单位)。

您应该使用sizeof(float) * size作为第二个参数。