Newer
Older
bpy.ops.constraint.childof_set_inverse(constraint=cns.name, owner='BONE')
cns.influence = 0
for (pb, cns, inf) in cnslist:
cns.influence = inf
return
#
# postProcess(args)
#
def postProcess(args):
human = args[0]
print("Postprocess %s" % human)
ob = loadedData['Object'][human]
except:
ob = None
if toggle & T_Diamond == 0 and ob:
Thomas Larsson
committed
deleteDiamonds(ob)
return
#
# deleteDiamonds(ob)
# Delete joint diamonds in main mesh
# Invisio = material # 1
#
def deleteDiamonds(ob):
bpy.context.scene.objects.active = ob
if not bpy.context.object:
return
print("Delete helper geometry in %s" % bpy.context.object)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
me = ob.data
invisioNum = -1
for mn,mat in enumerate(me.materials):
if "Invis" in mat.name:
invisioNum = mn
break
if invisioNum < 0:
print("WARNING: Nu Invisio material found. Cannot delete helper geometry")
elif BMeshAware:
Thomas Larsson
committed
for f in me.polygons:
if f.material_index >= invisioNum:
for vn in f.vertices:
me.vertices[vn].select = True
else:
for f in me.faces:
if f.material_index >= invisioNum:
for vn in f.vertices:
me.vertices[vn].select = True
if BMeshAware and toggle&T_CrashSafe:
theMessage = "\n *** WARNING ***\nHelper deletion turned off due to Blender crash.\nHelpers can be deleted by deleting all selected vertices in Edit mode\n **********\n"
print(theMessage)
else:
bpy.ops.object.mode_set(mode='EDIT')
print("Do delete")
bpy.ops.mesh.delete(type='VERT')
print("Verts deleted")
bpy.ops.object.mode_set(mode='OBJECT')
print("Back to object mode")
# defaultKey(ext, args, tokens, var, exclude, glbals, lcals):
Thomas Larsson
committed
theProperty = None
def propNames(string):
Thomas Larsson
committed
global alpha7
#string = string.encode('utf-8', 'strict')
Thomas Larsson
committed
# Alpha 7 compatibility
if string[0:2] == "&_":
string = "Mhf"+string[2:]
alpha7 = True
elif string[0] == "&":
string = "Mha"+string[1:]
alpha7 = True
elif string[0] == "*":
string = "Mhs"+string[1:]
alpha7 = True
elif len(string) > 4 and string[0:4] == "Hide":
Thomas Larsson
committed
string = "Mhh"+string[4:]
alpha7 = True
if string[0] == "_":
return None,None
elif (len(string) > 3 and
string[0:3] in ["Mha", "Mhf", "Mhs", "Mhh", "Mhv", "Mhc"]):
Thomas Larsson
committed
return name, '["%s"]' % name
Thomas Larsson
committed
else:
return string, '["%s"]' % string
def defProp(args, var, glbals, lcals):
proptype = args[0]
name = propNames(args[1])[0]
value = args[2]
rest = 'description="%s"' % args[3].replace("_", " ")
if len(args) > 4:
rest += ", " + args[4]
if name:
#expr = 'bpy.types.Object.%s = %sProperty(%s)' % (name, proptype, rest)
expr = '%s["%s"] = %s' % (var, name, value)
Thomas Larsson
committed
def defNewProp(name, proptype, rest):
expr = 'bpy.types.Object.%s = %sProperty(%s)' % (name, proptype, rest)
print(expr)
exec(expr)
Thomas Larsson
committed
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
def setProperty(args, var, glbals, lcals):
global theProperty
tip = ""
name = propNames(args[0])[0]
value = args[1]
if name:
expr = '%s["%s"] = %s' % (var, name, value)
exec(expr, glbals, lcals)
if len(args) > 2:
tip = 'description="%s"' % args[2].replace("_", " ")
if value in ["True", "False"]:
proptype = "Bool"
elif value[0] in ["'",'"']:
proptype = "String"
elif "." in value:
proptype = "Float"
else:
proptype = "Int"
theProperty = (name, tip, proptype)
Thomas Larsson
committed
Thomas Larsson
committed
def defineProperty(args):
global theProperty
if theProperty is None:
return
(name, tip, proptype) = theProperty
if len(args) >= 2 and proptype != "Bool":
if "BOOLEAN" in args[1]:
proptype = "Bool"
else:
tip = tip + "," + args[1].replace(":", "=").replace('"', " ")
Thomas Larsson
committed
expr = "bpy.types.Object.%s = %sProperty(%s)" % (name, proptype, tip)
theProperty = None
Thomas Larsson
committed
def defaultKey(ext, args, tokens, var, exclude, glbals, lcals):
Thomas Larsson
committed
global todo
Thomas Larsson
committed
return setProperty(args, var, glbals, lcals)
Thomas Larsson
committed
elif ext == 'PropKeys':
return defineProperty(args)
elif ext == 'DefProp':
return defProp(args, var, glbals, lcals)
if ext == 'bpyops':
expr = "bpy.ops.%s" % args[0]
print(expr)
exec(expr)
return
nvar = "%s.%s" % (var, ext)
#print(ext)
if ext in exclude:
return
#print("D", nvar)
if len(args) == 0:
rnaType = args[0]
if rnaType == 'Add':
print("*** Cannot Add yet ***")
return
elif rnaType == 'Refer':
typ = args[1]
name = args[2]
data = "loadedData['%s']['%s']" % (typ, name)
elif rnaType == 'Struct' or rnaType == 'Define':
typ = args[1]
name = args[2]
try:
data = eval(nvar, glbals, lcals)
except:
data = None
# print("Old structrna", nvar, data)
if data is None:
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
try:
creator = args[3]
except:
creator = None
# print("Creator", creator, eval(var,glbals,lcals))
try:
rna = eval(var,glbals,lcals)
data = eval(creator)
except:
data = None
# print("New struct", nvar, typ, data)
if rnaType == 'Define':
loadedData[typ][name] = data
if data:
for (key, val, sub) in tokens:
defaultKey(key, val, sub, "data", [], globals(), locals())
print("Struct done", nvar)
return
elif rnaType == 'PropertyRNA':
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
#print("PropertyRNA ", ext, var)
for (key, val, sub) in tokens:
defaultKey(ext, val, sub, nvar, [], glbals, lcals)
return
elif rnaType == 'Array':
for n in range(1, len(args)):
expr = "%s[%d] = %s" % (nvar, n-1, args[n])
exec(expr, glbals, lcals)
if len(args) > 0:
expr = "%s[0] = %s" % (nvar, args[1])
exec(expr, glbals, lcals)
return
elif rnaType == 'List':
data = []
for (key, val, sub) in tokens:
elt = eval(val[1], glbals, lcals)
data.append(elt)
elif rnaType == 'Matrix':
return
i = 0
n = len(tokens)
for (key, val, sub) in tokens:
if key == 'row':
for j in range(n):
expr = "%s[%d][%d] = %g" % (nvar, i, j, float(val[j]))
exec(expr, glbals, lcals)
i += 1
return
else:
try:
data = loadedData[rnaType][args[1]]
#print("From loaded", rnaType, args[1], data)
return data
except:
data = rnaType
#print(var, ext, data)
expr = "%s = %s" % (nvar, data)
try:
exec(expr, glbals, lcals)
except:
pushOnTodoList(var, expr, glbals, lcals)
return
#
#
#
def pushOnTodoList(var, expr, glbals, lcals):
global todo
print("Tdo", var)
print(dir(eval(var, glbals, lcals)))
MyError(
"Unrecognized expression %s.\n" % expr +
"This can mean that Blender's python API has changed\n" +
"since the MHX file was exported. Try to export again\n" +
"from an up-to-date MakeHuman nightly build.\n" +
"Alternatively, your Blender version may be obsolete.\n" +
"Download an up-to-date version from www.graphicall.org")
list = []
for c in mask:
if c == '0':
list.append(False)
else:
list.append(True)
return list
matrix = mathutils.Matrix()
i = 0
for (key, val, sub) in tokens:
if key == 'row':
matrix[i][0] = float(val[0])
matrix[i][1] = float(val[1])
matrix[i][2] = float(val[2])
matrix[i][3] = float(val[3])
i += 1
return matrix
def parseDefault(data, tokens, subkeys, exclude):
for (key, val, sub) in tokens:
if key in subkeys.keys():
for (key2, val2, sub2) in sub:
defaultKey(key2, val2, sub2, "data.%s" % subkeys[key], [], globals(), locals())
else:
defaultKey(key, val, sub, "data", exclude, globals(), locals())
def parseCollection(data, tokens, exclude):
Thomas Larsson
committed
"""
typeSplit = str(type(data)).split("'")
if typeSplit[0] != '<class ':
return None
classSplit = typeSplit[1].split(".")
if classSplit[0] == 'bpy' and classSplit[1] == 'types':
return classSplit[2]
elif classSplit[0] == 'bpy_types':
return classSplit[1]
else:
return None
if string == 'True':
return True
elif string == 'False':
return False
else:
Thomas Larsson
committed
"""
global rigLeg, rigArm, toggle
res = eval(condition, globals())
try:
res = eval(condition, globals())
#print("%s = %s" % (condition, res))
return not res
except:
#print("%s invalid!" % condition)
return True
global toggle
scn = bpy.context.scene
for n in range(len(scn.layers)):
scn.layers[n] = True
print("clearScene %s %s" % (toggle & T_Replace, scn))
if not toggle & T_Replace:
return scn
for ob in scn.objects:
Thomas Larsson
committed
if ob.type in ['MESH', 'ARMATURE', 'EMPTY', 'CURVE', 'LATTICE']:
Thomas Larsson
committed
ob.name = "#" + ob.name
try:
bpy.ops.object.mode_set(mode='OBJECT')
except:
pass
Thomas Larsson
committed
for grp in bpy.data.groups:
grp.name = "#" + grp.name
#
# hideLayers(args):
# args = sceneLayers sceneHideLayers boneLayers boneHideLayers or nothing
#
def hideLayers(args):
if len(args) > 1:
sceneLayers = int(args[2], 16)
sceneHideLayers = int(args[3], 16)
boneLayers = int(args[4], 16)
# boneHideLayers = int(args[5], 16)
boneHideLayers = 0
else:
sceneLayers = 0x00ff
sceneHideLayers = 0
boneLayers = 0
boneHideLayers = 0
mask = 1
hidelayers = []
for n in range(20):
scn.layers[n] = True if sceneLayers & mask else False
if sceneHideLayers & mask:
hidelayers.append(n)
mask = mask << 1
for ob in scn.objects:
for n in hidelayers:
if ob.layers[n]:
ob.hide = True
ob.hide_render = True
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
if boneLayers:
human = args[1]
try:
ob = loadedData['Object'][human]
except:
return
mask = 1
hidelayers = []
for n in range(32):
ob.data.layers[n] = True if boneLayers & mask else False
if boneHideLayers & mask:
hidelayers.append(n)
mask = mask << 1
for b in ob.data.bones:
for n in hidelayers:
if b.layers[n]:
b.hide = True
return
#
# readDefaults():
# writeDefaults():
#
ConfigFile = '~/mhx_import.cfg'
def readDefaults():
global toggle, toggleSettings, theScale
path = os.path.realpath(os.path.expanduser(ConfigFile))
try:
fp = open(path, 'rU')
print('Storing defaults')
except:
print('Cannot open "%s" for reading' % path)
return
bver = ''
for line in fp:
words = line.split()
if len(words) >= 3:
try:
toggle = int(words[0],16)
theScale = float(words[1])
except:
print('Configuration file "%s" is corrupt' % path)
fp.close()
toggleSettings = toggle
return
def writeDefaults():
global toggleSettings, theScale
path = os.path.realpath(os.path.expanduser(ConfigFile))
try:
fp = open(path, 'w')
print('Storing defaults')
except:
print('Cannot open "%s" for writing' % path)
return
fp.write("%x %f Graphicall" % (toggleSettings, theScale))
fp.close()
###################################################################################
#
# Postprocessing of rigify rig
#
Thomas Larsson
committed
# rigifyMhx(context, name):
#
###################################################################################
Thomas Larsson
committed
def rigifyMhx(context, name):
print("Modifying MHX rig to Rigify")
scn = context.scene
Thomas Larsson
committed
mhx = loadedData['Object'][name]
Thomas Larsson
committed
bpy.context.scene.objects.active = mhx
# Delete old widgets
"""
for ob in scn.objects:
if ob.type == 'MESH' and ob.name[0:3] == "WGT":
scn.objects.unlink(ob)
Thomas Larsson
committed
"""
# Save mhx bone locations
heads = {}
tails = {}
rolls = {}
parents = {}
extras = {}
bpy.ops.object.mode_set(mode='EDIT')
newParents = {
'head' : 'DEF-head',
'ribs' : 'DEF-ribs',
Thomas Larsson
committed
'upper_arm.L' : 'DEF-upper_arm.02.L',
'thigh.L' : 'DEF-thigh.02.L',
'upper_arm.R' : 'DEF-upper_arm.02.R',
'thigh.R' : 'DEF-thigh.02.R',
}
for eb in mhx.data.edit_bones:
heads[eb.name] = eb.head.copy()
tails[eb.name] = eb.tail.copy()
rolls[eb.name] = eb.roll
if eb.parent:
par = eb.parent.name
try:
parents[eb.name] = newParents[par]
except:
parents[eb.name] = par
else:
parents[eb.name] = None
extras[eb.name] = not eb.layers[16]
bpy.ops.object.mode_set(mode='OBJECT')
# Find corresponding meshes. Can be several (clothes etc.)
meshes = []
for ob in scn.objects:
for mod in ob.modifiers:
if (mod.type == 'ARMATURE' and mod.object == mhx):
meshes.append((ob, mod))
if meshes == []:
# Rename Head vertex group
for (mesh, mod) in meshes:
try:
vg = mesh.vertex_groups['DfmHead']
vg.name = 'DEF-head'
except:
pass
Thomas Larsson
committed
# Change meta bone locations
scn.objects.active = None
try:
Thomas Larsson
committed
bpy.ops.object.armature_human_metarig_add()
success = True
except:
success = False
if not success:
MyError("Unable to create advanced human. \n" \
"Make sure that the Rigify addon is enabled. \n" \
"It is found under Rigging.")
Thomas Larsson
committed
meta = context.object
bpy.ops.object.mode_set(mode='EDIT')
Thomas Larsson
committed
for eb in meta.data.edit_bones:
eb.head = heads[eb.name]
eb.tail = tails[eb.name]
eb.roll = rolls[eb.name]
extras[eb.name] = False
fingerPlanes = [
('UP-thumb.L', 'thumb.01.L', 'thumb.03.L', ['thumb.02.L']),
('UP-index.L', 'finger_index.01.L', 'finger_index.03.L', ['finger_index.02.L']),
('UP-middle.L', 'finger_middle.01.L', 'finger_middle.03.L', ['finger_middle.02.L']),
('UP-ring.L', 'finger_ring.01.L', 'finger_ring.03.L', ['finger_ring.02.L']),
('UP-pinky.L', 'finger_pinky.01.L', 'finger_pinky.03.L', ['finger_pinky.02.L']),
('UP-thumb.R', 'thumb.01.R', 'thumb.03.R', ['thumb.02.R']),
('UP-index.R', 'finger_index.01.R', 'finger_index.03.R', ['finger_index.02.R']),
('UP-middle.R', 'finger_middle.01.R', 'finger_middle.03.R', ['finger_middle.02.R']),
('UP-ring.R', 'finger_ring.01.R', 'finger_ring.03.R', ['finger_ring.02.R']),
('UP-pinky.R', 'finger_pinky.01.R', 'finger_pinky.03.R', ['finger_pinky.02.R']),
]
for (upbone, first, last, middles) in fingerPlanes:
extras[upbone] = False
Thomas Larsson
committed
#lineateChain(upbone, first, last, middles, 0.01, meta, heads, tails)
ikPlanes = [
('UP-leg.L', 'thigh.L', 'shin.L'),
('UP-arm.L', 'upper_arm.L', 'forearm.L'),
('UP-leg.R', 'thigh.R', 'shin.R'),
('UP-arm.R', 'upper_arm.R', 'forearm.R'),
]
for (upbone, first, last) in ikPlanes:
extras[upbone] = False
Thomas Larsson
committed
lineateChain(upbone, first, last, [], 0.1, meta, heads, tails)
bpy.ops.object.mode_set(mode='OBJECT')
Thomas Larsson
committed
# Generate rigify rig
bpy.ops.pose.rigify_generate()
Thomas Larsson
committed
scn.objects.unlink(meta)
rigify = context.object
rigify.name = name+"Rig"
layers = 20*[False]
layers[1] = True
rigify.layers = layers
Thomas Larsson
committed
rigify.show_x_ray = True
Thomas Larsson
committed
mod.object = rigify
grp = loadedData['Group'][name]
grp.objects.link(rigify)
# Parent widgets under empty
empty = bpy.data.objects.new("Widgets", None)
scn.objects.link(empty)
empty.layers = 20*[False]
empty.layers[19] = True
Thomas Larsson
committed
empty.parent = rigify
for ob in scn.objects:
if ob.type == 'MESH' and ob.name[0:4] == "WGT-" and not ob.parent:
ob.parent = empty
Thomas Larsson
committed
grp.objects.link(ob)
elif ob.parent == mhx:
ob.parent = rigify
Thomas Larsson
committed
# Copy extra bones to rigify rig
bpy.ops.object.mode_set(mode='EDIT')
for name in heads.keys():
if extras[name]:
Thomas Larsson
committed
eb = rigify.data.edit_bones.new(name)
eb.head = heads[name]
eb.tail = tails[name]
eb.roll = rolls[name]
for name in heads.keys():
if extras[name] and parents[name]:
Thomas Larsson
committed
eb = rigify.data.edit_bones[name]
eb.parent = rigify.data.edit_bones[parents[name]]
# Copy constraints etc.
bpy.ops.object.mode_set(mode='POSE')
for name in heads.keys():
if extras[name]:
pb1 = mhx.pose.bones[name]
Thomas Larsson
committed
pb2 = rigify.pose.bones[name]
pb2.custom_shape = pb1.custom_shape
pb2.lock_location = pb1.lock_location
pb2.lock_rotation = pb1.lock_rotation
pb2.lock_scale = pb1.lock_scale
b1 = pb1.bone
b2 = pb2.bone
b2.use_deform = b1.use_deform
b2.hide_select = b1.hide_select
b2.show_wire = b1.show_wire
layers = 32*[False]
if b1.layers[8]:
layers[28] = True
else:
layers[29] = True
if b1.layers[10]:
layers[2] = True
b2.layers = layers
for cns1 in pb1.constraints:
Thomas Larsson
committed
cns2 = copyConstraint(cns1, pb1, pb2, mhx, rigify)
Thomas Larsson
committed
rigify.data.bones.active = pb2.bone
bpy.ops.constraint.childof_set_inverse(constraint=cns2.name, owner='BONE')
# Create animation data
if mhx.animation_data:
for fcu in mhx.animation_data.drivers:
Thomas Larsson
committed
rigify.animation_data.drivers.from_existing(src_driver=fcu)
Thomas Larsson
committed
fixDrivers(rigify.animation_data, mhx, rigify)
Thomas Larsson
committed
mesh.parent = rigify
skeys = mesh.data.shape_keys
if skeys:
Thomas Larsson
committed
fixDrivers(skeys.animation_data, mhx, rigify)
scn.objects.unlink(mhx)
print("Rigify rig complete")
return
#
Thomas Larsson
committed
# lineateChain(upbone, first, last, middles, minDist, rig, heads, tails):
# lineate(pt, start, minDist, normal, offVector):
#
Thomas Larsson
committed
def lineateChain(upbone, first, last, middles, minDist, rig, heads, tails):
fb = rig.data.edit_bones[first]
lb = rig.data.edit_bones[last]
uhead = heads[upbone]
utail = tails[upbone]
tang = lb.tail - fb.head
tangent = tang/tang.length
up = (uhead+utail)/2 - fb.head
norm = up - tangent*tangent.dot(up)
normal = norm/norm.length
offVector = tangent.cross(normal)
vec = utail - uhead
fb.tail = lineate(fb.tail, fb.head, minDist, normal, offVector)
lb.head = lineate(lb.head, fb.head, minDist, normal, offVector)
for bone in middles:
Thomas Larsson
committed
mb = rig.data.edit_bones[bone]
mb.head = lineate(mb.head, fb.head, minDist, normal, offVector)
mb.tail = lineate(mb.tail, fb.head, minDist, normal, offVector)
return
def lineate(pt, start, minDist, normal, offVector):
diff = pt - start
diff = diff - offVector*offVector.dot(diff)
dist = diff.dot(normal)
if dist < minDist:
diff += (minDist - dist)*normal
return start + diff
#
Thomas Larsson
committed
# fixDrivers(adata, mhx, rigify):
Thomas Larsson
committed
def fixDrivers(adata, mhx, rigify):
if not adata:
return
for fcu in adata.drivers:
for var in fcu.driver.variables:
for targ in var.targets:
if targ.id == mhx:
Thomas Larsson
committed
targ.id = rigify
Thomas Larsson
committed
# copyConstraint(cns1, pb1, pb2, mhx, rigify):
Thomas Larsson
committed
def copyConstraint(cns1, pb1, pb2, mhx, rigify):
substitute = {
'Head' : 'DEF-head',
'MasterFloor' : 'root',
'upper_arm.L' : 'DEF-upper_arm.L.01',
'upper_arm.R' : 'DEF-upper_arm.R.01',
'thigh.L' : 'DEF-thigh.L.01',
'thigh.R' : 'DEF-thigh.R.01',
'shin.L' : 'DEF-shin.L.01',
'shin.R' : 'DEF-shin.R.01'
}
cns2 = pb2.constraints.new(cns1.type)
for prop in dir(cns1):
if prop == 'target':
if cns1.target == mhx:
Thomas Larsson
committed
cns2.target = rigify
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
else:
cns2.target = cns1.target
elif prop == 'subtarget':
try:
cns2.subtarget = substitute[cns1.subtarget]
except:
cns2.subtarget = cns1.subtarget
elif prop[0] != '_':
try:
expr = "cns2.%s = cns1.%s" % (prop, prop)
#print(pb1.name, expr)
exec(expr)
except:
pass
return cns2
#
# class OBJECT_OT_RigifyMhxButton(bpy.types.Operator):
#
class OBJECT_OT_RigifyMhxButton(bpy.types.Operator):
bl_idname = "mhxrig.rigify_mhx"
bl_label = "Rigify MHX rig"
bl_options = {'UNDO'}
def execute(self, context):
Thomas Larsson
committed
rigifyMhx(context, context.object.name)
return{'FINISHED'}
#
# class RigifyMhxPanel(bpy.types.Panel):
#
class RigifyMhxPanel(bpy.types.Panel):
bl_label = "Rigify MHX"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
@classmethod
def poll(cls, context):
if context.object:
return False
def draw(self, context):
return
###################################################################################
###################################################################################
DEBUG = False
from bpy.props import StringProperty, FloatProperty, EnumProperty, BoolProperty
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
class ErrorOperator(bpy.types.Operator):
bl_idname = "mhx.error"
bl_label = "Error when loading MHX file"
def execute(self, context):
return {'RUNNING_MODAL'}
def invoke(self, context, event):
global theErrorLines
maxlen = 0
for line in theErrorLines:
if len(line) > maxlen:
maxlen = len(line)
width = 20+5*maxlen
height = 20+5*len(theErrorLines)
#self.report({'INFO'}, theMessage)
wm = context.window_manager
return wm.invoke_props_dialog(self, width=width, height=height)
def draw(self, context):
global theErrorLines
for line in theErrorLines:
self.layout.label(line)
def MyError(message):
global theMessage, theErrorLines, theErrorStatus
theMessage = message
theErrorLines = message.split('\n')
theErrorStatus = True
bpy.ops.mhx.error('INVOKE_DEFAULT')
raise MhxError(theMessage)
class MhxError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class SuccessOperator(bpy.types.Operator):
bl_idname = "mhx.success"
bl_label = "MHX file successfully loaded:"
message = StringProperty()
def execute(self, context):
return {'RUNNING_MODAL'}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def draw(self, context):
self.layout.label(self.message + theMessage)
###################################################################################
#
# User interface
#
###################################################################################
Campbell Barton
committed
from bpy_extras.io_utils import ImportHelper
MhxBoolProps = [
("enforce", "Enforce version", "Only accept MHX files of correct version", T_EnforceVersion),
Thomas Larsson
committed
#("crash_safe", "Crash-safe", "Disable features that have caused Blender crashes", T_CrashSafe),
("mesh", "Mesh", "Use main mesh", T_Mesh),
("proxy", "Proxies", "Use proxies", T_Proxy),
#("armature", "Armature", "Use armature", T_Armature),
#("replace", "Replace scene", "Replace scene", T_Replace),
("cage", "Cage", "Load mesh deform cage", T_Cage),
("clothes", "Clothes", "Include clothes", T_Clothes),
("shapekeys", "Shapekeys", "Include shapekeys", T_Shapekeys),
("shapedrivers", "Shapekey drivers", "Include shapekey drivers", T_ShapeDrivers),
#("symm", "Symmetric shapes", "Keep shapekeys symmetric", T_Symm),
("diamond", "Helper geometry", "Keep helper geometry", T_Diamond),
("rigify", "Rigify", "Create rigify control rig", T_Rigify),
]
class ImportMhx(bpy.types.Operator, ImportHelper):
"""Import from MHX file format (.mhx)"""
bl_idname = "import_scene.makehuman_mhx"
bl_description = 'Import from MHX file format (.mhx)'
bl_label = "Import MHX"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
filename_ext = ".mhx"
filter_glob = StringProperty(default="*.mhx", options={'HIDDEN'})
filepath = StringProperty(subtype='FILE_PATH')
scale = FloatProperty(name="Scale", description="Default meter, decimeter = 1.0", default = theScale)
advanced = BoolProperty(name="Advanced settings", description="Use advanced import settings", default=False)
for (prop, name, desc, flag) in MhxBoolProps:
expr = '%s = BoolProperty(name="%s", description="%s", default=(toggleSettings&%s != 0))' % (prop, name, desc, flag)
exec(expr)
def draw(self, context):
layout = self.layout
layout.prop(self, "scale")
layout.prop(self, "advanced")
if self.advanced:
for (prop, name, desc, flag) in MhxBoolProps:
layout.prop(self, prop)
global toggle, toggleSettings, theScale, MhxBoolProps
if not self.advanced:
toggle = DefaultToggle
else:
toggle = T_Armature
for (prop, name, desc, flag) in MhxBoolProps:
expr = '(%s if self.%s else 0)' % (flag, prop)
toggle |= eval(expr)
toggleSettings = toggle
print("execute flags %x" % toggle)
#filepathname = self.filepath.encode('utf-8', 'strict')
try:
readMhxFile(self.filepath)
bpy.ops.mhx.success('INVOKE_DEFAULT', message = self.filepath)
except MhxError:
print("Error when loading MHX file %s:\n" % self.filepath + theMessage)
if self.advanced:
writeDefaults()
self.advanced = False
global toggle, theScale, MhxBoolProps
readDefaults()
for (prop, name, desc, flag) in MhxBoolProps:
expr = 'self.%s = (toggle&%s != 0)' % (prop, flag)
exec(expr)
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
###################################################################################
#
# Lipsync panel
#
###################################################################################
#