I am using python and OpenGL to render some 3d graphics.
While successfully rendering with an easier approach (without VAO and complex attribute pointers) as described here ( using just two calls to bind my VBO: glEnableClientState(GL_VERTEX_ARRAY); glVertexPointerf( vbo ) )
When trying to combine simple VBO (containing only vertex position data) and VAO I keep getting a black screen. To implement the current code version I found this SO answer that in detail describes how this should be done. But writing this on my own i am getting nothing except black screen.
Simplified code:
import OpenGL
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import shaders
from OpenGL.arrays import vbo
import numpy as np
glutInit()
glutInitContextVersion(3, 3)
glutInitContextProfile(GLUT_CORE_PROFILE)
### Init Widow
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
glutInitWindowPosition(0, 0)
wind = glutCreateWindow("OpenGL Window")
###
### Load shaders from files and compile into program
with open("vert.glsl", "r") as f:
vert_text = f.read()
with open("frag.glsl", "r") as f:
frag_text = f.read()
vert_shader = shaders.compileShader(vert_text, GL_VERTEX_SHADER)
frag_shader = shaders.compileShader(frag_text, GL_FRAGMENT_SHADER)
main_shader = shaders.compileProgram(vert_shader, frag_shader)
###
### Create Vertex Buffer Object
data_arr = np.array(
[[-1, -1, 0], [0, 1, 0], [1, -1, 0]], dtype=np.float32
) # define vertices
vvbo = glGenBuffers(1) # generate buffer
glBindBuffer(GL_ARRAY_BUFFER, vvbo) # bind buffer
glBufferData(
GL_ARRAY_BUFFER, data_arr.nbytes, data_arr, GL_DYNAMIC_DRAW
) # setud data for buffer
###
### Setup VAO
mvao = glGenVertexArrays(1) # Create Vertex Array Object
glBindVertexArray(mvao) # Bind VAO
glEnableVertexAttribArray(0) # Enable attribute: 0
glBindBuffer(GL_ARRAY_BUFFER, vvbo) # bind vertice's buffer
glVertexAttribPointer(
0, 3, GL_FLOAT, GL_FALSE, 3 * data_arr.dtype.itemsize, 0
) # setup attribute layout
###
glBindVertexArray(0) # unbind vao
glDisableVertexAttribArray(0) # desibale attribute
glBindBuffer(GL_ARRAY_BUFFER, 0) # unbind data buffer
def showScreen():
global main_shader, mvao
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # clear screen
glUseProgram(main_shader) # enable main shader
glBindVertexArray(mvao) # bind VAO
glDrawArrays(GL_TRIANGLES, 0, 3) # draw
glBindVertexArray(0) # unbind VAO
glUseProgram(0) # unbind shader
glutSwapBuffers() # update screen
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)
glutMainLoop()
frag.glsl:
#version 330 core
out vec4 _fragColor;
void main()
{
_fragColor = vec4(0.5);
}
vert.glsl:
#version 330 core
layout (location = 0) in vec3 aPos;
void main()
{
gl_Position = vec4(aPos, 1.0);
}
So what exactly I am doing wrong?
Python version -> 3.8
If a named buffer object is bound, then the 6th parameter of glVertexAttribPointer is treated as a byte offset into the buffer object's data store. But the type of the parameter is a pointer anyway (c_void_p).
So if the offset is 0, then the 6th parameter can either be None or c_void_p(0):
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * data_arr.dtype.itemsize, 0)
glVertexAttribPointer(
0, 3, GL_FLOAT, GL_FALSE, 3 * data_arr.dtype.itemsize, None
)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 18 days ago.
The community is reviewing whether to reopen this question as of 18 days ago.
Improve this question
I try to setup a simple 3D Engine in pyOpenGL. The current goal was to achieve a rectangle, which isn't displaying.
The render method I use is following:
#staticmethod
def render(model: RawModel):
glBindVertexArray(model.get_vao_id())
glEnableVertexAttribArray(0)
glDrawArrays(GL_TRIANGLES, 1, model.get_vertex_count())
glDisableVertexAttribArray(0)
glBindVertexArray(0)
I suppose something goes wrong with the glDrawArrays() method, because of how I bound my Buffer data:
#classmethod
def bind_indices_buffer(cls, attribute_number: int, data: list):
data = numpy.array(data, dtype='float32')
vbo_id = glGenBuffers(1)
cls.__vbos.append(vbo_id)
glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
glBufferData(GL_ARRAY_BUFFER, data, GL_STATIC_DRAW)
glVertexAttribPointer(attribute_number, 3, GL_FLOAT, False, 0, 0)
glBindBuffer(GL_ARRAY_BUFFER, 0)
The tutorial I followed was in Java and before the data was put in the glBufferData() method it was converted into a 'FloatBuffer' object. I don't know how to achieve that in Python so I just put it in as an float32 array.
Anyone knows what I exactly did wrong?
All of my files:
main.py:
from display_manager import DisplayManager
from renderer import Renderer
from loader import Loader
from raw_model import RawModel
from OpenGL.GLUT import *
def main():
vertices = [
# left bottom triangle
-0.5, 0.5, 0,
-0.5, -0.5, 0,
0.5, -0.5, 0,
# right top triangle
0.5, -0.5, 0,
0.5, 0.5, 0,
-0.5, 0.5, 0
]
display = DisplayManager()
display.create_display("test") # creates display
renderer = Renderer()
loader = Loader()
model = loader.load_to_vao(vertices)
while glutGetWindow() != 0:
renderer.prepare()
renderer.render(model)
glutMainLoopEvent()
if __name__ == '__main__':
main()
raw_model.py:
class RawModel:
def __init__(self, vao_id: int, vertex_count: int):
self.__vao_id = vao_id
self.__vertex_count = vertex_count
def get_vao_id(self):
return self.__vao_id
def get_vertex_count(self):
return self.__vertex_count
renderer.py:
from OpenGL.GL import *
from raw_model import RawModel
class Renderer:
#staticmethod
def prepare():
glClearColor(1, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT)
#staticmethod
def render(model: RawModel):
glBindVertexArray(model.get_vao_id())
glEnableVertexAttribArray(0)
glDrawArrays(GL_TRIANGLES, 1, model.get_vertex_count())
glDisableVertexAttribArray(0)
glBindVertexArray(0)
loader.py:
from OpenGL.GL import *
from OpenGL.GLUT import *
from raw_model import RawModel
class Loader:
__vaos = []
__vbos = []
def load_to_vao(self, positions: list):
vao_id = self.create_vao()
self.bind_indices_buffer(0, positions)
self.unbind_vao()
return RawModel(vao_id, len(positions))
#classmethod
def clean_up(cls):
for vao in cls.__vaos:
glDeleteVertexArrays(1, [vao])
for vbo in cls.__vbos:
glDeleteBuffers(1, [vbo])
#classmethod
def create_vao(cls):
vao_id = glGenVertexArrays(1)
cls.__vaos.append(vao_id)
glBindVertexArray(vao_id)
return vao_id
#classmethod
def bind_indices_buffer(cls, attribute_number: int, data: list):
vbo_id = glGenBuffers(1)
cls.__vbos.append(vbo_id)
glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
glBufferData(GL_ARRAY_BUFFER, str(data), GL_STATIC_DRAW)
glVertexAttribPointer(attribute_number, 3, GL_FLOAT, False, 0, 0)
glBindBuffer(GL_ARRAY_BUFFER, 0)
#staticmethod
def unbind_vao():
glBindVertexArray(0)
display_manager.py:
from OpenGL.GL import *
from OpenGL.GLUT import *
class DisplayManager:
__window_id = 0
def __init__(self, x: int = 1920, y: int = 1080):
if x is not None: self.__width = x
if y is not None: self.__height = y
self.next_window_id()
def create_display(self, window_name):
glutInit()
glutInitDisplayMode(GLUT_RGBA) # initialize colors
glutInitWindowSize(self.get_width(), self.get_height()) # set windows size
glutInitWindowPosition(0, 0) # set window position
glutCreateWindow(f"{window_name}") # create window (with a name) and set window attribute
glutSetWindow(self.get_window_id())
glutDisplayFunc(self.update_display)
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS) # prevent program from stopping
#staticmethod
def update_display():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Remove everything from screen (i.e. displays all white)
glLoadIdentity() # Reset all graphic/shape's position
glutSwapBuffers() # Important for double buffering
def destroy_window(self):
glutDestroyWindow(self.get_window_id())
def get_width(self):
return self.__width
def get_height(self):
return self.__height
#classmethod
def next_window_id(cls):
cls.__window_id += 1
def get_window_id(self):
return self.__window_id
The problem is here:
glVertexAttribPointer(attribute_number, 3, GL_FLOAT, False, 0, 0)
glVertexAttribPointer(attribute_number, 3, GL_FLOAT, False, 0, None)
The type of the lase argument of glVertexAttribIPointer is const GLvoid *. So the argument must be None or ctypes.c_void_p(0), but not 0.
I have separated the program to three different files, but I don't understand why I get error on glVertexAttribPointer on line 70. I'm using Python 3.10.8
main.py
import glfw
import Shaders
from OpenGL.GL import *
from OpenGL.GLUT import *
from Math_3d import Vector2f
class Window:
def __init__(self, width: int, height: int, title: str):
if not glfw.init():
raise Exception("glfw can not be initialized")
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)
self._win = glfw.create_window(width, height, title, None, None)
if not self._win:
glfw.terminate()
raise Exception("glfw window can not be created")
glfw.set_window_pos(self._win, 400, 200)
glfw.make_context_current(self._win)
def createshaders(self):
# Request program and shader slots from the GPU
program = glCreateProgram()
vertex = glCreateShader(GL_VERTEX_SHADER)
fragment = glCreateShader(GL_FRAGMENT_SHADER)
# Set shader sources
glShaderSource(vertex, Shaders.vertex_code)
glShaderSource(fragment, Shaders.fragment_code)
# Compile shaders
glCompileShader(vertex)
glCompileShader(fragment)
if not glGetShaderiv(vertex, GL_COMPILE_STATUS):
report_shader = glGetShaderInfoLog(vertex)
print(report_shader)
raise RuntimeError("Vertex shader compilation error")
if not glGetShaderiv(fragment, GL_COMPILE_STATUS):
report_frag = glGetShaderInfoLog(fragment)
print(report_frag)
raise RuntimeError("Fragment shader compilation error")
# Link objects to program
glAttachShader(program, vertex)
glAttachShader(program, fragment)
glLinkProgram(program)
if not glGetProgramiv(program, GL_LINK_STATUS):
print(glGetProgramInfoLog(program))
raise RuntimeError('Linking error')
# Get rid of shaders
glDetachShader(program, vertex)
glDetachShader(program, fragment)
# Make default program to run
glUseProgram(program)
# Vertex Buffer Object
# Create point vertex data
v2f_1 = Vector2f(0.0, 0.0)
# Request a buffer slot from GPU
buffer = glGenBuffers(1)
# Make this buffer the default one
glBindBuffer(GL_ARRAY_BUFFER, buffer)
strides = v2f_1.data.strides[0]
loc = glGetAttribLocation(program, 'position')
glEnableVertexAttribArray(loc)
glVertexAttribPointer(loc, 2, GL_FLOAT, False, strides, None)
# glBufferData(GL_ARRAY_BUFFER, v2f_1, v2f_1, GL_DYNAMIC_DRAW)
def renderscene(self):
while not glfw.window_should_close(self._win):
glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT)
glDrawArrays(GL_POINTS, 0, 1)
glfw.swap_buffers(self._win)
glfw.terminate()
if __name__ == '__main__':
win = Window(1024, 768, "GLFW Window")
win.createshaders() # Create and initialize shaders and initialize Vertex Buffer Object
win.renderscene() # Swap buffer and render scene
Shaders.py
vertex_code = """
attribute vec2 position;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
}
"""
fragment_code = """
void main()
{
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
}
"""
Math_3d.py
import numpy as np
class Vector2f:
def __init__(self, x, y):
self.data = np.array([x, y], dtype=np.float32)
if __name__ == '__main__':
vec2 = Vector2f(0.0, 0.0)
print(vec2.data)
print(type(vec2.data.strides[0]))
print(vec2.data.strides[0])
I have tried to debug the line 70, but did not get any good result while using PyCharm.
Any recommendations on this? Closest answers would be according to 61491497 and 56957118 what I am aiming for.
You're using a Core profile OpenGL Context (glfw.OPENGL_CORE_PROFILE). Therefore you have to create a Vertex Array Obejct:
class Window:
# [...]
def createshaders(self):
# [...]
v2f_1 = Vector2f(0.0, 0.0)
# Request a buffer slot from GPU
buffer = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, buffer)
strides = v2f_1.data.strides[0]
glBufferData(GL_ARRAY_BUFFER, v2f_1.data, GL_DYNAMIC_DRAW)
vao = glGenVertexArrays(1)
glBindVertexArray(vao)
loc = glGetAttribLocation(program, 'position')
glEnableVertexAttribArray(loc)
glVertexAttribPointer(loc, 2, GL_FLOAT, False, strides, None)
Additionally, you need to change either the background color or the fragment color, because you won't be able to see a black point on a black background. e.g. red:
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
I have written a code to render a triangle using a shader program. I want to rotate the triangle. I'm using PyGLM to set a transformation matrix. Here I'm presenting the whole code. If I run this code a triangle is appearing in the window as expected, but there is no rotation. I think I've failed to pass the transformation matrix to the buffer.
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GL import shaders
import numpy as np
import glm
VERTEX_SHADER = """
#version 330
in vec4 position;
in vec3 color;
out vec3 newColor;
void main()
{
gl_Position = position;
newColor = color;
}
"""
FRAGMENT_SHADER = """
#version 330
in vec3 newColor;
out vec4 outColor;
void main()
{
outColor = vec4(newColor,1.0f);
}
"""
shaderProgram = None
def initliaze():
global VERTEXT_SHADER
global FRAGMEN_SHADER
global shaderProgram
vertexshader = shaders.compileShader(VERTEX_SHADER, GL_VERTEX_SHADER)
fragmentshader = shaders.compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER)
shaderProgram = shaders.compileProgram(vertexshader, fragmentshader)
triangles = [-0.5, -0.5, 0.0, 1.0,0.0,0.0,
0.5, -0.5, 0.0, 0.0,1.0,0.0,
0.0, 0.5, 0.0, 0,0,0.0,1.0]
triangles = np.array(triangles, dtype=np.float32)
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, triangles.nbytes, triangles, GL_DYNAMIC_DRAW)
position = glGetAttribLocation(shaderProgram, 'position')
glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))
glEnableVertexAttribArray(position)
color = glGetAttribLocation(shaderProgram, 'color')
glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))
glEnableVertexAttribArray(color)
def render():
global shaderProgram
global angle
#shader
glUseProgram(shaderProgram)
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
#transform matrix
transform = glm.mat4(1)
transform = glm.translate(transform, glm.vec3(0.5,-0.5,0.0))
transform = glm.rotate(transform, glutGet(GLUT_ELAPSED_TIME),glm.vec3(0,0,1))
transformLoc = glGetUniformLocation(shaderProgram,"transform")
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm.value_ptr(transform))
#render program
glDrawArrays(GL_TRIANGLES, 0, 3)
glUseProgram(0)
glutSwapBuffers()
def main():
glutInit([])
glutInitWindowSize(640, 480)
glutCreateWindow("pyopengl with glut 2")
initliaze()
glutDisplayFunc(render)
glutMainLoop()
if __name__ == '__main__':
main()
In VERTEX_SHADER you didn't mentioned transform variable. So your triangle position remain fixed after you run the program. Change your VERTEX_SHADER as following.
VERTEX_SHADER = """
#version 330
in vec4 position;
in vec3 color;
out vec3 newColor;
uniform mat4 transform;
void main()
{
gl_Position = transform*position;
newColor = color;
}
"""
In your code you are accessing the location of location of a uniform variable transform by following line.
transformLoc = glGetUniformLocation(shaderProgram,"transform")
You should add glutPostRedisplay() function after the glutSwapBuffers() function to visualize the continuous change.
Looks like you will want to create your own library from GLM. What you're doing in the code above no longer works. As another user stated, this is a good template to build functionality from. I'd suggest downloading GLM, taking it apart, and reverse engineering what you need into Python.
I cannot figure this out for the life of me. I need a second pair of eyes ... or a better brain. I am trying to get this "Hello Triangle" python example working. I've been translating it from a c tutorial. However, I keep getting this error no matter what I do.
Traceback (most recent call last):
File ".../demo/tester.py", line 107, in <module>
if __name__ == '__main__': main()
File ".../demo/tester.py", line 87, in main
glDrawArrays(GL_TRIANGLES, 0, 3)
File ".../venv/lib/python3.6/site packages/OpenGL/platform/baseplatform.py", line 402, in __call__
return self( *args, **named )
File ".../venv/lib/python3.6/site-packages/OpenGL/error.py", line 232, in glCheckError
baseOperation = baseOperation,
OpenGL.error.GLError: GLError(
err = 1282,
description = b'invalid operation',
baseOperation = glDrawArrays,
cArguments = (GL_TRIANGLES, 0, 3)
My code is below. I am running on a Mac so you'll notice some things in there that might not be needed for PC. Everything works fine up until the glDrawArrays. I know that some of the functions between openGL for C vs python using pyOpenGL are a bit different. I've been cross referencing the documentation to make sure I am not trying write like a C programmer in Python.
try:
from AppKit import NSApp, NSApplication
except:
pass
import sys
import cyglfw3 as glfw
import numpy as np
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.arrays import vbo as glvbo
def main():
glfw.Init()
glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
window = glfw.CreateWindow(800, 600, 'LearnOpenGL', None)
if window is None:
glfw.Terminate()
exit()
glfw.MakeContextCurrent(window)
glfw.SetFramebufferSizeCallback(window, framebuffer_size_callback())
# Setting up a vertex buffer
verts = glvbo.VBO(
np.array([[0.0, 0.5, 0.0], [0.5, -0.5, 0.0], [-0.5, -0.5, 0.0]], 'f')
)
vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, verts.size, verts, GL_STATIC_DRAW)
vao = glGenVertexArrays(1)
glBindVertexArray(vao)
glEnableVertexAttribArray(vao)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
vertex_shader = """
#version 330 core
in vec3 vp;
void main() {
gl_Position = vec4(vp, 1.0);
}"""
fragment_shader = """
#version 330 core
out vec4 frag_color;
void main() {
frag_color = vec4(0.5, 0.0, 0.5, 1.0);
}"""
vs = glCreateShader(GL_VERTEX_SHADER)
glShaderSource(vs, vertex_shader)
glCompileShader(vs)
if glGetShaderiv(vs, GL_COMPILE_STATUS) != GL_TRUE:
raise Exception("vertex shader did not compile")
fs = glCreateShader(GL_FRAGMENT_SHADER)
glShaderSource(fs, fragment_shader)
glCompileShader(fs)
if glGetShaderiv(fs, GL_COMPILE_STATUS) != GL_TRUE:
raise Exception("fragment shader did not compile")
sp = glCreateProgram()
glAttachShader(sp, fs)
glAttachShader(sp, vs)
glLinkProgram(sp)
if glGetProgramiv(sp, GL_LINK_STATUS) != GL_TRUE:
raise Exception("program did not link")
while not glfw.WindowShouldClose(window):
processInput(window)
glClearColor(0.0, 0.0, 0.0, 1.0)
glClear(GL_COLOR_BUFFER_BIT)
glUseProgram(sp)
glBindVertexArray(vao)
glDrawArrays(GL_TRIANGLES, 0, 3) # This is where things happen
glfw.PollEvents()
glfw.SwapBuffers(window)
glfw.Terminate()
exit()
def framebuffer_size_callback():
glViewport(0, 0, 800, 600)
def processInput(window):
if glfw.GetKey(window, glfw.KEY_ESCAPE) == glfw.PRESS:
glfw.SetWindowShouldClose(window, True)
if __name__ == '__main__': main()
All I want to do at the end of the day, is draw a triangle :(
I determined there were 2 issues.
As BDL mentioned the glEnableVertexAttribArray was not setup appropriately. It needed an index and not a vertex array object.
The glBufferData size was incorrect as the size needed to be provided in bytes. A quick search online revealed that (numpy.size * numpy.itemsize) returns the size of the array.
With these 2 things done... I have a triangle.
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()