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