ops_generate_tree.py 53 KB

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