PyOpenGL - passing transformation matrix into shader [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am having trouble passing projection and modelview matrices into the GLSL shader from my PyOpenGL code. My understanding is that OpenGL matrices are column major, but when I pass in projection and modelview matrices as shown, I don't see anything. I tried the transpose of the matrices, and it worked for the modelview matrix, but the projection matrix doesn't work either way. Here is the code:
import OpenGL
from OpenGL.GL import *
from OpenGL.GL.shaders import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GLUT.freeglut import *
from OpenGL.arrays import vbo
import numpy, math, sys
strVS = """
attribute vec3 aVert;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform vec4 uColor;
varying vec4 vCol;
void main() {
// option #1 - fails
gl_Position = uPMatrix * uMVMatrix * vec4(aVert, 1.0);
// option #2 - works
gl_Position = vec4(aVert, 1.0);
// set color
vCol = vec4(uColor.rgb, 1.0);
}
"""
strFS = """
varying vec4 vCol;
void main() {
// use vertex color
gl_FragColor = vCol;
}
"""
# 3D scene
class Scene:
# initialization
def __init__(self):
# create shader
self.program = compileProgram(compileShader(strVS,
GL_VERTEX_SHADER),
compileShader(strFS,
GL_FRAGMENT_SHADER))
glUseProgram(self.program)
self.pMatrixUniform = glGetUniformLocation(self.program, 'uPMatrix')
self.mvMatrixUniform = glGetUniformLocation(self.program,
"uMVMatrix")
self.colorU = glGetUniformLocation(self.program, "uColor")
# attributes
self.vertIndex = glGetAttribLocation(self.program, "aVert")
# color
self.col0 = [1.0, 1.0, 0.0, 1.0]
# define quad vertices
s = 0.2
quadV = [
-s, s, 0.0,
-s, -s, 0.0,
s, s, 0.0,
s, s, 0.0,
-s, -s, 0.0,
s, -s, 0.0
]
# vertices
self.vertexBuffer = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
vertexData = numpy.array(quadV, numpy.float32)
glBufferData(GL_ARRAY_BUFFER, 4*len(vertexData), vertexData,
GL_STATIC_DRAW)
# render
def render(self, pMatrix, mvMatrix):
# use shader
glUseProgram(self.program)
# set proj matrix
glUniformMatrix4fv(self.pMatrixUniform, 1, GL_FALSE, pMatrix)
# set modelview matrix
glUniformMatrix4fv(self.mvMatrixUniform, 1, GL_FALSE, mvMatrix)
# set color
glUniform4fv(self.colorU, 1, self.col0)
#enable arrays
glEnableVertexAttribArray(self.vertIndex)
# set buffers
glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
glVertexAttribPointer(self.vertIndex, 3, GL_FLOAT, GL_FALSE, 0, None)
# draw
glDrawArrays(GL_TRIANGLES, 0, 6)
# disable arrays
glDisableVertexAttribArray(self.vertIndex)
class Renderer:
def __init__(self):
pass
def reshape(self, width, height):
self.width = width
self.height = height
self.aspect = width/float(height)
glViewport(0, 0, self.width, self.height)
glEnable(GL_DEPTH_TEST)
glDisable(GL_CULL_FACE)
glClearColor(0.8, 0.8, 0.8,1.0)
glutPostRedisplay()
def keyPressed(self, *args):
sys.exit()
def draw(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# build projection matrix
fov = math.radians(45.0)
f = 1.0/math.tan(fov/2.0)
zN, zF = (0.1, 100.0)
a = self.aspect
pMatrix = numpy.array([f/a, 0.0, 0.0, 0.0,
0.0, f, 0.0, 0.0,
0.0, 0.0, (zF+zN)/(zN-zF), -1.0,
0.0, 0.0, 2.0*zF*zN/(zN-zF), 0.0], numpy.float32)
# modelview matrix
mvMatrix = numpy.array([1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.5, 0.0, -5.0, 1.0], numpy.float32)
# render
self.scene.render(pMatrix, mvMatrix)
# swap buffers
glutSwapBuffers()
def run(self):
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(400, 400)
self.window = glutCreateWindow("Minimal")
glutReshapeFunc(self.reshape)
glutDisplayFunc(self.draw)
glutKeyboardFunc(self.keyPressed) # Checks for key strokes
self.scene = Scene()
glutMainLoop()
glutInit(sys.argv)
prog = Renderer()
prog.run()
When I use option #2 in the shader without either matrix, I get the following output:
What am I doing wrong?

Related

need to have glVertexAttribDivisor when doing glDrawElements

Im working on my little project and here is some code:
Quad definitions:
#Geometry definitions XYZ UV
quad_vertices = [-0.5, -0.5, 0.0, 0.0, 0.0,
0.5, -0.5, 0.0, 1.0, 0.0,
0.5, 0.5, 0.0, 1.0, 1.0,
-0.5, 0.5, 0.0, 0.0, 1.0]
quad_indices = [0, 1, 2, 2, 3, 0]
quad_vertices = np.array(quad_vertices, dtype=np.float32)
quad_indices = np.array(quad_indices, dtype=np.uint32)
Shader definition:
vertex_src2 = """
# version 330 core
layout(location = 0) in vec3 a_position;
layout(location = 1) in vec2 a_texture_uv;
layout(location = 2) in vec4 a_color;
layout(location = 3) in vec3 translation;
layout(location = 4) in vec3 scale;
layout(location = 5) in vec2 a_tex_index;
layout(location = 6) in vec4 a_effect_params; //currently not used
uniform mat4 projection;
uniform mat4 view;
out vec4 v_color;
out vec2 v_texture;
out float z_texture0;
out float z_texture1;
out vec4 effect_params;
mat4 BuildTranslation(vec3 delta)
{
return mat4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
delta, 1.0);
}
mat4 BuildRotation(vec3 delta){
return mat4(cos(radians(delta[2])), -sin(radians(delta[2])), 0.0, 0.0,
sin(radians(delta[2])), cos(radians(delta[2])), 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
}
mat4 BuildScale(vec3 delta){
return mat4(delta[0], 0.0, 0.0, 0.0,
0.0, delta[1], 0.0, 0.0,
0.0, 0.0, delta[2], 0.0,
0.0, 0.0, 0.0, 1.0);
}
void main()
{
mat4 model = BuildTranslation(translation) * BuildScale(scale);
gl_Position = projection * view * model * vec4(a_position, 1.0f);
v_texture = a_texture_uv;
v_color = a_color;
z_texture0 = a_tex_index.x;
z_texture1 = a_tex_index.y;
effect_params = vec4(0);
}
"""
#Fragment shader definition
fragment_src2 = """
# version 330 core
in vec4 v_color;
in vec2 v_texture;
in float z_texture0;
in float z_texture1;
in vec4 effect_params;
out vec4 out_color;
uniform int switcher;
uniform sampler2DArray s_texture;
void main()
{
if (switcher == 0){
float effectNo = effect_params[3];
vec4 texel = texture(s_texture, vec3(v_texture, z_texture0));
texel.a = texel.a * v_color.a;
if (texel.a < 0.05){
discard;
}
out_color = texel;
}
}
"""
Here are the bindings:
def bind_buffer_data(self):
glBindVertexArray(self.VAO)
glBindBuffer(GL_ARRAY_BUFFER, self.VBO[0])
glBufferData(GL_ARRAY_BUFFER, quad_vertices.nbytes, quad_vertices, GL_STATIC_DRAW)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.EBO)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, quad_indices.nbytes, quad_indices, GL_STATIC_DRAW)
for i in range(6):
glEnableVertexAttribArray(i)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0))
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(12))
glBindBuffer(GL_ARRAY_BUFFER, self.VBO[1]) // This is bound for later loading of buffer data during draw_object()
Final bindings and drawing:
def draw_object(self, depth, alpha=1.0, switcher=0):
self.color[3] = alpha
buffer_data = np.array(
[self.color[0], self.color[1], self.color[2], self.color[3],
self.pos_x, self.pos_y, depth,
self.scale[0], self.scale[1], self.scale[2],
0, 0],
dtype=np.float32)
glBindVertexArray(self.VAO)
glBindTexture(GL_TEXTURE_2D_ARRAY, self.get_current_texture())
glBufferData(GL_ARRAY_BUFFER, buffer_data.nbytes, buffer_data, GL_DYNAMIC_DRAW)
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 48, ctypes.c_void_p(0))
glVertexAttribDivisor(2, 1) #Cannot delete that?
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 48, ctypes.c_void_p(16))
glVertexAttribDivisor(3, 1) #Cannot delete that?
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 48, ctypes.c_void_p(28))
glVertexAttribDivisor(4, 1) #Cannot delete that?
glVertexAttribPointer(5, 2, GL_FLOAT, GL_FALSE, 48, ctypes.c_void_p(40))
glVertexAttribDivisor(5, 1) #Cannot delete that?
glUniform1i(shader.switcher_loc2, switcher)
glDrawElements(GL_TRIANGLES, len(quad_indices), GL_UNSIGNED_INT, None)
I'm very puzzled because above code works and everything renders properly. However as soon as I remove glVertexAttribDivisor lines it doesn't render anything. Any ideas why this is the case?
Note that I'm using glDrawElements not glDrawElementsInstanced. I thought that glDrawElements is not even looking at glVertexAttribDivisor because I'm drawing single primitive. Could it have something to do with the fact that I bound 2 different VBO's to GL_ARRAY_BUFFER target? But then... I'm calling glVertexAttribPointer function only when proper VBO is bound to the VAO as well as glBufferData, so I don't understand. Please help me understand this better.
So the misconception I had was that I thought that glDrawElements is going to draw me a single instance of a given primitive (quad in my case) using same attributes it was given from buffer for each individual vertex. That is not the case!
Without glVertexAttribDivisor only the first vertex out of 4 will get correct attributes and all the rest of them will get 0,0,0,0,0.... So if I double the buffer size in this case, half of them will get the data and something will render but garbage. With quadruple size of the given buffer everything renders as it should.
So my lesson to take away from this is that without vertexAttribDivisor specified, the attributes are going to be read from buffer as stride per vertex not per whole instance.

ModernGL set uniform

I'm considering switching to ModernGL over PyOpenGL, and I'm struggling to implement anything right now.
First of all, I would like to try the classic "triangle that changes shape using a time uniform and sine function", but I'm stuck on how to write to the uniform.
Here is what the documentation says about this:
A uniform is a global GLSL variable declared with the “uniform” storage qualifier. These act as
parameters that the user of a shader program can pass to that program.
In ModernGL, Uniforms can be accessed using Program.__getitem__() or Program.__iter__().
# Set a vec4 uniform
uniform['color'] = 1.0, 1.0, 1.0, 1.0
# Optionally we can store references to a member and set the value directly
uniform = program['color']
uniform.value = 1.0, 0.0, 0.0, 0.0
uniform = program['cameraMatrix']
uniform.write(camera_matrix)
This is my code:
import moderngl as mgl
import glfw
import numpy as np
import time
from math import sin
glfw.init()
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
window = glfw.create_window(800, 600, "__DELETEME__", None, None)
glfw.make_context_current(window)
context = mgl.create_context()
vertex_source = """
#version 330 core
in vec2 aPos;
uniform float time;
void main() {
gl_Position = vec4(aPos.x, aPos.y + sin(time), 0.0, 1.0);
}
"""
fragment_source = """
#version 330 core
out vec4 color;
void main(){
color = vec4(0.0, 0.0, 1.0, 1.0);
}
"""
program = context.program(vertex_shader=vertex_source, fragment_shader=fragment_source)
data = np.array([
0.5, 0,
-0.5, 0,
0, 0.5], dtype = "float32")
vbo = context.buffer(data.tobytes())
vao = context.vertex_array(program, vbo, "aPos")
uniform = program["time"]
uniform.value = 1.0
while not glfw.window_should_close(window):
now = time.time()
vao.render()
elapsed = time.time() - now
glfw.poll_events()
glfw.swap_buffers(window)
glfw.terminate()
Now it draws nothing. What am I doing wrong? Thanks!
The elapsed time is the difference between the start time and the current time. Get the start time before the application loop and compute the elapsed time in the loop in every frame:
start_time = time.time()
while not glfw.window_should_close(window):
elapsed = time.time() - start_time
# [...]
The value of the uniform "time" has to be updated continuously in the loop:
while not glfw.window_should_close(window):
# [...]
uniform.value = elapsed
You have to clear the display in every frame, in the application loop (See ModernGL Context):
while not glfw.window_should_close(window):
# [...]
context.clear(0.0, 0.0, 0.0)
vao.render()
Complete example:
import moderngl as mgl
import glfw
import numpy as np
import time
from math import sin
glfw.init()
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
window = glfw.create_window(800, 600, "__DELETEME__", None, None)
glfw.make_context_current(window)
context = mgl.create_context()
vertex_source = """
#version 330 core
in vec2 aPos;
uniform float time;
void main() {
gl_Position = vec4(aPos.x, aPos.y + sin(time), 0.0, 1.0);
}
"""
fragment_source = """
#version 330 core
out vec4 color;
void main(){
color = vec4(0.0, 0.0, 1.0, 1.0);
}
"""
program = context.program(vertex_shader=vertex_source, fragment_shader=fragment_source)
data = np.array([
0.5, 0,
-0.5, 0,
0, 0.5], dtype = "float32")
vbo = context.buffer(data.tobytes())
vao = context.vertex_array(program, vbo, "aPos")
uniform = program["time"]
uniform.value = 1.0
start_time = time.time()
while not glfw.window_should_close(window):
elapsed = time.time() - start_time
uniform.value = elapsed
context.clear(0.0, 0.0, 0.0)
vao.render()
glfw.poll_events()
glfw.swap_buffers(window)
glfw.terminate()

Changing OpenGL Vertex Buffer Object data via pyopengl OpenGL.arrays.vbo has no effect

I am stuck trying to change data in a VBO.
I setup a scene with 2 Triangle primitives using a VBO via the python OpenGL.arrays.vbo helper class. That worked.
Then I want to change the data (in the minimal example below just shift one vertex when a button is clicked) which I cannot bring to work. I'm not sure if I use the VBO incorrectly or if there is some triviality blocking the redraw on the PyQt5 side.
Below is the full minimal example, the important stuff takes play in the member functions initializeGL, paintGL, and shift.
Inside GLWidget.shift I tried different approaches following the docs and this answer without success. Any help is appreciated.
#!/usr/bin/env python
import ctypes
import sys
import numpy as np
import OpenGL.arrays.vbo as glvbo
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import (QApplication, QHBoxLayout, QOpenGLWidget,
QWidget, QPushButton)
import OpenGL.GL as gl
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.glWidget = GLWidget()
button = QPushButton('shift', self)
button.clicked.connect(self.glWidget.shift)
layout = QHBoxLayout()
layout.addWidget(self.glWidget)
layout.addWidget(button)
self.setLayout(layout)
class GLWidget(QOpenGLWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.object = None
def minimumSizeHint(self):
return QSize(400, 400)
def initializeGL(self):
gl.glClearColor(0., 0., 0., 0.)
# a red and a green triangle
self.vertices = np.array([
# <- x,y,z -----> <- r,g,b -->
-0.5, -0.2, 0.0, 1.0, 0.0, 0.0,
0.5, -0.5, 0.0, 1.0, 0.0, 0.0,
0.5, 0.5, 0.0, 1.0, 0.0, 0.0,
0.4, -0.2, 0.0, 0.0, 1.0, 0.0,
1.4, -0.5, 0.0, 0.0, 1.0, 0.0,
1.4, 0.5, 0.0, 0.0, 1.0, 0.0,
], 'f')
self.vbo = glvbo.VBO(self.vertices)
self.vbo.bind()
self.object = gl.glGenLists(1)
gl.glNewList(self.object, gl.GL_COMPILE)
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glEnableClientState(gl.GL_COLOR_ARRAY)
buffer_offset = ctypes.c_void_p
stride = (3+3)*self.vertices.itemsize
gl.glVertexPointer(3, gl.GL_FLOAT, stride, None)
gl.glColorPointer(3, gl.GL_FLOAT, stride, buffer_offset(12))
gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
gl.glDisableClientState(gl.GL_COLOR_ARRAY)
gl.glEndList()
gl.glShadeModel(gl.GL_FLAT)
def paintGL(self):
gl.glClear(
gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glLoadIdentity()
gl.glRotated(50.0, 0.0, 1.0, 0.0)
gl.glCallList(self.object)
def resizeGL(self, width, height):
side = min(width, height)
if side < 0:
return
gl.glViewport((width - side) // 2, (height - side) // 2, side,
side)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glOrtho(-1., +1., -1., +1., -100.0, 100.0)
gl.glMatrixMode(gl.GL_MODELVIEW)
def shift(self):
# shift y-position of one vertex
self.vertices[1] += 10.3
assert self.vertices is self.vbo.data
# version 1
# self.vbo.implementation.glBufferSubData(self.vbo.target, 0, self.vbo.data)
# version 2
# self.vbo[:] = self.vertices[:]
# self.vbo.bind()
# self.vbo.copy_data()
# version 2b (use slice)
# self.vbo[1:2] = self.vertices[1:2]
# self.vbo.bind()
# self.vbo.copy_data()
# version 3
self.vbo.set_array(self.vertices)
self.vbo.bind()
self.vbo.copy_data()
self.update()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
The code runs on an Ubuntu 18.04 machine under python 3.6 with
Vendor: Intel Open Source Technology Center
Renderer: Mesa DRI Intel(R) HD Graphics 5500 (Broadwell GT2)
OpenGL Version: 3.0 Mesa 19.2.8
Shader Version: 1.30
Sisplay lists (glGenList) are deprecated. What you try to encode in the list is the Vertex Specification.
I recommend to use a Vertex Array Object instead.
Create the VAO, before specifying the array of generic vertex attribute data:
class GLWidget(QOpenGLWidget):
# [...]
def initializeGL(self):
# [...]
self.vbo = glvbo.VBO(self.vertices)
self.vbo.bind()
self.vao = gl.glGenVertexArrays(1)
gl.glBindVertexArray(self.vao)
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glEnableClientState(gl.GL_COLOR_ARRAY)
buffer_offset = ctypes.c_void_p
stride = (3+3)*self.vertices.itemsize
gl.glVertexPointer(3, gl.GL_FLOAT, stride, None)
gl.glColorPointer(3, gl.GL_FLOAT, stride, buffer_offset(12))
gl.glBindVertexArray(0)
When you want to draw the object, then is sufficient to bind the VAO:
class GLWidget(QOpenGLWidget):
# [...]
def paintGL(self):
gl.glClear(
gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glLoadIdentity()
gl.glRotated(50.0, 0.0, 1.0, 0.0)
gl.glBindVertexArray(self.vao)
gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
gl.glBindVertexArray(0)
Note, the display list does not work, because certain commands are not compiled into the display list but are executed immediately, including glVertexPointer and glColorPointer. See glNewList.

How to access the modelview matrix in kivy?

I am writing a python application using Kivy for rendering some graphics. I would like to find out how to get access to the current modelview matrix within kivy, the same matrix as in the vertex shader.
Here is my example code (Python 2.7, Kivy 1.9):
#!/usr/bin/env python
from kivy.app import App
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.graphics import *
from kivy.graphics.transformation import Matrix
from kivy.resources import resource_find
from kivy.uix.widget import Widget
vertices = [0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
2.0, 0.0, 0.0, 0.0, 0.0, 1.0,
0.0, 2.0, 0.0, 0.0, 0.0, 1.0,
2.0, 2.0, 0.0, 0.0, 0.0, 1.0]
indices = [0, 1, 2, 1, 2, 3]
vformat = [(b'v_pos', 3, 'float'), (b'v_normal', 3, 'float')]
class Renderer(Widget):
def __init__(self, **kwargs):
super(Renderer, self).__init__(**kwargs)
self.canvas = RenderContext(compute_normal_mat=True)
self.canvas.shader.source = resource_find('simple.glsl')
with self.canvas:
PushMatrix()
Translate(0, -1, -3)
self.rot = Rotate(1, 0, 1, 0)
UpdateNormalMatrix()
self.mesh = Mesh(vertices=vertices, indices=indices,
fmt=vformat, mode='triangles')
PopMatrix()
Clock.schedule_interval(self.update_glsl, 1 / 60.)
def update_glsl(self, delta):
asp = self.width / float(self.height)
proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
self.canvas['projection_mat'] = proj
self.rot.angle += delta * 100
print self.canvas['modelview_mat']
class RendererApp(App):
def build(self):
return Renderer()
if __name__ == "__main__":
RendererApp().run()
and the shader file simple.glsl:
---VERTEX SHADER-----------------------------------
attribute vec3 v_pos;
attribute vec3 v_normal;
uniform mat4 modelview_mat;
uniform mat4 projection_mat;
varying vec4 normal_vec;
void main (void) {
normal_vec = vec4(v_normal, 0.0);
gl_Position = projection_mat * modelview_mat * vec4(v_pos, 1.0);
}
---FRAGMENT SHADER---------------------------------
uniform mat4 normal_mat;
varying vec4 normal_vec;
void main (void){
vec4 v_normal = normalize( normal_mat * normal_vec ) ;
float theta = clamp(abs(dot(v_normal, vec4(0.0, 0.0, 1.0, 1.0))), 0.0, 1.0);
gl_FragColor = vec4(theta, theta, theta, 1.0);
}
In the function update_glsl I need the current modelview matrix for some calculations. I tried self.canvas['modelview_mat'], but this give me always the identity matrix.

Looking for a simple OpenGL (3.2+) Python example that uses GLFW [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I am looking for a simple modern OpenGL (3.2+)example in Python.
I tried with GLUT and freeGLUT, but I am not able to get a 3.2 context on OS X (Mavericks). (This seems to be a known issue with GLUT/freeGLUT).
GLFW seems to be a modern lightweight alternative to GLUT, but it doesn't seem to have an official Python binding, and I could not find a simple example that uses 3.2 core profile features of OpenGL with GLFW and Python.
(I struggled with this problem, and so it could be useful for others, I am answering below as per SO guidelines.)
The code below uses PyOpenGL, PIL (for textures), numpy, GLFW and the corresponding Python binding cyglfw3.
Here is a screenshot of the output:
The main code is appended below. It uses some utility methods from a file called glutils.py (for loading texture, compiling shaders, etc.) which you can find here:
https://github.com/electronut/pp/tree/master/simplegl
Code listing follows:
import OpenGL
from OpenGL.GL import *
from OpenGL.GLUT import *
import numpy, math, sys, os
import glutils
import cyglfw3 as glfw
strVS = """
#version 330 core
layout(location = 0) in vec3 aVert;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform vec4 uColor;
uniform float uTheta;
out vec4 vCol;
out vec2 vTexCoord;
void main() {
// rotational transform
mat4 rot = mat4(
vec4( cos(uTheta), sin(uTheta), 0.0, 0.0),
vec4(-sin(uTheta), cos(uTheta), 0.0, 0.0),
vec4(0.0, 0.0, 1.0, 0.0),
vec4(0.0, 0.0, 0.0, 1.0)
);
// transform vertex
gl_Position = uPMatrix * uMVMatrix * rot * vec4(aVert, 1.0);
// set color
vCol = vec4(uColor.rgb, 1.0);
// set texture coord
vTexCoord = aVert.xy + vec2(0.5, 0.5);
}
"""
strFS = """
#version 330 core
in vec4 vCol;
in vec2 vTexCoord;
uniform sampler2D tex2D;
uniform bool showCircle;
out vec4 fragColor;
void main() {
if (showCircle) {
// discard fragment outside circle
if (distance(vTexCoord, vec2(0.5, 0.5)) > 0.5) {
discard;
}
else {
fragColor = texture(tex2D, vTexCoord);
}
}
else {
fragColor = texture(tex2D, vTexCoord);
}
}
"""
class Scene:
""" OpenGL 3D scene class"""
# initialization
def __init__(self):
# create shader
self.program = glutils.loadShaders(strVS, strFS)
glUseProgram(self.program)
self.pMatrixUniform = glGetUniformLocation(self.program,
'uPMatrix')
self.mvMatrixUniform = glGetUniformLocation(self.program,
"uMVMatrix")
self.colorU = glGetUniformLocation(self.program, "uColor")
# color
self.col0 = [1.0, 0.0, 0.0, 1.0]
# texture
self.tex2D = glGetUniformLocation(self.program, "tex2D")
# define quad vertices
quadV = [
-0.5, -0.5, 0.0,
0.5, -0.5, 0.0,
-0.5, 0.5, 0.0,
0.5, 0.5, 0.0
]
# set up vertex array object (VAO)
self.vao = glGenVertexArrays(1)
glBindVertexArray(self.vao)
# vertices
self.vertexBuffer = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
vertexData = numpy.array(quadV, numpy.float32)
glBufferData(GL_ARRAY_BUFFER, 4*len(vertexData), vertexData,
GL_STATIC_DRAW)
# enable vertex array
glEnableVertexAttribArray(0)
# set buffer data
glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
# unbind VAO
glBindVertexArray(0)
# time
self.t = 0
# texture
self.texId = glutils.loadTexture('test.png')
# show circle?
self.showCircle = False
# step
def step(self):
# increment angle
self.t = (self.t + 1) % 360
# set shader angle in radians
glUniform1f(glGetUniformLocation(self.program, 'uTheta'),
math.radians(self.t))
# render
def render(self, pMatrix, mvMatrix):
# use shader
glUseProgram(self.program)
# set proj matrix
glUniformMatrix4fv(self.pMatrixUniform, 1, GL_FALSE, pMatrix)
# set modelview matrix
glUniformMatrix4fv(self.mvMatrixUniform, 1, GL_FALSE, mvMatrix)
# show circle?
glUniform1i(glGetUniformLocation(self.program, 'showCircle'),
self.showCircle)
# enable texture
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.texId)
glUniform1i(self.tex2D, 0)
# bind VAO
glBindVertexArray(self.vao)
# draw
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)
# unbind VAO
glBindVertexArray(0)
class RenderWindow:
"""GLFW Rendering window class"""
def __init__(self):
# save current working directory
cwd = os.getcwd()
# initialize glfw - this changes cwd
glfw.Init()
# restore cwd
os.chdir(cwd)
# version hints
glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
# make a window
self.width, self.height = 640, 480
self.aspect = self.width/float(self.height)
self.win = glfw.CreateWindow(self.width, self.height, "test")
# make context current
glfw.MakeContextCurrent(self.win)
# initialize GL
glViewport(0, 0, self.width, self.height)
glEnable(GL_DEPTH_TEST)
glClearColor(0.5, 0.5, 0.5,1.0)
# set window callbacks
glfw.SetMouseButtonCallback(self.win, self.onMouseButton)
glfw.SetKeyCallback(self.win, self.onKeyboard)
glfw.SetWindowSizeCallback(self.win, self.onSize)
# create 3D
self.scene = Scene()
# exit flag
self.exitNow = False
def onMouseButton(self, win, button, action, mods):
#print 'mouse button: ', win, button, action, mods
pass
def onKeyboard(self, win, key, scancode, action, mods):
#print 'keyboard: ', win, key, scancode, action, mods
if action == glfw.PRESS:
# ESC to quit
if key == glfw.KEY_ESCAPE:
self.exitNow = True
else:
# toggle cut
self.scene.showCircle = not self.scene.showCircle
def onSize(self, win, width, height):
#print 'onsize: ', win, width, height
self.width = width
self.height = height
self.aspect = width/float(height)
glViewport(0, 0, self.width, self.height)
def run(self):
# initializer timer
glfw.SetTime(0.0)
t = 0.0
while not glfw.WindowShouldClose(self.win) and not self.exitNow:
# update every x seconds
currT = glfw.GetTime()
if currT - t > 0.1:
# update time
t = currT
# clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# build projection matrix
pMatrix = glutils.perspective(45.0, self.aspect, 0.1, 100.0)
mvMatrix = glutils.lookAt([0.0, 0.0, -2.0], [0.0, 0.0, 0.0],
[0.0, 1.0, 0.0])
# render
self.scene.render(pMatrix, mvMatrix)
# step
self.scene.step()
glfw.SwapBuffers(self.win)
# Poll for and process events
glfw.PollEvents()
# end
glfw.Terminate()
# main() function
def main():
print 'starting simpleglfw...'
rw = RenderWindow()
rw.run()
# call main
if __name__ == '__main__':
main()

Categories