1、glBufferData
std::vector<Vertex> mVertices;glGenVertexArrays( 1, &mVAO );glGenBuffers( 1, &mVBO );glBindVertexArray( mVAO );glBindBuffer( GL_ARRAY_BUFFER, mVBO );glBufferData( GL_ARRAY_BUFFER,mVertices.size() * sizeof( Vertex ),&mVertices[0], // !!!这里不是&mVerticesGL_STATIC_DRAW );glEnableVertexAttribArray( 0 );glVertexAttribPointer( 0,3,GL_FLOAT,GL_FALSE,sizeof( Vertex ),( void * ) 0 ); // 正确写法应该是( void * ) (0 * sizeof(GLfloat)),假设元素为GLfloat类型glBindVertexArray( 0 );
2、glUseProgram
//shader.use(); // 忘记调用glUseProgram,导致着色器并没有被使用shader.setInt( "task", TASK_COORD );shader.setMat4( "modelMatrix", glm::mat4( 1.0f ) );shader.setMat4( "viewMatrix", viewMatrix );shader.setMat4( "projectionMatrix", projectionMatrix );glBindVertexArray( VAO_coord );glDrawArrays( GL_LINES, 0, 6 );
3、glEnableVertexAttribArray
const GLfloat pos[] = { ... };const GLfloat normal[] = { ... };const GLfloat tex[] = { ... };glGenBuffers( 1, VBO ); // 创建VBOglBindBuffer( GL_ARRAY_BUFFER, *VBO );glBufferData( GL_ARRAY_BUFFER, len, vertices, GL_STATIC_DRAW ); // 填充数据// 填充缓冲glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(positions), &positions);glBufferSubData(GL_ARRAY_BUFFER, sizeof(positions), sizeof(normals), &normals);glBufferSubData(GL_ARRAY_BUFFER, sizeof(positions) + sizeof(normals), sizeof(tex), &tex);glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)(sizeof(positions)));glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)(sizeof(positions) + sizeof(normals)));glEnableVertexAttribArray( 0 ); // 特别容易漏掉这个glEnableVertexAttribArray( 1 );glEnableVertexAttribArray( 2 );
4、着色器中的奇怪问题
下面是一个几何着色器。
项目链接:https://github.com/JackieLong/OpenGL/tree/main/project_geometry_shader_test
#version 330 corelayout(triangles) in;layout(triangle_strip, max_vertices = 3) out;in vec2 texCoord[];uniform float time;out vec2 outTexCoord;vec4 explode(vec4 pos, vec3 normal);vec3 triangleNormal();void main() {vec3 normal = triangleNormal();// 如果用注释的代码,结果就异常,没有加载出模型gl_Position = explode(vec4(gl_in[0].gl_Position), normal);// gl_Position = explode(gl_in[0].gl_Position, normal);outTexCoord = texCoord[0];EmitVertex();gl_Position = explode(vec4(gl_in[1].gl_Position), normal);// gl_Position = explode(gl_in[1].gl_Position, normal);outTexCoord = texCoord[1];EmitVertex();gl_Position = explode(vec4(gl_in[2].gl_Position), normal);// gl_Position = explode(gl_in[2].gl_Position, normal);outTexCoord = texCoord[2];EmitVertex();EndPrimitive();}vec4 explode(vec4 pos, vec3 normal){return pos + vec4(normal * ((1.0 + sin(time)) / 2.0), 0.0);}vec3 triangleNormal(){vec3 fuck1 = vec3(gl_in[0].gl_Position - gl_in[1].gl_Position);vec3 fuck2 = vec3(gl_in[2].gl_Position - gl_in[1].gl_Position);return normalize(cross(fuck1, fuck2));}
