Giter VIP home page Giter VIP logo

pyopengl's Introduction

PyOpenGL and PyOpenGL_Accelerate

PyOpenGL is normally distributed via PyPI using standard pip:

$ pip install PyOpenGL PyOpenGL_accelerate

You can install this repository by branching/cloning and running pip:

$ cd pyopengl
$ pip install -e .
$ cd accelerate
$ pip install -e .

Note that to compile PyOpenGL_accelerate you will need to have a functioning Python extension-compiling environment.

Learning PyOpenGL

If you are new to PyOpenGL, you likely want to start with the OpenGLContext tutorial page. Those tutorials require OpenGLContext, (which is a big wrapper including a whole scenegraph engine, VRML97 parser, lots of demos, etc) you can install that with:

$ pip2.7 install "OpenGLContext-full==3.1.1"

Or you can clone it (including the tutorial sources) with:

$ git clone https://github.com/mcfletch/openglcontext.git

or (for GitHub usage):

$ git clone https://github.com/mcfletch/pyopengl.git

The documentation pages are useful for looking up the parameters and semantics of PyOpenGL calls.

Running Tests

You can run the PyOpenGL test suite from a source-code checkout, you will need:

  • git (for the checkout)
  • GLUT (FreeGLUT)
  • GLExtrusion library (libgle)
  • GLU (normally available on any OpenGL-capable machine)
  • tox (pip install tox)

Running the test suite from a top-level checkout looks like:

$ tox

The result being a lot of tests being run in a matrix of environments. All of the environment will pull in pygame, some will also pull in numpy. Some will have accelerate, and some will not.

Travis Tests Appveyor Build Latest PyPI Version Monthly download counter

pyopengl's People

Contributors

andriyor avatar cgohlke avatar epicwink avatar illume avatar kmichel avatar laerreal avatar mcfletch avatar mmatl avatar smoe avatar swt2c avatar t20100 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyopengl's Issues

Thread support

Hello, I am wondering if pyOpenGL has thread support

Typically resources are loaded on a separate thread whilst the main thread renders a loading progress bar

When I try to load textures on a separate thread, the thread cannot load them into the graphics card because the context doesn't seem to be available on that thread, do I need to use global on that thread to access the context or something?

Thanks

@mcfletch

Unable to import _errors

I'm unable to run the following from OpenGL.raw.GL import _errors on Arch Linux on mesa-18.2.3-1.
Every time I try, I get the following error trace:

  File "<stdin>", line 1, in <module>
  File "PYTHON_INSTALLATION/lib/python3.7/site-packages/OpenGL/raw/GL/_errors.py", line 4, in <module>
    _error_checker = _ErrorChecker( _p, _p.GL.glGetError )
  File "PYTHON_INSTALLATION/lib/python3.7/ctypes/__init__.py", line 369, in __getattr__
    func = self.__getitem__(name)
  File "PYTHON_INSTALLATION/lib/python3.7/ctypes/__init__.py", line 374, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: /usr/lib/libOSMesa.so.8: undefined symbol: glGetError

Caused by

_error_checker = _ErrorChecker( _p, _p.GL.glGetError )

I don't have any experience with OpenGL or Mesa, so I would really appreciate any help with resolving this issue.

Missing PyOpenGL-accelerate 3.1.3b2

https://pypi.org/project/PyOpenGL/#history has a 3.1.3b2, which has Python 3.7 compatibility fixes.

https://pypi.org/project/PyOpenGL-accelerate/#history doesnt have a 3.1.3b2

I suspect that PyOpenGL-accelerate 3.1.3b1 is incompatible with PyOpenGL-3.1.3b2 .

I am experiencing aborts and failures on Python 2.7 when PyOpenGL-accelerate 3.1.3b1 is installed with PyOpenGL-3.1.3b2 , especially when using numpy.

Like AttributeError: 'module' object has no attribute 'float128'

Cut a new release?

It's been quite a while since a release has been made, and there are various fixes committed. Any chance of cutting a new release?

NoneType error on import.

When I attempt to import the module in Python 3.8, I get this error:
Traceback (most recent call last): File "D:\pygame_test.py", line 3, in <module> from OpenGL.GLU import * File "D:\Python38-32\lib\site-packages\OpenGL\GLU\__init__.py", line 2, in <module> from OpenGL import platform File "D:\Python38-32\lib\site-packages\OpenGL\platform\__init__.py", line 36, in <module> _load() File "D:\Python38-32\lib\site-packages\OpenGL\platform\__init__.py", line 30, in _load plugin = plugin_class() TypeError: 'NoneType' object is not callable
This is my code:
import OpenGL import pygame from OpenGL.GLU import * print("Imports successful!") # If you see this printed to the console then installation was successful pygame.init() gameDisplay = pygame.display.set_mode((800,600)) pygame.display.set_caption('Test 101')

test_memory_usage fails on ARM aarch64

[  217s] =================================== FAILURES ===================================
[  217s] ______________________________ test_memory_usage _______________________________
[  217s] 
[  217s] args = (), named = {}
[  217s] 
[  217s]     @wraps( function )
[  217s]     def test_function( *args, **named ):
[  217s]         global SCREEN
[  217s]         pygame.display.init()
[  217s]         SCREEN = pygame.display.set_mode(
[  217s]             size,
[  217s]             pygame.OPENGL | pygame.DOUBLEBUF,
[  217s]         )
[  217s]         pygame.display.set_caption(name or function.__name__)
[  217s]         pygame.key.set_repeat(500,30)
[  217s]         try:
[  217s] >           return function(*args, **named)
[  217s] 
[  217s] tests/pygamegltest.py:42: 
[  217s] _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
[  217s] 
[  217s]     @pytest.mark.skipif(not psutil,reason='No psutil available')
[  217s]     @pytest.mark.skipif(not np,reason='No Numpy available')
[  217s]     @pygamegltest.pygametest()
[  217s]     def test_memory_usage():
[  217s]         """Test allocation as reported in Github #5"""
[  217s]         start = get_current_memory()
[  217s]         np_array = np.zeros( (120000, 1,6),dtype='f')
[  217s]         after_np = get_current_memory()
[  217s]         buffer = vbo.VBO( np_array )
[  217s]         with buffer:
[  217s]             after_transfer = get_current_memory()
[  217s]     
[  217s]         # 2.8MB buffer, on Python 2.7 is around 2.9MB usage, but on
[  217s]         # Python 3.6 we see a consistently higher memory usage (3.1MB),
[  217s]         # somewhat disturbing...
[  217s]         assert (after_np - start) <= 3200000, (after_np-start)
[  217s] >       assert (after_transfer - after_np) <= 3200000, (after_transfer-after_np)
[  217s] E       AssertionError: 3219456
[  217s] E       assert (130711552 - 127492096) <= 3200000
[  217s] 
[  217s] tests/test_vbo_memusage.py:36: AssertionError

No `GL_RG_INTEGER` in `OpenGL.images.COMPONENT_COUNTS` dictionary

I triggered a bug while trying to call glGetTexImage with GL_RG_INTEGER format. It throws ValueError: Unrecognised image format: GL_RG_INTEGER since GL_RG_INTEGER is not in OpenGL.images.COMPONENT_COUNTS. I hacked it around by adding it to the dictionary and it works.

huge memory allocation when sending numpy array to vbo, despite ERROR_ON_COPY

When I sent this big numpy array to the vbo, the memory goes up a gig.

The shape of the array is (120000, 1), each vertex is x,y,z,r,g,b.

I added OpenGL.ERROR_ON_COPY = True but it doesn't trigger.

the vbo line is self.vbo = vbo_mod.VBO( vertices, usage=buffer.usage) . Nothing special AFAICT.

The only lead I have, is that I build and delete many vao/vbos as the mesh is filled and they are kept in memory (even if one uses vbo.delete(), which I do ).

Either I am doing something wrong or I hit a buggy use case.

Any idea on how to solve this ?

glClear causes segmentation fault on OSMesa and OpenGL 2

What the title says. My context is initialized like this

    shared_win = None
    ctx = mesa.OSMesaCreateContext(GL_RGB, shared_win)
    win = ctx
    buf = arrays.GLubyteArray.zeros((height, width, 3))
    mesap = arrays.ArrayDatatype.dataPointer(buf)
    assert(mesa.OSMesaMakeCurrent(ctx, GLuint(mesap), GL_UNSIGNED_BYTE, width, height))

Apparently I can only use OSMesa with OpenGL 2, otherwise I wouldn't be using it.

I'm using Linux openSUSE Tumbleweed with Mesa drivers version 19.1.5.

OpenGL.error.GLError: GLError - err = 1281 - description = b'invalid value'

Im using https://github.com/swistakm/pyimgui, which uses this library and on clicking some custom keys on my Mouse (Logitech G502), I can consistently produce the following error, which crashes the application, any ideas?

Do note, that one of the custom keys will trigger the Windows action to "Show the Desktop", meaning minimize all windows and I believe its related to that, at least it seems like it.

Im using Python 3.9 on Windows 10 - 2004 with pyopengl 3.1.5.

OpenGL.error.GLError: GLError(
	err = 1281,
	description = b'invalid value',
	baseOperation = glScissor,
	cArguments = (81, 1, -35, 727)
)

I tried to put OpenGL.ERROR_CHECKING = False but that didn't do the trick yet.

"Unable to create basic Accelerated OpenGL renderer" on macOS

Hello pyopengl folks, pyqtgraph maintainer here. Love this library, we're able to have 3d capabilities thanks to pyopengl.

We're having some CI failures, relating to openGL, and I'm hoping that you all may have some input/suggestions.

on our macOS CI platforms, we intermittently get errors like:

=================================== FAILURES ===================================
___________________ testExamples[ GLMeshItem.py - PySide2 ] ____________________
[gw0] darwin -- Python 3.7.9 /Users/runner/hostedtoolcache/Python/3.7.9/x64/bin/python


Python 3.7.9 (default, Oct 28 2020, 13:24:28) 
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> >>> ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... Unable to create basic Accelerated OpenGL renderer.
Unable to create basic Accelerated OpenGL renderer.
Core Image is now using the software OpenGL renderer. This will be slow.
Fatal Python error: Segmentation fault

Current thread 0x0000000109b0cdc0 (most recent call first):
  File "/Users/runner/work/pyqtgraph/pyqtgraph/pyqtgraph/opengl/GLViewWidget.py", line 233 in paintGL
  File "<stdin>", line 12 in <module>

Failed Mesh Example Test Located in GLMeshItem.py 

I'm hoping you have some insight as to what we could try to make this process more robust, or if you all have seen this error before.

glGetTexImage issue with 3D Texture

Calling glGetTexImage with target GL_TEXTURE_3D raises the following exception (tested on macos with python3.7 and pyopengl 3.1.5 without accelerate):

Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 232, in 'calling callback function'
  File "test_glGetTexImage.py", line 36, in display
    gl.GL_FLOAT)
  File "lib/python3.7/site-packages/OpenGL/GL/images.py", line 398, in glGetTexImage
    dims = _get_texture_level_dims(target,level)
  File "lib/python3.7/site-packages/OpenGL/GL/images.py", line 238, in _get_texture_level_dims
    GL_1_1.glGetTexLevelParameteriv( target, level, GL_1_1.GL_TEXTURE_DEPTH, dim )
AttributeError: module 'OpenGL.raw.GL.VERSION.GL_1_1' has no attribute 'GL_TEXTURE_DEPTH'

This is due to GL_TEXTURE_DEPTH being defined in GL_1_2.

Here is the code to reproduce:

import OpenGL.GL as gl
import OpenGL.GLUT as glut
import numpy


def display():
    gl.glClearColor(1., 0., 0., 1.)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)

    gl.glEnable(gl.GL_TEXTURE_3D)
    texid = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_3D, texid)
    gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)

    data = numpy.random.random(5**3 * 3).astype(numpy.float32).reshape(5, 5, 5, 3)
    gl.glTexImage3D(
        gl.GL_TEXTURE_3D,
        0,
        gl.GL_RGB,
        data.shape[2],
        data.shape[1],
        data.shape[0],
        0,
        gl.GL_RGB,
        gl.GL_FLOAT,
        data)

    retrieved = gl.glGetTexImage(
        gl.GL_TEXTURE_3D,
        0,
        gl.GL_RGB,
        gl.GL_FLOAT)

    glut.glutSwapBuffers()


glut.glutInit()
glut.glutInitDisplayMode(glut.GLUT_RGBA)
glut.glutInitWindowPosition(0, 0)
glut.glutInitWindowSize(640, 480)
window = glut.glutCreateWindow(b"Test")
glut.glutDisplayFunc(display)
glut.glutMainLoop()

glTexImage2D leaks memory when numpy data is not contiguous

When a non-contiguous numpy array is passed to glTexImage2D(), or glBufferSubData() or probably any PyOpenGL routine that can take a numpy array it leaks memory. The reference count of the non-contiguous array is incremented and will then never be released. This must be related to PyOpenGL copying the numpy array to a contiguous one internally, then somehow forgetting to decref the original array which it increfed.

Here is example code (sorry only a fragment). If the data array is contiguous then its reference count before and after the glTexImage2D() call are the same. If it is not contiguous, the reference count of data after glTexImage2D() is one more than before.

            from sys import getrefcount
            rc1 = getrefcount(data)
            GL.glTexImage2D(gl_target, 0, iformat, size0, size1, 0, format, tdtype, data)
            rc2 = getrefcount(data)
            print ('teximage2d ', data.flags['C_CONTIGUOUS'], rc1, rc2)

When updating textures frequently this leaks a massive amount of memory and is hard to debug. The case I encountered was rendering text as an image and the numpy array was flipped vertically data[::-1] so that it appeared right side up making it non-contiguous.

glBufferSubData() fails with ctypes.ArgumentError for arg 4 numpy array

The glBufferSubData() call fails with the following type of traceback claiming it cannot handle a numpy array as the fourth argument. Usually this call works but if a certain PyOpenGL import occurs before calling this routine then it fails. The culprit is in PyOpenGL 3.1.0 file

OpenGL/raw/WGL/_types.py

at the following lines

HANDLE = POINTER(None) # /home/mcfletch/pylive/OpenGL-ctypes/src/wgl.h:60
!# TODO: figure out how to make the handle not appear as a void_p within the code...
HANDLE.final = True

Here ctypes.POINTER(None) returns ctypes.c_void_p and a "final" attribute is set on that. This causes the BasePlatform.finalArgType() method in OpenGL/platform/baseplatform.py to not convert the glBufferSubData() fourth argument from numpy arrays to c_void_p if the raw/WGL/_types.py file is imported before glBufferSubData() is first used. The first use caches the ctypes routine and determines the argument type conversion methods.

Not sure the best fix for this. Possibly HANDLE should be made a copy of ctypes.c_void_p.

This took approximately 8 solid hours of debugging to isolate as the condition under which the _types.py import happens early were hard to identify and the PyOpenGL code is extremely hard to read the flow with plugins and registry and other mechanisms that obscure the execution path.

File "C:\cygwin64\home\goddard\chimerax\ChimeraX.app\bin\lib\site-packages\chimerax\core\graphics\opengl.py", line 1688, in update_buffer_data
GL.glBufferSubData(btype, 0, None, d)
File "zr\accelerate\src\latebind.pyx", line 44, in OpenGL_accelerate.latebind.Curry.call (src\latebind.c:1216)
File "C:\cygwin64\home\goddard\chimerax\ChimeraX.app\bin\lib\site-packages\OpenGL\GL\VERSION\GL_1_5.py", line 125, in glBufferSubData
return baseOperation( target, offset, size, data )
File "zr\accelerate\src\latebind.pyx", line 32, in OpenGL_accelerate.latebind.LateBind.call (src\latebind.c:1015)
File "zr\accelerate\src\wrapper.pyx", line 314, in OpenGL_accelerate.wrapper.Wrapper.call (src\wrapper.c:6853)
File "zr\accelerate\src\wrapper.pyx", line 311, in OpenGL_accelerate.wrapper.Wrapper.call (src\wrapper.c:6777)
File "C:\cygwin64\home\goddard\chimerax\ChimeraX.app\bin\lib\site-packages\OpenGL\platform\baseplatform.py", line 402, in call
return self( *args, **named )
ctypes.ArgumentError: ("argument 4: <class 'TypeError'>: wrong type", (GL_ELEMENT_ARRAY_BUFFER, 0, 24, array([[0, 1, 2],
[0, 2, 3]], dtype=uint32)))

PyOpenGL version 3.1.3b2 AttributeError

I first reported this on conda-forge where I was getting the package from: conda-forge/pyopengl-feedstock#16

I'm using pyopengl in the vispy project and have Travis CI run tests weekly. Recently it started failing when pyopengl was switched from version 3.1.1a1 to version 3.1.3b2 with the following error for most of our operations:

self = <OpenGL.converters.SizedOutputOrInput object at 0x2b7757b86af0>
result = None
baseOperation = <OpenGL.platform.baseplatform.glGetBufferParameteriv object at 0x2b7757b0c7e8>
pyArgs = (GL_ARRAY_BUFFER, GL_BUFFER_SIZE, <object object at 0x2b7755acf6e0>)
cArgs = (GL_ARRAY_BUFFER, GL_BUFFER_SIZE, array([192], dtype=int32))
    def oldStyleReturn( self, result, baseOperation, pyArgs, cArgs ):
        """Retrieve cArgs[ self.index ]"""
>       result = cArgs[ self.outIndex ]
E       AttributeError: ('outIndex', <bound method SizedOutputOrInput.oldStyleReturn of <OpenGL.converters.SizedOutputOrInput object at 0x2b7757b86af0>>, (None, <OpenGL.platform.baseplatform.glGetBufferParameteriv object at 0x2b7757b0c7e8>, (GL_ARRAY_BUFFER, GL_BUFFER_SIZE, <object object at 0x2b7755acf6e0>), (GL_ARRAY_BUFFER, GL_BUFFER_SIZE, array([192], dtype=int32))), {})
../../../anaconda/envs/testenv/lib/python2.7/site-packages/OpenGL/converters.py:202: AttributeError

Any idea what may have changed to cause this? I also noticed 3.1.3 are the first releases since 2015 on PyPI so maybe that is an issue.

WGL extensions not found when using Python 3

WGL extensions are not found when using Python 3 due to use of strings where bytes are required. Below is a traceback trying to use the WGL_EXT_swap_control extension. Changing 3 lines in OpenGL/raw/WGL/_types.py to use bytes instead of strings using the as_8_bit() function fixes the problem. I've attached a patch with these changes.

In Python 3.1 with PyOpenGL 3.1.1a:
wgl_python3.patch.gz

from OpenGL.WGL.EXT import swap_control
swap_control.wglGetSwapIntervalEXT()


TypeError Traceback (most recent call last)
in ()
----> 1 swap_control.wglGetSwapIntervalEXT()

C:\Program Files\ChimeraX\bin\lib\site-packages\OpenGL\platform\baseplatform.py in call(self, *args, **named)
399 return None
400 def call( self, *args, **named ):
--> 401 if self.load():
402 return self( *args, **named )
403 else:

C:\Program Files\ChimeraX\bin\lib\site-packages\OpenGL\platform\baseplatform.py in load(self)
388 argNames = self.argNames,
389 extension = self.extension,
--> 390 error_checker = self.error_checker,
391 )
392 except AttributeError as err:

C:\Program Files\ChimeraX\bin\lib\site-packages\OpenGL\platform\win32.py in constructFunction(self, functionName, dll, resultType, argTypes, doc, argNames, extension, deprecated, module, error_checker)
127 deprecated,
128 module,
--> 129 error_checker=error_checker,
130 )
131 except AttributeError:

C:\Program Files\ChimeraX\bin\lib\site-packages\OpenGL\platform\baseplatform.py in constructFunction(self, functionName, dll, resultType, argTypes, doc, argNames, extension, deprecated, module, force_extension, error_checker)
146 """
147 is_core = (not extension) or extension.split('_')[1] == 'VERSION'
--> 148 if (not is_core) and not self.checkExtension( extension ):
149 raise AttributeError( """Extension not available""" )
150 argTypes = [ self.finalArgType( t ) for t in argTypes ]

C:\Program Files\ChimeraX\bin\lib\site-packages\OpenGL\platform\baseplatform.py in checkExtension(self, name)
268 if current is None:
269 from OpenGL import extensions
--> 270 result = extensions.ExtensionQuerier.hasExtension( name )
271 set[name] = result
272 return result

C:\Program Files\ChimeraX\bin\lib\site-packages\OpenGL\extensions.py in hasExtension(self, specifier)
96 def hasExtension( self, specifier ):
97 for registered in self.registered:
---> 98 result = registered( specifier )
99 if result:
100 return result

C:\Program Files\ChimeraX\bin\lib\site-packages\OpenGL\extensions.py in call(self, specifier)
103 def call( self, specifier ):
104 specifier = as_8_bit(specifier).replace(as_8_bit('.'),as_8_bit('_'))
--> 105 if not specifier.startswith( self.prefix ):
106 return None
107

TypeError: startswith first arg must be bytes or a tuple of bytes, not str

Accelerate module: `.pxd` files not shipped with source package (3.1.1a1)

In the source package of the accelerate module from PyPi, the .pxd and __init__.py files under the OpenGL_accelerate directory are not included. This means that regenerating the *.c files from *.pyx files using Cython fails:

cythoning src/arraydatatype.pyx to src/arraydatatype.c
Error compiling Cython file:
------------------------------------------------------------
...
"""Cython-coded Array-handling accelerator module"""
import ctypes
import OpenGL
from OpenGL._null import NULL as _NULL
from OpenGL import plugins
from OpenGL_accelerate.wrapper cimport cArgConverter, pyArgConverter, returnConverter
^
------------------------------------------------------------
src/arraydatatype.pyx:6:0: 'OpenGL_accelerate/wrapper.pxd' not found
Error compiling Cython file:
------------------------------------------------------------
...

Regenerating the *.c files from the *.pyx is necessary for more recent Python 3.7, and in any case is good practice when building distribution packages (I am the Fedora packager for PyOpenGL).

Could you include those source files in the source packages?

Upstream has renamed parameters (and we should have a procedure for that)

In this commit by @pdaniell-nv for KhronosGroup/OpenGL-Registry#285 the OpenGL API is updated to change parameter names for 14 entry points.

commit 37add60a829ac4b184089d982e4292a4044e2ca4
Author: Piers Daniell <[email protected]>
Date:   Wed Oct 30 10:22:44 2019 -0600

    Rename bufSize to count where necessary (#285)

    * Rename bufSize to count where necessary

    Also rename bufsize to bufSize.

    * Rebase

There are some issues that arise:

  • our wrappers are based on parameter names (not indices) and
  • here, the changed parameter names refer to parameters likely to be referenced in wrapper operations (e.g. wrappers that get bufSize by introspecting passed in numpy arrays)
  • python users who happen to be using the parameter names in a call will have their code fail on upgrade

The first two mean I'll need to go through and review those wrappers to be sure we don't reference the old names. That's not a big deal, there might be a few dozen lines of code affected.

The third has likely happened lots of times without being noticed, as I've not, in the past, remarked on parameter-name changes and users likely have just hit the change, looked at the updated API docs and made a change without complaining to me. Likely I need to make our auto-generated wrapping a bit smarter so that it flags such changes in the APIs and tells me we need to increment our external versions and create release notes about the changes.

Python, PyOpenGL and macOS BigSur

Hi @mcfletch ,

According to the macOS BigSur release note :

New in macOS Big Sur 11.0.1, the system ships with a built-in dynamic linker cache of all system-provided libraries. As part of this change, copies of dynamic libraries are no longer present on the filesystem. Code that attempts to check for dynamic library presence by looking for a file at a path or enumerating a directory will fail. Instead, check for library presence by attempting to dlopen() the path, which will correctly check for the library in the cache. (62986286)

This is handled by python devs (all the stuff regarding BigSur support is listed here).
Unfortunately, it seems it will be supported for python 3.8+.

At the PyOpenGL level, this line won't work anymore if using python 3.8-.

I've made a quick and dirty fix for my needs.

Are you interested in a more generic fix? If so, i can provide you a PR.

Regards,
Orel

Varying linewidth is possible like OpenGL coding?

I found below code for direct OpenGL coding.

GLfloat thickness;
for(int i=0;i<n-1;++i)
{
if(ThisIsTheLine[i]) //your truth function for vertex i->i+1
thickness=5.0;
else
thickness=1.0;
glLineWidth(thickness);
glBegin(GL_LINES);
glVertex3f(x[i],y[i],z[i]);
glVertex3f(x[i+1],y[i+1],z[i+1]);
glEnd();
}
glLineWidth(1.f);//reset

In python, currently the linewidth is implemented as below.

     px_scale = self.transforms.pixel_scale 
     width = px_scale * self._parent._width 
     GL.glLineWidth(max(width, 1.))

Is it possible to set glLineWidth individually, for lines drawed by VisPy implemented pyopengl code?

Suggesting improvement to glVertexAttribPointer(), possibly others

I just spent several hours trying to get my first PyOpenGL code to work. The problem was with the following two lines:

glVertexAttribPointer(vertcoords_loc, 2, GL_FLOAT, False, 16, 0)
glVertexAttribPointer(texcoords_loc , 2, GL_FLOAT, False, 16, 8)

I had to pull and gradually adapt an example found on the internet to finally figure out what I had to change:

glVertexAttribPointer(vertcoords_loc, 2, GL_FLOAT, False, 16, ctypes.c_void_p(0))
glVertexAttribPointer(texcoords_loc , 2, GL_FLOAT, False, 16, ctypes.c_void_p(8))

So, because the OpenGL API defines that the last parameter is a pointer to void even when it actually represents an offset (I'm working with a vertex buffer), PyOpenGL wants me to manually convert that offset into a void pointer using ctypes.

I'm a total beginner with Python, so I apologies if this is naïve, but wouldn't it be possible here to just drop that constraint, i.e. to implicitly convert the integer to a void pointer?

(Out of curiosity, what kind of implicit conversion is happening when you specify an integer literal as I did? How come no error was detected?)

Can't get glDepthFunc working

I was writing a small 3D viewer where i want to display certain 3d Objects using
Python3, OpenGL, Shaders and ElementLists.
Everything works fine, apart glDepthFunc does not appear to work
even when i use glDepthGFunc(GL_NEVER) it draws all triangles of my "cube"

Attached is a testcase which includes my viewer and a picture where glDepthFunc failed to work as expected.

Also in My3DViewer there is a glBeginLines() which should not be there, but it does not work without ...

Please give me some hints to correct my code .

Thank you

testcase.zip

glDrawElements accepts an empty list as the 4th parameter?

The GL spec for glDrawElements isnt entirely clear what goes in the indices parameter, the spec says a pointer to the indices to draw, ("Specifies a pointer to the location where the indices are stored.") probably actually meaning the index in the buffer to begin drawing from looking at examples online.

pyopengl however seem to accept a bunch of odd things in there (possibly things that can cast to a ctype void?) but will not accept any type of integer.

ctypes.c_void_p() and [] both work

python int, and ctypes.c_int(0) crash in the same way

GLuint(0) fails silently

The log appears to request an array-type to be passed as seen below, however passing it a list of indices also fails.

lib\site-packages\OpenGL\platform\baseplatform.py", line 415, in call
return self( *args, **named )
ctypes.ArgumentError: ("argument 4: <class 'TypeError'>: No array-type handler for type ctypes.c_ushort (value: c_ushort(0)) registered", (GL_TRIANGLES, 9, GL_UNSIGNED_SHORT, c_ushort(0)))

Problem: Headless rendering with nvidia and using libOpenGL.so

How can I make pyopengl use libOpenGL.so and not libGL.so.
For detailed explanation see Pro Tip: Linking OpenGL for Server-Side Rendering.

To use glX and OpenGL today, you should link against libOpenGL.so as well as libGLX.so. The first contains the OpenGL symbols, the latter the GLX symbols. If you want to use EGL context management instead, link against libOpenGL.so and libEGL.so.

I used lsof -p <pid> and for sure the python process loaded libGL.so and thus the EGL-OpenGL context was not working.

Compile Error

OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling

Is pyOpenGL only for Windows users?

When using pip to install pyOpenGL (versions from 3.1.0 to latest 0b2) has a version of ctypesloader.py that only looks for windows dll files:

"""ctypes abstraction layer

We keep rewriting functions as the main entry points change,
so let's just localise the changes here...
"""
import ctypes, logging, os, sys
_log = logging.getLogger( 'OpenGL.platform.ctypesloader' )
#_log.setLevel( logging.DEBUG )
ctypes_version = [
    int(x) for x in ctypes.__version__.split('.')
]
from ctypes import util
import OpenGL

DLL_DIRECTORY = os.path.join( os.path.dirname( OpenGL.__file__ ), 'DLLS' )

def loadLibrary( dllType, name, mode = ctypes.RTLD_GLOBAL ):
    """Load a given library by name with the given mode
    
    dllType -- the standard ctypes pointer to a dll type, such as
        ctypes.cdll or ctypes.windll or the underlying ctypes.CDLL or 
        ctypes.WinDLL classes.
    name -- a short module name, e.g. 'GL' or 'GLU'
    mode -- ctypes.RTLD_GLOBAL or ctypes.RTLD_LOCAL,
        controls whether the module resolves names via other
        modules already loaded into this process.  GL modules
        generally need to be loaded with GLOBAL flags
    
    returns the ctypes C-module object
    """
    if isinstance( dllType, ctypes.LibraryLoader ):
        dllType = dllType._dlltype
    fullName = None
    try:
        fullName = util.find_library( name )
        if fullName is not None:
            name = fullName
        elif os.path.isfile( os.path.join( DLL_DIRECTORY, name + '.dll' )):
            name = os.path.join( DLL_DIRECTORY, name + '.dll' )
    except Exception as err:
        _log.info( '''Failed on util.find_library( %r ): %s''', name, err )
        # Should the call fail, we just try to load the base filename...
        pass
    try:
        return dllType( name, mode )
    except Exception as err:
        err.args += (name,fullName)
        raise

def buildFunction( functionType, name, dll ):
    """Abstract away the ctypes function-creation operation"""
    return functionType( (name, dll), )

This is really weird, because past commits such as commit 3379c7e had code for loading Linux, MacOS, and Windows library files, not just Windows dll files.

The code that comes from pip does not even match the code up on the Github repo. Is there some sort of mix-up happening?

Unable to load numpy_formathandler when install from wheel

When using PyOpenGL-acceleratein version 3.1.5 from wheel there shown this warning:

OpenGL.arrays.numpymodule:Unable to load numpy_formathandler accelerator from OpenGL_accelerate

When install it from source

pip install PyOpenGL-accelerate  --no-binary :all:

This warning does not shown. There is some error in building wheel process?

test_buffer_api_basic fails on i586 and armv7l with accelerate support

test_buffer_api_basic fails on i586 and armv7l , presumably due to some 32bit arch problem.

[  121s] tests/test_arraydatatype.py::TestCoreDatatype::test_buffer_api_basic FAILED
[  121s] 
[  121s] =================================== FAILURES ===================================
[  121s] ____________________ TestCoreDatatype.test_buffer_api_basic ____________________
[  121s] 
[  121s] self = <test_arraydatatype.TestCoreDatatype testMethod=test_buffer_api_basic>
[  121s] 
[  121s]     @pytest.mark.skipif( not (
[  121s]         OpenGL.USE_ACCELERATE and acceleratesupport.ACCELERATE_AVAILABLE
[  121s]     ), reason="Need OpenGL_accelerate for buffer support")
[  121s]     def test_buffer_api_basic(self):
[  121s]         import array as silly_array
[  121s]         structures = [
[  121s]             (b'this and that',13,1,True,1,b'B',[13],[1]),
[  121s]         ]
[  121s]         if sys.version_info[:2] >= (2,7):
[  121s]             structures.append(
[  121s]                 # on Python 3.4 we do *not* get the (3) prefix :(
[  121s]                 ((GLint * 3)( 1,2,3 ),12,4,False,1,[b'(3)<i',b'(3)<l',b'<i'],[3],None),
[  121s]             )
[  121s]     
[  121s]         if sys.version_info[:2] >= (3,0):
[  121s]             # only supports buffer protocol in 3.x
[  121s]             structures.extend([
[  121s]                 (silly_array.array('I',[1,2,3]),12,4,False,1,b'I',[3],[4]),
[  121s]             ])
[  121s]         try:
[  121s]             structures.append( (memoryview(b'this'),4,1,True,1,b'B',[4],[1]) )
[  121s]         except NameError:
[  121s]             # Python 2.6 doesn't have memory view
[  121s]             pass
[  121s]         try:
[  121s]             if array:
[  121s]                 structures.extend( [
[  121s]                     (arange(0,9,dtype='I').reshape((3,3)),36,4,False,2,b'I',[3,3],[12,4]),
[  121s]                     (arange(0,9,dtype='I').reshape((3,3))[:,1],12,4,False,1,b'I',[3],[12]),
[  121s]                 ])
[  121s]         except NameError:
[  121s]             # Don't have numpy installed...
[  121s]             pass
[  121s]     
[  121s]         from OpenGL.arrays import _buffers
[  121s]         for object,length,itemsize,readonly,ndim,format,shape,strides in structures:
[  121s]             buf = _buffers.Py_buffer.from_object( object, _buffers.PyBUF_STRIDES|_buffers.PyBUF_FORMAT )
[  121s]             with buf:
[  121s]                 assert buf.len == length, (object,length,buf.len)
[  121s]                 assert buf.itemsize == itemsize, (object,itemsize,buf.itemsize)
[  121s]                 assert buf.readonly == readonly, (object,readonly,buf.readonly)
[  121s]                 assert buf.ndim == ndim, (object,ndim,buf.ndim)
[  121s]                 if isinstance( format, list):
[  121s] >                   assert buf.format in format, (object,format,buf.format)
[  121s] E                   AssertionError: (<test_arraydatatype.c_long_Array_3 object at 0xa8cdb7c4>, ['(3)<i', '(3)<l', '<i'], '<l')
[  121s] E                   assert '<l' in ['(3)<i', '(3)<l', '<i']
[  121s] E                    +  where '<l' = <OpenGL.arrays._buffers.Py_buffer object at 0xa8cdba94>.format
[  121s] 
[  121s] tests/test_arraydatatype.py:245: AssertionError

unhashable type exception when using glVertexAttribPointer with OSMesa and OpenGL 2.1

I'm getting this exception whenever i call glVertexAttribPointer in an OpenGL 2.1 context with OSMesa. That didn't happen when I was using an OpenGL 4.3 context with GLFW

I'm using openSUSE Tumbleweed with Mesa graphics drivers (19.1.5 version)

This is the full exception message:

Traceback (most recent call last):
  File "main.py", line 165, in <module>
    main()
  File "main.py", line 152, in main
    shape.render()
  File "main.py", line 118, in render
    self.teapot.render(self.material.shader)
  File "main.py", line 66, in render
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
  File "/home/guilherme/.local/lib/python3.7/site-packages/OpenGL/latebind.py", line 61, in __call__
    return self.wrapperFunction( self.baseFunction, *args, **named )
  File "/home/guilherme/.local/lib/python3.7/site-packages/OpenGL/GL/VERSION/GL_2_0.py", line 426, in glVertexAttribPointer
    contextdata.setValue( key, array )
  File "/home/guilherme/.local/lib/python3.7/site-packages/OpenGL/contextdata.py", line 65, in setValue
    current = storage.get( context )
TypeError: unhashable type

I'm trying to render something in headless mode, that's why I'm using OSMesa and gl2.1. Any help I can get here please?

visualization error

I want to visualize the 3D mesh into video. I am getting this by running visualization command line

File "C:\Users\hamid.farhidzadeh\Anaconda3\envs\pytorch\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\hamid.farhidzadeh\Anaconda3\envs\pytorch\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\hamid.farhidzadeh\Documents\pifuhd\apps\render_turntable.py", line 69, in
renderer = ColorRender(width=args.width, height=args.height)
File "C:\Users\hamid.farhidzadeh\Documents\pifuhd\lib\render\gl\color_render.py", line 34, in init
CamRender.init(self, width, height, name, program_files=program_files)
File "C:\Users\hamid.farhidzadeh\Documents\pifuhd\lib\render\gl\cam_render.py", line 32, in init
Render.init(self, width, height, name, program_files, color_size, ms_rate)
File "C:\Users\hamid.farhidzadeh\Documents\pifuhd\lib\render\gl\render.py", line 45, in init
_glut_window = glutCreateWindow("My Render .")
File "C:\Users\hamid.farhidzadeh\Anaconda3\envs\pytorch\lib\site-packages\OpenGL\GLUT\special.py", line 73, in glutCreateWindow
return __glutCreateWindowWithExit(title, _exitfunc)
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type

By searching I found out I need to modify :
https://github.com/facebookresearch/pifuhd/blob/master/lib/render/gl/render.py#L45
by adding b to name
_glut_window = glutCreateWindow(b"My Render .")

After fixing this I got the new error and couldn't find any solution for it. Any input is appropriated.

freeglut (foo): fgInitGL2: fghGenBuffers is NULL
Traceback (most recent call last):
File "C:\Users\hamid.farhidzadeh\Anaconda3\envs\pytorch\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\hamid.farhidzadeh\Anaconda3\envs\pytorch\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\hamid.farhidzadeh\Documents\pifuhd\apps\render_turntable.py", line 69, in
renderer = ColorRender(width=args.width, height=args.height)
File "C:\Users\hamid.farhidzadeh\Documents\pifuhd\lib\render\gl\color_render.py", line 34, in init
CamRender.init(self, width, height, name, program_files=program_files)
File "C:\Users\hamid.farhidzadeh\Documents\pifuhd\lib\render\gl\cam_render.py", line 32, in init
Render.init(self, width, height, name, program_files, color_size, ms_rate)
File "C:\Users\hamid.farhidzadeh\Documents\pifuhd\lib\render\gl\render.py", line 50, in init
glClampColor(GL_CLAMP_READ_COLOR, GL_FALSE)
File "C:\Users\hamid.farhidzadeh\Anaconda3\envs\pytorch\lib\site-packages\OpenGL\platform\baseplatform.py", line 405, in call
raise error.NullFunctionError(
OpenGL.error.NullFunctionError: Attempt to call an undefined function glClampColor, check for bool(glClampColor) before calling

AttributeError: 'DarwinPlatform' object has no attribute 'GLX'

py27-num0-accel0 develop-inst-noop: /Users/huangjiewen/pyopengl
py27-num0-accel0 installed: atomicwrites==1.2.1,attrs==18.2.0,funcsigs==1.0.2,more-itertools==4.3.0,pathlib2==2.3.2,pluggy==0.7.1,py==1.6.0,pygame==1.9.4,-e git+https://github.com/mcfletch/pyopengl.git@beea4e5987aa5c0cb4c480961fbe5be5fae5a759#egg=PyOpenGL,pytest==3.8.1,scandir==1.9.0,six==1.11.0
py27-num0-accel0 run-test-pre: PYTHONHASHSEED='508435173'
py27-num0-accel0 runtests: commands[0] | pytest -sv tests/
======================================================================================================================== test session starts ========================================================================================================================
platform darwin -- Python 2.7.15, pytest-3.8.1, py-1.6.0, pluggy-0.7.1 -- /Users/huangjiewen/pyopengl/.tox/py27-num0-accel0/bin/python2.7
cachedir: .pytest_cache
rootdir: /Users/huangjiewen/pyopengl, inifile:
collecting 0 items pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
INFO:OpenGL.acceleratesupport:No OpenGL_accelerate module loaded: No module named OpenGL_accelerate
collected 56 items / 1 errors

============================================================================================================================== ERRORS ===============================================================================================================================
_____________________________________________________________________________________________________________ ERROR collecting tests/test_glx_pygame.py _____________________________________________________________________________________________________________
tests/test_glx_pygame.py:5: in
from OpenGL.GLX import *
OpenGL/GLX/init.py:3: in
from OpenGL.GLX.VERSION.GLX_1_0 import *
OpenGL/GLX/VERSION/GLX_1_0.py:14: in
from OpenGL.raw.GLX.VERSION.GLX_1_0 import *
OpenGL/raw/GLX/VERSION/GLX_1_0.py:43: in
@_p.types(ctypes.POINTER(_cs.XVisualInfo),ctypes.POINTER(_cs.Display),_cs.c_int,ctypes.POINTER(_cs.c_int))
OpenGL/raw/GLX/VERSION/GLX_1_0.py:13: in _f
return _p.createFunction( function,_p.PLATFORM.GLX,'GLX_VERSION_GLX_1_0',error_checker=_errors._error_checker)
E AttributeError: 'DarwinPlatform' object has no attribute 'GLX'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
====================================================================================================================== 1 error in 1.68 seconds ======================================================================================================================
ERROR: InvocationError for command '/Users/huangjiewen/pyopengl/.tox/py27-num0-accel0/bin/pytest -sv tests/' (exited with code 2)

TypeError: constructFunction() got an unexpected keyword argument 'force_extension'

On AppVeyor (Windows), with the recent pre-release version 3.1.3b1:

File "C:\projects\silx\venv_test\lib\site-packages\silx\gui\_glutils\gl.py", line 50, in <module>
    import OpenGL.GL as _GL
  File "C:\projects\silx\venv_test\lib\site-packages\OpenGL\GL\__init__.py", line 6, in <module>
    from OpenGL.GL.images import *
  File "C:\projects\silx\venv_test\lib\site-packages\OpenGL\GL\images.py", line 628, in <module>
    suffix, arrayConstant, getattr(GL_1_1,functionName),
  File "C:\projects\silx\venv_test\lib\site-packages\OpenGL\GL\images.py", line 578, in typedImageFunction
    if baseFunction:
  File "C:\projects\silx\venv_test\lib\site-packages\OpenGL\platform\baseplatform.py", line 382, in __nonzero__
    self.load()
  File "C:\projects\silx\venv_test\lib\site-packages\OpenGL\platform\baseplatform.py", line 397, in load
    force_extension = self.force_extension,
TypeError: constructFunction() got an unexpected keyword argument 'force_extension'

gluNurbsSurface() takes 6 positional arguments but 12 were given

Here is the origin C++ code

//g++ -o 8-4 -Wall 8-4.cpp -mwindows glut32.lib -lopengl32 -lglu32
#include <windows.h>
#include <gl/glut.h>
#include <math.h>
GLUnurbsObj *pNurb = NULL;
GLint nNumPoints = 4;
GLfloat ctrlPoints[4][4][3] = {{
                                   {-6.0f, -6.0f, 0.0f},
                                   {-6.0f, -2.0f, 0.0f},
                                   {-6.8f, 2.0f, 0.0f},
                                   {-6.0f, 6.0f, 0.0f},
                               },
                               {{-2.0f, -6.0f, 0.0f},
                                {-2.0f, -2.8f, 8.0f},
                                {-2.0f, 2.0f, 8.0f},
                                {-2.0f, 6.0f, 0.0f}},
                               {{2.0f, -6.0f, 0.0f},
                                {2.0f, -2.0f, 8.0f},
                                {2.0f, 2.0f, 8.0f},
                                {2.0f, 6.0f, 0.0f}},
                               {{6.0f, -6.0f, 0.0f},
                                {6.0f, -2.0f, 0.0f},
                                {6.0f, 2.0f, 0.0f},
                                {6.0f, 6.0f, 0.0f}}};
// NURBS对象指针
GLfloat Knots[8] = {0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f};
static GLfloat xRot = 0.0f;

static GLfloat yRot = 0.0f;

void DrawPoints(void)
{
    //绘制控制点
    int i, j;
    glPointSize(5.0f);
    glColor3ub(255, 0, 0);
    glBegin(GL_POINTS);
    for (i = 0; i < 4; i++)
        for (j = 0; j < 4; j++)
            glVertex3fv(ctrlPoints[i][j]);
    glEnd();
}
void Initial()
{
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    //定义NURBS参数
    pNurb = gluNewNurbsRenderer();
    gluNurbsProperty(pNurb, GLU_SAMPLING_TOLERANCE, 25.0f);
    gluNurbsProperty(pNurb, GLU_DISPLAY_MODE, (GLfloat)GLU_OUTLINE_POLYGON);
}
void ReDraw(void)
{
    glColor3ub(0, 0, 220);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glRotatef(330.0f, 1.0f, 0.0f, 0.0f);
    glRotatef(xRot, 1.0f, 0.0f, 0.0f);
    glRotatef(yRot, 0.0f, 1.0f, 0.0f);
    gluBeginSurface(pNurb);
    gluNurbsSurface(pNurb,                // NURBS对象指针
                    8,                    //参数化u方向上的结点数目
                    Knots,                //参数化u方向上递增的结点值的数组
                    8,                    // 参数化v方向上的结点数目
                    Knots,                //参数化v方向上递增的结点值的数组
                    4 * 3,                //参数化u方向上相邻控制点之间的偏移量
                    3,                    //参数化v方向上相邻控制点之间的偏移量
                    &ctrlPoints[0][0][0], //包含曲面控制点的数组
                    4,                    //参数化u方向上的阶数
                    4,                    //参数化v方向上的阶数
                    GL_MAP2_VERTEX_3);    //曲面的类型
    gluEndSurface(pNurb);
    DrawPoints();
    glPopMatrix();
    glutSwapBuffers();
}
void SpecialKeys(int key, int x, int y)
{
    if (key == GLUT_KEY_UP)
        xRot -= 5.0f;
    if (key == GLUT_KEY_DOWN)
        xRot += 5.0f;
    if (key == GLUT_KEY_LEFT)
        yRot -= 5.0f;
    if (key == GLUT_KEY_RIGHT)
        yRot += 5.0f;
    if (xRot > 356.0f)
        xRot = 0.0f;
    if (xRot < -1.0f)
        xRot = 355.0f;
    if (yRot > 356.0f)
        yRot = 0.0f;
}
void Changesize(int w, int h)
{
    if (h == 0)
        h = 1;
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0f, (GLdouble)w / (GLdouble)h, 1.0, 40.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -20.0f);
    if (yRot < -1.0f)
        yRot = 355.0f;
    glutPostRedisplay();
}
int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutCreateWindow("NURBS curve");
    glutReshapeFunc(Changesize);
    glutDisplayFunc(ReDraw);
    glutSpecialFunc(SpecialKeys);
    Initial();
    glutMainLoop();
    return 0;
}

Which is worked properly.

But after I changed it into python code.

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import numpy as np
global pNurb
nNumPoints = 4
ctrlPoints = np.array([[
    [-6.0, -6.0, 0.0],
    [-6.0, -2.0, 0.0],
    [-6.8, 2.0, 0.0],
    [-6.0, 6.0, 0.0],
],
    [[-2.0, -6.0, 0.0],
     [-2.0, -2.8, 8.0],
     [-2.0, 2.0, 8.0],
     [-2.0, 6.0, 0.0]],
    [[2.0, -6.0, 0.0],
     [2.0, -2.0, 8.0],
     [2.0, 2.0, 8.0],
     [2.0, 6.0, 0.0]],
    [[6.0, -6.0, 0.0],
     [6.0, -2.0, 0.0],
     [6.0, 2.0, 0.0],
     [6.0, 6.0, 0.0]]])

Knots = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]

global xRot
global yRot
xRot = 0.0


yRot = 0.0


def DrawPoints():
    glPointSize(5.0)
    glColor3ub(255, 0, 0)
    glBegin(GL_POINTS)
    for i in range(4):
        for j in range(4):
            glVertex3fv(ctrlPoints[i][j])
    glEnd()


def Initial():
    global pNurb
    glClearColor(1.0, 1.0, 1.0, 1.0)
    pNurb = gluNewNurbsRenderer()
    gluNurbsProperty(pNurb, GLU_SAMPLING_TOLERANCE, 25.0)
    gluNurbsProperty(pNurb, GLU_DISPLAY_MODE, GLU_OUTLINE_POLYGON)


def ReDraw():
    glColor3ub(0, 0, 220)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glMatrixMode(GL_MODELVIEW)
    glPushMatrix()
    glRotatef(330.0, 1.0, 0.0, 0.0)
    glRotatef(xRot, 1.0, 0.0, 0.0)
    glRotatef(yRot, 0.0, 1.0, 0.0)
    gluBeginSurface(pNurb)
    gluNurbsSurface(pNurb,       # NURBS对象指针
                    8,  # 参数化u方向上的结点数目
                    Knots,       # 参数化u方向上递增的结点值的数组
                    8,  # 参数化v方向上的结点数目
                    Knots,       # 参数化v方向上递增的结点值的数组
                    4 * 3,       # 参数化u方向上相邻控制点之间的偏移量
                    3,  # 参数化v方向上相邻控制点之间的偏移量
                    ctrlPoints,  # 包含曲面控制点的数组
                    4,  # 参数化u方向上的阶数
                    4,  # 参数化v方向上的阶数
                    GL_MAP2_VERTEX_3)  # 曲面的类型
    gluEndSurface(pNurb)
    DrawPoints()
    glPopMatrix()
    glutSwapBuffers()


def SpecialKeys(key, x, y):
    global xRot
    global yRot
    if (key == GLUT_KEY_UP):
        xRot -= 5.0
    if (key == GLUT_KEY_DOWN):
        xRot += 5.0
    if (key == GLUT_KEY_LEFT):
        yRot -= 5.0
    if (key == GLUT_KEY_RIGHT):
        yRot += 5.0
    if (xRot > 356.0):
        xRot = 0.0
    if (xRot < -1.0):
        xRot = 355.0
    if (yRot > 356.0):
        yRot = 0.0


def Changesize(w, h):
    global xRot
    global yRot
    if (h == 0):
        h = 1
    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45.0, w / h, 1.0, 40.0)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslatef(0.0, 0.0, -20.0)
    if (yRot < -1.0):
        yRot = 355.0
    glutPostRedisplay()


def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
    glutCreateWindow("NURBS curve")
    glutReshapeFunc(Changesize)
    glutDisplayFunc(ReDraw)
    glutSpecialFunc(SpecialKeys)
    Initial()
    glutMainLoop()


main()

It says that

TypeError: gluNurbsSurface() takes 6 positional arguments but 12 were given

I read the definition of that function:

Find this:

 argNames=('nurb', 'sKnotCount', 'sKnots', 'tKnotCount', 'tKnots', 'sStride', 'tStride', 'control', 'sOrder', 'tOrder', 'type'),

I have googled it, and there seems nowhere to put the 'self'

Undefined function gluOrtho2D

It seems I'm unable to use the function gluOrtho2D from the GLU package.

Traceback (most recent call last):
  File "/home/spaceraiders/programming/opengl/./rendering.py", line 95, in <module>
    my_renderer = Renderer(SCREEN_SIZE)
  File "/home/spaceraiders/programming/opengl/./rendering.py", line 31, in __init__
    self.opengl_bind()
  File "/home/spaceraiders/programming/opengl/./rendering.py", line 41, in opengl_bind
    GLU.gluOrtho2D(0, self.screen_size[0], 0, self.screen_size[1])
  File "/home/spaceraiders/.local/lib/python3.9/site-packages/OpenGL/platform/baseplatform.py", line 423, in __call__
    raise error.NullFunctionError(
OpenGL.error.NullFunctionError: Attempt to call an undefined function gluOrtho2D, check for bool(gluOrtho2D) before calling

This doesn't quite make sense to me, because the function is being autocompleted. I'm using Python3.9, running the latest version of Arch Linux. I've also installed both PyOpenGL, along with PyOpenGL_accelerate using pip3. Is this an issue with me using Python3.9, Arch, or what?

Issue with osmesa

I have a working render stack, which renders normally when using X11 platform. However when I set the plataform to osmesa the following error happens:

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    from src.video_renderer import VideoRenderer
  File "/home/mateus/dev/still360/src/video_renderer.py", line 2, in <module>
    from OpenGL import GL
  File "/home/mateus/local/pyopengl/OpenGL/GL/__init__.py", line 4, in <module>
    from OpenGL.GL.VERSION.GL_1_1 import *
  File "/home/mateus/local/pyopengl/OpenGL/GL/VERSION/GL_1_1.py", line 14, in <module>
    from OpenGL.raw.GL.VERSION.GL_1_1 import *
  File "/home/mateus/local/pyopengl/OpenGL/raw/GL/VERSION/GL_1_1.py", line 7, in <module>
    from OpenGL.raw.GL import _errors
  File "/home/mateus/local/pyopengl/OpenGL/raw/GL/_errors.py", line 4, in <module>
    _error_checker = _ErrorChecker( _p, _p.GL.glGetError )
  File "/usr/lib64/python3.6/ctypes/__init__.py", line 361, in __getattr__
    func = self.__getitem__(name)
  File "/usr/lib64/python3.6/ctypes/__init__.py", line 366, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: /usr/lib/libOSMesa.so.8: undefined symbol: glGetError

The most strange is that it was working before, I am using Arch Linux with mesa-18.0.4-1. Any idea on how to fix that without downgrading?

Attempt to call an undefined function glutInit, check for bool(glutInit) before calling

Error: OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling

Python version: 3.8
pyopengl : 3.1.5
OS: windows 10

I got this error while trying to run this piece of code, ( im following a tutorial )

glutInit()  # Initialize a glut instance which will allow us to customize our window

glutInitDisplayMode(GLUT_RGBA)  # Set the display mode to be colored

glutInitWindowSize(500, 500)  # Set the width and height of your window

glutInitWindowPosition(0, 0)  # Set the position at which this windows should appear

wind = glutCreateWindow("OpenGL Coding Practice")  # Give your window a title

glutDisplayFunc(showScreen)  # Tell OpenGL to call the showScreen method continuously

glutIdleFunc(showScreen)  # Draw any graphics or shapes in the showScreen function at all times

glutMainLoop()  # Keeps the window created above displaying/running in a loop

Python 3.7 Build failure: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_type’; did you mean ‘curexc_type’?

pyopengl is currently failing to build on Fedora 29:

https://kojipkgs.fedoraproject.org//work/tasks/3539/27753539/build.log

gcc -pthread -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -fPIC -I/builddir/build/BUILD/PyOpenGL-3.1.1a1/PyOpenGL-accelerate-3.1.1a1/.. -I/builddir/build/BUILD/PyOpenGL-3.1.1a1/PyOpenGL-accelerate-3.1.1a1/src -I/builddir/build/BUILD/PyOpenGL-3.1.1a1/PyOpenGL-accelerate-3.1.1a1 -I/usr/include/python3.7m -c src/wrapper.c -o build/temp.linux-x86_64-3.7/src/wrapper.o
src/wrapper.c: In function ‘__Pyx_ExceptionSave’:
src/wrapper.c:11474:21: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_type’; did you mean ‘curexc_type’?
     *type = tstate->exc_type;
                     ^~~~~~~~
                     curexc_type
src/wrapper.c:11475:22: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_value’; did you mean ‘curexc_value’?
     *value = tstate->exc_value;
                      ^~~~~~~~~
                      curexc_value
src/wrapper.c:11476:19: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_traceback’; did you mean ‘curexc_traceback’?
     *tb = tstate->exc_traceback;
                   ^~~~~~~~~~~~~
                   curexc_traceback
src/wrapper.c: In function ‘__Pyx_ExceptionReset’:
src/wrapper.c:11488:24: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_type’; did you mean ‘curexc_type’?
     tmp_type = tstate->exc_type;
                        ^~~~~~~~
                        curexc_type
src/wrapper.c:11489:25: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_value’; did you mean ‘curexc_value’?
     tmp_value = tstate->exc_value;
                         ^~~~~~~~~
                         curexc_value
src/wrapper.c:11490:22: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_traceback’; did you mean ‘curexc_traceback’?
     tmp_tb = tstate->exc_traceback;
                      ^~~~~~~~~~~~~
                      curexc_traceback
src/wrapper.c:11491:13: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_type’; did you mean ‘curexc_type’?
     tstate->exc_type = type;
             ^~~~~~~~
             curexc_type
src/wrapper.c:11492:13: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_value’; did you mean ‘curexc_value’?
     tstate->exc_value = value;
             ^~~~~~~~~
             curexc_value
src/wrapper.c:11493:13: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_traceback’; did you mean ‘curexc_traceback’?
     tstate->exc_traceback = tb;
             ^~~~~~~~~~~~~
             curexc_traceback
src/wrapper.c: In function ‘__Pyx_GetException’:
src/wrapper.c:11536:24: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_type’; did you mean ‘curexc_type’?
     tmp_type = tstate->exc_type;
                        ^~~~~~~~
                        curexc_type
src/wrapper.c:11537:25: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_value’; did you mean ‘curexc_value’?
     tmp_value = tstate->exc_value;
                         ^~~~~~~~~
                         curexc_value
src/wrapper.c:11538:22: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_traceback’; did you mean ‘curexc_traceback’?
     tmp_tb = tstate->exc_traceback;
                      ^~~~~~~~~~~~~
                      curexc_traceback
src/wrapper.c:11539:13: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_type’; did you mean ‘curexc_type’?
     tstate->exc_type = local_type;
             ^~~~~~~~
             curexc_type
src/wrapper.c:11540:13: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_value’; did you mean ‘curexc_value’?
     tstate->exc_value = local_value;
             ^~~~~~~~~
             curexc_value
src/wrapper.c:11541:13: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_traceback’; did you mean ‘curexc_traceback’?
     tstate->exc_traceback = local_tb;
             ^~~~~~~~~~~~~
             curexc_traceback
error: command 'gcc' failed with exit status 1

EGL/GBM troubles

It seems that

prefix = 'EGL_'
assumed_version = [1,0]
version_prefix = 'EGL_VERSION_EGL_'

in raw/EGL/_types.py gives errors and should be

prefix = as_8_bit('EGL_')
assumed_version = [1,0]
version_prefix = as_8_bit('EGL_VERSION_EGL_')

The other issue is that I cannot call eglGetPlatformDisplayEXT to get a display because it's marked as part of an extension and pyopengl tries to check if the extension is present without specifying a display but my egl implementation (glvnd/mesa) answers with an error.
My workaround right now is

import OpenGL
import OpenGL.platform.egl
OpenGL.platform.PLATFORM = p = OpenGL.platform.egl.EGLPlatform()
from OpenGL.EGL import *
from OpenGL.EGL.EXT.platform_base import *
from OpenGL.EGL.MESA.platform_gbm import *
import ctypes

with open("/dev/dri/renderD128", "w") as f:
	gbm = ctypes.CDLL("libgbm.so")
	dev = gbm.gbm_create_device(f.fileno())

	eglGetPlatformDisplayEXT.extension = None
	oc = p.__class__.constructFunction
	def nc(*args, **kwargs):
		kwargs.update({"force_extension": True})
		return oc(p, *args, **kwargs)

	p.constructFunction = nc
	dpy = eglGetPlatformDisplayEXT(EGL_PLATFORM_GBM_MESA, ctypes.c_void_p(dev), ctypes.c_void_p(0))
	del p.constructFunction
	print(dpy)

GL_HALF_FLOAT support with glTexImage[2|3]D

Trying to use GL_HALF_FLOAT as type for glTexImage[2|3]D leads to the following error (tested on macos with python3.7 and pyopengl 3.1.5 without accelerate):

Traceback (most recent call last):
  File "lib/python3.7/site-packages/OpenGL/latebind.py", line 43, in __call__
    return self._finalCall( *args, **named )
TypeError: 'NoneType' object is not callable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 232, in 'calling callback function'
  File "test_half_float.py", line 62, in display
    self.prepare_texture()
  File "test_half_float.py", line 43, in prepare_texture
    image)
  File "lib/python3.7/site-packages/OpenGL/latebind.py", line 47, in __call__
    return self._finalCall( *args, **named )
  File "lib/python3.7/site-packages/OpenGL/wrapper.py", line 879, in wrapperCall
    pyArgs = tuple( calculate_pyArgs( args ))
  File "lib/python3.7/site-packages/OpenGL/wrapper.py", line 450, in calculate_pyArgs
    yield converter(args[index], self, args)
  File "lib/python3.7/site-packages/OpenGL/GL/images.py", line 455, in __call__
    arrayType = arrays.GL_CONSTANT_TO_ARRAY_TYPE[ images.TYPE_TO_ARRAYTYPE[ type ] ]
KeyError: (GL_HALF_FLOAT_ARB, <OpenGL.GL.images.ImageInputConverter object at 0x10c57ac18>)
Traceback (most recent call last):
  File "lib/python3.7/site-packages/OpenGL/latebind.py", line 43, in __call__
    return self._finalCall( *args, **named )

Code to reproduce:

import OpenGL
OpenGL.FULL_LOGGING = True

import OpenGL.GL as gl
import OpenGL.GLUT as glut
import numpy


class TestWindow:
    def __init__(self):
        self.texid = None

        glut.glutInit()
        glut.glutInitDisplayMode(glut.GLUT_RGBA)
        glut.glutInitWindowPosition(0, 0)
        glut.glutInitWindowSize(600, 480)
        self.window = glut.glutCreateWindow(b"Half float")
        glut.glutDisplayFunc(self.display)

    def prepare_texture(self):
        shape = 128, 128, 128
        image = numpy.random.random(numpy.prod(shape)).reshape(shape).astype(numpy.float16)

        if self.texid is None:
            gl.glEnable(gl.GL_TEXTURE_3D)
            self.texid = gl.glGenTextures(1)
            gl.glBindTexture(gl.GL_TEXTURE_3D, self.texid)
            gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
            gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST)
            gl.glTexParameteri(gl.GL_TEXTURE_3D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)

            gl.glTexImage3D(
                gl.GL_TEXTURE_3D,
                0,
                gl.GL_R16F,
                image.shape[2],
                image.shape[1],
                image.shape[0],
                0,
                gl.GL_RED,
                gl.GL_HALF_FLOAT,
                image)
        else:
            gl.glTexSubImage3D(
                gl.GL_TEXTURE_3D,
                0,
                0,
                0,
                0,
                image.shape[1],
                image.shape[1],
                image.shape[0],
                gl.GL_RED,
                gl.GL_HALF_FLOAT,
                image)

    def display(self):
        gl.glClearColor(1., 0., 0., 1.)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        self.prepare_texture()

        gl.glBegin(gl.GL_QUADS)
        gl.glTexCoord3f(0., 0., 1.)
        gl.glVertex2f(-1., -1.)

        gl.glTexCoord3f(1., 0., 1.)
        gl.glVertex2f(1., -1.)

        gl.glTexCoord3f(1., 1., 0.)
        gl.glVertex2f(1., 1.)

        gl.glTexCoord3f(0., 1., 0.)
        gl.glVertex2f(-1., 1.)
        gl.glEnd()

        glut.glutSwapBuffers()


test = TestWindow()

glut.glutMainLoop()

glGenTextures on Win64

When using PyOpenGL 3.1.1a1 (from pip install) on Win64, and numpy (1.16.2), I get the following error when trying to call glGenTextures(1):

AttributeError: ("module 'numpy' has no attribute 'float128'", 1, <OpenGL.platform.baseplatform.glGenTextures object at 0x0000022B15DF3120>

According to winpython/winpython#613, this is an error in PyOpenGL itself.

Can you please fix it, or tell me how to work around?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.