ops_generate_tree.py 52 KB

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