OpenGL exporting script?

Hey,

I am currently doing some work with OpenGL and it would be very usefull if I could export Blender models to opengl code. I only need the object it self as polygons, without any additional material, lighting or scene information.

Does anyone already have code for this? If not I’ll have to write it myself which shouldn’t be too hard but I would have to refresh my python for that :slight_smile:

(note, tried the search but couldn’t find anything usefull.)

Thanks,
Timothy

I did some edits on this a while back- take a look.


#!BPY

"""
Name: 'OpenGL (.c)...'
Blender: 232
Group: 'Export'
Tooltip: 'Save to a C source file'
"""

#####
#####  BLENDER TO OPENGL EXPORTER
#####
#####  2003 - Bruce "Sinner" Barrera
#####
#####  contact: [email protected]
#####
#####  2004 - Raphael Langerhorst
#####   + transformation
#####   + material
#####   + exporting of ALL meshes
#####
#####  contact: [email protected]
#####
#####  LAST UPDATED: 07 July 2005
#####
#####  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
#####

##### 
##### Notes from raphael:
##### 
##### * The filename is currently hardcoded (/home/raphael/blender_model.c)
#####   Simply change it to your needs inside the script (or write a
#####   dialog that asks for input - I'm no Python wizard - in fact this
#####   script is the only Python code I've written so far.
##### 
##### * Scaling and deformations:
#####   These are not handled in the script, you MUST select all objects
#####   of the scene and select
#####   Transform -> Clear/Apply -> Apply Size/Rotation  (Ctrl+A)
#####   Transform -> Clear/Apply -> Apply Deformation  (Shift+Ctrl+A)
#####   before exporting in order to have correct transformations
#####   in the exported file.
##### 
##### * ### NAO MODIFIQUE NADA DAKI PRA BAIXO, I don't know what this means
#####   (it's from the original author, I just left it in)
#####
##### * Tested against Blender 2.32
#####


#==================================================#
# New name based on old with a different extension #
#==================================================#
def newFName(ext):
	return Blender.Get('filename')[: -len(Blender.Get('filename').split('.', -1)[-1]) ] + ext

import Blender
from Blender import Object, NMesh
	
def save_opengl(filename):
	
	## Open file
	f = open(filename,"w")
	
	print "File %s created and opened. Now exporting..." % filename
	
	## Which object to export
	#currently all objects (meshes only - see below)
	objects = [ob for ob in Object.GetSelected() if ob.getType() == 'Mesh']
	
	index = 0
	for obj in objects:
		nmesh = NMesh.GetRawFromObject(obj.name)
	
		f.write("

//object: %s_%d
" % (nmesh.name, index) )
	
		f.write("void load_%d() {
" % index)
		index += 1
		
		#used for materials
		f.write("	float matColors[4];
");
		
		#transformation data
		
		#first translate, then rotate, then scale
		# because they are applied from "back to front"
		
		#we also store the current matrix and restore it
		# after the object is rendered (push, pop)
		f.write("	glPushMatrix();
")
		
		#translation
		
		locx = 0;
		locy = 0;
		locz = 0;
		if obj.LocX > 0.0001 or obj.LocX < -0.0001:
			locx = obj.LocX
		if obj.LocY > 0.0001 or obj.LocY < -0.0001:
			locy = obj.LocY
		if obj.LocZ > 0.0001 or obj.LocZ < -0.0001:
			locz = obj.LocZ
		
		f.write("	glTranslated(%.6f, %.6f, %.6f);
" % (locx, locy, locz))
		
		#rotation - this seems to be buggy !?
		if obj.RotX > 0.0001 or obj.RotX < -0.0001:
			f.write("  glRotated(%.6f,1,0,0);
" % (-obj.RotX*180*0.31831))
		if obj.RotY > 0.0001 or obj.RotY < -0.0001:
			f.write("  glRotated(%.6f,0,1,0);
" % (-obj.RotY*180*0.31831))
		if obj.RotZ > 0.0001 or obj.RotZ < -0.0001:
			f.write("  glRotated(%.6f,0,0,1);
" % (-obj.RotZ*180*0.31831))
		
		#scaling
		f.write("	glScaled(%.6f, %.6f, %.6f);
" % tuple(obj.size))
		
		tricount = 0
		lastMaterialIndex = -1;
		for face in nmesh.faces:
			vn = 0
			tricount = tricount + 1
			  
			#material - can be changed between glBegin and glEnd
			if nmesh.materials:
				if face.materialIndex != lastMaterialIndex:
					lastMaterialIndex = face.materialIndex
					material = nmesh.materials[face.materialIndex]
					print "exporting face material"
					
					#ambient and diffuse
					f.write("	matColors[0] = %.6f;
" % material.R)
					f.write("	matColors[1] = %.6f;
" % material.G)
					f.write("	matColors[2] = %.6f;
" % material.B)
					f.write("	matColors[3] = %.6f;
" % material.alpha)
					f.write("	glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,matColors);
")
					
					#specular
					specs = material.getSpecCol()
					f.write("	matColors[0] = %.6f;
" % specs[0])
					f.write("	matColors[1] = %.6f;
" % specs[1])
					f.write("	matColors[2] = %.6f;
" % specs[2])
					f.write("	matColors[3] = %.6f;
" % material.getSpecTransp())
					f.write("	glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,matColors);
")
			
			print "Exporting %s triangle(s)" % tricount  
			
			if len(face) == 3: f.write("	glBegin(GL_TRIANGLES);
")
			elif len(face) == 4: f.write("	glBegin(GL_QUADS);
")
			  
			for vertex in face.v:
				## Build glVertex3f
				f.write("	glNormal3f(%.6f, %.6f, %.6f);
" % tuple(vertex.no))
				f.write("	glVertex3f(%.6f, %.6f, %.6f);
" % tuple(vertex.co))
				vn+=1
			#print "glEnd();"
			f.write("	glEnd();
")
			
		f.write("	glPopMatrix();
")
		f.write("}
")
	
	f.write("

")
	
	#print "void loadModel() {"
	f.write("void loadModel() {
")
	
	index = 0
	
	for obj in objects:
		f.write("	load_%d();" % index)
		f.write("	//object: %s
" % obj.getData(1))
		index += 1
	
	f.write("}
")
	
	print "Export complete"
	
	f.close()


Blender.Window.FileSelector(save_opengl, 'Export Wavefront OBJ', newFName('c'))

Ah Looks like something I can re-use!

I’ll throw out quite a bit since I only want to export a selected object and I need to modify the rotation (local Y axis should point up).

I’ll probably do that later this week,… so I’ll post my changes here,… don’t think they’ll be very usefull for anyone though :slight_smile:

Timothy

I was working on a version with Rogerio Mazakina, here is the link to the current version, it will allow the model to be drawn in OpenGL with averaged normals (for smooth shading), materials and vertex animation:
http://www.winggamepak.com/gl_exporter.exe