python - opengl中四边形的颜色与指定的不同
问题描述
我创建的四边形与我指定的颜色不同。四边形应该是完全红色的,如下面的代码所示。每行中的最后三个值是指定颜色的值。
quad = [-0.5, -0.5, 0.0, width / height, 1.0, 0.0, 0.0,
-0.5, 0.5, 0.0, width / height, 1.0, 0.0, 0.0,
0.5, 0.5, 0.0, width / height, 1.0, 0.0, 0.0,
0.5, -0.5, 0.0, width / height, 1.0, 0.0, 0.0]
而不是预期的结果,我得到这个:
我怎样才能让四边形看起来全红,而不是多种颜色?
完整代码:
import math
import glfw
import numpy
import pyrr
from OpenGL.GL import *
from OpenGL.GL.shaders import *
width, height = 500, 500
def draw():
global shader
quad = [-0.5, -0.5, 0.0, width / height, 1.0, 0.0, 0.0,
-0.5, 0.5, 0.0, width / height, 1.0, 0.0, 0.0,
0.5, 0.5, 0.0, width / height, 1.0, 0.0, 0.0,
0.5, -0.5, 0.0, width / height, 1.0, 0.0, 0.0]
quad = numpy.array(quad,
dtype='float32')
indices = [0, 1, 2, 3]
indices = numpy.array(indices, dtype='uint32')
vertex_shader_ = """
#version 140
in vec4 position;
in vec3 color;
uniform mat4 transform;
out vec4 out_color;
void main(){
gl_Position = position;
out_color = vec4(color.rgb, 1);
};
"""
fragment_shader_ = """
#version 140
in vec4 out_color;
void main(){
gl_FragColor = out_color;
};
"""
shader = compileProgram(compileShader(vertex_shader_, GL_VERTEX_SHADER),
compileShader(fragment_shader_, GL_FRAGMENT_SHADER))
glUseProgram(shader)
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, quad.nbytes, quad, GL_STATIC_DRAW)
EBO = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)
position = glGetAttribLocation(shader, "position")
glVertexAttribPointer(position, 4, GL_FLOAT, GL_FALSE, 28, ctypes.c_void_p(0))
glEnableVertexAttribArray(position)
color = glGetAttribLocation(shader, "color")
glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(16))
glEnableVertexAttribArray(color)
def Screen():
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glDrawArrays(GL_POLYGON, 0, 4)
draw()
glViewport(0, 0, width, height)
def main():
global width, height
if not glfw.init():
return
window = glfw.create_window(500, 500, "Opengl GLFW Window", None, None)
if not window:
glfw.terminate()
return
glfw.make_context_current(window)
while not glfw.window_should_close(window):
glfw.poll_events()
Screen()
width, height = glfw.get_window_size(window)
print(width, height)
glViewport(0, 0, width, height)
glfw.swap_buffers(window)
glfw.terminate()
if __name__ == '__main__':
main()
解决方案
每个 glVertexAttribPointer() 中的 stride 参数被赋予两个不同的数字。感谢@genpfault 指出这一点!
推荐阅读
- javascript - 如何检测使用 window.open() 打开的窗口关闭事件
- javascript - 使用 underscore.js 返回子值最大的数组索引
- android - 在相对布局中向芯片组添加水平滚动
- javafx-11 - 在 Apache Netbeans 10 中创建 JavaFX11 应用程序时出错
- php - 简单的 PHP 重定向脚本不起作用。特别来自 geoplugin.net。有什么建议吗?
- unity3d - 在 Unity 的顶点着色器中丢弃顶点
- xamarin.forms - Plugin.Messaging.EmailMessageBuilder.withattachemnt 的附件抛出异常错误
- javascript - js:如何从二维数组中过滤掉重复项?
- c++ - 以下程序中的分段错误
- java - 创建自定义类以反序列化对象以检查数据完整性