def getArmature(): bns = [] #### the list of bones of skeleton skel = None #### skel arms = Armature.Get().values() for arm in arms: # get all them bones bns = arm.bones.values() if (len(bns) > 0): skel = arm break return skel
def _import_skeleton(node): skel = lbf.structures.Skeleton(node) scn = Blender.Scene.GetCurrent() arm = Armature.New(skel.name) arm.drawType = Armature.STICK arm.makeEditable() # blender is r,a,b,c, lbf is a,b,c,r root_quat = Quaternion(skel.root_rotation[3], *skel.root_rotation[0:3]) root_offset = Vector(skel.root_offset) bone_objects = [None] * skel.num_joints for i in range(0, skel.num_joints): eb = Armature.Editbone() eb.name = skel.names[i] parent = skel.parents[i] currentOffset = Vector(skel.offsets[i]) if parent >= 0: eb.head = Vector(0, 0, 0) + bone_objects[parent].tail eb.tail = eb.head + currentOffset eb.parent = bone_objects[parent] else: eb.head = Vector(0, 0, 0) eb.tail = currentOffset bone_objects[i] = eb arm.bones[eb.name] = eb ob = scn.objects.new(arm) ob.setMatrix( TranslationMatrix(root_offset) * root_quat.toMatrix().resize4x4()) arm.update() ob.makeDisplayList() Blender.Redraw() return ob
def createVertGroups(lines1, lines2, armatures): vertgroups = getVertexGroups(lines1) objectsdata = getObjectsData(lines2) boneass = getBoneAssignments(lines2) OBVertGroups = [] for i in range(0, len(boneass)): assignment = boneass[i] VertexGroups = [] #print objectsdata[i]['name'] for j in range(0, len(assignment)): vertgroup = vertgroups[assignment[j][0]] if vertgroup not in VertexGroups: VertexGroups.append(vertgroup) OBVertGroups.append(VertexGroups) ArmObjs = [] for i in range(0, len(OBVertGroups)): for arms in armatures: armobj = A.Get(arms) for j in range(0, len(OBVertGroups[i])): vertgroup = OBVertGroups[i] if vertgroup[j] in armobj.bones.keys( ) and len(ArmObjs) < i + 1: #print arms ArmObjs.append(arms) for i in range(0, len(OBVertGroups)): obj = Object.Get(objectsdata[i]['name']) mesh = obj.getData() assignment = boneass[i] for vg in OBVertGroups[i]: mesh.addVertGroup(vg) for j in range(0, len(assignment)): groupname = vertgroups[assignment[j][0]] if groupname in OBVertGroups[i]: mesh.assignVertsToGroup(groupname, assignment[j][1], assignment[j][2], 'replace') for i in range(0, len(ArmObjs)): armobj = Object.Get(ArmObjs[i]) meshobj = Object.Get(objectsdata[i]['name']) armobj.makeParentDeform([meshobj], 1, 0)
def save_opengl(filename): # Open file f = open(filename + ".c", "w") header_file = open(filename + ".h", "w") bone_file = open(filename + ".bone", "w") print "File %s created and opened. Now exporting..." % filename # Write all the preprocessors in the header file required to # make it work w/ vbo_Utilities.h : header_file.write("#ifndef MODEL_H") header_file.write("\n#define MODEL_H") header_file.write("\n\n#include <GL/gl.h>") header_file.write("\n#include <GL/glu.h>") header_file.write("\n\n#include \"Transformation.h\"") header_file.write("\n\n#include \"vbo_Utilities.h\"") header_file.write("\n\n#include \"bone.h\"") header_file.write( "\n\n// The following is the list of objects that will be exported :") # The actual object names and their estern declarations will be written out in the loop below f.write("#include \"%s.h\"\n\n" % filename) # Which object to export # currently all objects (meshes only - see below) objects = [ob for ob in Object.GetSelected() if ob.getType() == 'Mesh'] obj_index = 0 for obj in objects: nmesh = NMesh.GetRawFromObject(obj.name) header_file.write("\n\nextern CVBO_Model %s;" % (nmesh.name)) f.write("\n// Object: %s" % (nmesh.name)) f.write("\nCVBO_Model %s;" % (nmesh.name)) f.write("\n\nvoid make_%s_vbo_arrays () {" % (nmesh.name)) # Get the list of vertices for the object vertices = nmesh.verts[:] # Get the list of faces for the object faces = nmesh.faces[:] # initialize a refCount array for the vertices refCount_for_vertices = [] for idx in range(len(vertices)): refCount_for_vertices.append(0) # Make one pass through all the faces in the object # to identify all the vertices that will have to be split # into 2 or more vertices if they have different texture coordinates # as part of different faces. Example : vertices along uv-unwrapping_seams. # Naturally, this has to be done only if the mesh uses face-UV textures if nmesh.hasFaceUV(): for face in faces: for idx in range(len(face.v)): vertex_idx = face.v[idx].index if refCount_for_vertices[vertex_idx] == 0: refCount_for_vertices[vertex_idx] = 1 vertices[vertex_idx].uvco.x = face.uv[idx][0] vertices[vertex_idx].uvco.y = face.uv[idx][1] elif face.uv[idx][0] != vertices[ vertex_idx].uvco.x or face.uv[idx][1] != vertices[ vertex_idx].uvco.y: # get a new temp vert of type MyVert newVert = MyVert(0.0, 0.0, 0.0) refCount_for_vertices.append(1) # Copy over relevant stuff to newVert newVert.co = Co(vertices[vertex_idx].co.x, vertices[vertex_idx].co.y, vertices[vertex_idx].co.z) newVert.index = vertices[vertex_idx].index newVert.dup_vertex_index = vertices[vertex_idx].index newVert.no = No(vertices[vertex_idx].no.x, vertices[vertex_idx].no.y, vertices[vertex_idx].no.z) newVert.uvco = Uvco(vertices[vertex_idx].uvco.x, vertices[vertex_idx].uvco.y) # Append it to the list vertices.append(newVert) vertex_idx = len( vertices ) - 1 # new vertex_idx, of the newly appended vertex # Now set the diverged uvco and index at the newly appended vertex vertices[vertex_idx].uvco.x = face.uv[idx][0] vertices[vertex_idx].uvco.y = face.uv[idx][1] vertices[vertex_idx].index = vertex_idx # And, set the face's v to point to this newly appended vertex face.v[idx] = vertices[vertex_idx] numVerts = len(vertices) f.write("\n\tint numVertices = %d;\n" % numVerts) # Write out the list of vertices for the object f.write("\n\t// List of vertices for object %s" % (nmesh.name)) f.write("\n\tGLfloat vertices[] = {") for vertex in vertices: f.write("\n\t\t%f,\t%f,\t%f,\t1.0000," % (vertex.co.x, vertex.co.y, vertex.co.z)) f.write("\t\t// index : %d" % (vertex.index)) f.write("\n\t};") f.write( "\n\t%s.bulk_init_vertices (numVertices, (vec4 *)vertices);\n\n" % (nmesh.name)) # Write out the texture coordinates for the object if nmesh.hasFaceUV(): f.write("\n\t// List of texture_coords for object %s" % (nmesh.name)) f.write("\n\tGLfloat textures[] = {") for vertex in vertices: f.write("\n\t\t%f,\t%f," % (vertex.uvco.x, vertex.uvco.y)) f.write("\t\t// index : %d" % (vertex.index)) f.write("\n\t};") f.write( "\n\t%s.bulk_init_textures (numVertices, (vec2 *)textures);\n\n" % (nmesh.name)) # Write out the normals for the object f.write("\n\t// List of normals for object %s" % (nmesh.name)) f.write("\n\tGLfloat normals[] = {") for vertex in vertices: f.write("\n\t\t%f,\t%f,\t%f," % (vertex.no.x, vertex.no.y, vertex.no.z)) f.write("\t\t// index : %d" % (vertex.index)) f.write("\n\t};") f.write( "\n\t%s.bulk_init_normals (numVertices, (vec3 *)normals);\n\n" % (nmesh.name)) numFaces = 0 for face in nmesh.faces: numFaces = numFaces + 1 if len( face.v ) == 4: # , because quads will be exported as 2 triangles (see below) numFaces = numFaces + 1 f.write("\n\tint numFaces = %d;\n" % numFaces) # Write out the indices to form each face of the object f.write("\n\tGLuint indices[] = {") for face in nmesh.faces: f.write("\n\t\t") f.write("%d, " % face.v[0].index) f.write("%d, " % face.v[1].index) f.write("%d, " % face.v[2].index) if len(face.v) == 4: f.write("\n\t\t") f.write("%d, " % face.v[3].index) f.write("%d, " % face.v[0].index) f.write("%d, " % face.v[2].index) f.write("\n\t};") f.write("\n\t%s.bulk_init_indices (numFaces, (GLuint *)indices);\n\n" % (nmesh.name)) #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("\n\t%s.locX = %f;" % (nmesh.name, locx)) f.write("\n\t%s.locY = %f;" % (nmesh.name, locy)) f.write("\n\t%s.locZ = %f;" % (nmesh.name, locz)) f.write("\n\treturn;") f.write("\n}") # Bone stuff mesh = Mesh.Get(obj.name) obj.link(mesh) f.write("\n\n// Object : %s " % (mesh.name)) numRealVerts = len(mesh.verts) armatures = Armature.Get() # type: dict armature_names = armatures.keys() for armature_name in armature_names: f.write("\n// Armature %s, being used by %d users" % (armature_name, armatures[armature_name].users)) if armatures[ armature_name].users > 0: # being used by at least 1 user (helps discard deleted armatures which are (for some reason) still lying around in Blender) armature = armatures[armature_name] bones = armature.bones # type: dict bone_names = bones.keys() for bone_name in bone_names: # loop over all bones bone = bones[bone_name] f.write("\n\nBone %s;" % bone.name) header_file.write("\nextern Bone %s;" % bone.name) f.write("\n\nvoid init_%s_bone_influences () {" % bone.name) f.write("\n\tInfluence influences[] = {") num_influences = 0 for vertex_idx in range( numVerts ): # loop over all vertices, looking for The bone's influences # bone_file.write("\nindex : %d " % (vertex_idx)) if vertex_idx < numRealVerts: for influence in mesh.getVertexInfluences( vertex_idx): if influence[0] == bone.name: # bone_file.write("\n %s, %f" % (influence[0], influence[1])) f.write("\n\t\tInfluence(%d, %f)," % (vertex_idx, influence[1])) num_influences = num_influences + 1 elif vertex_idx >= numRealVerts: for influence in mesh.getVertexInfluences( vertices[vertex_idx].dup_vertex_index): if influence[0] == bone.name: # bone_file.write("\n %s, %f" % (influence[0], influence[1])) f.write("\n\t\tInfluence(%d, %f)," % (vertex_idx, influence[1])) num_influences = num_influences + 1 f.write("\n\t};") f.write("\n\n\t%s.bulkInitInfluences (%d, influences);" % (bone.name, num_influences)) f.write("\n\t%s.name = \"%s\";" % (bone.name, bone.name)) f.write("\n\n\treturn;") f.write("\n};\n") obj_index += 1 header_file.write("\n\nvoid initialize_all_models ();") header_file.write("\nvoid ready_all_models_for_render ();") f.write("\n\nvoid initialize_all_models () {") for obj in objects: nmesh = NMesh.GetRawFromObject(obj.name) f.write("\n\n\tmake_%s_vbo_arrays ();" % (nmesh.name)) f.write("\n\t%s.setTexture (\"./cube_texture_test.png\", PNG);" % nmesh.name) f.write("\n\t%s.setMatColor (0.2, 0.3, 0.4, 1.0);" % nmesh.name) # Bone stuff : armatures = Armature.Get() # type: dict armature_names = armatures.keys() for armature_name in armature_names: if armatures[ armature_name].users > 0: # being used by at least 1 user (helps discard deleted armatures which are (for some reason) still lying around in Blender) armature = armatures[armature_name] bones = armature.bones # type: dict bone_names = bones.keys() for bone_name in bone_names: # loop over all bones bone = bones[bone_name] f.write("\n\tinit_%s_bone_influences ();" % bone.name) f.write("\n\t%s.setVBO (&%s);" % (bone.name, obj.name)) f.write("\n\t%s.addBone (&%s);" % (obj.name, bone.name)) f.write("\n\n\treturn;\n}\n") f.write("\n\nvoid ready_all_models_for_render () {") for obj in objects: nmesh = NMesh.GetRawFromObject(obj.name) f.write("\n\t%s.make_ready_for_render ();" % nmesh.name) f.write("\n\n\treturn;\n}\n\n") header_file.write("\n\n#endif\n\n") print "Export complete" f.close()
def createArmature(armatures, FileName): ArmatureList = [] counter = 0 scn = Scene.getCurrent() for arms in armatures: bones = [] aboneslist = [] for bone in arms: bones.append(bone) newarmature = A.Armature('Ar' + FileName + str(counter)) newarmobj = Object.New('Armature', 'Ar' + FileName + str(counter)) newarm = A.Get('Ar' + FileName + str(counter)) ArmatureList.append('Ar' + FileName + str(counter)) for abone in bones: empty = Object.Get(abone) if empty.getParent() == None: newarm.makeEditable() newarm.drawType = A.OCTAHEDRON #newarm.drawNames = True vpos1 = empty.getMatrix('worldspace')[3] eb = A.Editbone() eb.head = Vector(vpos1[0], vpos1[1] + 15 * sf, vpos1[2]) eb.tail = Vector(vpos1[0], vpos1[1] + 25 * sf, vpos1[2]) newarm.bones['Root'] = eb aboneslist.append(abone) eb = A.Editbone() eb.head = Vector(vpos1[0], vpos1[1], vpos1[2]) eb.tail = Vector(vpos1[0], vpos1[1] + 10 * sf, vpos1[2]) eb.parent = newarm.bones['Root'] newarm.bones[abone] = eb else: newarm.makeEditable() newarm.drawType = A.OCTAHEDRON parent = empty.getParent() vpos1 = empty.getMatrix('worldspace')[3] vpos2 = parent.getMatrix('worldspace')[3] if parent.name not in aboneslist: eb = A.Editbone() eb.head = Vector(vpos2[0], vpos2[1], vpos2[2]) eb.tail = Vector(vpos1[0], vpos1[1], vpos1[2]) if parent.getParent() != None: pparent = parent.getParent() print pparent.name eb.parent = newarm.bones[pparent.name] newarm.bones[parent.name] = eb aboneslist.append(parent.name) #print " NewBone",abone newarmobj.link(newarm) scn.link(newarmobj) newarm.update() counter += 1 return ArmatureList
def ImportPSK(infile): print "Importing file: ", infile pskFile = file(infile, 'rb') # mesh = Mesh.New('mesh01') # read general header header = axChunkHeader() header.Load(pskFile) header.Dump() # read the PNTS0000 header header.Load(pskFile) header.Dump() axPoints = [] for i in range(0, header.dataCount): point = axPoint() point.Load(pskFile) axPoints.append(point) #mesh.verts.extend([[point.x, point.y, point.z]]) # read the VTXW0000 header header.Load(pskFile) header.Dump() xyzList = [] uvList = [] axVerts = [] for i in range(0, header.dataCount): vert = axVertex() vert.Load(pskFile) #vert.Dump() axVerts.append(vert) xyzList.append( Vector([ axPoints[vert.pointIndex].x, axPoints[vert.pointIndex].y, axPoints[vert.pointIndex].z ])) uvList.append(Vector([vert.u, vert.v])) mesh.verts.extend(xyzList) # read the FACE0000 header header.Load(pskFile) header.Dump() axTriangles = [] for i in range(0, header.dataCount): tri = axTriangle() tri.Load(pskFile) #tri.Dump() axTriangles.append(tri) SGlist = [] for i in range(0, header.dataCount): tri = axTriangles[i] mesh.faces.extend(tri.indexes) uvData = [] uvData.append(uvList[tri.indexes[0]]) uvData.append(uvList[tri.indexes[1]]) uvData.append(uvList[tri.indexes[2]]) mesh.faces[i].uv = uvData # collect a list of the smoothing groups if SGlist.count(tri.smoothingGroups) == 0: SGlist.append(tri.smoothingGroups) # assign a material index to the face #mesh.faces[-1].materialIndex = SGlist.index(indata[5]) mesh.faces[i].mat = tri.materialIndex mesh.update() meshObject = Object.New('Mesh', 'PSKMesh') meshObject.link(mesh) scene = Scene.GetCurrent() scene.link(meshObject) # read the MATT0000 header header.Load(pskFile) header.Dump() for i in range(0, header.dataCount): data = unpack('64s6i', pskFile.read(88)) matName = asciiz(data[0]) print("creating material", matName) if matName == "": matName = "no_texture" try: mat = Material.Get(matName) except: #print("creating new material:", matName) mat = Material.New(matName) # create new texture texture = Texture.New(matName) texture.setType('Image') # texture to material mat.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL) # read the REFSKELT header header.Load(pskFile) header.Dump() axReferenceBones = [] for i in range(0, header.dataCount): axReferenceBones.append(axReferenceBone()) axReferenceBones[i].Load(pskFile) #axReferenceBones[i].Dump() quat = axReferenceBones[i].quat if i == 0: axReferenceBones[i].parentIndex = -1 quat.y = -quat.y #quat.inverse() else: quat.inverse() # create an armature skeleton armData = Armature.Armature("PSK") armData.drawAxes = True armObject = Object.New('Armature', "ReferenceBones") armObject.link(armData) scene = Scene.GetCurrent() scene.objects.link(armObject) armData.makeEditable() editBones = [] for i in range(0, header.dataCount): refBone = axReferenceBones[i] refBone.name = refBone.name.replace(' ', '_') print("processing bone ", refBone.name) #if refBone.position.length == 0: #refBone.Dump() editBone = Armature.Editbone() editBone.name = refBone.name #editBone.length = refBone.position.length if refBone.parentIndex >= 0: refParent = axReferenceBones[refBone.parentIndex] parentName = refParent.name #print type(parentName) print("looking for parent bone", parentName) #parent = armData.bones[parentName] #parent. # editBone.head = refParent.position.copy() editParent = editBones[refBone.parentIndex] #editParent = armData.bones[editBones[refBone.parentIndex].name] #editParent = armData.bones[parentName] editBone.parent = editParent #editBone.tail = refBone.position #editBone.matrix = refBone.quat.toMatrix() #m = Matrix(QuatToMatrix(refParent.quat)) #rotatedPos = m * refBone.position.copy() rotatedPos = refParent.quat * refBone.position.copy() editBone.tail = refParent.position + rotatedPos refBone.position = refParent.position + rotatedPos #editBone.tail = refBone.position = refParent.position + refBone.position q1 = refParent.quat.copy() q2 = refBone.quat.copy() refBone.quat = QuatMultiply1(q1, q2) #editBone.matrix = refBone.quat.toMatrix() #matrix = Matrix(refParent.quat.toMatrix() * refBone.quat.toMatrix()) #m1 = refParent.quat.copy().toMatrix() #m2 = refBone.quat.toMatrix() #refBone.quat = matrix.toQuat() #editBone.options = [Armature.HINGE] #editBone.options = [Armature.HINGE, Armature.CONNECTED] editBone.options = [Armature.CONNECTED] else: editBone.head = Vector(0, 0, 0) editBone.tail = refBone.position.copy() #editBone.tail = refBone.quat.toMatrix() * refBone.position #editBone.options = [Armature.HINGE] #editBone.matrix = refBone.quat.toMatrix() editBones.append(editBone) armData.bones[editBone.name] = editBone # only update after adding all edit bones or it will crash Blender !!! armData.update() print("done processing reference bones") #for editBone in editBones: #armData.makeEditable() #armData.bones[editBone.name] = editBone #armData.update() armObject.makeDisplayList() scene.update() Window.RedrawAll() # read the RAWWEIGHTS header header.Load(pskFile) header.Dump() axBoneWeights = [] for i in range(0, header.dataCount): axBoneWeights.append(axBoneWeight()) axBoneWeights[i].Load(pskFile) #if i < 10: # axBoneWeights[i].Dump() # calculate the vertex groups vertGroupCreated = [] for i in range(0, len(axReferenceBones)): vertGroupCreated.append(0) for i in range(0, len(axReferenceBones)): refBone = axReferenceBones[i] for boneWeight in axBoneWeights: if boneWeight.boneIndex == i: # create a vertex group for this bone if not done yet if vertGroupCreated[i] == 0: print('creating vertex group:', refBone.name) mesh.addVertGroup(refBone.name) vertGroupCreated[i] = 1 for j in range(0, len(axVerts)): axVert = axVerts[j] #vertList.append(boneWeight.pointIndex) if boneWeight.pointIndex == axVert.pointIndex: mesh.assignVertsToGroup(refBone.name, [j], boneWeight.weight, Mesh.AssignModes.ADD) #mesh.assignVertsToGroup(refBone.name, vertList, ) armObject.makeParentDeform([meshObject], 0, 0) pskFile.close() Window.RedrawAll() print "PSK2Blender completed"
mfile.setSuperModelName(supermodel) # Process each child of the baseobj... mfile._objects = [] processobject(model, "NULL", mfile) # Mess around with Animations # (Note: doc says GetActions returns a "PyList", but in fact, it's a dict. # Blender has some funny nomenclature.) # (Also, it's not getAllChannelIpo(), it's getAllChannelIpos().) # The 2.33 Action API rules. Docs have typos though. =) mfile._animations = [] actions = NLA.GetActions() arms = Armature.Get() #for a in arms: # putlog(NBLog.DEBUG, # "Armature %s bones %s, children %s" # % (a, str(a.getBones()), scnobjchilds[a.getName()])) #test = Object.Get('cone2') #p = test.getParent(); #putlog(NBLog.DEBUG, "cone2 is parented to %s" % p.getName()) #putlog(NBLog.DEBUG, "Actionlist: %s" % repr(actions)) for a in actions: # Let's skip this animation bullshit. (For those who just # checked out the code and can't get the bloody thing to # work!)