示例#1
0
def read(filename):
    '''Read points in x, y, z format from file'''
	#start = time.clock()
	file = open(filename, "rb")
	objname = Blender.sys.splitext(Blender.sys.basename(filename))[0]
	me = NMesh.GetRaw()	
	# Collect data from RAW format
	for line in file.readlines():
		try:
			try:
				f1, f2, f3, f4  = map(float, line.split())
			except: # raw triangle so take first three only 
				#f1, f2, f3, f4, f5, f6, f7, f8, f9 = map(float, line.split())
				f1, f2, f3 = map(float, line.split())
			v = NMesh.Vert(f1, f2, f3)
			me.verts.append(v)
		except:
			continue
	NMesh.PutRaw(me, objname)
	Blender.Object.GetSelected()[0].name = objname
	Blender.Redraw()
	Blender.Window.DrawProgressBar(1.0, '')  # clear progressbar
	file.close()
	#end = time.clock()
	#seconds = " in %.2f %s" % (end-start, "seconds")
	message = "Successfully imported " + Blender.sys.basename(filename)# + seconds
	meshtools.print_boxed(message)
示例#2
0
def BlenderAddFace(me, colors, n1, n2, n3=None, n4=None):

    f = NMesh.Face()

    if (n4 != None):
        f.v = [me.verts[n1], me.verts[n2], me.verts[n3], me.verts[n4]]
        if (colors != None):
            f.col = [colors[n1], colors[n2], colors[n3], colors[n4]]
            f.uv = [(0, 0), (0, 1), (1, 1), (1, 0)]  # Needed because of bug
            f.mode = NMesh.FaceModes['SHAREDCOL']

    elif (n3 != None):
        f.v = [me.verts[n1], me.verts[n2], me.verts[n3]]
        if (colors != None):
            f.col = [colors[n1], colors[n2], colors[n3]]
            f.uv = [(0, 0), (0, 1), (1, 1)]  # Needed because of bug
            f.mode = NMesh.FaceModes['SHAREDCOL']

    else:
        f.v = [me.verts[n1], me.verts[n2]]
        if (colors != None):
            f.col = [colors[n1], colors[n2]]
            f.uv = [(0, 0), (0, 1)]
            f.mode = NMesh.FaceModes['SHAREDCOL']

    me.faces.append(f)
示例#3
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)
示例#4
0
 def GenerateVertices(me, rad, isegs, h, turn):
 	fanglestep = turn /float(isegs)
 	fangle = 0.0
 	while fangle < turn:
 		x = rad * cos(radians(fangle))
 		y = rad * sin(radians(fangle))
 		vert = NMesh.Vert(x, y, h)
 		me.verts.append(vert)
 		fangle += fanglestep
示例#5
0
def Torus(MajorRadius, MinorRadius, MajorDivisions, MinorDivisions,
          StartMinorAngle, Smooth):

    # deg 2 rad
    StartMinorAngle = (StartMinorAngle * 2 * pi) / 180

    def MakeVertexRing(vertex_list, angle):
        m = Mathutils.RotationMatrix(angle, 3, "z")
        for i in xrange(MinorDivisions):
            phi = (pi * 2 * i / MinorDivisions) + StartMinorAngle
            x = MajorRadius + MinorRadius * cos(phi)
            y = 0.0
            z = MinorRadius * sin(phi)

            v = Mathutils.Vector([x, y, z])
            v = Mathutils.VecMultMat(v, m)

            vertex_list.append(NMesh.Vert(v.x, v.y, v.z))

    ######### Creates a new mesh
    poly = NMesh.GetRaw()

    angle = 0
    da = 360.0 / MajorDivisions
    for _ in xrange(MajorDivisions):
        MakeVertexRing(poly.verts, angle)
        angle += da

    ######## Make faces
    for i in xrange(MajorDivisions):
        ring1_num = MinorDivisions * i
        ring2_num = MinorDivisions * ((i + 1) % MajorDivisions)
        for j in xrange(MinorDivisions):
            f = NMesh.Face()
            f.smooth = Smooth

            f.v.append(poly.verts[ring1_num + j])
            f.v.append(poly.verts[ring1_num + (j + 1) % MinorDivisions])
            f.v.append(poly.verts[ring2_num + (j + 1) % MinorDivisions])
            f.v.append(poly.verts[ring2_num + j])
            poly.faces.append(f)

    polyObj = NMesh.PutRaw(poly)
    return polyObj
示例#6
0
	def AddYRotatedVertexes(polygon_vertex_list, vertex_list, angle):
		c = cos(angle)
		s = sin(angle)

		for (x,y,z) in vertex_list:
			X = c*x - s*y
			Y = s*x + c*y
			Z = z

			polygon_vertex_list.append( NMesh.Vert(X,Y,Z) )
示例#7
0
def Disc(
	InnerRadius,
	OuterRadius,
	Segments,
	Subdivisions
	):

	poly = NMesh.GetRaw()


	#### Make vertices
	dr = (OuterRadius - InnerRadius)/Subdivisions
	r  = InnerRadius
	da = pi*2/Segments
	for _ in xrange(Subdivisions+1):
		alpha = 0.0
		for i in range(0,Segments):
			x = r * cos(alpha)
			y = r * sin(alpha)
			alpha += da
			poly.verts.append( NMesh.Vert(x,y,0.0) )

		r += dr

	#### Make faces
	for i in xrange(Subdivisions):
		ring0 = Segments * i
		ring1 = Segments * (i+1)
		for j in xrange(Segments):
			f = NMesh.Face()

			j0 = j
			j1 = (j+1) % Segments
			f.v.append(poly.verts[ring0 + j0])
			f.v.append(poly.verts[ring0 + j1])
			f.v.append(poly.verts[ring1 + j1])
			f.v.append(poly.verts[ring1 + j0])
			poly.faces.append(f)

	######### Creates a new Object with the new Mesh
	polyObj = NMesh.PutRaw(poly)
	return polyObj
示例#8
0
 def NewObject(flag):
 	global ob, me, sc
 	if flag == 1: DumpData()
 	DeselectAllObjects()
 	sc = Scene.GetCurrent()
 	cursorpos = Window.GetCursorPos()
 	ob = Object.New('Mesh', 'Cyl_')
 	me = NMesh.New('MyCylMesh')
 	ob.setLocation(cursorpos)
 	ob.link(me)
 	sc.link(ob)
示例#9
0
    def MakeVertexRing(vertex_list, angle):
        m = Mathutils.RotationMatrix(angle, 3, "z")
        for i in xrange(MinorDivisions):
            phi = (pi * 2 * i / MinorDivisions) + StartMinorAngle
            x = MajorRadius + MinorRadius * cos(phi)
            y = 0.0
            z = MinorRadius * sin(phi)

            v = Mathutils.Vector([x, y, z])
            v = Mathutils.VecMultMat(v, m)

            vertex_list.append(NMesh.Vert(v.x, v.y, v.z))
示例#10
0
def setpoly(me, nv, nf, Verts, Faces):

    for i in range(0, nv):

        v = NMesh.Vert(Verts[0][i], Verts[1][i], Verts[2][i])

        me.verts.append(v)

    for i in range(0, nf):

        f = NMesh.Face()

        f.v.append(me.verts[Faces[0][i]])

        f.v.append(me.verts[Faces[1][i]])

        f.v.append(me.verts[Faces[2][i]])

        f.smooth = 0

        me.faces.append(f)
示例#11
0
def makeLeaf(rotation, translation):
    vector = Vector([
        -leafSizeX.val / 2 * leafFactorButton.val, 0, 0 * leafFactorButton.val,
        1
    ])
    vector = MatMultVec(rotation, vector)
    vector = VecMultMat(vector, translation)
    v = NMesh.Vert(vector.x, vector.y, vector.z)
    foglie.verts.append(v)

    vector = Vector([
        leafSizeX.val / 2 * leafFactorButton.val, 0, 0 * leafFactorButton.val,
        1
    ])
    vector = MatMultVec(rotation, vector)
    vector = VecMultMat(vector, translation)
    v = NMesh.Vert(vector.x, vector.y, vector.z)
    foglie.verts.append(v)

    vector = Vector([
        leafSizeX.val / 2 * leafFactorButton.val, 0,
        leafSizeY.val * leafFactorButton.val, 1
    ])
    vector = MatMultVec(rotation, vector)
    vector = VecMultMat(vector, translation)
    v = NMesh.Vert(vector.x, vector.y, vector.z)
    foglie.verts.append(v)

    vector = Vector([
        -leafSizeX.val / 2 * leafFactorButton.val, 0,
        leafSizeY.val * leafFactorButton.val, 1
    ])
    vector = MatMultVec(rotation, vector)
    vector = VecMultMat(vector, translation)
    v = NMesh.Vert(vector.x, vector.y, vector.z)
    foglie.verts.append(v)
示例#12
0
 def faces(file, words, data):
   uvi=[]
   mesh=data['mesh']
   facecount=int(words[1])
   while facecount>0:
     f=NMesh.Face()
     line=map(int, file.readline().split())
     f.image=data['texture']
     for v in line[0:3]:
       f.v.append(mesh.verts[v])
     f.smooth=line[3]
     mesh.faces.append(f)
     uvi.append(line[4:7])
     facecount-=1
   data['uvi']=uvi
   if data.has_key('uvc'):
     fixuvs(data)
示例#13
0
def createDoodad(indexArray,facec,minsi,maxsi,minhei,maxhei,selec,amtmin,amtmax,facpercent):
	global doodadMesh
	global seltopsonly
	global tosel
	
	doodadMesh = NMesh.GetRaw()
	
	theamt = round(randnum(amtmin,amtmax),0)
	theamt = int(theamt)
	tosel = selec
	
	for i in range(0,(theamt)):
		if randnum(0,1) <= facpercent:
			index = round(randnum(1,len(indexArray)),0)
			index = indexArray[(int(index) - 1)]
			
			Xsi = randnum(minsi,maxsi)
			Ysi = randnum(minsi,maxsi)
			hei = randnum(minhei,maxhei)
					
			#Determine orientation
			orient = int(round(randnum(0.0,3.0)))
			
			#face to use as range
			facer = Face()
			facer.v.extend([facec.v[orient],facec.v[fixvertindex(1+orient)],facec.v[fixvertindex(2+orient)],facec.v[fixvertindex(3+orient)]])
			
			if index == 1:
				singleBox(facer,Xsi,Ysi,hei)
			if index == 2:
				doubleBox(facer,Xsi,Ysi,hei)
			if index == 3:
				tripleBox(facer,Xsi,Ysi,hei)
			if index == 4:
				LShape(facer,Xsi,Ysi,hei)
			if index == 5:
				TShape(facer,Xsi,Ysi,hei)
			if index == 6:
				if randnum(0.0,1.0) > .5:
					SShape(facer,Xsi,Ysi,hei)
				else:
					ZShape(facer,Xsi,Ysi,hei)
	
	return doodadMesh
示例#14
0
    def export_mesh(self, mesh, obj):
        file = self.file
        name = obj.name
        meshname = obj.getData(name_only=True)
        nmesh = NMesh.GetRaw(meshname)
        nmesh.transform(obj.matrixWorld)
        file.write("solid " + name + "\n")

        n_tri = 0  # number of tris in STL
        n_face = len(nmesh.faces)
        for i in range(0, n_face):
            face = nmesh.faces[i]
            nx = face.no[0]
            ny = face.no[1]
            nz = face.no[2]
            n_vert = len(face.v)
            if n_vert > 2:
                file.write("facet normal " + str(nx) + " " + str(ny) + " " +
                           str(nz) + "\n")
                file.write("  outer loop")
                for j in range(0, 3):
                    vert = face.v[j]
                    file.write("\n    vertex")
                    for k in range(0, 3):
                        file.write(" " + str(vert[k]))
                file.write("\n  endloop\n")
                file.write("endfacet\n")
                n_tri = n_tri + 1
                if n_vert > 3:
                    file.write("facet normal " + str(nx) + " " + str(ny) +
                               " " + str(nz) + "\n")
                    file.write("  outer loop")
                    for j in [0, 2, 3]:
                        vert = face.v[j]
                        file.write("\n    vertex")
                        for k in range(0, 3):
                            file.write(" " + str(vert[k]))
                    file.write("\n  endloop\n")
                    file.write("endfacet\n")
                    n_tri = n_tri + 1
        file.write("endsolid\n")
示例#15
0
# Import pour visualiser dans Blender
# Roucheyrolles Benjamin
# Licence Pro SIL Image et Son 2006/2007 

import Blender
from Blender import NMesh

objmesh='terrain'
rawfile=open("filepath:\\Fractal\\fractal.raw","r")
tabraw=rawfile.readlines()
rawfile.close()

mesh=NMesh.GetRaw()

for ligne in tabraw:

	ligne=ligne.replace('\n','')
	l=ligne.split(' ')
	
	# Création des coordonnées
	x=float(l[0])
	y=float(l[1])
	z=float(l[2])
	
	v=NMesh.Vert(x,y,z)
	mesh.verts.append(v)

NMesh.PutRaw(mesh,objmesh)

for i in range(0,n-1,1):
	for j in range(0,n-1,1):
示例#16
0
import Blender
import math, sys
from Blender import NMesh, Object, Scene
from math import *

PATH = "/home/carlos/"  # La ruta donde se salvara el OREj
nframes = 50

object = Object.GetSelected()
objname = object[0].name
meshname = object[0].data.name
mesh = NMesh.GetRaw(meshname)

filename = PATH + objname + ".orj"
file = open(filename, "w")
std = sys.stdout  # Asociamos stdout al fichero .orj
sys.stdout = file

print "# Objeto OREj:", objname
print "# Vertices Totales:", len(mesh.verts)
print "# Caras Totales:", len(mesh.faces)

# Escribimos toda la lista de vertices (v x y z)
for vertex in mesh.verts:
    x, y, z = vertex.co
    print "v %f %f %f" % (x, y, z)
# Escribimos toda la lista de caras (f v1 v2 v3 ...)
for face in mesh.faces:
    print "f",
    face.v.reverse()  # Invertimos las normales
    for vertex in face.v:
示例#17
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."
示例#18
0
def make_sel_face(verts):
    f = NMesh.Face(verts)
    f.sel = 1
    me.addFace(f)
示例#19
0
def make_sel_vert(*co):
    v = NMesh.Vert(*co)
    v.sel = 1
    me.verts.append(v)
    return v
示例#20
0
def make_faces():
    """ Analyse the mesh, make the faces corresponding to selected faces and
	fill the structures NE and NC """

    # make the differents flags consistent
    for e in me.edges:
        if e.flag & E_selected:
            e.v1.sel = 1
            e.v2.sel = 1

    NF = []  # NF : New faces
    for f in me.faces:
        V = f.v
        nV = len(V)
        enumV = range(nV)
        E = [me.findEdge(V[i], V[(i + 1) % nV]) for i in enumV]
        Esel = [x.flag & E_selected for x in E]

        # look for selected vertices and creates a list containing the new vertices
        newV = V[:]
        changes = False
        for (i, v) in enumerate(V):
            if v.sel:
                changes = True
                if Esel[i - 1] == 0 and Esel[i] == 1:
                    newV[i] = get_v(v, V[i - 1])
                elif Esel[i - 1] == 1 and Esel[i] == 0:
                    newV[i] = get_v(v, V[(i + 1) % nV])
                elif Esel[i - 1] == 1 and Esel[i] == 1:
                    newV[i] = get_v(v, V[i - 1], V[(i + 1) % nV])
                else:
                    newV[i] = [get_v(v, V[i - 1]), get_v(v, V[(i + 1) % nV])]

        if changes:
            # determine and store the face to be created

            lenV = [len(x) for x in newV]
            if 2 not in lenV:
                new_f = NMesh.Face(newV)
                if sum(Esel) == nV: new_f.sel = 1
                NF.append(new_f)

            else:
                nb2 = lenV.count(2)

                if nV == 4:  # f is a quad
                    if nb2 == 1:
                        ind2 = lenV.index(2)
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 1], newV[ind2][0], newV[ind2][1],
                                newV[ind2 - 3]
                            ]))
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 1], newV[ind2 - 2], newV[ind2 - 3]
                            ]))

                    elif nb2 == 2:
                        # We must know if the tuples are neighbours
                        ind2 = ''.join([str(x)
                                        for x in lenV + lenV[:1]]).find('22')

                        if ind2 != -1:  # They are
                            NF.append(
                                NMesh.Face([
                                    newV[ind2][0], newV[ind2][1],
                                    newV[ind2 - 3][0], newV[ind2 - 3][1]
                                ]))
                            NF.append(
                                NMesh.Face([
                                    newV[ind2][0], newV[ind2 - 1],
                                    newV[ind2 - 2], newV[ind2 - 3][1]
                                ]))

                        else:  # They aren't
                            ind2 = lenV.index(2)
                            NF.append(
                                NMesh.Face([
                                    newV[ind2][0], newV[ind2][1],
                                    newV[ind2 - 2][0], newV[ind2 - 2][1]
                                ]))
                            NF.append(
                                NMesh.Face([
                                    newV[ind2][1], newV[ind2 - 3],
                                    newV[ind2 - 2][0]
                                ]))
                            NF.append(
                                NMesh.Face([
                                    newV[ind2][0], newV[ind2 - 1],
                                    newV[ind2 - 2][1]
                                ]))

                    elif nb2 == 3:
                        ind2 = lenV.index(3)
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 1][1], newV[ind2],
                                newV[ind2 - 3][0]
                            ]))
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 1][0], newV[ind2 - 1][1],
                                newV[ind2 - 3][0], newV[ind2 - 3][1]
                            ]))
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 3][1], newV[ind2 - 2][0],
                                newV[ind2 - 2][1], newV[ind2 - 1][0]
                            ]))

                    else:
                        if (newV[0][1].co-newV[3][0].co).length + (newV[1][0].co-newV[2][1].co).length \
                         < (newV[0][0].co-newV[1][1].co).length + (newV[2][0].co-newV[3][1].co).length :
                            ind2 = 0
                        else:
                            ind2 = 1
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 1][0], newV[ind2 - 1][1],
                                newV[ind2][0], newV[ind2][1]
                            ]))
                        NF.append(
                            NMesh.Face([
                                newV[ind2][1], newV[ind2 - 3][0],
                                newV[ind2 - 2][1], newV[ind2 - 1][0]
                            ]))
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 3][0], newV[ind2 - 3][1],
                                newV[ind2 - 2][0], newV[ind2 - 2][1]
                            ]))

                else:  # f is a tri
                    if nb2 == 1:
                        ind2 = lenV.index(2)
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 2], newV[ind2 - 1], newV[ind2][0],
                                newV[ind2][1]
                            ]))

                    elif nb2 == 2:
                        ind2 = lenV.index(3)
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 1][1], newV[ind2],
                                newV[ind2 - 2][0]
                            ]))
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 2][0], newV[ind2 - 2][1],
                                newV[ind2 - 1][0], newV[ind2 - 1][1]
                            ]))

                    else:
                        ind2 = min([
                            ((newV[i][1].co - newV[i - 1][0].co).length, i)
                            for i in enumV
                        ])[1]
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 1][1], newV[ind2][0],
                                newV[ind2][1], newV[ind2 - 2][0]
                            ]))
                        NF.append(
                            NMesh.Face([
                                newV[ind2 - 2][0], newV[ind2 - 2][1],
                                newV[ind2 - 1][0], newV[ind2 - 1][1]
                            ]))

                # Preparing the corners
                for i in enumV:
                    if lenV[i] == 2: NC.setdefault(V[i], []).append(newV[i])

            old_faces.append(f)

            # Preparing the Edges
            for i in enumV:
                if Esel[i]:
                    verts = [newV[i], newV[(i + 1) % nV]]
                    if V[i].index > V[(i + 1) % nV].index: verts.reverse()
                    NE.setdefault(E[i], []).append(verts)

    # Create the faces
    for f in NF:
        me.addFace(f)
示例#21
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")
示例#22
0
def loadgeomnode(file, words, pdata):
  def objprop(file, words, data):
    data['nwnprops'].write('%s.%s=%s\n'%(data['object'].name, words[0], words[1]))
  def parent(file, words, data):
    if words[1]=='NULL':
      data['nwnprops'].write('SCENE.baseobjectname=%s\n'%data['object'].name)
    else:
      p=Object.Get(words[1])
      p.makeParent([data['object']])
  def position(file, words, data):
    data['object'].setLocation(map(float, words[1:4]))
  def orientation(file, words, data):
    data['object'].setEuler(nwn2euler(map(float, words[1:5])))
  def bitmap(file, words, data):
    global filename
    imagefname=os.path.dirname(filename) + '\\' + words[1]+'.tga'
    try:
      image=Image.Get(imagefname)
    except NameError:
      try:
	image=Image.Load(imagefname)
      except IOError:
        print '**************ERROR********************'
        print 'file : ' + filename
        print 'texture : ' + words[1]+'.tga unknown in directory : '
        print os.path.dirname(filename)
        print 'check if the bitmap exists with an other extension => translate in tga format'
        print 'or move it in the directory of the .mdl model'
        print 'null.tga could be used instead of the current one'
        print '**************ERROR********************'
        imagefname=os.path.dirname(filename) + '\\null.tga'
        image=Image.Load(imagefname)
        pass
    data['nwnprops'].write('%s.texture=%s\n'%(data['object'].name, words[1]))
    data['texture']=image

  def verts(file, words, data):
    vertexcount=int(words[1])
    while vertexcount>0:
      data['mesh'].verts.append(apply(NMesh.Vert, map(float, file.readline().split())))
      vertexcount-=1
  # Well, Torlack's NWN model decompiler puts faces after tverts.
  # NWN's sample file had it the other way around, so we support both.
  def fixuvs(data):
    mesh=data['mesh']
    uvi=data['uvi']
    uvc=data['uvc']
    for fi in range(len(uvi)):
      face=mesh.faces[fi]
      face.uv=map(lambda x: uvc[x], uvi[fi])
      face.mode=NMesh.FaceModes.TEX
    # TODO: recalculate the normals. They're all random, and PutRaw cancels transforms.
    #NMesh.PutRaw(mesh, data['object'].name)
    mesh.update()
  def faces(file, words, data):
    uvi=[]
    mesh=data['mesh']
    facecount=int(words[1])
    while facecount>0:
      f=NMesh.Face()
      line=map(int, file.readline().split())
      f.image=data['texture']
      for v in line[0:3]:
        f.v.append(mesh.verts[v])
      f.smooth=line[3]
      mesh.faces.append(f)
      uvi.append(line[4:7])
      facecount-=1
    data['uvi']=uvi
    if data.has_key('uvc'):
      fixuvs(data)
  def tverts(file, words, data):
    mesh=data['mesh']
    uvc=[]
    uvcount=int(words[1])
    while uvcount>0:
      uvc.append(tuple(map(float, file.readline().split()[0:2])))
      uvcount-=1
    data['uvc']=uvc
    if data.has_key('uvi'):
      fixuvs(data)
  nodedict={'parent': parent, 'position': position, 'bitmap': bitmap,
        'verts': verts, 'faces': faces, 'endnode': linereaderbreak,
        'tverts': tverts, 'orientation': orientation, 'tilefade': objprop}
  data=None
  if words[1]=='dummy':
    data={'object': Object.New('Empty')}
  elif words[1]=='trimesh':
    data={'object': Object.New('Mesh'), 'mesh': NMesh.New(words[2])}
    data['object'].link(data['mesh'])
  else:
    return	# unsupported node type
  # Note: Blender 2.27, New(type, name) didn't work. object.name worked.
  data['object'].name=words[2]
  data['nwnprops']=pdata['nwnprops']
  linereader(file, nodedict, data)
  pdata['scene'].link(data['object'])
示例#23
0
 def GenerateVertex(me, x, y, z):
 	vert = NMesh.Vert(x, y, z)
 	me.verts.append(vert)
示例#24
0
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#=============================================================================



# This script must run from a editor window in Blender. It take a mesh from a .vtk file and 
# import it to the scene in Blender
import vtk
import Blender
from Blender import NMesh
import Tex_VTKBlender
reload(Tex_VTKBlender)
#Cargamos ahora la malla de vtk empleada en ESQUI
reader = vtk.vtkPolyDataReader()
reader.SetFileName("Poner aqui el nombre del archivo .vtk a importar a Blender")

mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(reader.GetOutput())

me = NMesh.New()
me = Tex_VTKBlender.PolyDataMapperToBlender(mapper)
try:
	# Si estamos con la API BPython 2.42
	NMesh.PutRaw(me)
else:
	# Si estamos con la API BPython 2.36
	Blender.Scene.AddMesh(me) 
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()
示例#26
0
		s = sin(angle)

		for (x,y,z) in vertex_list:
			X = c*x - s*y
			Y = s*x + c*y
			Z = z

			polygon_vertex_list.append( NMesh.Vert(X,Y,Z) )
	
	def deg2rad(angle):
		return pi*angle/180.0
	def rad2deg(angle):
		return 180*angle/pi
	
	######### Creates a new mesh
	poly = NMesh.GetRaw()

	#### make vertexes
	vert = MakeVertexRectange()
	if UseAngles:
		da			= float(EndAngle-StartAngle)/Segments
		angle		= StartAngle
		segments	= Segments+1
	else:
		da			= 360.0/Segments
		angle		= 0.0
		segments	= Segments

	angle	= deg2rad(angle)
	da		= deg2rad(da)
示例#27
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()
# 3DNPcam
#
# Use this script with a scene scriptlink
# Don't forget to link your Camera to an Empty with a "Track To"-Constraint

import Blender
from Blender import Scene, NMesh

import math
from math import *

scene = Scene.GetCurrent()
context = scene.getRenderingContext()
obj = Blender.Object.Get("Camera")
frame = context.currentFrame()
camspheremesh = NMesh.GetRaw("CameraBoss")
camsphereobj = Blender.Object.Get('CameraBoss')
vertamount = len(camspheremesh.verts)
size = camsphereobj.getSize()

if frame <= vertamount:
    vert = camspheremesh.verts[frame - 1]
else:
    vert = camspheremesh.verts[vertamount]

obj.setLocation(vert.co[0] * size[0], vert.co[1] * size[1],
                vert.co[2] * size[2])
	def ParseMesh( self, szMeshName ):
		print "\tfound Mesh", szMeshName
		self.FindNextCharacter( '{' )
		nHierarchyLevel = 1

		aLineTokens = self.TokeniseLine()
		aVertices = self.ParseVec3Array( int( aLineTokens[ 0 ]))
		aLineTokens = self.TokeniseLine()
		aFaces = self.ParseFaceArray( int( aLineTokens[ 0 ]))
		aMaterialList = []

		while self.m_uLineIndex < self.m_uLineCount:
			uBaseLine = self.m_uLineIndex
			aLineTokens = self.TokeniseLine()
			strToken = aLineTokens[ 0 ].lower()

			if "material" == strToken:
				aMaterialList.append( self.ParseMaterial() )

			elif "meshmateriallist" == strToken:
				nHierarchyLevel += 1
				self.FindNextCharacter( '{' )
				aLineTokens = self.TokeniseLine()
				uMaterialCount = int( aLineTokens[ 0 ])
				aLineTokens = self.TokeniseLine()
				aMaterialFaces = self.ParseIntArray( int( aLineTokens[ 0 ]))

				print "\tMaterial Count =", uMaterialCount, "Material Faces =", len( aMaterialFaces )

			elif "meshnormals" == strToken:
				self.FindBracePair()

#				nHierarchyLevel += 1
#				self.FindNextCharacter( '{' )
#				aLineTokens = self.TokeniseLine()
#				aNormals = self.ParseVec3Array( int( aLineTokens[ 0 ]))
#				aLineTokens = self.TokeniseLine()
#				aNormalFaces = self.ParseFaceArray( int( aLineTokens[ 0 ]))
#				print "\tNormal count =", len( aNormals ), "Normal Faces =", len( aNormalFaces )

			elif "meshtexturecoords" == strToken:
				nHierarchyLevel += 1
				self.FindNextCharacter( '{' )
				aLineTokens = self.TokeniseLine()
				aTexCoords = self.ParseVec2Array( int( aLineTokens[ 0 ]))

			elif "skinweights" == strToken:
				self.ParseSkinWeights()

			elif "xskinmeshheader" == strToken:
				self.ParseXSkinMeshHeader()

			elif -1 != string.find( self.m_aLines[ uBaseLine ], '}' ):
				nHierarchyLevel -= 1

				if 0 == nHierarchyLevel:
					print "End Mesh"
					break
			else:
				print "Unexpected Mesh Token '", strToken, "' on line", self.m_uLineIndex
				break

		print "Vertex count =", len( aVertices ), "Face Count =", len( aFaces ), "Tex Coord count =", len( aTexCoords )
		meshCurrent = NMesh.GetRaw()

		for vertex in aVertices:
			v3Vertex = Blender.Mathutils.Vector( vertex ) * self.matrix
			meshCurrent.verts.append( NMesh.Vert( v3Vertex[ 0 ], v3Vertex[ 2 ], v3Vertex[ 1 ]))

#		aMaterialList = []
#		material = Material.New( "Material_Test" )
#		material.rgbCol = [ float(words[0]), float(words[1]), float(words[2]) ]
#		material.setAlpha( float(words[3]) )
#		aMaterialList.append( material )
#		meshCurrent.setMaterials( aMaterialList )
#		meshCurrent.update()

		aImageList = []
		uFaceIndex = 0

		for material in aMaterialList:
			szFileName = self.szDirectoryName + '\\' + material[ 0 ]
			print "Loading Image " + szFileName
			aImageList.append( Image.Load( szFileName ))

		for face in aFaces:
			faceNew = NMesh.Face()
			faceNew.v.append( meshCurrent.verts[ face[ 0 ]])
			faceNew.uv.append( (aTexCoords[ face[ 0 ]][ 0 ], -aTexCoords[ face[ 0 ]][ 1 ]) )
			faceNew.v.append( meshCurrent.verts[ face[ 2 ]])
			faceNew.uv.append( (aTexCoords[ face[ 2 ]][ 0 ], -aTexCoords[ face[ 2 ]][ 1 ]) )
			faceNew.v.append( meshCurrent.verts[ face[ 1 ]])
			faceNew.uv.append( (aTexCoords[ face[ 1 ]][ 0 ], -aTexCoords[ face[ 1 ]][ 1 ]) )
			faceNew.image = aImageList[ aMaterialFaces[ uFaceIndex ]]
#			faceNew.materialIndex = uMaterialIndex
#			faceNew.smooth = 1
			meshCurrent.faces.append( faceNew )
			uFaceIndex += 1

		NMesh.PutRaw( meshCurrent, self.szModelName + "_" + str( self.uMeshIndex ), 1 )
		self.uMeshIndex += 1
		meshCurrent.update()
示例#30
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