No "release ahoy" yet, so it's probably still ok for these last minute updates (excuse me anyway):

Script bug fixes:
- Paths import: SVG update sent by author Jean-Michel Soler;
- Wavefront OBJ import / export updates sent by author Campbell Barton.
This commit is contained in:
Willian Padovani Germano
2005-05-30 02:26:40 +00:00
parent c073febf08
commit 4b99e61cf2
3 changed files with 95 additions and 112 deletions

View File

@@ -1,7 +1,7 @@
""" """
SVG 2 OBJ translater, 0.2.6 SVG 2 OBJ translater, 0.2.7
(c) jm soler juillet/novembre 2004, released under Blender Artistic Licence (c) jm soler juillet/novembre 2004, released under Blender Artistic Licence
for the Blender 2.34/35 Python Scripts Bundle. for the Blender 2.34/33 Python Scripts Bundle.
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
# Page officielle : # Page officielle :
# http://jmsoler.free.fr/didacticiel/blender/tutor/cpl_import_svg.htm # http://jmsoler.free.fr/didacticiel/blender/tutor/cpl_import_svg.htm
@@ -56,7 +56,8 @@ Changelog:
0.2.4 : - better hash for command with followed by a lone data 0.2.4 : - better hash for command with followed by a lone data
(h,v) or uncommun number (a) (h,v) or uncommun number (a)
0.2.5 : - correction for gimp import 0.2.5 : - correction for gimp import
0.2.6 : - correction for illustrator 10 SVG 0.2.6 : - correction for illustrator 10 SVG
0.2.7 : - correction for inskape 0.40 cvs SVG
================================================================================== ==================================================================================
==================================================================================""" =================================================================================="""
@@ -118,11 +119,11 @@ def filtreFICHIER(nom):
t=t.replace('\n','') t=t.replace('\n','')
if t.upper().find('<SVG')==-1 : if t.upper().find('<SVG')==-1 :
name = "OK?%t| Not a valid file or an empty file ... " # if no %xN int is set, indices start from 1 name = "ERROR: invalid or empty file ... " # if no %xN int is set, indices start from 1
result = Blender.Draw.PupMenu(name) result = Blender.Draw.PupMenu(name)
return "false" return "false"
elif t.upper().find('<PATH')==-1: elif t.upper().find('<PATH')==-1:
name = "OK?%t| Sorry, no Path in this file ... " # if no %xN int is set, indices start from 1 name = "ERROR: there's no Path in this file ... " # if no %xN int is set, indices start from 1
result = Blender.Draw.PupMenu(name) result = Blender.Draw.PupMenu(name)
return "false" return "false"
else: else:
@@ -484,21 +485,32 @@ def get_tag(val,t):
def get_val(val,t): def get_val(val,t):
d="" d=""
#print t
for l in t: for l in t:
if l.find(val+'="')!=-1: if l.find(val+'="')!=-1:
#print 'l', l
# 0.2.7 : - correction for inskape 0.40 cvs SVG
l=l.replace('>','')
# 0.2.7 : -- end
d=l[l[:-1].rfind('"')+1:-1] d=l[l[:-1].rfind('"')+1:-1]
for nn in d : #print 'd', d
if '012345670.'.find(nn)==-1: for nn in d:
if '0123456789.'.find(nn)==-1:
d=d.replace(nn,"") d=d.replace(nn,"")
#print d
d=float(d) d=float(d)
break break
#else:
# print l
d=0.0 d=0.0
return d return d
def get_BOUNDBOX(BOUNDINGBOX,SVG,viewbox): def get_BOUNDBOX(BOUNDINGBOX,SVG,viewbox):
if viewbox==0: if viewbox==0:
h=get_val('height',SVG) h=get_val('height',SVG)
print 'h : ',h
w=get_val('width',SVG) w=get_val('width',SVG)
print 'w :',w
BOUNDINGBOX['rec']=[0.0,0.0,w,h] BOUNDINGBOX['rec']=[0.0,0.0,w,h]
r=BOUNDINGBOX['rec'] r=BOUNDINGBOX['rec']
BOUNDINGBOX['coef']=w/h BOUNDINGBOX['coef']=w/h
@@ -609,6 +621,7 @@ def scan_FILE(nom):
SVG,viewbox=get_content('viewBox',SVG) SVG,viewbox=get_content('viewBox',SVG)
SVG=SVG.split(' ') SVG=SVG.split(' ')
print SVG
if viewbox==0: if viewbox==0:
BOUNDINGBOX = get_BOUNDBOX(BOUNDINGBOX,SVG,0) BOUNDINGBOX = get_BOUNDBOX(BOUNDINGBOX,SVG,0)
else: else:

View File

@@ -2,7 +2,7 @@
""" """
Name: 'Wavefront (.obj)...' Name: 'Wavefront (.obj)...'
Blender: 232 Blender: 237
Group: 'Export' Group: 'Export'
Tooltip: 'Save a Wavefront OBJ File' Tooltip: 'Save a Wavefront OBJ File'
""" """
@@ -46,39 +46,13 @@ Run this script from "File->Export" menu to export all meshes.
# New name based on old with a different extension # # New name based on old with a different extension #
#==================================================# #==================================================#
def newFName(ext): def newFName(ext):
return Get('filename')[: -len(Get('filename').split('.', -1)[-1]) ] + ext return Get('filename')[: -len(Get('filename').split('.', -1)[-1]) ] + ext
#===============================================#
# Strips the slashes from the front of a string #
#===============================================#
def stripPath(path):
for CH in range(len(path), 0, -1):
if path[CH-1] == "/" or path[CH-1] == "\\":
path = path[CH:]
break
return path
#==================#
# Apply Transform #
#==================#
def apply_transform(vert, matrix_4x4):
vertCopy = Mathutils.CopyVec(vert)
vertCopy.resize4D()
return Mathutils.VecMultMat(vertCopy, matrix_4x4)
#=================================#
# Apply Transform (normal vector) #
#=================================#
def apply_normal_transform(norm, matrix_3x3):
vertCopy = Mathutils.CopyVec(norm)
vertCopy.resize3D()
return Mathutils.VecMultMat(vertCopy, matrix_3x3)
from Blender import * from Blender import *
NULL_MAT = '(null)' NULL_MAT = '(null)'
NULL_IMG = '(null)' NULL_IMG = '(null)' # from docs at http://astronomy.swin.edu.au/~pbourke/geomformats/obj/ also could be 'off'
def save_mtl(filename): def save_mtl(filename):
file = open(filename, "w") file = open(filename, "w")
@@ -117,8 +91,9 @@ def save_mtl(filename):
def save_obj(filename): def save_obj(filename):
time1 = sys.time() time1 = sys.time()
scn = Scene.GetCurrent()
# First output all material # First output all material
mtlfilename = filename[:-4] + '.mtl' mtlfilename = '%s.mtl' % '.'.join(filename.split('.')[:-1])
save_mtl(mtlfilename) save_mtl(mtlfilename)
file = open(filename, "w") file = open(filename, "w")
@@ -128,63 +103,48 @@ def save_obj(filename):
file.write('# www.blender.org\n') file.write('# www.blender.org\n')
# Tell the obj file what material file to use. # Tell the obj file what material file to use.
file.write('mtllib %s\n' % (stripPath(mtlfilename))) file.write('mtllib %s\n' % ( mtlfilename.split('\\')[-1].split('/')[-1] ))
# Initialize totals, these are updated each object # Initialize totals, these are updated each object
totverts = totuvco = 0 totverts = totuvco = 0
# Get all meshs # Get all meshs
for ob in Object.Get(): for ob in scn.getChildren():
if ob.getType() != 'Mesh': if ob.getType() != 'Mesh':
continue continue
m = NMesh.GetRawFromObject(ob.name) m = NMesh.GetRawFromObject(ob.name)
m.transform(ob.matrix)
# remove any edges, is not written back to the mesh so its not going to
# modify the open file. if not m.faces: # Make sure there is somthing to write
for f in m.faces:
if len(f.v) < 3:
m.faces.remove(f)
if len(m.faces) == 0: # Make sure there is somthing to write.
continue #dont bother with this mesh. continue #dont bother with this mesh.
# Set the default mat # Set the default mat
currentMatName = NULL_MAT currentMatName = NULL_MAT
currentImgName = NULL_IMG currentImgName = NULL_IMG
#file.write('o ' + ob.getName() + '_' + m.name + '\n') # Write Object name
file.write('o %s_%s\n' % (ob.getName(), m.name)) # Write Object name file.write('o %s_%s\n' % (ob.getName(), m.name)) # Write Object name
# Works 100% Yay
matrix_4x4 = ob.getMatrix('worldspace')
# matrix for transformation of normal vectors
matrix_3x3 = Mathutils.Matrix([matrix_4x4[0][0], matrix_4x4[0][1], matrix_4x4[0][2]],
[matrix_4x4[1][0], matrix_4x4[1][1], matrix_4x4[1][2]],
[matrix_4x4[2][0], matrix_4x4[2][1], matrix_4x4[2][2]])
# Vert # Vert
for v in m.verts: for v in m.verts:
# Transform the vert file.write('v %s %s %s\n' % (v.co.x, v.co.y, v.co.z))
vTx = apply_transform(v.co, matrix_4x4)
file.write('v %s %s %s\n' % (vTx[0], vTx[1], vTx[2]))
# UV # UV
for f in m.faces: for f in m.faces:
''' # Export edges?
if len(f.v) < 3:
continue
'''
for uvIdx in range(len(f.v)): for uvIdx in range(len(f.v)):
if f.uv: if f.uv:
file.write('vt %s %s 0.0\n' % (f.uv[uvIdx][0], f.uv[uvIdx][1])) file.write('vt %s %s 0.0\n' % (f.uv[uvIdx][0], f.uv[uvIdx][1]))
else: else:
file.write('vt 0.0 0.0 0.0\n') file.write('vt 0.0 0.0 0.0\n')
# NORMAL # NORMAL
for f1 in m.faces: for f1 in m.faces:
for v in f1.v: for v in f1.v:
# Transform the normal file.write('vn %s %s %s\n' % (v.no.x, v.no.y, v.no.z))
noTx = apply_normal_transform(v.no, matrix_3x3)
noTx.normalize()
file.write('vn %s %s %s\n' % (noTx[0], noTx[1], noTx[2]))
uvIdx = 0 uvIdx = 0
for f in m.faces: for f in m.faces:
# Check material and change if needed. # Check material and change if needed.
@@ -192,23 +152,23 @@ def save_obj(filename):
if currentMatName != m.materials[f.mat].getName(): if currentMatName != m.materials[f.mat].getName():
currentMatName = m.materials[f.mat].getName() currentMatName = m.materials[f.mat].getName()
file.write('usemtl %s\n' % (currentMatName)) file.write('usemtl %s\n' % (currentMatName))
elif currentMatName != NULL_MAT: elif currentMatName != NULL_MAT:
currentMatName = NULL_MAT currentMatName = NULL_MAT
file.write('usemtl %s\n' % (currentMatName)) file.write('usemtl %s\n' % (currentMatName))
# UV IMAGE # UV IMAGE
# If the face uses a different image from the one last set then add a usemap line. # If the face uses a different image from the one last set then add a usemap line.
if f.image: if f.image:
if f.image.filename != currentImgName: if f.image.filename != currentImgName:
currentImgName = f.image.filename currentImgName = f.image.filename
# Set a new image for all following faces # Set a new image for all following faces
file.write( 'usemat %s\n' % (stripPath(currentImgName))) file.write( 'usemapusemap %s\n' % currentImgName.split('\\')[-1].split('/')[-1] )
elif currentImgName != NULL_IMG: # Not using an image so set to NULL_IMG elif currentImgName != NULL_IMG: # Not using an image so set to NULL_IMG
currentImgName = NULL_IMG currentImgName = NULL_IMG
# Set a new image for all following faces # Set a new image for all following faces
file.write( 'usemat %s\n' % (stripPath(currentImgName))) file.write( 'usemap %s\n' % currentImgName) # No splitting needed.
file.write('f ') file.write('f ')
for v in f.v: for v in f.v:
@@ -216,7 +176,7 @@ def save_obj(filename):
uvIdx+=1 uvIdx+=1
file.write('\n') file.write('\n')
# Make the indicies global rather then per mesh # Make the indicies global rather then per mesh
totverts += len(m.verts) totverts += len(m.verts)
totuvco += uvIdx totuvco += uvIdx

View File

@@ -2,7 +2,7 @@
""" """
Name: 'Wavefront (.obj)...' Name: 'Wavefront (.obj)...'
Blender: 232 Blender: 237
Group: 'Import' Group: 'Import'
Tooltip: 'Load a Wavefront OBJ File' Tooltip: 'Load a Wavefront OBJ File'
""" """
@@ -65,11 +65,7 @@ def pathName(path,name):
# Strips the slashes from the back of a string # # Strips the slashes from the back of a string #
#==============================================# #==============================================#
def stripPath(path): def stripPath(path):
for CH in range(len(path), 0, -1): return path.split('/')[-1].split('\\')[-1]
if path[CH-1] == "/" or path[CH-1] == "\\":
path = path[CH:]
break
return path
#====================================================# #====================================================#
# Strips the prefix off the name before writing # # Strips the prefix off the name before writing #
@@ -146,7 +142,7 @@ def load_mat_image(mat, img_fileName, type, mesh):
#==================================================================================# #==================================================================================#
def load_mtl(dir, mtl_file, mesh): def load_mtl(dir, mtl_file, mesh):
# Remove ./ # Remove ./
if mtl_file[:2] == './': if mtl_file.endswith('./'):
mtl_file= mtl_file[2:] mtl_file= mtl_file[2:]
mtl_fileName = dir + mtl_file mtl_fileName = dir + mtl_file
@@ -190,22 +186,22 @@ def load_mtl(dir, mtl_file, mesh):
load_mat_image(currentMat, img_fileName, 'Kd', mesh) load_mat_image(currentMat, img_fileName, 'Kd', mesh)
lIdx+=1 lIdx+=1
#======================================================================# #===========================================================================#
# Returns unique name of object (preserve overwriting existing meshes) # # Returns unique name of object/mesh (preserve overwriting existing meshes) #
#======================================================================# #===========================================================================#
def getUniqueName(name): def getUniqueName(name):
uniqueInt = 0 uniqueInt = 0
while 1: while 1:
try: try:
ob = Object.Get(name) ob = Object.Get(name)
# Okay, this is working, so lets make a new name # Okay, this is working, so lets make a new name
name += '.' + str(uniqueInt) name = '%s.%d' % (name, uniqueInt)
uniqueInt +=1 uniqueInt +=1
except: except:
if NMesh.GetRaw(name) == None: if name not in NMesh.GetNames():
return name return name
else: else:
name += '.' + str(uniqueInt) name = '%s.%d' % (name, uniqueInt)
uniqueInt +=1 uniqueInt +=1
#==================================================================================# #==================================================================================#
@@ -246,7 +242,7 @@ def load_obj(file):
# This dummy vert makes life a whole lot easier- # This dummy vert makes life a whole lot easier-
# pythons index system then aligns with objs, remove later # pythons index system then aligns with objs, remove later
vertList = [NMesh.Vert(0, 0, 0)] # store tuple uv pairs here vertList = [NMesh.Vert(0, 0, 0)]
nullMat = getMat(NULL_MAT) nullMat = getMat(NULL_MAT)
@@ -266,7 +262,7 @@ def load_obj(file):
# Load all verts first (texture verts too) # # Load all verts first (texture verts too) #
#==================================================================================# #==================================================================================#
lIdx = 0 lIdx = 0
print len(fileLines) print 'file length: %d' % len(fileLines)
while lIdx < len(fileLines): while lIdx < len(fileLines):
l = fileLines[lIdx] l = fileLines[lIdx]
@@ -442,7 +438,7 @@ def load_obj(file):
unique_count = 0 unique_count = 0
while newObjectName in meshList.keys(): while newObjectName in meshList.keys():
newObjectName = l[0] + '_' + str(unique_count) newObjectName = '%s_%d' % (l[0], unique_count)
unique_count +=1 unique_count +=1
else: # The the object/group name given else: # The the object/group name given
newObjectName += '_'.join(l[1:]) newObjectName += '_'.join(l[1:])
@@ -460,17 +456,17 @@ def load_obj(file):
# MATERIAL # MATERIAL
elif l[0] == 'usemtl': elif l[0] == 'usemtl':
if l[1] == '(null)': if len(l) == 1 or l[1] == '(null)':
currentMat = getMat(NULL_MAT) currentMat = getMat(NULL_MAT)
else: else:
currentMat = getMat(' '.join(l[1:])) # Use join in case of spaces currentMat = getMat(' '.join(l[1:])) # Use join in case of spaces
# MATERIAL # MATERIAL
elif l[0] == 'usemat': elif l[0] == 'usemat' or l[0] == 'usemap':
if l[1] == '(null)': if len(l) == 1 or l[1] == '(null)' or l[1] == 'off':
currentImg = NULL_IMG currentImg = NULL_IMG
else: else:
currentImg = getImg(DIR + ' '.join(l[1:])) # Use join in case of spaces currentImg = getImg('%s%s' % (DIR, ' '.join(l[1:]).replace('./', '') ) ) # Use join in case of spaces
# MATERIAL FILE # MATERIAL FILE
elif l[0] == 'mtllib': elif l[0] == 'mtllib':
@@ -481,29 +477,43 @@ def load_obj(file):
#==============================================# #==============================================#
# Write all meshs in the dictionary # # Write all meshs in the dictionary #
#==============================================# #==============================================#
for ob in Scene.GetCurrent().getChildren(): # Deselect all
ob.sel = 0
importedObjects = []
for mk in meshList.keys(): for mk in meshList.keys():
# Applies material properties to materials alredy on the mesh as well as Textures. # Applies material properties to materials alredy on the mesh as well as Textures.
if mtl_fileName != '': if mtl_fileName != '':
load_mtl(DIR, mtl_fileName, meshList[mk][0]) load_mtl(DIR, mtl_fileName, meshList[mk][0])
if len(meshList[mk][0].verts) >1:
meshList[mk][0].verts.pop(0) meshList[mk][0].verts.pop(0)
name = getUniqueName(mk) # Ignore no vert meshes.
ob = NMesh.PutRaw(meshList[mk][0], name) if not meshList[mk][0].verts:
ob.name = name continue
name = getUniqueName(mk)
ob = NMesh.PutRaw(meshList[mk][0], name)
ob.name = name
importedObjects.append(ob)
# Select all imported objects.
for ob in importedObjects:
ob.sel = 1
print "obj import time: ", sys.time() - time1 print "obj import time: ", sys.time() - time1
Window.FileSelector(load_obj, 'Import Wavefront OBJ') Window.FileSelector(load_obj, 'Import Wavefront OBJ')
'''
# For testing compatibility # For testing compatibility
#import os import os
#for obj in os.listdir('/obj/'): for obj in os.listdir('/obj/'):
# if obj[-3:] == 'obj': if obj.lower().endswith('obj'):
# print obj print obj
# newScn = Scene.New(obj) newScn = Scene.New(obj)
# newScn.makeCurrent() newScn.makeCurrent()
# load_obj('/obj/' + obj) load_obj('/obj/' + obj)
'''