Does glBufferData need a Buffer object as the 'data' parameter? [closed] - python

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.

Related

glGenVertexArrays function doesn't work in every Python script

The glGenVertexArrays function throws this excpetion in one script (loader.py): "OpenGL.error.NullFunctionError: Attempt to call an undefined function glGenVertexArrays", but not in the other script (display_manager.py)
I guess it has something to do with initialization.
loader.py (the 'create_vao' function is relevant)
from raw_model import RawModel
from OpenGL.GL import *
from OpenGL.GLUT import *
class Loader:
__vaos = []
__vbos = []
def load_to_vao(self, positions: list):
vao_id = self.create_vao()
self.store_data_in_attribute_list(0, positions)
self.unbind_vao()
return RawModel(vao_id, len(positions)//3)
#classmethod
def clean_up(cls):
for vao in cls.__vaos:
glDeleteVertexArrays(vao)
for vbo in cls.__vbos:
glDeleteBuffers(vbo)
#classmethod
def create_vao(cls):
vao_id = glGenVertexArrays(1)
cls.__vaos.append(vao_id)
glBindVertexArray(vao_id)
return vao_id
#classmethod
def store_data_in_attribute_list(cls, attribute_number: int, data: list):
vbo_id = glGenBuffers()
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)
#staticmethod
def unbind_vao():
glBindVertexArray(0)
display_manager.py (the 'create_display' function is relevant):
from OpenGL.GL import *
from OpenGL.GLUT import *
class DisplayManager:
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
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
print(glGenVertexArrays(1))
input("This ran")
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 get_width(self):
return self.__width
def get_height(self):
return self.__height
#classmethod
def set_window(cls, window):
cls.__WIND = window
I already tried to include the glutInit function into the loader.py script, with no success. I also tried to figure out in which scripts the glGenVertexArrays function works, with no real clue.
In my main.py function I called the create_vao method before I even created the window. Swapping the order did the trick.

Why glVertexAttribPointer throws 1282 error while trying to draw one point on screen with pyOpenGL and glfw?

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);

Getting black screen using VAO in PyOpenGL

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
)

Point Cloud Distortion when Drawing with modern OpenGL

I found this nice tutorial of drawing and rotating a cube with PyQt and modern OpenGL. My objective was to adapt the script for point clouds, by doing the following (see also code below):
Load point cloud using Open3D and extract coordinates & colors as numpy arrays
Create Vertex Buffer Objects (VBOs) from the arrays
Change the drawing function to gl.glDrawElements(gl.GL_POINTS, ...)
Unfortunately then the point cloud is very distorted and thin (see screenshot). It should actually be a room with chairs and walls.
Do you see if I made a mistake with the VBOs or drawing? Or is there a better way of loading a point cloud?
I tested the example with the old fixed pipeline (glBegin(GL_POINTS) ... glEnd()) and there the point cloud is correctly drawn (but also the performance really bad!).
from PyQt5 import QtCore # core Qt functionality
from PyQt5 import QtGui # extends QtCore with GUI functionality
from PyQt5 import QtOpenGL # provides QGLWidget, a special OpenGL QWidget
from PyQt5 import QtWidgets
import OpenGL.GL as gl # python wrapping of OpenGL
from OpenGL import GLU # OpenGL Utility Library, extends OpenGL functionality
from OpenGL.arrays import vbo
import numpy as np
import open3d as o3d
import sys
# Loading the point cloud from file
def load_pointcloud():
pcd = o3d.io.read_point_cloud("../pointclouds/0004.ply")
print(pcd)
print("Pointcloud Center: " + str(pcd.get_center()))
points = np.asarray(pcd.points)
colors = np.asarray(pcd.colors)
return points, colors
#### here was only the GUI code (slider, ...) , which works fine! ####
class GLWidget(QtOpenGL.QGLWidget):
def __init__(self, parent=None):
self.parent = parent
QtOpenGL.QGLWidget.__init__(self, parent)
def initializeGL(self):
self.qglClearColor(QtGui.QColor(250, 250, 250)) # initialize the screen to blue
gl.glEnable(gl.GL_DEPTH_TEST) # enable depth testing
self.initGeometryPC()
self.rotX = 0.0
self.rotY = 0.0
self.rotZ = 0.0
def setRotX(self, val):
self.rotX = val
def setRotY(self, val):
self.rotY = val
def setRotZ(self, val):
self.rotZ = val
def resizeGL(self, width, height):
gl.glViewport(0, 0, width, height)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
aspect = width / float(height)
#GLU.gluPerspective(45.0, aspect, 1.0, 100.0) #GLU.gluPerspective(45.0, aspect, 1.0, 100.0)
gl.glOrtho(-2.0, 2.0, -2.0, 2.0, 1.0, 100.0)
gl.glMatrixMode(gl.GL_MODELVIEW)
def paintGL(self):
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glPushMatrix() # push the current matrix to the current stack
gl.glTranslate(0.0, 0.0, -5.0) # third, translate cube to specified depth
#gl.glScale(.5, .5, .5) # second, scale point cloud
gl.glRotate(self.rotX, 1.0, 0.0, 0.0)
gl.glRotate(self.rotY, 0.0, 1.0, 0.0)
gl.glRotate(self.rotZ, 0.0, 0.0, 1.0)
gl.glTranslate(-0.5, -0.5, -0.5) # first, translate point cloud center to origin
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glEnableClientState(gl.GL_COLOR_ARRAY)
gl.glVertexPointer(3, gl.GL_FLOAT, 0, self.vertVBO)
gl.glColorPointer(3, gl.GL_FLOAT, 0, self.colorVBO)
gl.glPointSize(2)
gl.glDrawElements(gl.GL_POINTS, len(self.pointsIdxArray), gl.GL_UNSIGNED_INT, self.pointsIdxArray)
gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
gl.glDisableClientState(gl.GL_COLOR_ARRAY)
gl.glPopMatrix() # restore the previous modelview matrix
# Push geometric data to GPU
def initGeometryPC(self):
points, colors = load_pointcloud()
self.pointsVtxArray = points
self.vertVBO = vbo.VBO(np.reshape(self.pointsVtxArray, (1, -1)).astype(np.float32))
self.vertVBO.bind()
self.pointsClrArray = colors
self.colorVBO = vbo.VBO(np.reshape(self.pointsClrArray, (1, -1)).astype(np.float32))
self.colorVBO.bind()
self.pointsIdxArray = np.arange(len(points))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
After a long search I came upon this stackoverflow-post. I adapted my code to that answer by storing point coordinates and colors together in one vbo-object (gl.glGenBuffers(1)). Then I define the vertex and color pointer with the specific stride and offset:
gl.glVertexPointer(3, gl.GL_FLOAT, 6*4, None)
Stride= 24 bytes: [x, y, z, r, g, b] * sizeof(float)
gl.glColorPointer(3, gl.GL_FLOAT, 6*4, ctypes.c_void_p(3*4))
Offset= 12 bytes: the rgb color starts after the 3 coordinates x, y, z
And finally I use gl.glDrawArrays(gl.GL_POINTS, 0, noOfVertices) for drawing the point cloud.
The full code can be seen below (marked with ### NEW ### comments):
from PyQt5 import QtCore # core Qt functionality
from PyQt5 import QtGui # extends QtCore with GUI functionality
from PyQt5 import QtOpenGL # provides QGLWidget, a special OpenGL QWidget
from PyQt5 import QtWidgets
import OpenGL.GL as gl # python wrapping of OpenGL
from OpenGL import GLU # OpenGL Utility Library, extends OpenGL functionality
from OpenGL.arrays import vbo
import numpy as np
import open3d as o3d
import ctypes
import sys # we'll need this later to run our Qt application
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self) # call the init for the parent class
self.resize(300, 300)
self.setWindowTitle('Hello OpenGL App')
self.glWidget = GLWidget(self)
self.initGUI()
timer = QtCore.QTimer(self)
timer.setInterval(20) # period, in milliseconds
timer.timeout.connect(self.glWidget.updateGL)
timer.start()
def initGUI(self):
central_widget = QtWidgets.QWidget()
gui_layout = QtWidgets.QVBoxLayout()
central_widget.setLayout(gui_layout)
self.setCentralWidget(central_widget)
gui_layout.addWidget(self.glWidget)
sliderX = QtWidgets.QSlider(QtCore.Qt.Horizontal)
sliderX.valueChanged.connect(lambda val: self.glWidget.setRotX(val))
sliderY = QtWidgets.QSlider(QtCore.Qt.Horizontal)
sliderY.valueChanged.connect(lambda val: self.glWidget.setRotY(val))
sliderZ = QtWidgets.QSlider(QtCore.Qt.Horizontal)
sliderZ.valueChanged.connect(lambda val: self.glWidget.setRotZ(val))
gui_layout.addWidget(sliderX)
gui_layout.addWidget(sliderY)
gui_layout.addWidget(sliderZ)
class GLWidget(QtOpenGL.QGLWidget):
def __init__(self, parent=None):
self.parent = parent
QtOpenGL.QGLWidget.__init__(self, parent)
def initializeGL(self):
self.qglClearColor(QtGui.QColor(100, 100, 100)) # initialize the screen to blue
gl.glEnable(gl.GL_DEPTH_TEST) # enable depth testing
self.initGeometry()
self.rotX = 0.0
self.rotY = 0.0
self.rotZ = 0.0
def setRotX(self, val):
self.rotX = val
def setRotY(self, val):
self.rotY = val
def setRotZ(self, val):
self.rotZ = val
def resizeGL(self, width, height):
gl.glViewport(0, 0, width, height)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
aspect = width / float(height)
GLU.gluPerspective(45.0, aspect, 1.0, 100.0)
gl.glMatrixMode(gl.GL_MODELVIEW)
def paintGL(self):
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glPushMatrix() # push the current matrix to the current stack
gl.glTranslate(0.0, 0.0, -3.0) # third, translate cube to specified depth
#gl.glScale(20.0, 20.0, 20.0) # second, scale cube
gl.glRotate(self.rotX, 1.0, 0.0, 0.0)
gl.glRotate(self.rotY, 0.0, 1.0, 0.0)
gl.glRotate(self.rotZ, 0.0, 0.0, 1.0)
gl.glTranslate(-0.5, -0.5, -0.5) # first, translate cube center to origin
# Point size
gl.glPointSize(3)
### NEW ###
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo)
stride = 6*4 # (24 bates) : [x, y, z, r, g, b] * sizeof(float)
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glVertexPointer(3, gl.GL_FLOAT, stride, None)
gl.glEnableClientState(gl.GL_COLOR_ARRAY)
offset = 3*4 # (12 bytes) : the rgb color starts after the 3 coordinates x, y, z
gl.glColorPointer(3, gl.GL_FLOAT, stride, ctypes.c_void_p(offset))
noOfVertices = self.noPoints
gl.glDrawArrays(gl.GL_POINTS, 0, noOfVertices)
gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
gl.glDisableClientState(gl.GL_COLOR_ARRAY)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
### NEW ###
gl.glPopMatrix() # restore the previous modelview matrix
def initGeometry(self):
vArray = self.LoadVertices()
self.noPoints = len(vArray) // 6
print("No. of Points: %s" % self.noPoints)
self.vbo = self.CreateBuffer(vArray)
### NEW ###
def LoadVertices(self):
pcd = o3d.io.read_point_cloud("../pointclouds/0004.ply")
print(pcd)
print("Pointcloud Center: " + str(pcd.get_center()))
points = np.asarray(pcd.points).astype('float32')
colors = np.asarray(pcd.colors).astype('float32')
attributes = np.concatenate((points, colors),axis=1)
print("Attributes shape: " + str(attributes.shape))
return attributes.flatten()
def CreateBuffer(self, attributes):
bufferdata = (ctypes.c_float*len(attributes))(*attributes) # float buffer
buffersize = len(attributes)*4 # buffer size in bytes
vbo = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, buffersize, bufferdata, gl.GL_STATIC_DRAW)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
return vbo
### NEW ###
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
However, I still did not find the correct parameters for initial approach above with two separate VBOs for coordinate and color. So I am happy for further comments.

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