#!BPY

"""
Name: 'ZyberFlux (.zfx)...'
Blender: 234
Group: 'Export'
Tooltip: 'Export selected mesh to ZyberFlux format'
"""

import Blender
import sys

def write(filename):

	file = open(filename, "wb")
	std=sys.stdout
	sys.stdout=file
	
	objects = Blender.Object.GetSelected()

	#print the objects
	print "objects % d" % len(objects)
	for object in objects:
		if object:
			#print object name
			#print object.name
			
			mesh = Blender.NMesh.GetRaw(object.data.name)

			#print mesh name
			#print object.data.name
			
		        #print the max smooth angle
		        #print "max smooth angle % d" % mesh.maxSmoothAngle

		        #print the vertices
			print "vertices % d" % len(mesh.verts)
			for vert in mesh.verts:
				print "% f % f % f" % (vert.co[0], vert.co[1], vert.co[2])
				
		        #print the normals
			print "normals % d" % len(mesh.verts)
			for vert in mesh.verts:
				print "% f % f % f" % (vert.no[0], vert.no[1], vert.no[2])	

		        #print the texcoords
			print "texcoords % d" % len(mesh.verts)
			for vert in mesh.verts:
				print "% f % f" % (vert.uvco[0], vert.uvco[1])
			
			#print the faces
			print "faces % d" % len(mesh.faces)
			for face in mesh.faces:
				if len(face.v) == 3:
					print "% d % d % d" % (face.v[0].index, face.v[1].index, face.v[2].index)
				elif len(face.v) == 4:
					print "% d % d % d" % (face.v[0].index, face.v[1].index, face.v[2].index)
					print "% d % d % d" % (face.v[2].index, face.v[3].index, face.v[0].index)
				else:
					pass

				#print "materialIndex=%d" % face.materialIndex
				#print "texcoords"
				#print face.uv

			#print the materials
			print "materials % d" % len(mesh.materials)
			for material in mesh.materials:
				#print "name=!%s!" % material.name
				print "rgb=(%f, %f, %f)" % (material.R, material.G, material.B)
				print "alpha=%f" % material.alpha
				print "amb=%f" % material.amb
				print "emit=%f" % material.emit
				print "spec=%f" % material.spec
				#print "hard=%f" % material.hard
				print "specCol=(%f, %f, %f)" % (material.specCol[0], material.specCol[1], material.specCol[2])
				print "specTransp=%f" % material.specTransp
				#print "ref=%f" % material.ref
				#print "mirCol=(%f, %f, %f)" % (material.mirCol[0], material.mirCol[1], material.mirCol[2])
				
			        #count this materials textures
				num_textures = 0
				material_textures = material.getTextures()
				for mtex in material_textures:
					if mtex:
						if mtex.tex.type == Blender.Texture.Types.IMAGE:
							num_textures = num_textures + 1
				print "num_textures=%d" % num_textures
						
			        #print this materials textures
				for mtex in material_textures:
					if mtex:
						if mtex.tex.type == Blender.Texture.Types.IMAGE:
							print mtex.tex.image.filename
							
	file.close()
	sys.stdout=std

	
def fs_callback(filename):
	if filename.find('.zfx', -4) <= 0: filename += '.zfx'
	write(filename)

Blender.Window.FileSelector(fs_callback, "Export ZyberFlux")
