Add-on: export a mesh as an OpenGL display list

Ok, I know this will only benefit very few people but that doesn't stop me from sharing :-)

A cloud of OpenGL Suzannes

What is it?

A tiny add-on that exports a small Python file containing OpenGL code to display a mesh.

What is it good for?

Blender has OpenGL bindings available for use in Python scripts. You can use these OpenGL drawing commands to display for example overlays over your 3D view with a draw handler.
If you would want to draw some sort of complex object you would have to recreate it using glVertex3f() calls which is a lot of work as soon as the model is more than a few vertices. This add-on generates the code for you in the form of a function that creates a display list.

How does it work?

When you select File -> Export -> Export mesh as OpenGL snippet it will open a file dialog and then it will write Python code to the selected file.
It will write the vertex coordinates (in object space) and the vertex normals of the active object. It will triangulate the mesh internally before writing it. There is currently no check if there is an active object or that the active object is a mesh.

What does the resulting Python code look like?

The export for a plain Suzanne mesh looks like this:

import bgl

def Suzanne():
 shapelist = bgl.glGenLists(1)
 bgl.glNewList(shapelist, bgl.GL_COMPILE)
 bgl.glBegin(bgl.GL_TRIANGLES)
 bgl.glNormal3f(0.9693,-0.245565,-0.011830)
 bgl.glVertex3f(0.4688,-0.757812,0.242188)
 bgl.glNormal3f(0.6076,-0.608505,-0.510393)
 bgl.glVertex3f(0.5000,-0.687500,0.093750)
 bgl.glNormal3f(0.8001,-0.599853,-0.002850)
        ... lots of calls omitted ...
 bgl.glVertex3f(-0.5938,0.164062,-0.125000)
 bgl.glEnd()
 bgl.glEndList()
 return shapelist

That code is so old fashioned, why?

If you ask any questions on forums like stack-overflow about older versions of OpenGL (and old in this context essentially means anything before OpenGL 3.0) you will be told over and over again that you shouldn't use it and that investing time in it is wasteful or even stupid.
You will have to live with that :-)
The fact is that even though Blender certainly runs on newer versions of OpenGL, the Python bindings it provides are based on version 2.1 and I am not sure when that will change. And yes, even 2.1 supports stuff like vertex arrays but those are quite cumbersome to use, not documented in the Blender Python API any in many situations overkill and not really a speed improvement: If all you want is some fancy overlay, using a compiled display list is pretty fast.

Where can I download it?

The add-on is available on GitHub.

No comments:

Post a comment