ops_generate_tree.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. from bpy.types import Operator
  2. import bpy
  3. from .utilities import (prRed, prGreen, prPurple, prWhite,
  4. prOrange,
  5. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  6. wrapOrange,)
  7. def mantis_poll_op(context):
  8. space = context.space_data
  9. if hasattr(space, "node_tree"):
  10. if (space.node_tree):
  11. return (space.tree_type == "MantisTree")
  12. return False
  13. def create_inheritance_node(pb, parent_name, bone_inherit_node, node_tree):
  14. from bpy.types import PoseBone
  15. parent_node = node_tree.nodes.new("linkInherit")
  16. parent_bone_node = node_tree.nodes.get(parent_name)
  17. if not parent_bone_node:
  18. raise RuntimeError("Can't Find parent node!!")
  19. parent_node.location = parent_bone_node.location; parent_node.location.x+=200
  20. node_tree.links.new(parent_bone_node.outputs["xForm Out"], parent_node.inputs['Parent'])
  21. if isinstance(pb, PoseBone):
  22. parent_node.inputs["Connected"].default_value = pb.bone.use_connect
  23. parent_node.inputs["Inherit Scale"].default_value = pb.bone.inherit_scale
  24. parent_node.inputs["Inherit Rotation"].default_value = pb.bone.use_inherit_rotation
  25. else:
  26. parent_node.inputs["Connected"].default_value = False
  27. parent_node.inputs["Inherit Scale"].default_value = "FULL"
  28. parent_node.inputs["Inherit Rotation"].default_value = True
  29. if (bone_inherit_node.get(parent_bone_node.name)):
  30. bone_inherit_node[parent_bone_node.name].append(parent_node)
  31. else:
  32. bone_inherit_node[parent_bone_node.name] = [parent_node]
  33. return parent_node
  34. def get_pretty_name(name):
  35. if name == "bbone_curveinx": return "BBone X Curve-In"
  36. elif name == "bbone_curveinz": return "BBone Z Curve-In"
  37. elif name == "bbone_curveoutx": return "BBone X Curve-Out"
  38. elif name == "bbone_curveoutz": return "BBone Z Curve-Out"
  39. elif name == "BBone HQ Deformation":
  40. raise NotImplementedError(wrapRed("I wasn't expecting this property to be driven lol why would you even want to do that"))
  41. elif name == "bbone_handle_type_start": return "BBone Start Handle Type"
  42. elif name == "bbone_handle_type_end": return "BBone End Handle Type"
  43. elif name == "bbone_x": return "BBone X Size"
  44. elif name == "bbone_z": return "BBone Z Size"
  45. elif name == "bbone_rollin": return "BBone Roll-In"
  46. elif name == "bbone_rollout": return "BBone Roll-Out"
  47. elif name == "bbone_scalein": return "BBone Scale-In"
  48. elif name == "bbone_scaleout": return "BBone Scale-Out"
  49. pretty = name.replace("_", " ")
  50. words = pretty.split(" "); pretty = ''
  51. for word in words:
  52. pretty+=(word.capitalize()); pretty+=' '
  53. return pretty [:-1] #omit the last trailing space
  54. constraint_link_map={
  55. 'COPY_LOCATION' : "LinkCopyLocation",
  56. 'COPY_ROTATION' : "LinkCopyRotation",
  57. 'COPY_SCALE' : "LinkCopyScale",
  58. 'COPY_TRANSFORMS' : "LinkCopyTransforms",
  59. 'LIMIT_DISTANCE' : "LinkLimitDistance",
  60. 'LIMIT_LOCATION' : "LinkLimitLocation",
  61. 'LIMIT_ROTATION' : "LinkLimitRotation",
  62. 'LIMIT_SCALE' : "LinkLimitScale",
  63. 'DAMPED_TRACK' : "LinkDampedTrack",
  64. 'LOCKED_TRACK' : "LinkLockedTrack",
  65. 'STRETCH_TO' : "LinkStretchTo",
  66. 'TRACK_TO' : "LinkTrackTo",
  67. 'CHILD_OF' : "LinkInheritConstraint",
  68. 'IK' : "LinkInverseKinematics",
  69. 'ARMATURE' : "LinkArmature",
  70. 'SPLINE_IK' : "LinkSplineIK",
  71. 'TRANSFORM' : "LinkTransformation",
  72. }
  73. def create_relationship_node_for_constraint(node_tree, c):
  74. if cls_name := constraint_link_map.get(c.type):
  75. return node_tree.nodes.new(cls_name)
  76. else:
  77. prRed ("Not yet implemented: %s" % c.type)
  78. return None
  79. def fill_parameters(node, c, context):
  80. # just try the basic parameters...
  81. node.mute = not c.enabled
  82. if c.mute == True and c.enabled == True:
  83. node.mute = c.mute
  84. # this is obviously stupid, but it's the new API as of, IIRC, 2.80
  85. try:
  86. owner_space = c.owner_space
  87. if c.owner_space == 'CUSTOM':
  88. pass
  89. #raise NotImplementedError("Custom Space is a TODO")
  90. if ( input := node.inputs.get("Owner Space") ):
  91. input.default_value = owner_space
  92. except AttributeError:
  93. pass
  94. try:
  95. target_space = c.target_space
  96. if c.target_space == 'CUSTOM':
  97. pass
  98. #raise NotImplementedError("Custom Space is a TODO")
  99. if ( input := node.inputs.get("Target Space") ):
  100. input.default_value = target_space
  101. except AttributeError:
  102. pass
  103. try:
  104. use_x, use_y, use_z = c.use_x, c.use_y, c.use_z
  105. if ( input := node.inputs.get("Axes") ):
  106. input.default_value[0] = use_x
  107. input.default_value[1] = use_y
  108. input.default_value[2] = use_z
  109. except AttributeError:
  110. pass
  111. try:
  112. invert_x, invert_y, invert_z = c.invert_x, c.invert_y, c.invert_z
  113. if ( input := node.inputs.get("Invert") ):
  114. input.default_value[0] = invert_x
  115. input.default_value[1] = invert_y
  116. input.default_value[2] = invert_z
  117. except AttributeError:
  118. pass
  119. try:
  120. influence = c.influence
  121. if ( input := node.inputs.get("Influence") ):
  122. input.default_value = influence
  123. except AttributeError:
  124. pass
  125. # gonna dispense with the try/except from here on
  126. if (c.type == 'COPY_LOCATION'):
  127. node.inputs["Head/Tail"].default_value = c.head_tail
  128. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  129. elif (c.type == 'COPY_ROTATION'):
  130. node.inputs["RotationOrder"].default_value = c.euler_order
  131. # ofset (legacy) is not supported TODO BUG
  132. if (mix_mode := c.mix_mode) == 'OFFSET':
  133. mix_mode = 'AFTER'
  134. node.inputs["Rotation Mix"].default_value = mix_mode
  135. elif (c.type == 'COPY_SCALE'):
  136. #node.inputs["Additive"].default_value = c.use_make_uniform # not yet implemented
  137. #node.inputs["Power"].default_value = c.head_tail
  138. node.inputs["Average"].default_value = c.use_make_uniform
  139. node.inputs["Offset"].default_value = c.use_offset
  140. elif (c.type == 'COPY_TRANSFORMS'):
  141. node.inputs["Head/Tail"].default_value = c.head_tail
  142. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  143. node.inputs["Mix"].default_value = c.mix_mode
  144. elif (c.type == 'LIMIT_DISTANCE'):
  145. print ("Not yet handled: ", c.type)
  146. elif (c.type in ['LIMIT_LOCATION', 'LIMIT_ROTATION', 'LIMIT_SCALE']):
  147. # print (c.type)
  148. try:
  149. node.inputs["Use Max X"].default_value = c.use_max_x
  150. node.inputs["Use Max Y"].default_value = c.use_max_y
  151. node.inputs["Use Max Z"].default_value = c.use_max_z
  152. #
  153. node.inputs["Use Min X"].default_value = c.use_min_x
  154. node.inputs["Use Min Y"].default_value = c.use_min_y
  155. node.inputs["Use Min Z"].default_value = c.use_min_z
  156. except AttributeError: # rotation
  157. node.inputs["Use X"].default_value = c.use_limit_x
  158. node.inputs["Use Y"].default_value = c.use_limit_y
  159. node.inputs["Use Z"].default_value = c.use_limit_z
  160. node.inputs["Max X"].default_value = c.max_x
  161. node.inputs["Max Y"].default_value = c.max_y
  162. node.inputs["Max Z"].default_value = c.max_z
  163. #
  164. node.inputs["Min X"].default_value = c.min_x
  165. node.inputs["Min Y"].default_value = c.min_y
  166. node.inputs["Min Z"].default_value = c.min_z
  167. elif (c.type == 'DAMPED_TRACK'):
  168. node.inputs["Head/Tail"].default_value = c.head_tail
  169. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  170. node.inputs["Track Axis"].default_value = c.track_axis
  171. elif (c.type == 'LOCKED_TRACK'):
  172. node.inputs["Head/Tail"].default_value = c.head_tail
  173. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  174. node.inputs["Track Axis"].default_value = c.track_axis
  175. node.inputs["Lock Axis"].default_value = c.lock_axis
  176. elif (c.type == 'STRETCH_TO'):
  177. node.inputs["Head/Tail"].default_value = c.head_tail
  178. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  179. node.inputs["Volume Variation"].default_value = c.bulge
  180. node.inputs["Use Volume Min"].default_value = c.use_bulge_min
  181. node.inputs["Volume Min"].default_value = c.bulge_min
  182. node.inputs["Use Volume Max"].default_value = c.use_bulge_max
  183. node.inputs["Volume Max"].default_value = c.bulge_max
  184. node.inputs["Smooth"].default_value = c.bulge_smooth
  185. node.inputs["Maintain Volume"].default_value = c.volume
  186. node.inputs["Rotation"].default_value = c.keep_axis
  187. elif (c.type == 'TRACK_TO'):
  188. print ("Not yet handled: ", c.type)
  189. elif (c.type == 'CHILD_OF'):
  190. print ("Not yet handled: ", c.type)
  191. elif (c.type == 'IK'):
  192. node.inputs["Chain Length"].default_value = c.chain_count
  193. node.inputs["Use Tail"].default_value = c.use_tail
  194. node.inputs["Stretch"].default_value = c.use_stretch
  195. # this isn't quite right lol
  196. node.inputs["Position"].default_value = c.weight
  197. node.inputs["Rotation"].default_value = c.orient_weight
  198. if not (c.use_location):
  199. node.inputs["Position"].default_value = 0
  200. if not (c.use_rotation):
  201. node.inputs["Rotation"].default_value = 0
  202. elif (c.type == 'ARMATURE'):
  203. node.inputs["Preserve Volume"].default_value = c.use_deform_preserve_volume
  204. node.inputs["Use Envelopes"].default_value = c.use_bone_envelopes
  205. node.inputs["Use Current Location"].default_value = c.use_current_location
  206. for i in range(len(c.targets)):
  207. with context.temp_override(node=node):
  208. bpy.ops.mantis.link_armature_node_add_target()
  209. node.inputs["Weight."+str(i).zfill(3)].default_value = c.targets[i].weight
  210. elif (c.type == 'SPLINE_IK'):
  211. node.inputs["Chain Length"].default_value = c.chain_count
  212. node.inputs["Even Divisions"].default_value = c.use_even_divisions
  213. node.inputs["Chain Offset"].default_value = c.use_chain_offset
  214. node.inputs["Use Curve Radius"].default_value = c.use_curve_radius
  215. node.inputs["Y Scale Mode"].default_value = c.y_scale_mode
  216. node.inputs["XZ Scale Mode"].default_value = c.xz_scale_mode
  217. elif (c.type == 'TRANSFORM'):
  218. # I can't be arsed to do all this work..
  219. from .link_nodes import transformation_props_sockets as props
  220. for prop, (sock_name, _unused) in props.items():
  221. if "from" in prop:
  222. if prop in ["map_from"] or "to" in prop:
  223. pass
  224. elif c.map_from == 'LOCATION':
  225. if "scale" in prop:
  226. continue
  227. if "rot" in prop:
  228. continue
  229. elif c.map_from == 'ROTATION':
  230. if "rot" not in prop:
  231. continue
  232. elif c.map_from == 'SCALE':
  233. if "scale" not in prop:
  234. continue
  235. if "to" in prop:
  236. if prop in ["map_to"] or "from" in prop:
  237. pass
  238. elif c.map_from == 'LOCATION':
  239. if "scale" in prop:
  240. continue
  241. if "rot" in prop:
  242. continue
  243. elif c.map_from == 'ROTATION':
  244. if "rot" not in prop:
  245. continue
  246. elif c.map_from == 'SCALE':
  247. if "scale" not in prop:
  248. continue
  249. node.inputs[sock_name].default_value = getattr(c, prop)
  250. if prop in "mute":
  251. node.inputs[sock_name].default_value = not getattr(c, prop)
  252. # should probably do it this way all over actually.
  253. else:
  254. raise NotImplementedError("Not handled yet: %s" % c.type)
  255. return None
  256. def walk_edit_bone(armOb, bone):
  257. # this is a simplified version of the node-tree walking code
  258. bonePath, bones, lines, seek = [0,], set(), [], bone
  259. while (True):
  260. curheight = len(bonePath)-1; ind = bonePath[-1]
  261. if (curheight == 0) and (ind > len(bone.children)-1):
  262. break
  263. if (curheight > 0):
  264. parent = seek.parent
  265. if (ind > len(seek.children)-1 ):
  266. bonePath[curheight-1]+=1
  267. del bonePath[curheight]
  268. seek = parent
  269. continue
  270. # should work...
  271. seek = get_bone_from_path(bone, bonePath)
  272. if (seek.name not in bones):
  273. lines.append(bonePath.copy())
  274. bones.add(seek.name)
  275. if (seek.children):
  276. bonePath.append(0)
  277. else:
  278. bonePath[curheight] = bonePath[curheight] + 1
  279. seek = seek.parent
  280. return lines
  281. def get_bone_from_path(root_bone, path):
  282. # this function assumes the path is valid
  283. path = path.copy(); bone = root_bone
  284. while(path):
  285. bone = bone.children[path.pop(0)]
  286. return bone
  287. def setup_custom_properties(bone_node, pb):
  288. for k, v in pb.items(): # Custom Properties
  289. socktype, prop_type = '', type(v)
  290. # print (prop_type)
  291. if prop_type == bool:
  292. socktype = 'ParameterBoolSocket'
  293. elif prop_type == int:
  294. socktype = 'ParameterIntSocket'
  295. elif prop_type == float:
  296. socktype = 'ParameterFloatSocket'
  297. elif prop_type == bpy.props.FloatVectorProperty:
  298. socktype = 'ParameterVectorSocket'
  299. elif prop_type == str:
  300. socktype = 'ParameterStringSocket'
  301. else:
  302. continue # it's a PointerProp or something
  303. #if self.prop_type == 'ENUM':
  304. # sock_type = 'ParameterStringSocket'
  305. new_prop = bone_node.inputs.new( socktype, k)
  306. bone_node.outputs.new( socktype, k)
  307. # set its value and limits and such
  308. # from rna_prop_ui import rna_idprop_ui_create
  309. # I have no idea how to get the data in a sane way, I guess I will use this...
  310. ui_data = pb.id_properties_ui(k).as_dict()
  311. new_prop.default_value = ui_data['default']
  312. try:
  313. new_prop.min = ui_data['min']
  314. new_prop.max = ui_data['max']
  315. new_prop.soft_min = ui_data['soft_min']
  316. new_prop.soft_max = ui_data['soft_max']
  317. except AttributeError:
  318. pass # it's not a number
  319. except KeyError:
  320. pass # same, or not defined maybe
  321. try:
  322. new_prop.description = ui_data['description']
  323. except KeyError:
  324. prOrange("Figure out why this happens?")
  325. def setup_ik_settings(bone_node, pb):
  326. # Set Up IK settings:
  327. stiffness = [pb.ik_stiffness_x, pb.ik_stiffness_y, pb.ik_stiffness_z]
  328. lock = [pb.lock_ik_x, pb.lock_ik_y, pb.lock_ik_z]
  329. limit = [pb.use_ik_limit_x, pb.use_ik_limit_y, pb.use_ik_limit_z]
  330. bone_node.inputs["IK Stretch"].default_value = pb.ik_stretch
  331. bone_node.inputs["Lock IK"].default_value = lock
  332. bone_node.inputs["IK Stiffness"].default_value = stiffness
  333. bone_node.inputs["Limit IK"].default_value = limit
  334. bone_node.inputs["X Min"].default_value = pb.ik_min_x
  335. bone_node.inputs["X Max"].default_value = pb.ik_max_x
  336. bone_node.inputs["Y Min"].default_value = pb.ik_min_y
  337. bone_node.inputs["Y Max"].default_value = pb.ik_max_y
  338. bone_node.inputs["Z Min"].default_value = pb.ik_min_z
  339. bone_node.inputs["Z Max"].default_value = pb.ik_max_z
  340. def setup_vp_settings(bone_node, pb, do_after, node_tree):
  341. # bone_node.inputs["Hide"].default_value = pb.bone.hide
  342. bone_node.inputs["Custom Object Scale"].default_value = pb.custom_shape_scale_xyz
  343. bone_node.inputs["Custom Object Translation"].default_value = pb.custom_shape_translation
  344. bone_node.inputs["Custom Object Rotation"].default_value = pb.custom_shape_rotation_euler
  345. bone_node.inputs["Custom Object Scale to Bone Length"].default_value = pb.use_custom_shape_bone_size
  346. bone_node.inputs["Custom Object Wireframe"].default_value = pb.bone.show_wire
  347. # bone_node.inputs["Layer Mask"].default_value = pb.bone.layers
  348. collection_membership = ''
  349. for col in pb.bone.collections:
  350. # TODO: implement this!
  351. pass
  352. bone_node.inputs["Bone Collection"].default_value = collection_membership
  353. if (shape_ob := pb.custom_shape):
  354. shape_n = None
  355. for n in node_tree.nodes:
  356. if n.name == shape_ob.name:
  357. shape_n = n
  358. break
  359. else: # we make it now
  360. shape_n = node_tree.nodes.new("InputExistingGeometryObject")
  361. shape_n.name = shape_ob.name
  362. shape_n.label = shape_ob.name
  363. shape_n.inputs["Name"].default_value = shape_ob.name
  364. node_tree.links.new(shape_n.outputs["Object"], bone_node.inputs['Custom Object'])
  365. if (shape_xform_ob := pb.custom_shape_transform): # not implemented just yet
  366. shape_xform_n = None
  367. for n in node_tree.nodes:
  368. if n.name == shape_xform_ob.name:
  369. shape_xform_n = n
  370. node_tree.links.new(shape_xform_n.outputs["xForm"], bone_node.inputs['Custom Object xForm Override'])
  371. break
  372. else: # make it a task
  373. do_after.add( ("Custom Object xForm Override", bone_node.name , shape_xform_ob.name ) )
  374. # all the above should be in a function.
  375. def setup_df_settings(bone_node, pb):
  376. bone_node.inputs["Deform"].default_value = pb.bone.use_deform
  377. # TODO: get the rest of these working
  378. # eb.envelope_distance = self.evaluate_input("Envelope Distance")
  379. # eb.envelope_weight = self.evaluate_input("Envelope Weight")
  380. # eb.use_envelope_multiply = self.evaluate_input("Envelope Multiply")
  381. # eb.head_radius = self.evaluate_input("Envelope Head Radius")
  382. # eb.tail_radius = self.evaluate_input("Envelope Tail Radius")
  383. def create_driver(in_node_name, out_node_name, armOb, finished_drivers, switches, driver_vars, fcurves, drivers, node_tree, context):
  384. # TODO: CLEAN this ABOMINATION
  385. print ("DRIVER: ", in_node_name, out_node_name)
  386. in_node = node_tree.nodes[ in_node_name]
  387. out_node = node_tree.nodes[out_node_name]
  388. for fc in armOb.animation_data.drivers:
  389. if (in_node.label not in fc.data_path) or ( "[\""+out_node.label+"\"]" not in fc.data_path):
  390. # print ("node not in name?: %s" % fc.data_path)
  391. continue
  392. if fc.data_path in finished_drivers:
  393. continue
  394. finished_drivers.add(fc.data_path)
  395. print ("Creating driver.... %s" % fc.data_path)
  396. keys = []
  397. for k in fc.keyframe_points:
  398. key = {}
  399. for prop in dir(k):
  400. if ("__" in prop) or ("bl_" in prop): continue
  401. #it's __name__ or bl_rna or something
  402. key[prop] = getattr(k, prop)
  403. keys.append(key)
  404. switch, inverted = False, False
  405. if (fc.evaluate(0) == 0) and (fc.evaluate(1) == 1):
  406. switch = True
  407. elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  408. switch = True; inverted = True
  409. if (fc.driver.type == 'SCRIPTED'):
  410. #print (fc.driver.expression)
  411. if not (len(fc.driver.variables) == 1 and fc.driver.expression == fc.driver.variables[0].name):
  412. switch = False
  413. if (switch):
  414. # OK, let's prepare before making the node
  415. # we want to reuse existing nodes if possible.
  416. target_string = fc.driver.variables[0].targets[0].data_path
  417. if target_string == "":
  418. for var in fc.driver.variables:
  419. print (var)
  420. print (var.name)
  421. print (var.targets)
  422. bone = target_string.split("pose.bones[\"")[1]
  423. bone = bone.split("\"]")[0]
  424. bone_node = node_tree.nodes.get(bone)
  425. if not (bone_node):
  426. raise RuntimeError("excpected to find....", bone)
  427. p_string = fc.driver.variables[0].targets[0].data_path
  428. p_string = p_string.split("[\"")[-1]; p_string = p_string.split("\"]")[0]
  429. #switch_node.inputs["Parameter"].default_value = p_string
  430. #switch_node.inputs["Parameter Index"].default_value = fc.array_index
  431. #switch_node.inputs["Invert Switch"].default_value = inverted
  432. parameter = fc.data_path
  433. # Try to find an existing node.
  434. fail = False
  435. switch_node = None
  436. for n in switches:
  437. # if n.inputs[0].is_linked:
  438. # if n.inputs[0].links[0].from_node != bone_node:
  439. # fail = True
  440. if n.inputs[0].is_linked:
  441. if n.inputs[0].links[0].from_node != bone_node:
  442. fail = True
  443. if n.inputs[0].links[0].from_socket != bone_node.outputs.get(p_string):
  444. fail = True
  445. else:
  446. if n.inputs[0].default_value != p_string:
  447. fail = True
  448. if n.inputs[1].default_value != fc.array_index:
  449. fail = True
  450. if n.inputs[2].default_value != inverted:
  451. fail = True
  452. if not fail:
  453. switch_node = n
  454. break # found it!
  455. else:
  456. # make and connect the switch node
  457. switch_node = node_tree.nodes.new("UtilitySwitch"); switches.append(switch_node)
  458. # node_tree.links.new(bone_node.outputs["xForm Out"], switch_node.inputs[0])
  459. try:
  460. node_tree.links.new(bone_node.outputs[p_string], switch_node.inputs[0])
  461. except KeyError:
  462. prRed("this is such bad code lol fix this", p_string)
  463. switch_node.inputs[1].default_value = fc.array_index
  464. switch_node.inputs[2].default_value = inverted
  465. #print (" Inverted? ", inverted, (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0), switch_node.inputs[3].default_value)
  466. if not inverted:
  467. print (" --> Check this node: %s" % switch_node.name)
  468. # this may be a custom property or a normal property...
  469. # this should lead to a constraint
  470. if len(parameter.split("[\"") ) == 3:
  471. property = parameter.split(".")[-1]
  472. if (property == 'mute'): # this is mapped to the 'Enable' socket...
  473. prop_in = out_node.inputs.get('Enable')
  474. else:
  475. prop_in = out_node.inputs.get(get_pretty_name(property))
  476. if prop_in:
  477. node_tree.links.new(switch_node.outputs["Driver"], prop_in)
  478. else:
  479. print (" couldn't find: ", property, out_node.label, out_node.name)
  480. # this won't always work tho
  481. #Finally, it should be noted that we are assuming it uses the same object ...
  482. # drivers from Rigify always should use the same object, but I want to support
  483. # detecting drivers across objects.
  484. else: # we'll have to set this one up manually
  485. # Let's make the variable nodes, the Driver node, and the fCurve node.
  486. # Get the variable information
  487. if (True):
  488. var_nodes = []; num_vars = 0
  489. for num_vars, var in enumerate(fc.driver.variables):
  490. target1, target2, bone_target, bone_target2 = [None]*4
  491. var_data = {}
  492. var_data["Variable Type"] = var.type
  493. var_data["Property"] = ""
  494. if len(var.targets) >= 1:
  495. target1 = var.targets[0]
  496. if (var_data["Variable Type"] != 'SINGLE_PROP'):
  497. bone_target = var.targets[0].bone_target
  498. else: # figure it out by the data path string.
  499. target_string = var.targets[0].data_path
  500. bone_target = target_string.split("pose.bones[\"")[1]; bone_target = bone_target.split("\"]")[0]
  501. # we also need to get the property.
  502. p_string = fc.driver.variables[0].targets[0].data_path
  503. p_string = p_string.split("[\"")[-1]; p_string = p_string.split("\"]")[0]
  504. var_data["Property"] = p_string
  505. if (var_data["Variable Type"] == 'TRANSFORMS'):
  506. transform_channel_map = {
  507. "LOC_X" : ('location', 0),
  508. "LOC_Y" : ('location', 1),
  509. "LOC_Z" : ('location', 2),
  510. "ROT_X" : ('rotation', 0),
  511. "ROT_Y" : ('rotation', 1),
  512. "ROT_Z" : ('rotation', 2),
  513. "ROT_W" : ('rotation', 3),
  514. "SCALE_X" : ('scale', 0),
  515. "SCALE_Y" : ('scale', 1),
  516. "SCALE_Z" : ('scale', 2),
  517. "SCALE_AVG" : ('scale', 3), }
  518. # if (var.transform_type in transform_channel_map.keys()):
  519. # var_data["Property"], var_data["Property Index"] = transform_channel_map[var.transform_type]
  520. prRed("I am pretty sure this thing does not friggin work with whatever it is I commented above...")
  521. var_data["Evaluation Space"] = var.targets[0].transform_space
  522. var_data["Rotation Mode"] = var.targets[0].rotation_mode
  523. if len(var.targets) == 2:
  524. target2 = var.targets[1]
  525. bone_target2 = var.targets[1].bone_target
  526. # check if the variable already exists in the tree.
  527. target_node1, target_node2 = None, None
  528. if (target1 and bone_target):
  529. target_node1 = node_tree.nodes[bone_target]
  530. elif (target1 and not bone_target):
  531. target_node1 = node_tree.nodes[target1]
  532. if (target2 and bone_target2):
  533. target_node2 = node_tree.nodes[bone_target2]
  534. elif (target2 and not bone_target2):
  535. target_node2 = node_tree.nodes[target2]
  536. var_node = None
  537. for n in driver_vars:
  538. fail = False
  539. if (inp := n.inputs['xForm 1']).is_linked:
  540. if inp.links[0].from_node != target_node1:
  541. fail = True
  542. if (inp := n.inputs['xForm 2']).is_linked:
  543. if inp.links[0].from_node != target_node2:
  544. fail = True
  545. #
  546. if n.inputs[0].default_value != var_data["Variable Type"]:
  547. fail = True
  548. if n.inputs[1].default_value != var_data["Property"]:
  549. fail = True
  550. try:
  551. if n.inputs[2].default_value != var_data["Property Index"]:
  552. fail = True
  553. if n.inputs[3].default_value != var_data["Evaluation Space"]:
  554. fail = True
  555. if n.inputs[4].default_value != var_data["Rotation Mode"]:
  556. fail = True
  557. except KeyError:
  558. pass # this is a SCRIPTED node it seems
  559. if not fail:
  560. var_node = n
  561. prWhite("Variable Node Found %s!" % var_node )
  562. break # found it!
  563. else:
  564. var_node = node_tree.nodes.new("UtilityDriverVariable"); driver_vars.append(var_node)
  565. prRed("Creating Node: %s" % var_node.name)
  566. for key, value in var_data.items():
  567. try:
  568. var_node.inputs[key].default_value = value
  569. except TypeError as e: # maybe it is a variable\
  570. if key == "Variable Type":
  571. var_node.inputs[key].default_value = "SINGLE_PROP"
  572. else: raise e
  573. if (target1 and bone_target):
  574. node_tree.links.new(node_tree.nodes[bone_target].outputs['xForm Out'], var_node.inputs['xForm 1'])
  575. elif (target1 and not bone_target):
  576. node_tree.links.new(node_tree.nodes[target1].outputs['xForm Out'], var_node.inputs['xForm 1'])
  577. if (target2 and bone_target2):
  578. node_tree.links.new(node_tree.nodes[bone_target2].outputs['xForm Out'], var_node.inputs['xForm 2'])
  579. elif (target2 and not bone_target2):
  580. node_tree.links.new(node_tree.nodes[target2].outputs['xForm Out'], var_node.inputs['xForm 2'])
  581. var_nodes.append(var_node)
  582. num_vars+=1 # so the len(num_vars) will be correct
  583. # get the keyframes from the driver fCurve
  584. keys = {}
  585. from mathutils import Vector
  586. if len(fc.keyframe_points) > 0:
  587. # TODO: make this do more than co_ui
  588. for i, k in enumerate(fc.keyframe_points):
  589. keys[i] = {'co_ui':k.co_ui}
  590. # print (fc.data_path)
  591. # print (len(fc.keyframe_points))
  592. # raise NotImplementedError("Not needed for first milestone")
  593. else:
  594. # fc_ob = fCurve_node.fake_fcurve_ob
  595. # node_fc = fc_ob.animation_data.action.fcurves[0]
  596. # fc.keyframe_points.add(2)
  597. if ((len(fc.modifiers) == 0) or ((fc.evaluate(0) == 0) and (fc.evaluate(1) == 1))):
  598. keys[0] = {'co_ui':Vector((0, 0))}
  599. keys[1] = {'co_ui':Vector((1, 1))}
  600. elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  601. keys[0] = {'co_ui':Vector((0, 1))}
  602. keys[1] = {'co_ui':Vector((1, 0))}
  603. else:
  604. print ("Could not get keys!")
  605. # TODO find out why this happens
  606. # I HAVE NO IDEA
  607. pass
  608. # elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  609. # kf0 = fc.keyframe_points[0]; kf0.co_ui = (0, 1)
  610. # kf1 = fc.keyframe_points[1]; kf1.co_ui = (1, 0)
  611. # now get the fCurve
  612. fCurve_node = None
  613. for n in fcurves:
  614. fc_ob = n.fake_fcurve_ob; node_fc = fc_ob.animation_data.action.fcurves[0]
  615. node_keys = {}
  616. for i, k in enumerate(node_fc.keyframe_points):
  617. node_keys[i] = {'co_ui':k.co_ui}
  618. # now let's see if they are the same:
  619. if (keys != node_keys):
  620. continue
  621. fCurve_node = n
  622. break
  623. else:
  624. fCurve_node = node_tree.nodes.new("UtilityFCurve")
  625. # fc_ob = fCurve_node.fake_fcurve_ob
  626. # node_fc = fc_ob.animation_data.action.fcurves[0]
  627. # fcurves.append(fCurve_node)
  628. # while(node_fc.keyframe_points): # clear it, it has a default FC
  629. # node_fc.keyframe_points.remove(node_fc.keyframe_points[0], fast=True)
  630. # node_fc.update()
  631. # node_fc.keyframe_points.add(len(keys))
  632. # for k, v in keys.items():
  633. # node_fc.keyframe_points[k].co_ui = v['co_ui']
  634. # # todo eventually the other dict elements ofc
  635. for num_keys, (k, v) in enumerate(keys.items()):
  636. fCurve_node.inputs.new("KeyframeSocket", "Keyframe."+str(num_keys).zfill(3))
  637. kf_node = node_tree.nodes.new("UtilityKeyframe")
  638. kf_node.inputs[0].default_value = v['co_ui'][0]
  639. kf_node.inputs[1].default_value = v['co_ui'][1]
  640. node_tree.links.new(kf_node.outputs[0], fCurve_node.inputs[num_keys])
  641. # NOW the driver itself
  642. driver_node = None
  643. # checc for it...
  644. driver_node = node_tree.nodes.new("UtilityDriver")
  645. driver_node.inputs["Driver Type"].default_value = fc.driver.type
  646. driver_node.inputs["Expression"].default_value = fc.driver.expression.replace ('var', 'a')
  647. # HACK, fix the above with a more robust solution
  648. node_tree.links.new(fCurve_node.outputs[0], driver_node.inputs['fCurve'])
  649. for i, var_node in zip(range(num_vars), var_nodes):
  650. # TODO TODO BUG HACK
  651. with context.temp_override(node=driver_node):
  652. bpy.ops.mantis.driver_node_add_variable()
  653. # This causes an error when you run it from the console! DO NOT leave this
  654. node_tree.links.new(var_node.outputs[0], driver_node.inputs[-1])
  655. # HACK duplicated code from earlier...
  656. parameter = fc.data_path
  657. prWhite( "parameter: %s" % parameter)
  658. property = ''
  659. if len(parameter.split("[\"") ) == 3:
  660. property = parameter.split(".")[-1]
  661. if (property == 'mute'): # this is mapped to the 'Enable' socket...
  662. prop_in = out_node.inputs.get('Enable')
  663. else:
  664. prop_in = out_node.inputs.get(get_pretty_name(property))
  665. if not prop_in: # this is a HACK because my solution is terrible and also bad
  666. if property == "head_tail":
  667. prop_in = out_node.inputs.get("Head/Tail")
  668. # the socket should probably know what Blender thing is being mapped to it as a custom prop
  669. if not prop_in:
  670. # try one last thing:
  671. property = parameter.split("targets[")[-1]
  672. target_index = int(property[0])
  673. property = "targets[" + property # HACK lol
  674. # get the property by index...
  675. prop_in = out_node.inputs[target_index*2+6+1] # this is the weight, not the target
  676. if prop_in:
  677. prRed (" found: %s, %s, %s" % (property, out_node.label, out_node.name))
  678. node_tree.links.new(driver_node.outputs["Driver"], prop_in)
  679. else:
  680. prRed (" couldn't find: %s, %s, %s" % (property, out_node.label, out_node.name))
  681. elif len(parameter.split("[\"") ) == 2:
  682. # print (parameter.split("[\"") ); raise NotImplementedError
  683. property = parameter.split(".")[-1]
  684. else:
  685. prWhite( "parameter: %s" % parameter)
  686. prRed (" couldn't find: ", property, out_node.label, out_node.name)
  687. def set_parent_from_node(pb, bone_inherit_node, node_tree):
  688. bone = pb.bone
  689. possible_parent_nodes = bone_inherit_node.get(bone.parent.name)
  690. # Set the parent
  691. parent = None
  692. if not (possible_parent_nodes):
  693. parent = create_inheritance_node(pb, bone.parent.name, bone_inherit_node, node_tree)
  694. else:
  695. for ppn in possible_parent_nodes:
  696. # check if it has the right connected, inherit scale, inherit rotation
  697. if ppn.inputs["Connected"].default_value != pb.bone.use_connect:
  698. continue
  699. if ppn.inputs["Inherit Scale"].default_value != pb.bone.inherit_scale:
  700. continue
  701. if ppn.inputs["Inherit Rotation"].default_value != pb.bone.use_inherit_rotation:
  702. continue
  703. parent = ppn; break
  704. else:
  705. parent = create_inheritance_node(pb, bone.parent.name, bone_inherit_node, node_tree)
  706. return parent
  707. def do_generate_geom(ob, node_tree, parent_node=None):
  708. ob_node = node_tree.nodes.new("xFormGeometryObject")
  709. ob_node.name = ob.name; ob_node.label = ob.name
  710. ob_node.inputs["Name"].default_value=ob.name+"_MANTIS"
  711. if ob.data:
  712. geometry_node = node_tree.nodes.new("InputExistingGeometryData")
  713. geometry_node.inputs[0].default_value=ob.data.name
  714. node_tree.links.new(input=geometry_node.outputs[0], output=ob_node.inputs["Geometry"])
  715. matrix_of = node_tree.nodes.new("UtilityMatrixFromXForm")
  716. existing_ob = node_tree.nodes.new("InputExistingGeometryObject")
  717. existing_ob.inputs["Name"].default_value = ob.name
  718. node_tree.links.new(input=existing_ob.outputs[0], output=matrix_of.inputs[0])
  719. node_tree.links.new(input=matrix_of.outputs[0], output=ob_node.inputs["Matrix"])
  720. # Generate Deformers
  721. prev_def_node = None
  722. for m in ob.modifiers:
  723. if m.type == "ARMATURE":
  724. def_node = node_tree.nodes.new("DeformerArmature")
  725. def_node.inputs["Blend Vertex Group"].default_value = m.vertex_group
  726. def_node.inputs["Invert Vertex Group"].default_value = m.invert_vertex_group
  727. def_node.inputs["Preserve Volume"].default_value = m.use_deform_preserve_volume
  728. def_node.inputs["Use Multi Modifier"].default_value = m.use_multi_modifier
  729. def_node.inputs["Use Envelopes"].default_value = m.use_bone_envelopes
  730. def_node.inputs["Use Vertex Groups"].default_value = m.use_vertex_groups
  731. # def_node.inputs["Copy Skin Weights From"]
  732. def_node.inputs["Skinning Method"].default_value="EXISTING_GROUPS"
  733. def_ob = node_tree.nodes.get(m.object.name)
  734. # get the deformer's target object...
  735. if def_ob:
  736. node_tree.links.new(input=def_ob.outputs["xForm Out"], output=def_node.inputs["Armature Object"])
  737. if prev_def_node:
  738. node_tree.links.new(input=prev_def_node.outputs["Deformer"], inputs=def_node.inputs["Deformer"])
  739. prev_def_node = def_node
  740. if prev_def_node:
  741. node_tree.links.new(input=prev_def_node.outputs["Deformer"], output=ob_node.inputs["Deformer"])
  742. if parent_node:
  743. node_tree.links.new(input=parent_node.outputs["Inheritance"], output=ob_node.inputs["Relationship"])
  744. # not doing this
  745. # matrix_node = node_tree.nodes.new("InputMatrix")
  746. # matrix_node.first_row=ob.matrix_world[0:3]
  747. # matrix_node.second_row=ob.matrix_world[4:7]
  748. # matrix_node.third_row=ob.matrix_world[8:11]
  749. # matrix_node.fourth_row=ob.matrix_world[12:15]
  750. # node_tree.links.new(input=matrix_node.outputs[0], output=ob_node.inputs["Matrix"])
  751. def do_generate_armature(armOb, context, node_tree, parent_node=None):
  752. from time import time
  753. start = time()
  754. meta_rig_nodes = {}
  755. bone_inherit_node = {}
  756. do_after = set()
  757. armature = node_tree.nodes.new("xFormArmatureNode")
  758. mr_node_name = armOb.name
  759. if not (mr_node:= meta_rig_nodes.get(mr_node_name)):
  760. mr_node = node_tree.nodes.new("UtilityMetaRig")
  761. meta_rig_nodes[mr_node_name] = mr_node
  762. mr_node.inputs[0].search_prop=armOb
  763. node_tree.links.new(input=mr_node.outputs[0], output=armature.inputs["Matrix"])
  764. if parent_node:
  765. node_tree.links.new()
  766. bones = []
  767. for root in armOb.data.bones:
  768. if root.parent is None:
  769. iter_start= time()
  770. milestone=time()
  771. prPurple("got the bone paths", time() - milestone); milestone=time()
  772. armature.inputs["Name"].default_value = armOb.name + "_MANTIS"
  773. armature.name = armOb.name; armature.label = armOb.name
  774. bones.extend([root])
  775. if parent_node:
  776. node_tree.links.new(input=parent_node.outputs["Inheritance"], output=armature.inputs["Relationship"])
  777. # for bone_path in lines:
  778. for bone in bones:
  779. prGreen(time() - milestone); milestone=time()
  780. # first go through the bone path and find relevant information
  781. bone_node = node_tree.nodes.new("xFormBoneNode")
  782. bone_node.inputs["Name"].default_value = bone.name
  783. bone_node.name, bone_node.label = bone.name, bone.name
  784. matrix = bone.matrix_local.copy()
  785. bone_node.inputs["Matrix"].default_value = [
  786. matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
  787. matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
  788. matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], # last element is bone length, for mantis
  789. matrix[3][0], matrix[3][1], matrix[3][2], bone.length ] #matrix[3][3], ]
  790. mr_node_name = armOb.name+":"+bone.name
  791. if not (mr_node:= meta_rig_nodes.get(mr_node_name)):
  792. mr_node = node_tree.nodes.new("UtilityMetaRig")
  793. meta_rig_nodes[mr_node_name] = mr_node
  794. mr_node.inputs[0].search_prop=armOb
  795. mr_node.inputs[1].search_prop=armOb
  796. mr_node.inputs[1].bone=bone.name
  797. mr_node.inputs[1].default_value=bone.name
  798. node_tree.links.new(input=mr_node.outputs[0], output=bone_node.inputs["Matrix"])
  799. pb = armOb.pose.bones[bone.name]
  800. if bone.parent: # not a root
  801. parent = set_parent_from_node(pb, bone_inherit_node, node_tree)
  802. print("Got parent node", time() - milestone); milestone=time()
  803. if parent is None:
  804. raise RuntimeError("No parent node?")
  805. else: # This is a root
  806. if (parent := bone_inherit_node.get(armOb.name)) is None:
  807. parent = node_tree.nodes.new("linkInherit")
  808. bone_inherit_node[armOb.name] = [parent]
  809. node_tree.links.new(armature.outputs["xForm Out"], parent.inputs['Parent'])
  810. parent.inputs["Inherit Rotation"].default_value = True
  811. node_tree.links.new(parent.outputs["Inheritance"], bone_node.inputs['Relationship'])
  812. bone_node.inputs["Lock Location"].default_value = pb.lock_location
  813. bone_node.inputs["Lock Rotation"].default_value = pb.lock_rotation
  814. bone_node.inputs["Lock Scale"].default_value = pb.lock_scale
  815. bone_node.inputs["Rotation Order"].default_value = pb.rotation_mode
  816. setup_custom_properties(bone_node, pb)
  817. setup_ik_settings(bone_node, pb)
  818. setup_vp_settings(bone_node, pb, do_after, node_tree)
  819. setup_df_settings(bone_node, pb)
  820. # BBONES
  821. bone_node.inputs["BBone X Size"].default_value = pb.bone.bbone_x
  822. bone_node.inputs["BBone Z Size"].default_value = pb.bone.bbone_z
  823. bone_node.inputs["BBone Segments"].default_value = pb.bone.bbone_segments
  824. if pb.bone.bbone_mapping_mode == "CURVED":
  825. bone_node.inputs["BBone HQ Deformation"].default_value = True
  826. bone_node.inputs["BBone Start Handle Type"].default_value = pb.bone.bbone_handle_type_start
  827. bone_node.inputs["BBone End Handle Type"].default_value = pb.bone.bbone_handle_type_end
  828. bone_node.inputs["BBone Custom Start Handle"].default_value = pb.bone.bbone_handle_type_start
  829. bone_node.inputs["BBone Custom End Handle"].default_value = pb.bone.bbone_handle_type_end
  830. bone_node.inputs["BBone X Curve-In"].default_value = pb.bone.bbone_curveinx
  831. bone_node.inputs["BBone Z Curve-In"].default_value = pb.bone.bbone_curveinz
  832. bone_node.inputs["BBone X Curve-Out"].default_value = pb.bone.bbone_curveoutx
  833. bone_node.inputs["BBone Z Curve-Out"].default_value = pb.bone.bbone_curveoutz
  834. prRed("BBone Implementation is not complete, expect errors and missing features for now")
  835. #
  836. for c in pb.constraints:
  837. prWhite("constraint %s for %s" % (c.name, pb.name), time() - milestone); milestone=time()
  838. # make relationship nodes and set up links...
  839. if ( c_node := create_relationship_node_for_constraint(node_tree, c)):
  840. c_node.label = c.name
  841. # this node definitely has a parent inherit node.
  842. c_node.location = parent.location; c_node.location.x += 200
  843. try:
  844. node_tree.links.new(parent.outputs["Inheritance"], c_node.inputs['Input Relationship'])
  845. except KeyError: # not a inherit node anymore
  846. node_tree.links.new(parent.outputs["Output Relationship"], c_node.inputs['Input Relationship'])
  847. parent = c_node
  848. #Target Tasks:
  849. if (hasattr(c, "target") and not hasattr(c, "subtarget")):
  850. do_after.add( ("Object Target", c_node.name , c.target.name ) )
  851. if (hasattr(c, "subtarget")):
  852. if c.target and c.subtarget: # this node has a target, find the node associated with it...
  853. do_after.add( ("Target", c_node.name , c.subtarget ) )
  854. else:
  855. do_after.add( ("Object Target", c_node.name , c.target.name ) )
  856. if (hasattr(c, "pole_subtarget")):
  857. if c.pole_target and c.pole_subtarget: # this node has a pole target, find the node associated with it...
  858. do_after.add( ("Pole Target", c_node.name , c.pole_subtarget ) )
  859. fill_parameters(c_node, c, context)
  860. if (hasattr(c, "targets")): # Armature Modifier, annoying.
  861. for i in range(len(c.targets)):
  862. if (c.targets[i].subtarget):
  863. do_after.add( ("Target."+str(i).zfill(3), c_node.name , c.targets[i].subtarget ) )
  864. # Driver Tasks
  865. if armOb.animation_data:
  866. for fc in armOb.animation_data.drivers:
  867. pb_string = fc.data_path.split("[\"")[1]; pb_string = pb_string.split("\"]")[0]
  868. try:
  869. c_string = fc.data_path.split("[\"")[2]; c_string = c_string.split("\"]")[0]
  870. do_after.add ( ("driver", bone_node.name, c_node.name) )
  871. except IndexError: # the above expects .pose.bones["some name"].constraints["some constraint"]
  872. do_after.add ( ("driver", bone_node.name, bone_node.name) ) # it's a property I guess
  873. try:
  874. node_tree.links.new(parent.outputs["Inheritance"], bone_node.inputs['Relationship'])
  875. except KeyError: # may have changed, see above
  876. node_tree.links.new(parent.outputs["Output Relationship"], bone_node.inputs['Relationship'])
  877. prPurple("iteration: ", time() - iter_start)
  878. bones.extend(bone.children)
  879. finished_drivers = set()
  880. switches, driver_vars, fcurves, drivers = [],[],[],[]
  881. # Now do the tasks.
  882. for (task, in_node_name, out_node_name) in do_after:
  883. prOrange(task, in_node_name, out_node_name)
  884. # prPurple(len(node_tree.nodes))
  885. if task in ['Object Target']:
  886. in_node = node_tree.nodes[ in_node_name ]
  887. out_node= node_tree.nodes.new("InputExistingGeometryObject")
  888. out_node.inputs["Name"].default_value=out_node_name
  889. node_tree.links.new(out_node.outputs["Object"], in_node.inputs["Target"])
  890. if task in ['Target', 'Pole Target']:
  891. in_node = node_tree.nodes[ in_node_name ]
  892. try:
  893. out_node = node_tree.nodes[ out_node_name ]
  894. except KeyError:
  895. prRed (f"Failed to find node: {out_node_name} as pole target for node: {in_node_name} and input {task}")
  896. #
  897. node_tree.links.new(out_node.outputs["xForm Out"], in_node.inputs[task])
  898. elif (task[:6] == 'Target'):
  899. in_node = node_tree.nodes[ in_node_name ]
  900. out_node = node_tree.nodes[ out_node_name ]
  901. #
  902. node_tree.links.new(out_node.outputs["xForm Out"], in_node.inputs[task])
  903. elif task in ["Custom Object xForm Override"]:
  904. shape_xform_n = None
  905. for n in node_tree.nodes:
  906. if n.name == out_node_name:
  907. shape_xform_n = n
  908. node_tree.links.new(shape_xform_n.outputs["xForm Out"], node_tree.nodes[in_node_name].inputs['Custom Object xForm Override'])
  909. break
  910. else: # make it a task
  911. prRed("Cannot set custom object transform override for %s to %s" % (in_node_name, out_node_name))
  912. elif task in ["driver"]:
  913. create_driver(in_node_name, out_node_name, armOb, finished_drivers, switches, driver_vars, fcurves, drivers, node_tree, context)
  914. # annoyingly, Rigify uses f-modifiers to setup its fcurves
  915. # I do not intend to support fcurve modifiers in Mantis at this time
  916. for child in armOb.children:
  917. its_parent = None
  918. parent_name = armOb.name
  919. if child.parent_type == "BONE":
  920. parent_name = child.parent_bone
  921. if not (possible_parent_nodes := bone_inherit_node.get(parent_name)):
  922. its_parent = create_inheritance_node(child, parent_name, bone_inherit_node, node_tree)
  923. else:
  924. for ppn in possible_parent_nodes: # check if it has the right connected, inherit scale, inherit rotation
  925. if ppn.inputs["Connected"].default_value != False: continue
  926. if ppn.inputs["Inherit Scale"].default_value != "FULL": continue
  927. if ppn.inputs["Inherit Rotation"].default_value != True: continue
  928. its_parent = ppn; break
  929. else:
  930. its_parent = create_inheritance_node(pb, parent_name, bone_inherit_node, node_tree)
  931. if child.type in ["MESH", "CURVE", "EMPTY"]:
  932. do_generate_geom(child, node_tree, its_parent)
  933. if child.type in ["ARMATURE"]:
  934. do_generate_armature(armOb, context, node_tree, parent_node=its_parent)
  935. for node in node_tree.nodes:
  936. node.select = False
  937. prGreen("Finished generating %d nodes in %f seconds." % (len(node_tree.nodes), time() - start))
  938. return armature
  939. class GenerateMantisTree(Operator):
  940. """Generate Mantis Tree From Selected"""
  941. bl_idname = "mantis.generate_tree"
  942. bl_label = "Generate Mantis Tree from Selected"
  943. @classmethod
  944. def poll(cls, context):
  945. return (mantis_poll_op(context))
  946. def execute(self, context):
  947. space = context.space_data
  948. path = space.path
  949. node_tree = space.path[len(path)-1].node_tree
  950. do_profile=False
  951. #This will generate it in the current node tree and OVERWRITE!
  952. node_tree.nodes.clear() # is this wise?
  953. import cProfile
  954. from os import environ
  955. print (environ.get("DOPROFILE"))
  956. if environ.get("DOPROFILE"):
  957. do_profile=True
  958. if do_profile:
  959. cProfile.runctx("do_generate_armature(context.active_object, context, node_tree)", None, locals())
  960. else:
  961. node_tree.do_live_update = False
  962. do_generate_armature(context.active_object, context, node_tree)
  963. from .utilities import SugiyamaGraph
  964. try:
  965. for n in node_tree.nodes:
  966. n.select = True # Sugiyama sorting requires selection.
  967. SugiyamaGraph(node_tree, 16)
  968. except ImportError:
  969. pass
  970. node_tree.do_live_update = True
  971. return {"FINISHED"}