当前位置: 首页>>代码示例>>Python>>正文


Python BPyMesh.getMeshFromObject方法代码示例

本文整理汇总了Python中BPyMesh.getMeshFromObject方法的典型用法代码示例。如果您正苦于以下问题:Python BPyMesh.getMeshFromObject方法的具体用法?Python BPyMesh.getMeshFromObject怎么用?Python BPyMesh.getMeshFromObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BPyMesh的用法示例。


在下文中一共展示了BPyMesh.getMeshFromObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: write

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def write(filename):
	start = Blender.sys.time()
	if not filename.lower().endswith('.raw'):
		filename += '.raw'
	
	scn= Blender.Scene.GetCurrent()
	ob= scn.objects.active
	if not ob:
		Blender.Draw.PupMenu('Error%t|Select 1 active object')
		return
	
	file = open(filename, 'wb')
	
	mesh = BPyMesh.getMeshFromObject(ob, None, True, False, scn)
	if not mesh:
		Blender.Draw.PupMenu('Error%t|Could not get mesh data from active object')
		return
	
	mesh.transform(ob.matrixWorld)
	
	
	file = open(filename, "wb")
	for f in mesh.faces:
		for v in f:
			file.write('%.6f %.6f %.6f ' % tuple(v.co))
		file.write('\n')
	file.close()
	
	end = Blender.sys.time()
	message = 'Successfully exported "%s" in %.4f seconds' % ( Blender.sys.basename(filename), end-start)
	print message
开发者ID:Synric,项目名称:synricproj,代码行数:33,代码来源:raw_export.py

示例2: write

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def write(filename):
  
  Blender.Window.WaitCursor(1)
  
  if not filename.lower().endswith('.begc'):
    filename += '.begc'
  out = file(filename, "w")
  objects = Blender.Object.GetSelected()
  
  num_objects = 0
  for object in objects:
    if object.type == 'Mesh':
      num_objects = num_objects + 1
      
  out.write('%d\n' % num_objects)
  node_offset = 0
  for object in objects:
    if object.type == 'Mesh':
      out.write(object.name)
      out.write('\n')
  for object in objects:
    if object.type == 'Mesh':

      mesh = BPyMesh.getMeshFromObject(object, None, True, False, bpy.data.scenes.active)
      #mesh  = object.getData(0,1)
      mesh.transform(object.matrixWorld)
      faces = mesh.faces
      nodes = mesh.verts
      out.write('%d' % len(nodes))
      out.write(' %d\n' % len(faces))
      for n in nodes:
        #out.write("%e " % n.co[0])
        #out.write("%e " % n.co[1])
        #out.write("%e\n" % n.co[2])
        out.write("%e "  % n.co[0])
        out.write("%e "  % n.co[1])
        out.write("%e\n" % n.co[2])
      for f in faces:
        N = len(f.verts)
        if N < 3 and N > 4:
          Blender.Draw.PupMenu('Error%t|Only triangles and quads allowed')
          return
        out.write("%d" % N)
        for v in f.verts:
          out.write(' %d' % (v.index + node_offset))
        out.write('\n')
      node_offset = node_offset + len(nodes)

  Blender.Window.WaitCursor(0)
开发者ID:mtav,项目名称:script_inception_public,代码行数:51,代码来源:bfdtd_export.py

示例3: exportPath

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def exportPath(curve, filename):
  print "Exporting curve "+curve.name+" to "+filename
  
  mesh = BPyMesh.getMeshFromObject(curve)
  mesh.transform(curve.matrixWorld)
  numVertices = len(mesh.verts)

  file = open(filename, "w")
  for i in range(0, numVertices):
    vertex = mesh.verts[i]
    file.write("%g %g %g\n" % (vertex.co[0], vertex.co[1], vertex.co[2]))
  if curve.data.isCyclic():
    vertex = mesh.verts[0]
    file.write("%g %g %g\n" % (vertex.co[0], vertex.co[1], vertex.co[2]))    
  file.close()
开发者ID:kralf,项目名称:morsel,代码行数:17,代码来源:morsel_paths_export.py

示例4: write

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def write(filename):
	start = Blender.sys.time()
	if not filename.lower().endswith('.ml.txt'):
		filename += '.ml.txt'
	
	scn= Blender.Scene.GetCurrent()
	ob= scn.objects.active
	if not ob:
		Blender.Draw.PupMenu('Error%t|Select 1 active object')
		return
	
	file = open(filename, 'wb')
	
	mesh = BPyMesh.getMeshFromObject(ob, None, True, False, scn)
	if not mesh:
		Blender.Draw.PupMenu('Error%t|Could not get mesh data from active object')
		return
	
	mesh.transform(ob.matrixWorld)
	
	with open(filename, "w") as ml_file:
		ml_file.write('#MiniLight\n')
		ml_file.write('%d\n' % DEFAULT_ITERATIONS)
		ml_file.write('%d %d\n' % DEFAULT_RESOLUTION)
		ml_file.write('(%.2f %.2f %.2f) (%.2f %.2f %.2f) %.2f\n' % DEFAULT_CAMERA)
		ml_file.write('(%.2f %.2f %.2f) (%.2f %.2f %.2f)\n' % DEFAULT_SKY_AND_GROUND)
		
		for f in mesh.faces:
			if len(f) != 3:
				Blender.Draw.PupMenu('Error%t|Non-triangular face found in mesh')
				return
			for v in f:
				ml_file.write('(%.6f %.6f %.6f) ' % tuple(v.co))
			ml_file.write('(%.6f %.6f %.6f) ' % DEFAULT_COLOR)
			ml_file.write('(%.6f %.6f %.6f)\n' % DEFAULT_REFLECTIVITY)
	
	end = Blender.sys.time()
	message = 'Successfully exported "%s" in %.4f seconds' % ( Blender.sys.basename(filename), end-start)
	print message
开发者ID:UIKit0,项目名称:scripts,代码行数:41,代码来源:minilight_export.py

示例5: write

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def write(filename):
    start = Blender.sys.time()
    file = open(filename, "wb")

    scn = Blender.Scene.GetCurrent()
    objects = list(scn.objects.context)

    if not objects:
        Blender.Draw.PupMenu("Error%t|No Objects selected")
        return

    try:
        objects.sort(key=lambda a: a.name)
    except:
        objects.sort(lambda a, b: cmp(a.name, b.name))

    text = generate_text()
    desc = generate_desc()
    icon = ""  # generate_icon()

    meshes = []
    mesh_object_name_lookup = {}  # for name lookups only

    for obj in objects:
        mesh = BPyMesh.getMeshFromObject(obj, None, True, False, scn)
        if mesh:
            mesh.transform(obj.matrixWorld)
            meshes.append(mesh)
            mesh_object_name_lookup[mesh] = obj.name
    del obj

    material_names = get_used_material_names(meshes)
    tags = generate_tags(material_names)
    surfs = generate_surfs(material_names)
    chunks = [text, desc, icon, tags]

    meshdata = cStringIO.StringIO()

    layer_index = 0

    for mesh in meshes:
        layr = generate_layr(mesh_object_name_lookup[mesh], layer_index)
        pnts = generate_pnts(mesh)
        bbox = generate_bbox(mesh)
        pols = generate_pols(mesh)
        ptag = generate_ptag(mesh, material_names)
        clip = generate_clip(mesh, material_names)

        if mesh.faceUV:
            vmad_uv = generate_vmad_uv(mesh)  # per face

        if mesh.vertexColors:
            # if meshtools.average_vcols:
            # 	vmap_vc = generate_vmap_vc(mesh)  # per vert
            # else:
            vmad_vc = generate_vmad_vc(mesh)  # per face

        write_chunk(meshdata, "LAYR", layr)
        chunks.append(layr)
        write_chunk(meshdata, "PNTS", pnts)
        chunks.append(pnts)
        write_chunk(meshdata, "BBOX", bbox)
        chunks.append(bbox)
        write_chunk(meshdata, "POLS", pols)
        chunks.append(pols)
        write_chunk(meshdata, "PTAG", ptag)
        chunks.append(ptag)

        if mesh.vertexColors:
            # if meshtools.average_vcols:
            # 	write_chunk(meshdata, "VMAP", vmap_vc)
            # 	chunks.append(vmap_vc)
            # else:
            write_chunk(meshdata, "VMAD", vmad_vc)
            chunks.append(vmad_vc)

        if mesh.faceUV:
            write_chunk(meshdata, "VMAD", vmad_uv)
            chunks.append(vmad_uv)
            write_chunk(meshdata, "CLIP", clip)
            chunks.append(clip)

        layer_index += 1
        mesh.verts = None  # save some ram

    del mesh_object_name_lookup

    for surf in surfs:
        chunks.append(surf)

    write_header(file, chunks)
    write_chunk(file, "ICON", icon)
    write_chunk(file, "TEXT", text)
    write_chunk(file, "DESC", desc)
    write_chunk(file, "TAGS", tags)
    file.write(meshdata.getvalue())
    meshdata.close()
    for surf in surfs:
        write_chunk(file, "SURF", surf)
    write_chunk(file, "DATE", "August 19, 2005")
#.........这里部分代码省略.........
开发者ID:Synric,项目名称:synricproj,代码行数:103,代码来源:lightwave_export.py

示例6: write

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def write(filename):
    start = Blender.sys.time()
    if not filename.lower().endswith(".tmf"):
        filename += ".tmf"

    scn = Blender.Scene.GetCurrent()
    ob = scn.objects.active
    if not ob:
        Blender.Draw.PupMenu("Error%t|Select 1 active object")
        return

    file = open(filename, "wb")

    mesh = BPyMesh.getMeshFromObject(ob, None, True, False, scn)
    if not mesh:
        Blender.Draw.PupMenu("Error%t|Could not get mesh data from active object")
        return

    mesh.transform(ob.matrixWorld)

    file = open(filename, "wb")

    # Write vertex coords and normals
    file.write("C " + ` len(mesh.verts) ` + "\n")
    for v in mesh.verts:
        file.write("%.6f %.6f %.6f " % tuple(v.co))
        file.write("\n")

    file.write("N " + ` len(mesh.verts) ` + "\n")
    for v in mesh.verts:
        file.write("%.6f %.6f %.6f " % tuple(v.no))
        file.write("\n")

        # Process faces
    faces = len(mesh.faces)
    data = ""
    uvdata = ""
    for face in mesh.faces:
        if face.v[2] < 0:
            # discard
            faces = faces - 1
        elif face.v[2] < 0:
            # Already a triangle, add it to the data, do not change the count
            data = data + ` face.v[0].index ` + " " + ` face.v[1].index ` + " " + ` face.v[2].index ` + "\n"
            for v in face.uv:
                add_uvdata(uvdata, v)
        else:
            # this one is a quad
            # Break it up into two triangles
            # Hence one additional face
            faces = faces + 1
            data = data + ` face.v[0].index ` + " " + ` face.v[1].index ` + " " + ` face.v[3].index ` + "\n"
            data = data + ` face.v[1].index ` + " " + ` face.v[2].index ` + " " + ` face.v[3].index ` + "\n"
            uvdata = add_uvdata(uvdata, face.uv[0])
            uvdata = add_uvdata(uvdata, face.uv[1])
            uvdata = add_uvdata(uvdata, face.uv[3])
            uvdata = uvdata + "\n"
            uvdata = add_uvdata(uvdata, face.uv[1])
            uvdata = add_uvdata(uvdata, face.uv[2])
            uvdata = add_uvdata(uvdata, face.uv[3])
            uvdata = uvdata + "\n"
            # Now I can write the header with the correct face count, and then the data
    file.write("F " + ` faces ` + "\n")
    file.write(data)
    uvs = faces * 3
    file.write("T " + ` uvs ` + "\n")
    file.write(uvdata)

    file.close()

    end = Blender.sys.time()
    message = 'Successfully exported "%s" in %.4f seconds' % (Blender.sys.basename(filename), end - start)
    print message
开发者ID:trezker,项目名称:le-bomb,代码行数:75,代码来源:tmf_export.py

示例7: file_callback

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def file_callback(filename):

    if not filename.lower().endswith(".ctm"):
        filename += ".ctm"

        # Get object mesh from the selected object
    scn = bpy.data.scenes.active
    ob = scn.objects.active
    if not ob:
        Blender.Draw.PupMenu("Error%t|Select 1 active object")
        return
    mesh = BPyMesh.getMeshFromObject(ob, None, False, False, scn)
    if not mesh:
        Blender.Draw.PupMenu("Error%t|Could not get mesh data from active object")
        return

        # Check which mesh properties are present...
    hasVertexUV = mesh.vertexUV or mesh.faceUV
    hasVertexColors = mesh.vertexColors

    # Show a GUI for the export settings
    pupBlock = []
    EXPORT_APPLY_MODIFIERS = Draw.Create(1)
    pupBlock.append(("Apply Modifiers", EXPORT_APPLY_MODIFIERS, "Use transformed mesh data."))
    EXPORT_NORMALS = Draw.Create(1)
    pupBlock.append(("Normals", EXPORT_NORMALS, "Export vertex normal data."))
    if hasVertexUV:
        EXPORT_UV = Draw.Create(1)
        pupBlock.append(("UVs", EXPORT_UV, "Export texface UV coords."))
    if hasVertexColors:
        EXPORT_COLORS = Draw.Create(1)
        pupBlock.append(("Colors", EXPORT_COLORS, "Export vertex Colors."))
    EXPORT_MG2 = Draw.Create(0)
    pupBlock.append(("Fixed Point", EXPORT_MG2, "Use limited precision algorithm (MG2 method = better compression)."))
    if not Draw.PupBlock("Export...", pupBlock):
        return

        # Adjust export settings according to GUI selections
    EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
    EXPORT_NORMALS = EXPORT_NORMALS.val
    if hasVertexUV:
        EXPORT_UV = EXPORT_UV.val
    else:
        EXPORT_UV = False
    if hasVertexColors:
        EXPORT_COLORS = EXPORT_COLORS.val
    else:
        EXPORT_COLORS = False
    EXPORT_MG2 = EXPORT_MG2.val

    # If the user wants to export MG2, then show another GUI...
    if EXPORT_MG2:
        pupBlock = []
        EXPORT_VPREC = Draw.Create(0.01)
        pupBlock.append(("Vertex", EXPORT_VPREC, 0.0001, 1.0, "Relative vertex precision (fixed point)."))
        if EXPORT_NORMALS:
            EXPORT_NPREC = Draw.Create(1.0 / 256.0)
            pupBlock.append(("Normal", EXPORT_NPREC, 0.0001, 1.0, "Normal precision (fixed point)."))
        if EXPORT_UV:
            EXPORT_UVPREC = Draw.Create(1.0 / 1024.0)
            pupBlock.append(("UV", EXPORT_UVPREC, 0.0001, 1.0, "UV precision (fixed point)."))
        if EXPORT_COLORS:
            EXPORT_CPREC = Draw.Create(1.0 / 256.0)
            pupBlock.append(("Color", EXPORT_CPREC, 0.0001, 1.0, "Color precision (fixed point)."))
        if not Draw.PupBlock("Fixed point precision...", pupBlock):
            return

            # Adjust export settings according to GUI selections
    if EXPORT_MG2:
        EXPORT_VPREC = EXPORT_VPREC.val
    else:
        EXPORT_VPREC = 0.1
    if EXPORT_MG2 and EXPORT_NORMALS:
        EXPORT_NPREC = EXPORT_NPREC.val
    else:
        EXPORT_NPREC = 0.1
    if EXPORT_MG2 and EXPORT_UV:
        EXPORT_UVPREC = EXPORT_UVPREC.val
    else:
        EXPORT_UVPREC = 0.1
    if EXPORT_MG2 and EXPORT_COLORS:
        EXPORT_CPREC = EXPORT_CPREC.val
    else:
        EXPORT_CPREC = 0.1

    is_editmode = Blender.Window.EditMode()
    if is_editmode:
        Blender.Window.EditMode(0, "", 0)
    Window.WaitCursor(1)
    try:
        # Get the mesh, again, if we wanted modifiers (from GUI selection)
        if EXPORT_APPLY_MODIFIERS:
            mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False, scn)
            if not mesh:
                Blender.Draw.PupMenu("Error%t|Could not get mesh data from active object")
                return
            mesh.transform(ob.matrixWorld, True)

            # Count triangles (quads count as two triangles)
        triangleCount = 0
#.........这里部分代码省略.........
开发者ID:rgkoo,项目名称:meshlab,代码行数:103,代码来源:openctm_export.py

示例8: export

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
 def export(self, scene, world, alltextures,\
         EXPORT_APPLY_MODIFIERS = False,\
         EXPORT_TRI=             False,\
     ):
     
     print "Info: starting X3D export to " + self.filename + "..."
     self.writeHeader()
     # self.writeScript()
     self.writeNavigationInfo(scene)
     self.writeBackground(world, alltextures)
     self.writeFog(world)
     self.proto = 0
     
     
     # COPIED FROM OBJ EXPORTER
     if EXPORT_APPLY_MODIFIERS:
         temp_mesh_name = '~tmp-mesh'
     
         # Get the container mesh. - used for applying modifiers and non mesh objects.
         containerMesh = meshName = tempMesh = None
         for meshName in Blender.NMesh.GetNames():
             if meshName.startswith(temp_mesh_name):
                 tempMesh = Mesh.Get(meshName)
                 if not tempMesh.users:
                     containerMesh = tempMesh
         if not containerMesh:
             containerMesh = Mesh.New(temp_mesh_name)
     # -------------------------- 
     
     
     for ob_main in scene.objects.context:
         for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
             objType=ob.type
             objName=ob.name
             self.matonly = 0
             if objType == "Camera":
                 self.writeViewpoint(ob, ob_mat, scene)
             elif objType in ("Mesh", "Curve", "Surf", "Text") :
                 if  EXPORT_APPLY_MODIFIERS or objType != 'Mesh':
                     me= BPyMesh.getMeshFromObject(ob, containerMesh, EXPORT_APPLY_MODIFIERS, False, scene)
                 else:
                     me = ob.getData(mesh=1)
                 
                 self.writeIndexedFaceSet(ob, me, ob_mat, world, EXPORT_TRI = EXPORT_TRI)
             elif objType == "Lamp":
                 data= ob.data
                 datatype=data.type
                 if datatype == Lamp.Types.Lamp:
                     self.writePointLight(ob, ob_mat, data, world)
                 elif datatype == Lamp.Types.Spot:
                     self.writeSpotLight(ob, ob_mat, data, world)
                 elif datatype == Lamp.Types.Sun:
                     self.writeDirectionalLight(ob, ob_mat, data, world)
                 else:
                     self.writeDirectionalLight(ob, ob_mat, data, world)
             # do you think x3d could document what to do with dummy objects?
             #elif objType == "Empty" and objName != "Empty":
             #   self.writeNode(ob, ob_mat)
             else:
                 #print "Info: Ignoring [%s], object type [%s] not handle yet" % (object.name,object.getType)
                 pass
     
     self.file.write("\n</Scene>\n</X3D>")
     
     if EXPORT_APPLY_MODIFIERS:
         if containerMesh:
             containerMesh.verts = None
     
     self.cleanup()
开发者ID:Tcll5850,项目名称:UMC3.0a,代码行数:71,代码来源:x3d_export.py

示例9: writeMeshData

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
    def writeMeshData(self, parent, mesh, obj):
        
        aMesh = BPyMesh.getMeshFromObject(obj, self.getContainerMesh(), True, scn=self.scene)
        
        if len(aMesh.faces) == 0:
            return
        
        print("Writing mesh %s" % mesh.name)
        
        materials = aMesh.materials
        
        has_quads = False
        for f in aMesh.faces:
            if len(f) == 4:
                has_quads = True
                break
        
        if has_quads:
            oldmode = Mesh.Mode()
            Mesh.Mode(Mesh.SelectModes['FACE'])
            
            aMesh.sel = True
            tempob = self.scene.objects.new(aMesh)
            aMesh.quadToTriangle(0) # more=0 shortest length
            oldmode = Mesh.Mode(oldmode)
            self.scene.objects.unlink(tempob)
            
            Mesh.Mode(oldmode)
        
        data = self.doc.createDataElement(mesh.name+"_data", None, None, None, None)    
        parent.appendChild(data)
        
        # Mesh indices
        matCount = len(materials)
        if matCount == 0:
            matCount = 1
        indices = [[] for m in range(matCount)] #@UnusedVariable
        vertices = []
        vertex_dict = {}
       
        print("Faces: %i" % len(aMesh.faces))
        
        i = 0
        for face in aMesh.faces:
            mv = None
            for i, v in enumerate(face):
                if face.smooth:
                    if aMesh.faceUV:
                        mv = vertex(v.index, None, face.uv[i])
                    else:
                        mv = vertex(v.index, None, None)
                else:
                    if aMesh.faceUV:
                        mv = vertex(v.index, face.no, face.uv[i])
                    else:
                        mv = vertex(v.index, face.no)
                index, added = appendUnique(vertex_dict, mv)
                indices[face.mat].append(index)
                if added:
                    vertices.append(mv)


        # Single or no material: write all in one data block
        if not matCount > 1:
            valueElement = self.doc.createIntElement(None, "index")
            valueElement.setValue(' '.join(map(str, indices[0])))
            data.appendChild(valueElement)
       
        print("Vertices: %i" % len(vertex_dict))
        
        # Vertex positions
        value_list = []
        for v in vertices:
            value_list.append("%.6f %.6f %.6f" % tuple(aMesh.verts[v.index].co))
                
        valueElement = self.doc.createFloat3Element(None, "position")
        valueElement.setValue(' '.join(value_list))
        data.appendChild(valueElement)
        
        # Vertex normals
        value_list = []
        for v in vertices:
            if v.normal == None:
                value_list.append("%.6f %.6f %.6f" % tuple(aMesh.verts[v.index].no))
            else:
                value_list.append("%.6f %.6f %.6f" % tuple(v.normal))
     
        valueElement = self.doc.createFloat3Element(None, "normal")
        valueElement.setValue(' '.join(value_list))
        data.appendChild(valueElement)

        # Vertex texCoord
        if aMesh.faceUV:
            value_list = []
            for v in vertices:
                value_list.append("%.6f %.6f" % tuple(v.texcoord))
    
            valueElement =self. doc.createFloat2Element(None, "texcoord")
            valueElement.setValue(' '.join(value_list))
            data.appendChild(valueElement);
#.........这里部分代码省略.........
开发者ID:binhbt,项目名称:Blender-Exporter,代码行数:103,代码来源:xml3d_exporter.py

示例10: apply_deform

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def apply_deform():
	scn= bpy.data.scenes.active
	#Blender.Window.EditMode(0)
	
	NAME_LENGTH = 19
	SUFFIX = "_def"
	SUFFIX_LENGTH = len(SUFFIX)
	# Get all object and mesh names
	

	ob_list = list(scn.objects.context)
	ob_act = scn.objects.active
	
	# Assume no soft body
	has_sb= False
	
	# reverse loop so we can remove objects (metaballs in this case)
	for ob_idx in xrange(len(ob_list)-1, -1, -1):
		ob= ob_list[ob_idx]
		
		ob.sel = 0 # deselect while where checking the metaballs
		
		# Test for a softbody
		if not has_sb and ob.isSB():
			has_sb= True
		
		# Remove all numbered metaballs because their disp list is only on the main metaball (un numbered)
		if ob.type == 'MBall':
			name= ob.name
			# is this metaball numbered?
			dot_idx= name.rfind('.') + 1
			if name[dot_idx:].isdigit():
				# Not the motherball, ignore it.
				del ob_list[ob_idx]
			
	
	if not ob_list:
		Blender.Draw.PupMenu('No objects selected, nothing to do.')
		return
	
	
	if has_sb:
		curframe=Blender.Get('curframe')
		for f in xrange(curframe):
			Blender.Set('curframe',f+1)
			Blender.Window.RedrawAll()

	used_names = [ob.name for ob in Blender.Object.Get()]
	used_names.extend(Blender.NMesh.GetNames())
	
	
	deformedList = []
	for ob in ob_list:
		
		# Get the mesh data
		new_me= BPyMesh.getMeshFromObject(ob, vgroups=False)
		
		if not new_me:
			continue # Object has no display list
		
		
		name = ob.name
		new_name = "%s_def" % name[:NAME_LENGTH-SUFFIX_LENGTH]
		num = 0
		
		while new_name in used_names:
			new_name = "%s_def.%.3i" % (name[:NAME_LENGTH-(SUFFIX_LENGTH+SUFFIX_LENGTH)], num)
			num += 1
		used_names.append(new_name)
		
		new_me.name= new_name
		
		new_ob= scn.objects.new(new_me)
		new_ob.setMatrix(ob.matrixWorld)
		
		# Make the active duplicate also active
		if ob == ob_act:
			scn.objects.active = new_ob
		
		# Original object was a mesh? see if we can copy any vert groups.
		if ob.type =='Mesh':
			copy_vgroups(ob, new_ob)
	
	Blender.Window.RedrawAll()
开发者ID:Synric,项目名称:synricproj,代码行数:86,代码来源:object_apply_def.py

示例11: write

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def write(filename, objects,\
EXPORT_NORMALS_HQ=False,\
EXPORT_MTL=True,  EXPORT_COPY_IMAGES=False,\
EXPORT_APPLY_MODIFIERS=True, EXPORT_BLEN_OBS=True,\
EXPORT_GROUP_BY_OB=False):
    '''
    Basic write function. The context and options must be alredy set
    This can be accessed externaly
    eg.
    write( 'c:\\test\\foobar.obj', Blender.Object.GetSelected() ) # Using default options.
    '''
    
    def veckey3d(v):
        return round(v.x, 6), round(v.y, 6), round(v.z, 6)
        
    def veckey2d(v):
        return round(v.x, 6), round(v.y, 6)
    
    print 'WTF Export path: "%s"' % filename
    temp_mesh_name = '~tmp-mesh'

    time1 = sys.time()
    scn = Scene.GetCurrent()

    file = open(filename, "w")
    file.write('<?xml version="1.0"?>\n')
    file.write('<OPEN_TRACK>\n')

    # Write Header
    # file.write('\n<!--\n'
    #            + '  Blender3D v%s WTF File: %s\n' % (Blender.Get('version'), Blender.Get('filename').split('/')[-1].split('\\')[-1] )
    #            + '  www.blender3d.org\n'
    #            + '-->\n\n')

    # Get the container mesh. - used for applying modifiers and non mesh objects.
    containerMesh = meshName = tempMesh = None
    for meshName in Blender.NMesh.GetNames():
        if meshName.startswith(temp_mesh_name):
            tempMesh = Mesh.Get(meshName)
            if not tempMesh.users:
                containerMesh = tempMesh
    if not containerMesh:
        containerMesh = Mesh.New(temp_mesh_name)
    
    del meshName
    del tempMesh
    
    # Initialize totals, these are updated each object
    totverts = totuvco = totno = 0
    
    face_vert_index = 0
    
    globalNormals = {}
    
    file.write('\n<library_objects>\n')
    # Get all meshs
    for ob_main in objects:
        obnamestring = fixName(ob_main.name)
        file.write('\t<object id="%s">\n' % obnamestring) # Write Object name

        for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
            # Will work for non meshes now! :)
            # getMeshFromObject(ob, container_mesh=None, apply_modifiers=True, vgroups=True, scn=None)
            me = BPyMesh.getMeshFromObject(ob, containerMesh, EXPORT_APPLY_MODIFIERS, False, scn)
            if not me:
                file.write('\t\t<loc>%.6f %.6f %.6f</loc>\n' % tuple(ob_main.loc)) # Write Object name
                file.write('\t\t<rot>%.6f %.6f %.6f</rot>\n' % tuple(ob_main.rot)) # Write Object name
                continue
            
            faceuv = me.faceUV
            
            # We have a valid mesh
            if me.faces:
                # Add a dummy object to it.
                has_quads = False
                for f in me.faces:
                    if len(f) == 4:
                        has_quads = True
                        break
                
                if has_quads:
                    oldmode = Mesh.Mode()
                    Mesh.Mode(Mesh.SelectModes['FACE'])
                    
                    me.sel = True
                    tempob = scn.objects.new(me)
                    me.quadToTriangle(0) # more=0 shortest length
                    oldmode = Mesh.Mode(oldmode)
                    scn.objects.unlink(tempob)
                    
                    Mesh.Mode(oldmode)
            
            # Make our own list so it can be sorted to reduce context switching
            faces = [ f for f in me.faces ]
            edges = me.edges
            
            if not (len(faces)+len(edges)+len(me.verts)): # Make sure there is somthing to write
                continue # dont bother with this mesh.
            
            me.transform(ob_mat)
#.........这里部分代码省略.........
开发者ID:hejibo,项目名称:PyTorcs,代码行数:103,代码来源:export_wtf.py

示例12: write

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def write(filename):
    start = Blender.sys.time()
    if not filename.lower().endswith('.js'):
    	filename += '.js'
    
    scn= Blender.Scene.GetCurrent()
    ob= scn.objects.active
    if not ob:
    	Blender.Draw.PupMenu('Error%t|Select 1 active object')
    	return
    
    file = open(filename, 'wb')
    
    mesh = BPyMesh.getMeshFromObject(ob, None, True, False, scn)
    if not mesh:
    	Blender.Draw.PupMenu('Error%t|Could not get mesh data from active object')
    	return
    
    mesh.transform(ob.matrixWorld)
    
    #classname = clean(ob.name)
    classname = filename.split('/')[-1].replace('.js','')
    
    file = open(filename, "wb")
    
    file.write('var %s = function () {\n\n' % classname)
    file.write('\tvar scope = this;\n\n')
    file.write('\tTHREE.Geometry.call(this);\n\n')
    
    for v in mesh.verts:
        file.write('\tv( %.6f, %.6f, %.6f );\n' % (v.co.x, v.co.z, -v.co.y)) # co
    
    file.write('\n')
    
    for f in mesh.faces:
        if len(f.verts) == 3:
            file.write('\tf3( %d, %d, %d, %.6f, %.6f, %.6f );\n' % (f.verts[0].index, f.verts[1].index, f.verts[2].index, f.verts[0].no.x, f.verts[0].no.z, -f.verts[0].no.y))
        else:
            file.write('\tf4( %d, %d, %d, %d, %.6f, %.6f, %.6f );\n' % (f.verts[0].index, f.verts[1].index, f.verts[2].index, f.verts[3].index, f.verts[0].no.x, f.verts[0].no.z, -f.verts[0].no.y))
    face_index_pairs = [ (face, index) for index, face in enumerate(mesh.faces)]
    
    file.write('\n')
    '''
    for f in me.faces:
		if me.faceUV:
		    if len(f.verts) == 3:
		        file.write('\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f );\n' % (f.uv[0][0], 1.0-f.uv[0][1], f.uv[1][0], 1.0-f.uv[1][1], f.uv[2][0], 1.0-f.uv[2][1])
	'''
    for f in mesh.faces:
	    if mesh.faceUV:
	        if len(f.verts) == 3:
	            file.write('\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f );\n' % (f.uv[0].x, 1.0 - f.uv[0].y, f.uv[1].x, 1.0 - f.uv[1].y, f.uv[2].x, 1.0 - f.uv[2].y))
	        else:
	            file.write('\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f);\n' % (f.uv[0].x, 1.0 - f.uv[0].y, f.uv[1].x, 1.0 - f.uv[1].y, f.uv[2].x, 1.0 - f.uv[2].y, f.uv[3].x, 1.0 - f.uv[3].y))
	
    file.write('\n')
    file.write('\tfunction v( x, y, z ) {\n\n')
    file.write('\t\tscope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );\n\n')
    file.write('\t}\n\n')
    file.write('\tfunction f3( a, b, c, nx, ny, nz ) {\n\n')
    file.write('\t\tscope.faces.push( new THREE.Face3( a, b, c, nx && ny && nz ? new THREE.Vector3( nx, ny, nz ) : null ) );\n\n')
    file.write('\t}\n\n')
    file.write('\tfunction f4( a, b, c, d, nx, ny, nz ) {\n\n')
    file.write('\t\tscope.faces.push( new THREE.Face4( a, b, c, d, nx && ny && nz ? new THREE.Vector3( nx, ny, nz ) : null ) );\n\n')
    file.write('\t}\n\n')
    file.write('\tfunction uv( u1, v1, u2, v2, u3, v3, u4, v4 ) {\n\n')
    file.write('\t\tvar uv = [];\n')
    file.write('\t\tuv.push( new THREE.UV( u1, v1 ) );\n')
    file.write('\t\tuv.push( new THREE.UV( u2, v2 ) );\n')
    file.write('\t\tuv.push( new THREE.UV( u3, v3 ) );\n')
    file.write('\t\tif ( u4 && v4 ) uv.push( new THREE.UV( u4, v4 ) );\n')
    file.write('\t\tscope.uvs.push( uv );\n')
    file.write('\t}\n\n')
    file.write('}\n\n')
    file.write('%s.prototype = new THREE.Geometry();\n' % classname)
    file.write('%s.prototype.constructor = %s;' % (classname, classname))
    file.close()
开发者ID:AlexKarry,项目名称:three.js,代码行数:79,代码来源:threejs_export.py

示例13: file_callback

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def file_callback(filename):
	
	if not filename.lower().endswith('.submesh'):
		filename += '.submesh'
	
	scn= bpy.data.scenes.active
	ob= scn.objects.active
	if not ob:
		Blender.Draw.PupMenu('Error%t|Select 1 active object')
		return
	
	file = open(filename, 'wb')
	
	EXPORT_APPLY_MODIFIERS = Draw.Create(1)
	EXPORT_NORMALS = Draw.Create(1)
	EXPORT_UV = Draw.Create(1)
	EXPORT_COLORS = Draw.Create(1)
	#EXPORT_EDGES = Draw.Create(0)
	
	pup_block = [\
	('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data.'),\
	('Normals', EXPORT_NORMALS, 'Export vertex normal data.'),\
	('UVs', EXPORT_UV, 'Export texface UV coords.'),\
	('Colors', EXPORT_COLORS, 'Export vertex Colors.'),\
	#('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\
	]
	
	if not Draw.PupBlock('Export...', pup_block):
		return
	
	is_editmode = Blender.Window.EditMode()
	if is_editmode:
		Blender.Window.EditMode(0, '', 0)
	
	Window.WaitCursor(1)
	
	EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
	EXPORT_NORMALS = EXPORT_NORMALS.val
	EXPORT_UV = EXPORT_UV.val
	EXPORT_COLORS = EXPORT_COLORS.val
	#EXPORT_EDGES = EXPORT_EDGES.val
	
	mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False, scn)
	
	if not mesh:
		Blender.Draw.PupMenu('Error%t|Could not get mesh data from active object')
		return
	
	mesh.transform(ob.matrixWorld)
	
	faceUV = mesh.faceUV
	vertexUV = mesh.vertexUV
	vertexColors = mesh.vertexColors
	
	if (not faceUV) and (not vertexUV):		EXPORT_UV = False
	if not vertexColors:					EXPORT_COLORS = False
	
	if not EXPORT_UV:						faceUV = vertexUV = False
	if not EXPORT_COLORS:					vertexColors = False
	
	# incase
	color = uvcoord = uvcoord_key = normal = normal_key = None
	
	verts = [] # list of dictionaries
	# vdict = {} # (index, normal, uv) -> new index
	vdict = [{} for i in xrange(len(mesh.verts))]
	vert_count = 0
	for i, f in enumerate(mesh.faces):
		smooth = f.smooth
		if not smooth:
			normal = tuple(f.no)
			normal_key = rvec3d(normal)
			
		if faceUV:			uv = f.uv
		if vertexColors:	col = f.col
		for j, v in enumerate(f):
			if smooth:
				normal=		tuple(v.no)
				normal_key = rvec3d(normal)
			
			if faceUV:
				uvcoord=	uv[j][0], 1.0-uv[j][1]
				uvcoord_key = rvec2d(uvcoord)
			elif vertexUV:
				uvcoord=	v.uvco[0], 1.0-v.uvco[1]
				uvcoord_key = rvec2d(uvcoord)
			
			if vertexColors:	color=		col[j].r, col[j].g, col[j].b
			
			
			key = normal_key, uvcoord_key, color
			
			vdict_local = vdict[v.index]
			
			if (not vdict_local) or (not vdict_local.has_key(key)):
				vdict_local[key] = vert_count;
				verts.append( (tuple(v.co), normal, uvcoord, color) )
				vert_count += 1
	
	
#.........这里部分代码省略.........
开发者ID:cody82,项目名称:spacewar-arena,代码行数:103,代码来源:spacewar_export.py

示例14: file_callback

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def file_callback(filename):
	
	if not filename.lower().endswith('.ply'):
		filename += '.ply'
	
	scn= bpy.data.scenes.active
	ob= scn.objects.active
	if not ob:
		Blender.Draw.PupMenu('Error%t|Select 1 active object')
		return
	
	file = open(filename, 'wb')
	
	EXPORT_APPLY_MODIFIERS = Draw.Create(1)
	EXPORT_NORMALS = Draw.Create(1)
	EXPORT_UV = Draw.Create(1)
	EXPORT_COLORS = Draw.Create(1)
	#EXPORT_EDGES = Draw.Create(0)
	
	pup_block = [\
	('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data.'),\
	('Normals', EXPORT_NORMALS, 'Export vertex normal data.'),\
	('UVs', EXPORT_UV, 'Export texface UV coords.'),\
	('Colors', EXPORT_COLORS, 'Export vertex Colors.'),\
	#('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\
	]
	
	if not Draw.PupBlock('Export...', pup_block):
		return
	
	is_editmode = Blender.Window.EditMode()
	if is_editmode:
		Blender.Window.EditMode(0, '', 0)
	
	Window.WaitCursor(1)
	
	EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
	EXPORT_NORMALS = EXPORT_NORMALS.val
	EXPORT_UV = EXPORT_UV.val
	EXPORT_COLORS = EXPORT_COLORS.val
	#EXPORT_EDGES = EXPORT_EDGES.val
	
	mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False, scn)
	
	if not mesh:
		Blender.Draw.PupMenu('Error%t|Could not get mesh data from active object')
		return
	
	mesh.transform(ob.matrixWorld)
	
	faceUV = mesh.faceUV
	vertexUV = mesh.vertexUV
	vertexColors = mesh.vertexColors
	
	if (not faceUV) and (not vertexUV):		EXPORT_UV = False
	if not vertexColors:					EXPORT_COLORS = False
	
	if not EXPORT_UV:						faceUV = vertexUV = False
	if not EXPORT_COLORS:					vertexColors = False
	
	# incase
	color = uvcoord = uvcoord_key = normal = normal_key = None
	
	verts = [] # list of dictionaries
	# vdict = {} # (index, normal, uv) -> new index
	vdict = [{} for i in xrange(len(mesh.verts))]
	vert_count = 0
	for i, f in enumerate(mesh.faces):
		smooth = f.smooth
		if not smooth:
			normal = tuple(f.no)
			normal_key = rvec3d(normal)
			
		if faceUV:			uv = f.uv
		if vertexColors:	col = f.col
		for j, v in enumerate(f):
			if smooth:
				normal=		tuple(v.no)
				normal_key = rvec3d(normal)
			
			if faceUV:
				uvcoord=	uv[j][0], 1.0-uv[j][1]
				uvcoord_key = rvec2d(uvcoord)
			elif vertexUV:
				uvcoord=	v.uvco[0], 1.0-v.uvco[1]
				uvcoord_key = rvec2d(uvcoord)
			
			if vertexColors:	color=		col[j].r, col[j].g, col[j].b
			
			
			key = normal_key, uvcoord_key, color
			
			vdict_local = vdict[v.index]
			
			if (not vdict_local) or (not vdict_local.has_key(key)):
				vdict_local[key] = vert_count;
				verts.append( (tuple(v.co), normal, uvcoord, color) )
				vert_count += 1
	
	
#.........这里部分代码省略.........
开发者ID:Synric,项目名称:synricproj,代码行数:103,代码来源:ply_export.py

示例15: main

# 需要导入模块: import BPyMesh [as 别名]
# 或者: from BPyMesh import getMeshFromObject [as 别名]
def main():
	PREF_Z_LOC= Blender.Draw.PupMenu('Cut Z Location%t|Original Faces|Cutting Polyline')
	
	if PREF_Z_LOC==-1:
		return
	PREF_Z_LOC-=1
	
	Blender.Window.WaitCursor(1)
	
	print '\nRunning Cookie Cutter'
	time= Blender.sys.time()
	scn = Blender.Scene.GetCurrent()
	obs= [ob for ob in scn.objects.context if ob.type in ('Mesh', 'Curve')]
	MULTIRES_ERROR = False
	
	# Divide into 2 lists- 1 with faces, one with only edges
	terrains=	[] #[me for me in mes if me.faces]
	cutters=	[] #[me for me in mes if not me.faces]
	
	terrain_type= auto_class(['mesh', 'bounds', 'face_bounds', 'edge_bounds', 'edge_dict', 'cutters', 'matrix'])
	
	for ob in obs:
		if ob.type == 'Mesh':
			me= ob.getData(mesh=1)
		elif ob.data.flag & 1: # Is the curve 3D? else don't use.
			me= BPyMesh.getMeshFromObject(ob) # get the curve
		else:
			continue
			
		# a new terrain instance
		if me.multires:
			MULTIRES_ERROR = True		
		else:
			t= terrain_type()
			
			t.matrix= ob.matrixWorld * Blender.Window.GetViewMatrix()
			
			# Transform the object by its matrix
			me.transform(t.matrix)
			
			# Set the terrain bounds
			t.bounds=		bounds_xy(me.verts)
			t.edge_bounds= 	[bounds_xy(ed) for ed in me.edges]
			t.mesh=			me
			
			if me.faces: # Terrain.
				t.edge_dict=					mesh_edge_dict(me)
				t.face_bounds=					[bounds_xy(f) for f in me.faces]
				t.cutters= 						[] # Store cutting objects that cut us here
				terrains.append(t)
			elif len(me.edges)>2: # Cutter
				cutters.append(t)
	
	totcuts= len(terrains)*len(cutters)
	if not totcuts:
		Blender.Window.WaitCursor(0)
		Blender.Draw.PupMenu('ERROR%t|Select at least 1 closed loop mesh (edges only)|as the cutter...|and 1 or more meshes to cut into')
	
	crazy_point= Vector(100000, 100000)
	
	for t in terrains:
		for c in cutters:
			# Main curring function
			terrain_cut_2d(t, c, PREF_Z_LOC)
			
			# Was the terrain touched?
			if len(t.face_bounds) != len(t.mesh.faces):
				t.edge_dict=					mesh_edge_dict(t.mesh)
				# remake the bounds
				t.edge_bounds=					[bounds_xy(ed) for ed in t.mesh.edges]
				t.face_bounds=					[bounds_xy(f) for f in t.mesh.faces]
				t.cutters.append(c)
			
			print '\t%i remaining' % totcuts
			totcuts-=1
		
		# SELECT INTERNAL FACES ONCE THIS TERRAIN IS CUT
		Blender.Mesh.Mode(Blender.Mesh.SelectModes['FACE'])
		t.mesh.sel= 0
		for c in t.cutters:
			edge_verts_c= [(ed_c.v1.co, ed_c.v2.co) for ed_c in c.mesh.edges]
			for f in t.mesh.faces:
				# How many edges do we intersect on our way to the faces center
				if not f.hide and not f.sel: # Not alredy selected
					c= f.cent
					if point_in_bounds(c, t.bounds):
						isect_count= 0
						for edv1, edv2 in edge_verts_c:
							isect_count += (LineIntersect2D(c, crazy_point,  edv1, edv2) != None)
						
						if isect_count%2:
							f.sel= 1
	Blender.Mesh.Mode(Blender.Mesh.SelectModes['FACE'])
	
	# Restore the transformation
	for data in (terrains, cutters):
		for t in data:
			if t.mesh.users: # it may have been a temp mesh from a curve.
				t.mesh.transform(t.matrix.copy().invert())
	
#.........这里部分代码省略.........
开发者ID:Synric,项目名称:synricproj,代码行数:103,代码来源:object_cookie_cutter.py


注:本文中的BPyMesh.getMeshFromObject方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。