我正在尝试为三角形添加木质纹理。代码仅适用于三角形。但当我尝试添加纹理时会出现错误。我认为问题出在 GLSL 或创建 EBO/VBO 中(不确定)。整个屏幕保持黑色。这是完整的代码。我在这里做错了什么?from OpenGL.GL import *from OpenGL.GLU import *from OpenGL.GL import shadersimport glfwimport numpy as npfrom PIL import ImageVERTEX_SHADER = """#version 330 layout (location = 0) in vec4 position; in vec2 InTexCoords; out vec2 OutTexCoords; void main(){ gl_Position = position; OutTexCoords = InTexCoords; }"""FRAGMENT_SHADER = """#version 330 out vec4 FragColor; uniform vec4 triangleColor; in vec2 OutTexCoords; uniform sampler2D sampleTex; void main() { FragColor = texture(sampleTex,OutTexCoords); }"""shaderProgram = Nonedef initialize(): global VERTEXT_SHADER global FRAGMENT_SHADER global shaderProgram #compiling shaders vertexshader = shaders.compileShader(VERTEX_SHADER, GL_VERTEX_SHADER) fragmentshader = shaders.compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER) #creating shaderProgram shaderProgram = shaders.compileProgram(vertexshader, fragmentshader) #vertex and indices data #triangle #texture vertices = [-0.5, -0.5, 0.0, 0.0,0.0, 0.5, -0.5, 0.0, 1.0,0.0, 0.0, 0.5, 0.0, 0.5,1.0] indices = [0,1,2] vertices = np.array(vertices, dtype=np.float32) indices = np.array(vertices, dtype=np.float32) #add vertices to buffer VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) #add indices to buffer EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW) position = 0 glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(position)我试图遵循本教程learnopengl。但教程是用 C++ 编写的。此外,我的方法略有不同。我没有在顶点中添加颜色代码。但我不认为这是添加纹理的方式的问题。
1 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
的 stride 参数glVertexAttribPointer
指定连续通用顶点属性之间的字节偏移量。您的属性由具有 3 个分量的顶点坐标和具有 2 个分量的纹理坐标组成。因此,你的步幅参数必须为 20(5 * 4 字节)而不是 24:
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0))
glVertexAttribPointer(texCoords,2, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))
glVertexAttribPointer(texCoords,2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(12))
索引的数据类型必须是整数。绘制调用 ( ) 中的类型glDrawElements(..., ..., GL_UNSIGNED_INT, ...)
必须与此类型匹配。使用uint32
而不是float
(和vertices
-> indices
):
indices = np.array(indices, dtype=np.uint32)
将通用顶点属性索引与命名属性变量 ( ) 关联起来必须在链接程序之前(在 之前)glBindAttribLocation
完成。我建议通过布局限定符 设置属性索引:glLinkProgram
layout (location = 0) in vec4 position; layout (location = 1) in vec2 InTexCoords;
添加回答
举报
0/150
提交
取消