• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
ic0de

Writing export scripts for blender

3 posts in this topic

Does anyone know any tutorials for writing an export script for blender 2.5/2.6, I need write a script to export 3d models for my game. If anyone knows an existing script that I can modify to fit my purposes could they post a link, my format is pretty simple:

For each face output three vertices:

[code]

-0.5 -0.5 -0.5 0.0 0.0 0.0 -1.0 0.0
0.5 -0.5 -0.5 0.5 0.0 0.0 -1.0 0.0
-0.5 -0.5 0.5 0.0 0.5 0.0 -1.0 0.0
[/code]


each line represents a vertex and the attributes of said vertex in the order: x y z u v nx ny nz, where the last three numbers represent the normal vector.

It does other stuff like define textures and normal maps but the script doesn't need to do that as I could input them manually.

So once again my question is where could I find a tutorial to write blender exports scripts or does anyone know of a similar existing script that I could modify?
0

Share this post


Link to post
Share on other sites
Maybe it would be easier to simply export as Wavefront OBJ, and then write a small utility to convert that to your format. Since most 3d applications support OBJ, you wouldn't even be limiting yourself to Blender.
1

Share this post


Link to post
Share on other sites
I have to agree with Chris_F, it is much better to write an importer for your rendering engine that accepts known formats than to write a new format exporter for blender. The idea of manually inputing UV coords makes me shudder. Obj is a great way to go for static meshes. For animated meshes its a different story, lots of "depends" answers.

Cheers,

Bob
0

Share this post


Link to post
Share on other sites
Writing an exporter is a good idea, since you can choose what to export, and in a format that can loaded without any processing (e.g. organising triangles, indices).

You should look at how the exporter for easy formats like the .obj works, to learn how to do it, which is what I did.

Here's my exporter, though note lots of it is commented out since it was originally made to work with the previous version of blender before the update, and I haven't gotten around to fixing it.

The file format I used was a tree structure with tag names, similar to xml. You might want to use xml initially to save in, then switch to storing things in bytes later on to speed up loading times.
[code]

import bpy, os, struct, random, re, time, math, mathutils
from datetime import datetime
from myfile import *

def objectCompare(x, y):
if x.parent == y.parent:
return 0

if x.parent == None:
return -1

if y.parent == None:
return 1

return objectCompare(x.parent, y.parent)

def writeString(out, name):
if len(name) == 0:
out.write(struct.pack('i', 0))
else:
out.write(struct.pack('i', len(name)))
out.write(name.encode('utf8'))

total_vertices_count = 0
total_indices_count = 0
materialIndices = dict()
meshIndices = dict()
lampIndices = dict()

def writeMaterials(out):
materials = [ma for ma in bpy.data.materials.values()] # if ma.users > 0

for i, ma in enumerate(materials):
materialNode = OutNode("material", [])

materialIndices[ma.name] = i

materialNode.data.append(
OutNode("name", bytes(ma.name.encode('utf8'))))

materialNode.data.append(
OutNode("alpha", struct.pack('f', ma.alpha)))

materialNode.data.append(
OutNode("emit", struct.pack('f', ma.emit)))

materialNode.data.append(
OutNode("diffuse",
struct.pack('f', ma.diffuse_color.r) +
struct.pack('f', ma.diffuse_color.g) +
struct.pack('f', ma.diffuse_color.b)))

materialNode.data.append(
OutNode("specular",
struct.pack('f', ma.specular_color.r) +
struct.pack('f', ma.specular_color.g) +
struct.pack('f', ma.specular_color.b)))

materialNode.data.append(
OutNode("specular_intensity",
struct.pack('f', ma.specular_intensity)))

#material textures
# mts = [mt for mt in ma.texture_slots if mt != None and mt.texture != None and mt.texture.type == 'IMAGE']

# out.write(struct.pack('i', len(mts))) #material_textures_num

# for mt in mts:
# #out.write(struct.pack('i', textureIndices[mt.tex.name])) #material_texture_index
# writeString(out, mt.texture.name)
# writeString(out, mt.uv_layer)
# writeString(out, re.sub('(\\\)', '/', mt.texture.image.filename if mt.texture.image.filename[0:2] != '//' else mt.texture.image.filename[2:]))

materialNode.write(out)

def writeMeshes(out):
global total_vertices_count
global total_indices_count

meshes = [me for me in bpy.data.meshes.values()
if me.users > 0 and len(me.faces) > 0]

for i,me in enumerate(meshes):
meshNode = OutNode("mesh", [])

meshIndices[me.name] = i

meshNode.data.append(
OutNode("name", bytes(me.name.encode('utf8'))))

colLayerNames = me.vertex_colors
uvLayerNames = me.uv_textures

#tangents = [] #[uvLayer_ind][faceInd][faceVertInd] = tangent
#smooth_tangents = [[Vector(0,0,0) for v in me.vertices] for u in uvLayerNames] #[uvLayer_ind][meshVertInd] = smooth_tangent
#smooth_tangent_sums = [[0 for v in me.vertices] for u in uvLayerNames] #[uvLayer_ind][meshVertInd] = smooth_tangent_sum

#todo
# #get + store tangents
# for uvLayerName in uvLayerNames:
# me.activeUVLayer = uvLayerName
# tangents.append(me.getTangents())

# #get + store smooth_tangents
# for faceInd, face in enumerate(me.faces):
# for fvInd,fv in enumerate(face.vertices):
# for uvLayerInd, uvLayerName in enumerate(uvLayerNames):
# smooth_tangents[uvLayerInd][fv.index] += tangents[uvLayerInd][faceInd][fvInd]
# smooth_tangent_sums[uvLayerInd][fv.index] += 1

# for a in range(0,len(uvLayerNames)):
# for b in range(0, len(me.vertices)):
# #print(smooth_tangents[a][b], smooth_tangent_sums[a][b])
# smooth_tangents[a][b] /= smooth_tangent_sums[a][b]

# for a in range(0,len(uvLayerNames)):
# for b in range(0, len(me.vertices)):
# smooth_tangents[a][b] = smooth_tangents[a][b].normalize()
# #print(smooth_tangents[a][b])


#
out_positions = []
out_normals = []
out_texCoords = [[] for n in uvLayerNames] #[uvLayer][out_vertInd] = texCoord
out_tangents = [[] for n in uvLayerNames] #[uvLayer][out_vertInd] = tangent
out_colors = [[] for n in colLayerNames] #[colLayer][out_vertInd] = color
out_indices = [[]] if len(me.materials) == 0 else [[] for ma in me.materials] #[meMaInd] = face_indices
out_vertInds = dict() #['p n tcs tgs cs'] = out_vertexInd

#get out verts
for faceInd, face in enumerate(me.faces):
triIndices = [[0,1,2]]

if len(face.vertices) == 4:
triIndices.append([0,2,3])

for triIndex in triIndices:
for faceVecIndex in triIndex:
key = ''

#position
p = me.vertices[face.vertices[faceVecIndex]].co
key += '%f %f %f '%(p.x,p.y,p.z)

#normal
n = (me.vertices[face.vertices[faceVecIndex]].normal if face.use_smooth == 1 else face.normal).normalized()
key += '%f %f %f '%(n.x,n.y,n.z)

#texCoord
# tcs = []

# for uvLayerInd, uvLayerName in enumerate(uvLayerNames):
# me.activeUVLayer = uvLayerName
# tc = face.uv[faceVecIndex]
# key += '%f %f '%(tc[0],tc[1])
# tcs.append(tc)

#tangent
# tgs = []

# for uvLayerInd, uvLayerName in enumerate(uvLayerNames):
# me.activeUVLayer = uvLayerName
# tg = smooth_tangents[uvLayerInd][face.vertices[faceVecIndex].index] if face.use_smooth == 1 else tangents[uvLayerInd][faceInd][faceVecIndex] #tangents[uvLayerInd][faceInd][faceVecIndex] #
# key += '%f %f %f '%(tg.x,tg.y,tg.z)
# tgs.append(tg)

#color
# cs = []

# for colLayerInd, colLayerName in enumerate(colLayerNames):
# me.activeColorLayer = colLayerName
# c = face.col[faceVecIndex]
# key += '%i %i %i %i '%(c[0],c[1],c[2],c[3])
# cs.append(c)

#
if key not in out_vertInds:
out_vertInds[key] = len(out_vertInds)
out_positions.append(p)
out_normals.append(n)

# for k in range(0,len(uvLayerNames)):
# out_texCoords[k].append(tcs[k])
# out_tangents[k].append(tgs[k])

# for k in range(0,len(colLayerNames)):
# out_colors[k].append(cs[k])

out_indices[face.material_index].append(out_vertInds[key])

#
indicesNum = 0

for meMatIndices in out_indices:
indicesNum += len(meMatIndices)

#
total_vertices_count += len(out_vertInds)
total_indices_count += indicesNum

#
meshNode.data.append(OutNode("vertices_num", struct.pack('i', len(out_vertInds))))
meshNode.data.append(OutNode("indices_num", struct.pack('i', indicesNum)))
positionsData = b""
normalsData = b""
indicesData = b""

#write positions
for p in out_positions:

positionsData += struct.pack('f', p.y)
positionsData += struct.pack('f', p.z)
positionsData += struct.pack('f', p.x)

meshNode.data.append(OutNode("positions", positionsData))

#write normals
for n in out_normals:
normalsData += struct.pack('f', n.y)
normalsData += struct.pack('f', n.z)
normalsData += struct.pack('f', n.x)

meshNode.data.append(OutNode("normals", normalsData))

#write uvLayersNum
#out.write(struct.pack('i',len(uvLayerNames)))

#
# for uvLayerInd, uvLayerName in enumerate(uvLayerNames):
# #write uvLayerName
# writeString(out, uvLayerNames[uvLayerInd])

# #write texCoords
# for tc in out_texCoords[uvLayerInd]:
# out.write(struct.pack('f', tc[0]))
# out.write(struct.pack('f', tc[1]))

# #write tangents
# for tg in out_tangents[uvLayerInd]:
# out.write(struct.pack('f', 0))
# out.write(struct.pack('f', 0))
# out.write(struct.pack('f', 1))

# #out.write(struct.pack('f', tg.y))
# #out.write(struct.pack('f', tg.z))
# #out.write(struct.pack('f', tg.x))

# #write bitangents
# for i in range(0,len(out_vertInds)):
# btg = out_normals[i].cross(out_tangents[uvLayerInd][i]).normalize()
# out.write(struct.pack('f', btg.y))
# out.write(struct.pack('f', btg.z))
# out.write(struct.pack('f', btg.x))

#write colLayersNum
#out.write(struct.pack('i',len(colLayerNames)))

#
# for colLayerInd, colLayerName in enumerate(colLayerNames):
# #write colLayerName
# writeString(out, colLayerNames[colLayerInd])

# #write colors
# for c in out_colors[colLayerInd]:
# out.write(struct.pack('f', c[0]/255.0))
# out.write(struct.pack('f', c[1]/255.0))
# out.write(struct.pack('f', c[2]/255.0))
# out.write(struct.pack('f', c[3]/255.0))

#write indices
for meMatIndices in out_indices:
for i in meMatIndices:
indicesData += struct.pack('I', i)

meshNode.data.append(OutNode("indices", indicesData))

# #write subsetsNum
# out.write(struct.pack('i',len(me.materials)))

# #subsets
# subsetIndicesStart = 0

# for meMaInd, meMa in enumerate(me.materials):
# subset_indicesNum = len(out_indices[meMaInd])

# #write maInd
# out.write(struct.pack('i',materialIndices[meMa.name]))

# #write indicesStart
# out.write(struct.pack('i',subsetIndicesStart))

# #write indicesNum
# out.write(struct.pack('i',subset_indicesNum))

# #
# subsetIndicesStart += subset_indicesNum


# #shape info, for physics
# if True:
# points = []
# pointIndices = dict()
# shapeIndices = []

# vertPointIndices = []

# for v in me.vertices:
# k = '%f %f %f'%(v.co.x,v.co.y,v.co.z)

# if k not in pointIndices:
# pointIndices[k] = len(points)
# points.append(v.co)

# vertPointIndices.append(pointIndices[k])

# for f in me.faces:
# inds = [[0,1,2],[0,2,3]] if len(f.vertices) == 4 else [[0,1,2]]

# for ind in inds:
# for a in ind:
# shapeIndices.append(vertPointIndices[f.vertices[a]])

# #
# radius2 = 0
# radiusX2 = 0
# radiusY2 = 0
# radiusZ2 = 0

# x = 0
# y = 0
# z = 0

# posX = 0
# posY = 0
# posZ = 0

# negX = 0
# negY = 0
# negZ = 0

# for p in points:
# yz = mathutils.Vector((0,p.y,p.z))
# xz = mathutils.Vector((p.x,0,p.z))
# xy = mathutils.Vector((p.x,p.y,0))

# #
# new_radius2 = p.dot(p)

# if new_radius2 > radius2:
# radius2 = new_radius2

# #
# new_radiusX2 = yz.dot(yz)

# if new_radiusX2 > radiusX2:
# radiusX2 = new_radiusX2

# #
# new_radiusY2 = xz.dot(xz)

# if new_radiusY2 > radiusY2:
# radiusY2 = new_radiusY2

# #
# new_radiusZ2 = xy.dot(xy)

# if new_radiusZ2 > radiusZ2:
# radiusZ2 = new_radiusZ2

# #
# if p.x > posX:
# posX = p.x

# if p.x < negX:
# negX = p.x

# if abs(p.x) > x:
# x = abs(p.x)

# #
# if p.y > posY:
# posY = p.y

# if p.y < negY:
# negY = p.y

# if abs(p.y) > y:
# y = abs(p.y)
# #
# if p.z > posZ:
# posZ = p.z

# if p.z < negZ:
# negZ = p.z

# if abs(p.z) > z:
# z = abs(p.z)

# #
# out.write(struct.pack('d', x))
# out.write(struct.pack('d', y))
# out.write(struct.pack('d', z))

# out.write(struct.pack('d', posX))
# out.write(struct.pack('d', posY))
# out.write(struct.pack('d', posZ))

# out.write(struct.pack('d', negX))
# out.write(struct.pack('d', negY))
# out.write(struct.pack('d', negZ))

# out.write(struct.pack('d', math.sqrt(radius2)))
# out.write(struct.pack('d', math.sqrt(radiusX2)))
# out.write(struct.pack('d', math.sqrt(radiusY2)))
# out.write(struct.pack('d', math.sqrt(radiusZ2)))

# #
# out.write(struct.pack('i', len(points)))

# #
# for p in points:
# out.write(struct.pack('d', p.y))
# out.write(struct.pack('d', p.z))
# out.write(struct.pack('d', p.x))

# #
# for i in shapeIndices:
# out.write(struct.pack('I', i))
meshNode.write(out)

# def writeLamps(out):
# #LampTypes = [k.lower() for k,v in Lamp.Types.items()]

# lamps = [la for la in bpy.data.lamps.values() if la.users > 0]

# out.write(struct.pack('i', len(lamps)))

# for laInd, la in enumerate(lamps):
# lampIndices[la.name] = laInd

# writeString(out, la.name)

# writeString(out, la.type)


# out.write(struct.pack('f', la.color.r))
# out.write(struct.pack('f', la.color.g))
# out.write(struct.pack('f', la.color.b))
# out.write(struct.pack('f', la.distance))
# out.write(struct.pack('f', la.energy))


# if la.type == 'POINT':
# ""
# elif la.type == 'SUN':
# ""
# elif la.type == 'SPOT':
# ""
# elif la.type == 'HEMI':
# ""
# elif la.type == 'AREA':
# ""

# #out.write(struct.pack('f', la.quad1))
# #out.write(struct.pack('f', la.quad2))
# #out.write(struct.pack('f', la.spotSize))
# #out.write(struct.pack('f', la.spotBlend))

def writeObjects(out):
objects = [ob for ob in bpy.data.objects.values() if ob.users > 0]
#objects.sort(objectCompare)

objectIndices = dict()

for obInd, ob in enumerate(objects):
objectNode = OutNode("object", [])
objectNode.data.append(OutNode("name", bytes(ob.name.encode('utf8'))))

objectIndices[ob.name] = obInd

if ob.parent != None:
objectNode.data.append(OutNode("parent_index", struct.pack('i', objectIndices[ob.parent.name])))

objectNode.data.append(OutNode("position", struct.pack('f', ob.location[1]) +
struct.pack('f', ob.location[2]) + struct.pack('f', ob.location[0])))

objectNode.data.append(OutNode("axis_angle", struct.pack('f', ob.rotation_axis_angle[1]) +
struct.pack('f', ob.rotation_axis_angle[2]) + struct.pack('f', ob.rotation_axis_angle[0]) +
struct.pack('f', ob.rotation_axis_angle[3])))

objectNode.data.append(OutNode("scale", struct.pack('f', ob.scale[1]) +
struct.pack('f', ob.scale[2]) + struct.pack('f', ob.scale[0])))

if ob.type == 'MESH':
objectNode.data.append(OutNode("mesh_index", struct.pack('i', meshIndices[ob.data.name])))

objectNode.write(out)

def main():

fileName = 'untitled.model' if bpy.data.filepath == '' else os.path.splitext(bpy.data.filepath)[0]+".model"

#Window.DrawProgressBar (0.0, '')
#Window.DrawProgressBar (0.9, 'Exporting...')

t = time.time()

out = open(fileName, 'wb')

#writeTextures(out)
writeMaterials(out)
writeMeshes(out)
#writeLamps(out)
writeObjects(out)
out.close()

print(datetime.now().strftime("%H:%M:%S") + " Export to %s took %s secs with %i verts, %i tris."%(os.path.basename(fileName), str(round(time.time() - t,4)), total_vertices_count, total_indices_count/3))
#Window.DrawProgressBar (1.0, '')


if __name__ == "__main__":
main()

#http://www.blender.org/documentation/blender_python_api_2_57_release/bpy.types.html
"""
with open("D:/temp/oldocs/App/model_export.py", "r") as fh:
exec(fh.read()+"\n", globals(), locals())
"""


[/code]



Right now the exporter only exports meshes (positions, normals and indices), objects (position, scale, rotation, name, etc), and some material info.




You should just look at my code to get an idea, since explaining the file format and loader might be too much hassle, especially since the loader is written in scheme.


0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0