Example #1
0
def ObjExport(FILE, Name, type):
    #================================
    global returncode
    global vertexcount
    global uvcount
    global Transform
    global multiflag
    global exporttype

    vertexcount = 0
    uvcount = 0
    returncode = 0
    print("Writing %s..." % Name)
    FILE.write(
        "# Wavefront OBJ (1.0) exported by lynx's OBJ import/export script\n\n"
    )

    Objects = Object.GetSelected()
    if Objects == []:
        print("You have not selected an object!")
        returncode = 4
    else:
        for object in Objects:
            MtlList = []
            if len(Objects) > 1 or exporttype > 1:
                Transform = CreateMatrix(object, Transform)
                multiflag = 1

            mesh = NMesh.GetRawFromObject(object.name)
            ObjName = mesh.name
            has_uvco = mesh.hasVertexUV()

            FILE.write("# Meshname:\t%s\n" % ObjName)

            faces = mesh.faces
            materials = mesh.materials
            Vertices = mesh.verts
            GlobalMaterials = Material.Get()

            if len(materials) > 1 and len(GlobalMaterials) > 0 and type < 4:
                CreateMtlFile(Name, materials, MtlList)

            # Total Vertices and faces; comment if not useful
            FILE.write("# Total number of Faces:\t%s\n" % len(faces))
            FILE.write("# Total number of Vertices:\t%s\n" % len(Vertices))

            FILE.write("\n")

            # print first image map for uvcoords to use
            # to be updated when we get access to other textures
            if mesh.hasFaceUV():
                FILE.write("# UV Texture:\t%s\n\n" % mesh.hasFaceUV())

            if len(materials) > 1 and len(GlobalMaterials) > 0 and type < 3:
                UseLayers(faces, Vertices, MtlList, has_uvco, FILE, ObjName,
                          Name)
            elif len(materials) > 1 and len(GlobalMaterials) > 0 and type == 3:
                UseMtl(faces, Vertices, MtlList, has_uvco, FILE, ObjName, Name)
            else:
                Standard(faces, Vertices, has_uvco, FILE, ObjName)
Example #2
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()
Example #3
0
def export_geometry(obj, filename):
    #mesh = "";verts="";faces="";numverts=""
    islight = obj.name.startswith("meshlight")
    if islight:
        print "o exporting meshlight " + obj.name + "..."
    else:
        print "o exporting mesh " + obj.name + "..."
    # get the mesh data
    mesh = NMesh.GetRawFromObject(obj.name)
    if islight:
        mesh.transform(obj.getMatrix(), 1)
    verts = mesh.verts
    faces = mesh.faces
    numfaces = faces.__len__()
    numverts = verts.__len__()
    if numfaces > 100000:
        print "   -> large mesh detected - creating binary ra3 file"
        ra3filename = filename.replace(".sc", "_%s.ra3" % obj.name)
        RA3FILE = open(ra3filename, 'wb')
        print "   -> creating \"%s\" ..." % ra3filename
        print "   -> counting triangles ..."
        numtris = 0
        for face in faces:
            num = len(face.v)
            if num == 4:
                numtris = numtris + 2
            elif num == 3:
                numtris = numtris + 1
        print "   -> writing %s points" % numverts
        RA3FILE.write(struct.pack("<II", numverts, numtris))
        for vert in verts:
            RA3FILE.write(
                struct.pack("<fff", vert.co[0], vert.co[1], vert.co[2]))
        print "   -> writing %s triangles" % numtris
        for face in faces:
            num = len(face.v)
            if num == 4:
                RA3FILE.write(
                    struct.pack("<III", face.v[0].index, face.v[1].index,
                                face.v[2].index))
                RA3FILE.write(
                    struct.pack("<III", face.v[0].index, face.v[2].index,
                                face.v[3].index))
            elif num == 3:
                RA3FILE.write(
                    struct.pack("<III", face.v[0].index, face.v[1].index,
                                face.v[2].index))
        RA3FILE.close()
        print "   -> done writing file"
        FILE.write("\n\nobject {\n")
        if len(mesh.materials) == 1:
            FILE.write("\tshader \"" + mesh.materials[0].name + ".shader\"\n")
        elif len(mesh.materials) > 1:
            FILE.write("\tshaders %d\n" % (len(mesh.materials)))
            for mat in mesh.materials:
                FILE.write("\t\t\"" + mat.name + ".shader\"\n")
        else:
            FILE.write("\tshader def\n")
        mat = obj.getMatrix()
        FILE.write(
            "\ttransform col\n\t\t%s %s %s %s\n\t\t%s %s %s %s\n\t\t%s %s %s %s\n\t\t%s %s %s %s\n"
            %
            (mat[0][0], mat[0][1], mat[0][2], mat[0][3], mat[1][0], mat[1][1],
             mat[1][2], mat[1][3], mat[2][0], mat[2][1], mat[2][2], mat[2][3],
             mat[3][0], mat[3][1], mat[3][2], mat[3][3]))
        FILE.write("\ttype file-mesh\n")
        FILE.write("\tname \"" + obj.name + "\"\n")
        FILE.write("\tfilename \"%s\"\n" % os.path.basename(ra3filename))
        FILE.write("}\n")
        return
    if numverts > 0:
        if islight:
            FILE.write("\n\nlight {\n")
            FILE.write("\ttype meshlight\n")
            FILE.write("\tname \"" + obj.name + "\"\n")
            if len(mesh.materials) >= 1:
                matrl = mesh.materials[0]
                FILE.write("\temit { \"sRGB nonlinear\" %s %s %s }\n" %
                           (matrl.R, matrl.G, matrl.B))
            else:
                FILE.write("\temit 1 1 1\n")
            FILE.write("\tradiance %s\n" % (MESHLIGHTPOWER.val))
            FILE.write("\tsamples %s\n" % DSAMPLES.val)
        else:
            FILE.write("\n\nobject {\n")
            if len(mesh.materials) == 1:
                FILE.write("\tshader \"" + mesh.materials[0].name +
                           ".shader\"\n")
            elif len(mesh.materials) > 1:
                FILE.write("\tshaders %d\n" % (len(mesh.materials)))
                for mat in mesh.materials:
                    FILE.write("\t\t\"" + mat.name + ".shader\"\n")
            else:
                FILE.write("\tshader def\n")
            mat = obj.getMatrix()
            FILE.write(
                "\ttransform col\n\t\t%s %s %s %s\n\t\t%s %s %s %s\n\t\t%s %s %s %s\n\t\t%s %s %s %s\n"
                % (mat[0][0], mat[0][1], mat[0][2], mat[0][3], mat[1][0],
                   mat[1][1], mat[1][2], mat[1][3], mat[2][0], mat[2][1],
                   mat[2][2], mat[2][3], mat[3][0], mat[3][1], mat[3][2],
                   mat[3][3]))
            FILE.write("\ttype generic-mesh\n")
            FILE.write("\tname \"" + obj.name + "\"\n")

        FILE.write("\tpoints %d\n" % (numverts))
        for vert in verts:
            FILE.write("\t\t%s %s %s\n" % (vert.co[0], vert.co[1], vert.co[2]))
        numtris = 0
        for face in faces:
            num = len(face.v)
            if num == 4:
                numtris = numtris + 2
            elif num == 3:
                numtris = numtris + 1
        FILE.write("\ttriangles %d\n" % (numtris))
        allsmooth = True
        allflat = True
        for face in faces:
            num = len(face.v)
            smooth = face.smooth != 0
            allsmooth &= smooth
            allflat &= not smooth
            if num == 4:
                FILE.write("\t\t%d %d %d\n" %
                           (face.v[0].index, face.v[1].index, face.v[2].index))
                FILE.write("\t\t%d %d %d\n" %
                           (face.v[0].index, face.v[2].index, face.v[3].index))
            elif num == 3:
                FILE.write("\t\t%d %d %d\n" %
                           (face.v[0].index, face.v[1].index, face.v[2].index))
        ## what kind of normals do we have?
        if not islight:
            if allflat:
                FILE.write("\tnormals none\n")
            elif allsmooth:
                FILE.write("\tnormals vertex\n")
                for vert in verts:
                    FILE.write("\t\t%s %s %s\n" %
                               (vert.no[0], vert.no[1], vert.no[2]))
            else:
                FILE.write("\tnormals facevarying\n")
                for face in faces:
                    num = len(face.v)
                    if face.smooth != 0:
                        if num == 4:
                            index0 = face.v[0].index
                            index1 = face.v[1].index
                            index2 = face.v[2].index
                            index3 = face.v[3].index
                            FILE.write(
                                "\t\t%s %s %s %s %s %s %s %s %s\n" %
                                (verts[index0].no[0], verts[index0].no[1],
                                 verts[index0].no[2], verts[index1].no[0],
                                 verts[index1].no[1], verts[index1].no[2],
                                 verts[index2].no[0], verts[index2].no[1],
                                 verts[index2].no[2]))
                            FILE.write(
                                "\t\t%s %s %s %s %s %s %s %s %s\n" %
                                (verts[index0].no[0], verts[index0].no[1],
                                 verts[index0].no[2], verts[index2].no[0],
                                 verts[index2].no[1], verts[index2].no[2],
                                 verts[index3].no[0], verts[index3].no[1],
                                 verts[index3].no[2]))
                        elif num == 3:
                            index0 = face.v[0].index
                            index1 = face.v[1].index
                            index2 = face.v[2].index
                            FILE.write(
                                "\t\t%s %s %s %s %s %s %s %s %s\n" %
                                (verts[index0].no[0], verts[index0].no[1],
                                 verts[index0].no[2], verts[index1].no[0],
                                 verts[index1].no[1], verts[index1].no[2],
                                 verts[index2].no[0], verts[index2].no[1],
                                 verts[index2].no[2]))
                    else:
                        fnx = face.no[0]
                        fny = face.no[1]
                        fnz = face.no[2]
                        if num == 4:
                            FILE.write(
                                "\t\t%s %s %s %s %s %s %s %s %s\n" %
                                (fnx, fny, fnz, fnx, fny, fnz, fnx, fny, fnz))
                            FILE.write(
                                "\t\t%s %s %s %s %s %s %s %s %s\n" %
                                (fnx, fny, fnz, fnx, fny, fnz, fnx, fny, fnz))
                        elif num == 3:
                            FILE.write(
                                "\t\t%s %s %s %s %s %s %s %s %s\n" %
                                (fnx, fny, fnz, fnx, fny, fnz, fnx, fny, fnz))
            if mesh.hasFaceUV():
                tx = 1
                ty = 1
                if len(mesh.materials) >= 1:
                    if len(mesh.materials[0].getTextures()) >= 1:
                        if mesh.materials[0].getTextures()[0] <> None:
                            tx = mesh.materials[0].getTextures(
                            )[0].tex.repeat[0]
                            ty = mesh.materials[0].getTextures(
                            )[0].tex.repeat[1]
                FILE.write("\tuvs facevarying\n")
                for face in faces:
                    num = len(face.v)
                    if num == 4:
                        FILE.write("\t\t%s %s %s %s %s %s\n" %
                                   (tx * face.uv[0][0], ty * face.uv[0][1],
                                    tx * face.uv[1][0], ty * face.uv[1][1],
                                    tx * face.uv[2][0], ty * face.uv[2][1]))
                        FILE.write("\t\t%s %s %s %s %s %s\n" %
                                   (tx * face.uv[0][0], ty * face.uv[0][1],
                                    tx * face.uv[2][0], ty * face.uv[2][1],
                                    tx * face.uv[3][0], ty * face.uv[3][1]))
                    elif num == 3:
                        FILE.write("\t\t%s %s %s %s %s %s\n" %
                                   (tx * face.uv[0][0], ty * face.uv[0][1],
                                    tx * face.uv[1][0], ty * face.uv[1][1],
                                    tx * face.uv[2][0], ty * face.uv[2][1]))
            else:
                FILE.write("\tuvs none\n")
            if len(mesh.materials) > 1:
                FILE.write("\tface_shaders\n")
                for face in faces:
                    num = len(face.v)
                    if num == 4:
                        FILE.write("\t\t%d\n" % (face.materialIndex))
                        FILE.write("\t\t%d\n" % (face.materialIndex))
                    elif num == 3:
                        FILE.write("\t\t%d\n" % (face.materialIndex))
        FILE.write("}\n")
Example #4
0
    def writeMeshcoordArm(self, obj, arm_ob):
        global index_list, flip_z
        #TransformMatrix
        mat = self.getLocMat(obj)
        self.writeArmFrames(mat, make_legal_name(obj.name))
        mesh = NMesh.GetRawFromObject(obj.name)
        self.file.write("Mesh {\n")
        numface = len(mesh.faces)
        #VERTICES NUMBER
        numvert = 0
        for face in mesh.faces:
            numvert = numvert + len(face.v)
        self.file.write("%d;\n" % (numvert))
        if numvert == 0:
            print "Mesh named", mesh.name, "has no vertices.Problems may occur using the .x file"
        #VERTICES COORDINATES
        counter = 0
        for face in mesh.faces:
            counter += 1
            for n in range(len(face.v)):
                index_list.append(face.v[n].index)
                vec_vert = Vector([(face.v[n].co[0]), face.v[n].co[1],
                                   face.v[n].co[2], 1])
                if arm_ob:
                    f_vec_vert = vec_vert * mat
                else:
                    f_vec_vert = vec_vert
                self.file.write(
                    "%f; %f; %f;" %
                    (round(f_vec_vert[0], 4), round(
                        f_vec_vert[1], 4), round(f_vec_vert[2], 4)))
                if counter == numface:
                    if n == len(face.v) - 1:
                        self.file.write(";\n")
                    else:
                        self.file.write(",\n")
                else:
                    self.file.write(",\n")
        if flip_z:
            a3 = 0
            b3 = 2
            c3 = 1
            a4 = 0
            b4 = 3
            c4 = 2
            d4 = 1
        else:
            a3 = 0
            b3 = 1
            c3 = 2
            a4 = 0
            b4 = 1
            c4 = 2
            d4 = 3

        #FACES NUMBER
        self.file.write("%s;\n" % (numface))
        coun, counter = 0, 0
        for face in mesh.faces:
            coun += 1
            separator = ','
            if coun == numface:
                separator = ';'
            if len(face.v) == 3:
                self.file.write(
                    "3; %d, %d, %d;%c\n" %
                    (counter + a3, counter + b3, counter + c3, separator))
                counter += 3
            elif len(face.v) == 4:
                self.file.write("4; %d, %d, %d, %d;%c\n" %
                                (counter + a4, counter + b4, counter + c4,
                                 counter + d4, separator))
                counter += 4
            elif len(face.v) < 3:
                print "WARNING:the mesh has faces with less then 3 vertices"
                print "        It my be not exported correctly."
Example #5
0
        def select_modifier(RVK1, RVK2, DATA2):
            # ======================================================
            # in case of modifiers, use =============================
            # ======================================================
            if RVK1.modifiers:
                #MODIFIERS=1
                POSSMOD = [Value(t) for t in POSSMOD_list]
                AUTHMOD = [Value(t) for t in AUTHMOD_list]
                if DEBUG: print 'POSSMOD:', POSSMOD, '\nAUTHMOD:', AUTHMOD
                MODRVK1 = RVK1.modifiers
                block = []
                # ===================================================
                # ===  Bloc Menu Modifiers ===1 doc =================
                # ===================================================
                m = 0
                for mod in MODRVK1:
                    if DEBUG: print mod.type
                    if mod.type in POSSMOD:
                        BMOD[0].append([
                            Draw.Create(0), mod.type, m,
                            POSSMOD_list[POSSMOD.index(mod.type)],
                            mod[Modifier.Settings.RENDER] == 1,
                            mod[Modifier.Settings.EDITMODE] == 1
                        ])
                    elif mod.type in AUTHMOD:
                        BMOD[1].append([
                            Draw.Create(1), mod.type, m,
                            AUTHMOD_list[AUTHMOD.index(mod.type)],
                            mod[Modifier.Settings.RENDER] == 1,
                            mod[Modifier.Settings.EDITMODE] == 1
                        ])
                    m += 1
                # ===================================================
                # ===  Bloc Menu Modifiers ===2 display =============
                # ===================================================
                block.append(BMOD[1][0])
                for B in BMOD[1][1:]:
                    block.append((B[3], B[0], ""))
                block.append(BMOD[0][0])
                block.append("not alredy implemented")
                block.append("in this script.")
                for B in BMOD[0][1:]:
                    block.append((B[3], B[0], ""))
                retval = Blender.Draw.PupBlock("MESH 2 RVK", block)
                # ===================================================
                # ===  unset Modifiers  =============================
                # ===================================================
                for B in BMOD[0][1:]:
                    if DEBUG: print B[2]
                    MODRVK1[B[2]][Modifier.Settings.RENDER] = 0
                for B in BMOD[1]:
                    if not B[1]:
                        MODRVK1[B[2]][Modifier.Settings.RENDER] = 0
                # ===================================================
                # ===  update Modifiers =============================
                # ===================================================
                #RVK1.makeDisplayList()
            # =======================================================
            # ===  get deformed mesh ================================
            # =======================================================
            RVK1NAME = Object.GetSelected()[0].getName()
            meshrvk1 = NMesh.GetRawFromObject(RVK1NAME)
            if DEBUG: print len(meshrvk1.verts)
            # =======================================================
            # ===  get normal mesh for vertex group =================
            # =======================================================
            DATA1 = RVK1.getData()
            # =======================================================
            # ===  get destination mesh  ============================
            # =======================================================
            DATA2 = RVK2.getData()
            if DEBUG: print len(meshrvk1.verts)
            if DEBUG: print len(DATA2.verts)
            # ========================================================
            # ===== is there the same number of vertices =============
            # ========================================================
            if len(meshrvk1.verts) == len(DATA2.verts):
                name = "Do you want to replace or add vertex groups ? %t| YES %x1| NO ? %x2 "
                result = Draw.PupMenu(name)
                if result == 1:
                    # =====================================================
                    # ===== Do we save vertex groups ?  ===================
                    # =====================================================
                    GROUPNAME2 = DATA2.getVertGroupNames()
                    if len(GROUPNAME2) != 0:
                        for GROUP2 in GROUPNAME2:
                            DATA2.removeVertGroup(GROUP2)
                    GROUPNAME1 = DATA1.getVertGroupNames()
                    if len(GROUPNAME1) != 0:
                        for GROUP1 in GROUPNAME1:
                            DATA2.addVertGroup(GROUP1)
                            DATA2.assignVertsToGroup(
                                GROUP1, DATA1.getVertsFromGroup(GROUP1), 1.0,
                                'replace')
                # ========================================================
                # ===== now copy the vertices coords =====================
                # ========================================================
                for v in meshrvk1.verts:
                    i = meshrvk1.verts.index(v)
                    v1 = DATA2.verts[i]
                    for n in [0, 1, 2]:
                        v1.co[n] = v.co[n]
                DATA2.update()
                DATA2.insertKey(FRAME, 'relative')
                DATA2.update()
                RVK2.makeDisplayList()

                if RVK1.modifiers:
                    # ===================================================
                    # ===  unset Modifiers  =============================
                    # ===================================================
                    for B in BMOD[0][1:]:
                        MODRVK1[B[2]][Modifier.Settings.RENDER] |= B[-2]
                    for B in BMOD[1]:
                        if not B[1]:
                            MODRVK1[B[2]][Modifier.Settings.RENDER] |= B[-2]

            else:
                name = "Meshes Objects must have the same number of vertices %t|Ok. %x1"
                result = Draw.PupMenu(name)
                return
def exportObject(obj):
    objmesh = NMesh.GetRawFromObject(obj.getName())
    objfaces = objmesh.faces
    objfacelists = list()
    for fac in objfaces:
        objfacelists.append(fac.v)
    for i in range(len(objfacelists)):
        for j in range(len(objfacelists[i])):
            objfacelists[i][j] = objfacelists[i][j].index
#	print objfacelists
    objmaterials = objmesh.materials
    objvertices = objmesh.verts
    vertcoords = list()
    for vert in objvertices:
        vertcoords.append(vert.co)
#	print vertcoords
    vertnormals = list()
    for vert in objvertices:
        vertnormals.append(vert.no)
#	print vertnormals
#	texcoords = list()
#	for vert in objvertices:
#		texcoords.append(vert.uvco)
#	print texcoords
    texcoords = list()
    for fac in objfaces:
        texcoords.append(fac.uv)


#	print texcoords

    filename = "%s_%s.xmesh" % (obj.getName(), objmesh.name)
    FILE = open(filename, "w")
    FILE.write("<!--\n")
    FILE.write("Vegastrike XMESH <" + filename +
               "> from Blender (by dandandaman's script)\n")

    # Polycount info
    FILE.write("Total number of Faces:   \t%s\n" % len(objfaces))
    FILE.write("Total number of Vertices:\t%s\n" % len(objvertices))
    FILE.write("-->\n")

    quads = list()
    tris = list()

    global teximg
    teximg = [objfaces[0].image]

    for fac in objfaces:
        if len(fac.v) == 4:
            quads.append(fac)
        elif len(fac.v) == 3:
            tris.append(fac)
        if fac.image not in teximg and (fac.image):
            teximg.append(fac.image)

    texname = ""
    tex_ind = 0
    while (tex_ind < len(teximg)):
        if not teximg[tex_ind]:
            tex_ind += 1
        else:
            texname = teximg[tex_ind].getName()
            tex_ind += 1

    # FIXME: add texture header!!!
    FILE.write("<Mesh ")
    FILE.write("texture = \"%s\">\n" % texname)

    # Print all vertices and vertice normals to file
    FILE.write("<Points>\n")
    for i in range(len(objvertices)):
        FILE.write("\t<Point>\n")
        FILE.write(
            "\t\t<Location x=\"%s\" y=\"%s\" z=\"%s\"/> <!-- %s -->\n" %
            (objvertices[i][0], objvertices[i][1], objvertices[i][2], i))
        FILE.write("\t\t<Normal i=\"%s\" j=\"%s\" k=\"%s\"/>\n" %
                   (vertnormals[i][0], vertnormals[i][1], vertnormals[i][2]))
        FILE.write("\t</Point>\n")
    FILE.write("</Points>\n")

    FILE.write("<Polygons>\n")

    makePolys(tris, FILE)
    makePolys(quads, FILE)

    #	if (quads):					#FIXME: Add helper function for polygons to make this easier!!!
    #		for quad in quads:
    #			FILE.write("\t<Quad>\n")
    #			for j in range(len(quad.v)):
    #				if has_uv:
    #					FILE.write("\t\t<Vertex point=\"%s\" s=\"%s\" t=\"%s\"/>\n" % ((quad.v[j] + 1), quad.uv[j][0], quad.uv[j][1]))
    #				else:
    #					FILE.write("\t\t<Vertex point=\"%s\" s=\"\" t=\"\"/>\n" % (quad.v[j] + 1))
    #			FILE.write("\t</Quad>\n")
    #
    #	if (tris):
    #		for tri in tris:
    #			FILE.write("\t<Tri>\n")
    #			for j in range(len(tri.v)):
    #				if has_uv:
    #					FILE.write("\t\t<Vertex point=\"%s\" s=\"%s\" t=\"%s\"/>\n" % ((tri.v[j] + 1), tri.uv[j][0], tri.uv[j][1]))
    #				else:
    #					FILE.write("\t\t<Vertex point=\"%s\" s=\"\" t=\"\"/>\n" % (tri.v[j] + 1))
    #			FILE.write("\t</Tri>\n")
    #
    #

    FILE.write("</Polygons>\n<Material>\n</Material>\n</Mesh>")
    FILE.close()
    print("Written " + filename)
    print "\t%s contains %s faces (%s quads, %s tris) and %s vertices" % (
        filename, len(objfaces), len(quads), len(tris), len(objvertices))
    printErrors()
def write(filename):
    editmode = Window.EditMode()
    if editmode: Window.EditMode(0)
    print "Start export"
    out = file(filename, "w")

    for material in Material.get():
        out.write('Material %s\n' % (material.name))
        out.write(
            'Diffuse %f %f %f %f\n' %
            (material.R, material.G, material.B, material.getTranslucency()))
        out.write('Ambient %f\n' % (material.amb))
        out.write('Specular %f %f %f %f\n' %
                  (material.getSpecCol()[0], material.getSpecCol()[1],
                   material.getSpecCol()[2], material.getSpecTransp()))

    for object in Blender.Object.Get():
        if (object.getType() == "Mesh"):
            out.write('%s %s\n' % (object.getType(), object.getName()))
            index_list = []
            mesh = NMesh.GetRawFromObject(object.name)

            for face in mesh.faces:
                for n in range(len(face.v)):
                    index_list.append(face.v[n].index)

            out.write('%s\n' % (len(mesh.faces)))  # Write the number of faces
            out.write('%s\n' %
                      (len(object.data.verts)))  # Write the number of vertices
            out.write('%s\n' %
                      (len(index_list)))  # Write the number of indices

            for material in mesh.materials:
                out.write('Material %s\n' % material.name)

            out.write('Loc %f %f %f\n' %
                      (object.matrixWorld[3][0], object.matrixWorld[3][1],
                       object.matrixWorld[3][2]))

            for vert in object.data.verts:
                out.write('v %f %f %f n %f %f %f\n' %
                          (vert.co.x, vert.co.y, vert.co.z, vert.no.x,
                           vert.no.y, vert.no.z))

            for index in index_list:
                out.write('i %s\n' % (index))

        elif (object.getType() == "Camera"):
            data = object.data
            cam = Camera.get(data.name)
            out.write('Camera %s\n' % (data.name))
            out.write('Right %f %f %f\n' %
                      (object.getMatrix()[0][0], object.getMatrix()[0][1],
                       object.getMatrix()[0][2]))
            out.write('Up %f %f %f\n' %
                      (object.getMatrix()[1][0], object.getMatrix()[1][1],
                       object.getMatrix()[1][2]))
            out.write('Forward %f %f %f\n' %
                      (object.getMatrix()[2][0], object.getMatrix()[2][1],
                       object.getMatrix()[2][2]))
            out.write('Loc %f %f %f\n' %
                      (object.getLocation()[0], object.getLocation()[1],
                       object.getLocation()[2]))
            out.write('Far %f\n' % (cam.getClipEnd()))
            out.write('Near %f\n' % (cam.getClipStart()))
            out.write('FOV %f\n' % (2.0 * math.atan(16.0 / cam.getLens())))

        elif object.getType() == "Lamp":
            data = object.data
            light = Lamp.get(data.name)
            if light.type == Lamp.Types.Lamp:
                out.write('Light Type Unsupported')
            elif light.type == Lamp.Types.Spot:
                out.write('Light Type Unsupported')
            elif light.type == Lamp.Types.Sun:
                out.write('Light %s\n' % (data.name))
                out.write('Type Omni\n')
                out.write('Color %f %f %f\n' % (light.R, light.G, light.B))
                out.write('Right %f %f %f\n' %
                          (object.getMatrix()[0][0], object.getMatrix()[0][1],
                           object.getMatrix()[0][2]))
                out.write('Up %f %f %f\n' %
                          (object.getMatrix()[1][0], object.getMatrix()[1][1],
                           object.getMatrix()[1][2]))
                out.write('Forward %f %f %f\n' %
                          (object.getMatrix()[2][0], object.getMatrix()[2][1],
                           object.getMatrix()[2][2]))
                out.write('Loc %f %f %f\n' %
                          (object.matrixWorld[3][0], object.matrixWorld[3][1],
                           object.matrixWorld[3][2]))
            else:
                out.write('Light Type Unsupported')

    out.close()
    print "End export"
Example #8
0
def exportMesh(obj, file, loc, size, quat):
    mesh = NMesh.GetRawFromObject(obj.getName())

    indent(file)
    file.write("<Mesh name=\"%s\" numVertices=\"%d\" numFaces=\"%d\" " %
               (obj.getName(), len(mesh.verts), len(mesh.faces)))
    file.write("x=\"%3.5f\" y=\"%3.5f\" z=\"%3.5f\" " %
               (loc[0], loc[2], -loc[1]))
    file.write("sx=\"%3.5f\" sy=\"%3.5f\" sz=\"%3.5f\" " %
               (size[0], size[1], size[2]))
    file.write("qw=\"%3.5f\" qx=\"%3.5f\" qy=\"%3.5f\" qz=\"%3.5f\"" %
               (quat[0], quat[1], quat[2], quat[3]))
    file.write(">\n")
    setIndent(1)

    for mat in mesh.materials:
        exportMaterial(mat, file)
    if len(mesh.materials) > 0:
        file.write("\n")

    textures = []
    if mesh.hasFaceUV():
        for face in mesh.faces:
            if not face.image:
                continue

            if textures.count(face.image) == 0:
                textures.append(face.image)

    for tex in textures:
        exportTexture(tex, file)
    if len(textures) > 0:
        file.write("\n")

    for vert in mesh.verts:
        indent(file)
        file.write("<Vertex x=\"%3.5f\" y=\"%3.5f\" z=\"%3.5f\" " %
                   (vert.co[0], vert.co[2], -vert.co[1]))
        file.write("nx=\"%3.5f\" ny=\"%3.5f\" nz=\"%3.5f\"/>\n" %
                   (vert.no[0], vert.no[2], -vert.no[1]))

    file.write("\n")

    for face in mesh.faces:
        indent(file)
        file.write("<Face smooth=\"%d\" " % face.smooth)
        file.write("nx=\"%3.5f\" ny=\"%3.5f\" nz=\"%3.5f\" " %
                   (face.normal[0], face.normal[2], -face.normal[1]))

        if face.image:
            file.write("texture=\"%d\" " % (textures.index(face.image)))
        else:
            file.write("texture=\"-1\" ")

        mat = face.materialIndex
        if mat >= len(mesh.materials):
            mat = -1

        file.write("material=\"%d\">\n" % (mat))

        setIndent(1)
        for i in range(3):
            indent(file)
            file.write("<Vertex index=\"%d\" " % face.v[i].index)

            if mesh.hasFaceUV() and face.image:
                file.write("u=\"%1.3f\" v=\"%1.3f\"" %
                           (face.uv[i][0], 1.0 - face.uv[i][1]))

            file.write("/>\n")

        setIndent(-1)

        #		file.write(" vertex1=\"%d\" vertex2=\"%d\" vertex3=\"%d\"/>\n" %(face.v[0].index, face.v[1].index, face.v[2].index))
        indent(file)
        file.write("</Face>\n")

    Object.GetSelected().remove(obj)
    for child in Object.GetSelected():
        if child.parent == obj:
            export(child, file)
            Object.GetSelected().remove(child)

    setIndent(-1)
    indent(file)
    file.write("</Mesh>\n\n")
Example #9
0
def deform2rvk():
	POSSMOD_list=['EDGESPLIT',
								'DECIMATE',
								'SUBSURF',
								'BOOLEAN',
								'BUILD',
								'MIRROR',
								'ARRAY']

	AUTHMOD_list=['LATTICE',
	              'CURVE',
	              'WAVE',
	              'ARMATURE']

	MODIFIERS=0

	BMOD=[['Possible Modifiers'],
				['Allowed Modifiers']]

	#	=================================================================
	# at leat 2 objects ===============================================
	#	=================================================================
	if len(Object.GetSelected())>1 :
		RVK1=Object.GetSelected()[0]
		RVK2=Object.GetSelected()[1]
		# =============================================================
		# must be 2 meshes ============================================
		# =============================================================
		if RVK1.getType()=='Mesh' and RVK2.getType()=='Mesh':
			FRAME=Blender.Get('curframe')
			DATA2=RVK2.getData()
			if DEBUG: print DATA2.getKey()
			# ============================================================
			# at least the second must have a shape key ==================
			# ============================================================
			if DATA2.getKey():
				# ======================================================
				# in case of modifiers use =============================
				# ======================================================
				if RVK1.modifiers:
					MODIFIERS=1
					POSSMOD=[Value(t) for t in POSSMOD_list]
					AUTHMOD=[Value(t) for t in AUTHMOD_list]
					if DEBUG: print 'POSSMOD:',POSSMOD,'\nAUTHMOD:', AUTHMOD
					MODRVK1=RVK1.modifiers
					block = []
					# ===================================================
					# ===  Bloc Menu Modifiers ===1 doc =================
					# ===================================================
					m=0
					for mod in  MODRVK1:
						if DEBUG: print mod.type
						if mod.type in POSSMOD:
							BMOD[0].append([Draw.Create(0),mod.type,
																	m,
																	POSSMOD_list[POSSMOD.index(mod.type)],
																	mod[Modifier.Settings.RENDER]==1,
																	mod[Modifier.Settings.EDITMODE]==1
																	])
						elif mod.type in AUTHMOD:
							BMOD[1].append([Draw.Create(1),
															mod.type,
																	m,
																	AUTHMOD_list[AUTHMOD.index(mod.type)],
																	mod[Modifier.Settings.RENDER]==1,
																	mod[Modifier.Settings.EDITMODE]==1
																	])
						m+=1
					# ===================================================
					# ===  Bloc Menu Modifiers ===2 display =============
					# ===================================================
					block.append(BMOD[1][0])
					for	B in BMOD[1][1:]:
						block.append((B[3],B[0],""))
					block.append(BMOD[0][0])
					block.append("not alredy implemented")
					block.append("in this script.")
					for	B in BMOD[0][1:]:
						block.append((B[3],B[0],""))
					retval = Blender.Draw.PupBlock("MESH 2 RVK", block)
					# ===================================================
					# ===  unset Modifiers  =============================
					# ===================================================
					for	B in BMOD[0][1:]:
						if DEBUG: print B[2]
						MODRVK1[B[2]][Modifier.Settings.RENDER]=0
					for	B in BMOD[1]:
						if not B[1]:
							MODRVK1[B[2]][Modifier.Settings.RENDER]=0
					# ===================================================
					# ===  update Modifiers =============================
					# ===================================================
					#RVK1.makeDisplayList()
				# =======================================================
				# ===  get deformed mesh ================================
				# =======================================================
				RVK1NAME=Object.GetSelected()[0].getName()
				meshrvk1=NMesh.GetRawFromObject(RVK1NAME)
				if DEBUG: print len(meshrvk1.verts)
				# =======================================================
				# ===  get normal mesh for vertex group =================
				# =======================================================
				DATA1=RVK1.getData()
				# =======================================================
				# ===  get destination mesh  ============================
				# =======================================================
				DATA2=RVK2.getData()
				if DEBUG: print len(meshrvk1.verts)
				if DEBUG: print len(DATA2.verts)
				# ========================================================
				# ===== is there the same number of vertices =============
				# ========================================================
				if len(meshrvk1.verts)==len(DATA2.verts):
					name = "Do you want to replace or add vertex groups ? %t| YES %x1| NO ? %x2 "
					result = Draw.PupMenu(name)
					if result==1:
						# =====================================================
						# ===== Do we save vertex groups ?  ===================
						# =====================================================
						GROUPNAME2=DATA2.getVertGroupNames()
						if len(GROUPNAME2)!=0:
							for GROUP2 in GROUPNAME2:
								DATA2.removeVertGroup(GROUP2)
						GROUPNAME1=DATA1.getVertGroupNames()
						if len(GROUPNAME1)!=0:
							for GROUP1 in GROUPNAME1:
								DATA2.addVertGroup(GROUP1)
								DATA2.assignVertsToGroup(GROUP1,DATA1.getVertsFromGroup(GROUP1),1.0,'replace')
					# ========================================================
					# ===== now copy the vertices coords =====================
					# ========================================================
					for v in meshrvk1.verts:
						i= meshrvk1.verts.index(v)
						v1=DATA2.verts[i]
						for n in [0,1,2]:
							v1.co[n]=v.co[n]
					DATA2.update()
					DATA2.insertKey(FRAME,'relative')
					DATA2.update()
					RVK2.makeDisplayList()
					if MODIFIERS:
						# ===================================================
						# ===  unset Modifiers  =============================
						# ===================================================
						for	B in BMOD[0][1:]:
							MODRVK1[B[2]][Modifier.Settings.RENDER]|=B[-2]
						for	B in BMOD[1]:
							if not B[1]:
								MODRVK1[B[2]][Modifier.Settings.RENDER]|=B[-2]
				else:
					name = "Meshes Objects must the same number of vertices %t| Ok. %x1"
					result = Draw.PupMenu(name)
					return
			else:
				name = "Second Object must have  at least a shape key %t| Ok. %x1"
				result = Draw.PupMenu(name)
				return
		else:
			name = "Object must be Meshes %t| Ok. %x1"
			result = Draw.PupMenu(name)
			return
	else :
		name = "At least 2 Meshes as to be selected %t| Ok. %x1"
		result = Draw.PupMenu(name)
		return
	Blender.Redraw()
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("\n\n//object: %s_%d\n" % (nmesh.name, index))

        f.write("function load_%d() {\n" % index)
        index += 1

        #used for materials
        f.write("\tvar matColors=[];\n")

        #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("\tgl.PushMatrix();\n")

        #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("\tgl.Translated(%.6f, %.6f, %.6f);\n" % (locx, locy, locz))

        #rotation - this seems to be buggy !?
        if obj.RotX > 0.0001 or obj.RotX < -0.0001:
            f.write("  gl.Rotated(%.6f,1,0,0);\n" %
                    (-obj.RotX * 180 * 0.31831))
        if obj.RotY > 0.0001 or obj.RotY < -0.0001:
            f.write("  gl.Rotated(%.6f,0,1,0);\n" %
                    (-obj.RotY * 180 * 0.31831))
        if obj.RotZ > 0.0001 or obj.RotZ < -0.0001:
            f.write("  gl.Rotated(%.6f,0,0,1);\n" %
                    (-obj.RotZ * 180 * 0.31831))

        #scaling
        f.write("\tgl.Scaled(%.6f, %.6f, %.6f);\n" % 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("\tmatColors[0] = %.6f;\n" % material.R)
                    f.write("\tmatColors[1] = %.6f;\n" % material.G)
                    f.write("\tmatColors[2] = %.6f;\n" % material.B)
                    f.write("\tmatColors[3] = %.6f;\n" % material.alpha)
                    f.write(
                        "\tgl.Materialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,matColors);\n"
                    )

                    #specular
                    specs = material.getSpecCol()
                    f.write("\tmatColors[0] = %.6f;\n" % specs[0])
                    f.write("\tmatColors[1] = %.6f;\n" % specs[1])
                    f.write("\tmatColors[2] = %.6f;\n" % specs[2])
                    f.write("\tmatColors[3] = %.6f;\n" %
                            material.getSpecTransp())
                    f.write(
                        "\tgl.Materialfv(GL_FRONT_AND_BACK,GL_SPECULAR,matColors);\n"
                    )

            print "Exporting %s triangle(s)" % tricount

            if len(face) == 3: f.write("\tgl.Begin(GL_TRIANGLES);\n")
            elif len(face) == 4: f.write("\tgl.Begin(GL_QUADS);\n")

            for vertex in face.v:
                ## Build glVertex3f
                f.write("\tgl.Normal3f(%.6f, %.6f, %.6f);\n" %
                        tuple(vertex.no))
                f.write("\tgl.Vertex3f(%.6f, %.6f, %.6f);\n" %
                        tuple(vertex.co))
                vn += 1
            #print "glEnd();"
            f.write("\tgl.End();\n")

        f.write("\tgl.PopMatrix();\n")
        f.write("}\n")

    f.write("\n\n")

    #print "void loadModel() {"
    f.write("function loadModel() {\n")

    index = 0

    for obj in objects:
        f.write("\tload_%d();" % index)
        f.write("\t//object: %s\n" % obj.getData())
        index += 1

    f.write("}\n")

    print "Export complete"

    f.close()