ops_generate_tree.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. parent_node = node_tree.nodes.new("linkInherit")
  15. parent_bone_node = node_tree.nodes.get(parent_name)
  16. if not parent_bone_node:
  17. raise RuntimeError("Can't Find parent node!!")
  18. parent_node.location = parent_bone_node.location; parent_node.location.x+=200
  19. node_tree.links.new(parent_bone_node.outputs["xForm Out"], parent_node.inputs['Parent'])
  20. parent_node.inputs["Connected"].default_value = pb.bone.use_connect
  21. parent_node.inputs["Inherit Scale"].default_value = pb.bone.inherit_scale
  22. parent_node.inputs["Inherit Rotation"].default_value = pb.bone.use_inherit_rotation
  23. if (bone_inherit_node.get(parent_bone_node.name)):
  24. bone_inherit_node[parent_bone_node.name].append(parent_node)
  25. else:
  26. bone_inherit_node[parent_bone_node.name] = [parent_node]
  27. return parent_node
  28. def get_pretty_name(name):
  29. if name == "bbone_curveinx": return "BBone X Curve-In"
  30. elif name == "bbone_curveinz": return "BBone Z Curve-In"
  31. elif name == "bbone_curveoutx": return "BBone X Curve-Out"
  32. elif name == "bbone_curveoutz": return "BBone Z Curve-Out"
  33. elif name == "BBone HQ Deformation":
  34. raise NotImplementedError(wrapRed("I wasn't expecting this property to be driven lol why would you even want to do that"))
  35. elif name == "bbone_handle_type_start": return "BBone Start Handle Type"
  36. elif name == "bbone_handle_type_end": return "BBone End Handle Type"
  37. elif name == "bbone_x": return "BBone X Size"
  38. elif name == "bbone_z": return "BBone Z Size"
  39. elif name == "bbone_rollin": return "BBone Roll-In"
  40. elif name == "bbone_rollout": return "BBone Roll-Out"
  41. elif name == "bbone_scalein": return "BBone Scale-In"
  42. elif name == "bbone_scaleout": return "BBone Scale-Out"
  43. pretty = name.replace("_", " ")
  44. words = pretty.split(" "); pretty = ''
  45. for word in words:
  46. pretty+=(word.capitalize()); pretty+=' '
  47. return pretty [:-1] #omit the last trailing space
  48. constraint_link_map={
  49. 'COPY_LOCATION' : "LinkCopyLocation",
  50. 'COPY_ROTATION' : "LinkCopyRotation",
  51. 'COPY_SCALE' : "LinkCopyScale",
  52. 'COPY_TRANSFORMS' : "LinkCopyTransforms",
  53. 'LIMIT_DISTANCE' : "LinkLimitDistance",
  54. 'LIMIT_LOCATION' : "LinkLimitLocation",
  55. 'LIMIT_ROTATION' : "LinkLimitRotation",
  56. 'LIMIT_SCALE' : "LinkLimitScale",
  57. 'DAMPED_TRACK' : "LinkDampedTrack",
  58. 'LOCKED_TRACK' : "LinkLockedTrack",
  59. 'STRETCH_TO' : "LinkStretchTo",
  60. 'TRACK_TO' : "LinkTrackTo",
  61. 'CHILD_OF' : "LinkInheritConstraint",
  62. 'IK' : "LinkInverseKinematics",
  63. 'ARMATURE' : "LinkArmature",
  64. 'SPLINE_IK' : "LinkSplineIK",
  65. 'TRANSFORM' : "LinkTransformation",
  66. }
  67. def create_relationship_node_for_constraint(node_tree, c):
  68. if cls_name := constraint_link_map.get(c.type):
  69. return node_tree.nodes.new(cls_name)
  70. else:
  71. prRed ("Not yet implemented: %s" % c.type)
  72. return None
  73. def fill_parameters(node, c, context):
  74. # just try the basic parameters...
  75. node.mute = not c.enabled
  76. if c.mute == True and c.enabled == True:
  77. node.mute = c.mute
  78. # this is obviously stupid, but it's the new API as of, IIRC, 2.80
  79. try:
  80. owner_space = c.owner_space
  81. if c.owner_space == 'CUSTOM':
  82. pass
  83. #raise NotImplementedError("Custom Space is a TODO")
  84. if ( input := node.inputs.get("Owner Space") ):
  85. input.default_value = owner_space
  86. except AttributeError:
  87. pass
  88. try:
  89. target_space = c.target_space
  90. if c.target_space == 'CUSTOM':
  91. pass
  92. #raise NotImplementedError("Custom Space is a TODO")
  93. if ( input := node.inputs.get("Target Space") ):
  94. input.default_value = target_space
  95. except AttributeError:
  96. pass
  97. try:
  98. use_x, use_y, use_z = c.use_x, c.use_y, c.use_z
  99. if ( input := node.inputs.get("Axes") ):
  100. input.default_value[0] = use_x
  101. input.default_value[1] = use_y
  102. input.default_value[2] = use_z
  103. except AttributeError:
  104. pass
  105. try:
  106. invert_x, invert_y, invert_z = c.invert_x, c.invert_y, c.invert_z
  107. if ( input := node.inputs.get("Invert") ):
  108. input.default_value[0] = invert_x
  109. input.default_value[1] = invert_y
  110. input.default_value[2] = invert_z
  111. except AttributeError:
  112. pass
  113. try:
  114. influence = c.influence
  115. if ( input := node.inputs.get("Influence") ):
  116. input.default_value = influence
  117. except AttributeError:
  118. pass
  119. # gonna dispense with the try/except from here on
  120. if (c.type == 'COPY_LOCATION'):
  121. node.inputs["Head/Tail"].default_value = c.head_tail
  122. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  123. elif (c.type == 'COPY_ROTATION'):
  124. node.inputs["RotationOrder"].default_value = c.euler_order
  125. # ofset (legacy) is not supported TODO BUG
  126. if (mix_mode := c.mix_mode) == 'OFFSET':
  127. mix_mode = 'AFTER'
  128. node.inputs["Rotation Mix"].default_value = mix_mode
  129. elif (c.type == 'COPY_SCALE'):
  130. #node.inputs["Additive"].default_value = c.use_make_uniform # not yet implemented
  131. #node.inputs["Power"].default_value = c.head_tail
  132. node.inputs["Average"].default_value = c.use_make_uniform
  133. node.inputs["Offset"].default_value = c.use_offset
  134. elif (c.type == 'COPY_TRANSFORMS'):
  135. node.inputs["Head/Tail"].default_value = c.head_tail
  136. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  137. node.inputs["Mix"].default_value = c.mix_mode
  138. elif (c.type == 'LIMIT_DISTANCE'):
  139. print ("Not yet handled: ", c.type)
  140. elif (c.type in ['LIMIT_LOCATION', 'LIMIT_ROTATION', 'LIMIT_SCALE']):
  141. # print (c.type)
  142. try:
  143. node.inputs["Use Max X"].default_value = c.use_max_x
  144. node.inputs["Use Max Y"].default_value = c.use_max_y
  145. node.inputs["Use Max Z"].default_value = c.use_max_z
  146. #
  147. node.inputs["Use Min X"].default_value = c.use_min_x
  148. node.inputs["Use Min Y"].default_value = c.use_min_y
  149. node.inputs["Use Min Z"].default_value = c.use_min_z
  150. except AttributeError: # rotation
  151. node.inputs["Use X"].default_value = c.use_limit_x
  152. node.inputs["Use Y"].default_value = c.use_limit_y
  153. node.inputs["Use Z"].default_value = c.use_limit_z
  154. node.inputs["Max X"].default_value = c.max_x
  155. node.inputs["Max Y"].default_value = c.max_y
  156. node.inputs["Max Z"].default_value = c.max_z
  157. #
  158. node.inputs["Min X"].default_value = c.min_x
  159. node.inputs["Min Y"].default_value = c.min_y
  160. node.inputs["Min Z"].default_value = c.min_z
  161. elif (c.type == 'DAMPED_TRACK'):
  162. node.inputs["Head/Tail"].default_value = c.head_tail
  163. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  164. node.inputs["Track Axis"].default_value = c.track_axis
  165. elif (c.type == 'LOCKED_TRACK'):
  166. node.inputs["Head/Tail"].default_value = c.head_tail
  167. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  168. node.inputs["Track Axis"].default_value = c.track_axis
  169. node.inputs["Lock Axis"].default_value = c.lock_axis
  170. elif (c.type == 'STRETCH_TO'):
  171. node.inputs["Head/Tail"].default_value = c.head_tail
  172. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  173. node.inputs["Volume Variation"].default_value = c.bulge
  174. node.inputs["Use Volume Min"].default_value = c.use_bulge_min
  175. node.inputs["Volume Min"].default_value = c.bulge_min
  176. node.inputs["Use Volume Max"].default_value = c.use_bulge_max
  177. node.inputs["Volume Max"].default_value = c.bulge_max
  178. node.inputs["Smooth"].default_value = c.bulge_smooth
  179. node.inputs["Maintain Volume"].default_value = c.volume
  180. node.inputs["Rotation"].default_value = c.keep_axis
  181. elif (c.type == 'TRACK_TO'):
  182. print ("Not yet handled: ", c.type)
  183. elif (c.type == 'CHILD_OF'):
  184. print ("Not yet handled: ", c.type)
  185. elif (c.type == 'IK'):
  186. node.inputs["Chain Length"].default_value = c.chain_count
  187. node.inputs["Use Tail"].default_value = c.use_tail
  188. node.inputs["Stretch"].default_value = c.use_stretch
  189. # this isn't quite right lol
  190. node.inputs["Position"].default_value = c.weight
  191. node.inputs["Rotation"].default_value = c.orient_weight
  192. if not (c.use_location):
  193. node.inputs["Position"].default_value = 0
  194. if not (c.use_rotation):
  195. node.inputs["Rotation"].default_value = 0
  196. elif (c.type == 'ARMATURE'):
  197. node.inputs["Preserve Volume"].default_value = c.use_deform_preserve_volume
  198. node.inputs["Use Envelopes"].default_value = c.use_bone_envelopes
  199. node.inputs["Use Current Location"].default_value = c.use_current_location
  200. for i in range(len(c.targets)):
  201. with context.temp_override(node=node):
  202. bpy.ops.mantis.link_armature_node_add_target()
  203. elif (c.type == 'SPLINE_IK'):
  204. node.inputs["Chain Length"].default_value = c.chain_count
  205. node.inputs["Even Divisions"].default_value = c.use_even_divisions
  206. node.inputs["Chain Offset"].default_value = c.use_chain_offset
  207. node.inputs["Use Curve Radius"].default_value = c.use_curve_radius
  208. node.inputs["Y Scale Mode"].default_value = c.y_scale_mode
  209. node.inputs["XZ Scale Mode"].default_value = c.xz_scale_mode
  210. elif (c.type == 'TRANSFORM'):
  211. # I can't be arsed to do all this work..
  212. from .link_containers import transformation_props_sockets as props
  213. for prop, (sock_name, _unused) in props.items():
  214. if "from" in prop:
  215. if prop in ["map_from"] or "to" in prop:
  216. pass
  217. elif c.map_from == 'LOCATION':
  218. if "scale" in prop:
  219. continue
  220. if "rot" in prop:
  221. continue
  222. elif c.map_from == 'ROTATION':
  223. if "rot" not in prop:
  224. continue
  225. elif c.map_from == 'SCALE':
  226. if "scale" not in prop:
  227. continue
  228. if "to" in prop:
  229. if prop in ["map_to"] or "from" in prop:
  230. pass
  231. elif c.map_from == 'LOCATION':
  232. if "scale" in prop:
  233. continue
  234. if "rot" in prop:
  235. continue
  236. elif c.map_from == 'ROTATION':
  237. if "rot" not in prop:
  238. continue
  239. elif c.map_from == 'SCALE':
  240. if "scale" not in prop:
  241. continue
  242. node.inputs[sock_name].default_value = getattr(c, prop)
  243. if prop in "mute":
  244. node.inputs[sock_name].default_value = not getattr(c, prop)
  245. # should probably do it this way all over actually.
  246. else:
  247. raise NotImplementedError("Not handled yet: %s" % c.type)
  248. return None
  249. def walk_edit_bone(armOb, bone):
  250. # this is a simplified version of the node-tree walking code
  251. bonePath, bones, lines, seek = [0,], set(), [], bone
  252. while (True):
  253. curheight = len(bonePath)-1; ind = bonePath[-1]
  254. if (curheight == 0) and (ind > len(bone.children)-1):
  255. break
  256. if (curheight > 0):
  257. parent = seek.parent
  258. if (ind > len(seek.children)-1 ):
  259. bonePath[curheight-1]+=1
  260. del bonePath[curheight]
  261. seek = parent
  262. continue
  263. # should work...
  264. seek = get_bone_from_path(bone, bonePath)
  265. if (seek.name not in bones):
  266. lines.append(bonePath.copy())
  267. bones.add(seek.name)
  268. if (seek.children):
  269. bonePath.append(0)
  270. else:
  271. bonePath[curheight] = bonePath[curheight] + 1
  272. seek = seek.parent
  273. return lines
  274. def get_bone_from_path(root_bone, path):
  275. # this function assumes the path is valid
  276. path = path.copy(); bone = root_bone
  277. while(path):
  278. bone = bone.children[path.pop(0)]
  279. return bone
  280. def setup_custom_properties(bone_node, pb):
  281. for k, v in pb.items(): # Custom Properties
  282. socktype, prop_type = '', type(v)
  283. # print (prop_type)
  284. if prop_type == bool:
  285. socktype = 'ParameterBoolSocket'
  286. elif prop_type == int:
  287. socktype = 'ParameterIntSocket'
  288. elif prop_type == float:
  289. socktype = 'ParameterFloatSocket'
  290. elif prop_type == bpy.props.FloatVectorProperty:
  291. socktype = 'ParameterVectorSocket'
  292. elif prop_type == str:
  293. socktype = 'ParameterStringSocket'
  294. else:
  295. continue # it's a PointerProp or something
  296. #if self.prop_type == 'ENUM':
  297. # sock_type = 'ParameterStringSocket'
  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. # from rna_prop_ui import rna_idprop_ui_create
  302. # I have no idea how to get the data in a sane way, I guess I will use this...
  303. ui_data = pb.id_properties_ui(k).as_dict()
  304. new_prop.default_value = ui_data['default']
  305. try:
  306. new_prop.min = ui_data['min']
  307. new_prop.max = ui_data['max']
  308. new_prop.soft_min = ui_data['soft_min']
  309. new_prop.soft_max = ui_data['soft_max']
  310. except AttributeError:
  311. pass # it's not a number
  312. except KeyError:
  313. pass # same, or not defined maybe
  314. try:
  315. new_prop.description = ui_data['description']
  316. except KeyError:
  317. prOrange("Figure out why this happens?")
  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.append( ("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. print (" --> Check this node: %s" % switch_node.name)
  461. # this may be a custom property or a normal property...
  462. # this should lead to a constraint
  463. if len(parameter.split("[\"") ) == 3:
  464. property = parameter.split(".")[-1]
  465. if (property == 'mute'): # this is mapped to the 'Enable' socket...
  466. prop_in = out_node.inputs.get('Enable')
  467. else:
  468. prop_in = out_node.inputs.get(get_pretty_name(property))
  469. if prop_in:
  470. node_tree.links.new(switch_node.outputs["Driver"], prop_in)
  471. else:
  472. print (" couldn't find: ", property, out_node.label, out_node.name)
  473. # this won't always work tho
  474. #Finally, it should be noted that we are assuming it uses the same object ...
  475. # drivers from Rigify always should use the same object, but I want to support
  476. # detecting drivers across objects.
  477. else: # we'll have to set this one up manually
  478. # Let's make the variable nodes, the Driver node, and the fCurve node.
  479. # Get the variable information
  480. if (True):
  481. var_nodes = []; num_vars = 0
  482. for num_vars, var in enumerate(fc.driver.variables):
  483. target1, target2, bone_target, bone_target2 = [None]*4
  484. var_data = {}
  485. var_data["Variable Type"] = var.type
  486. var_data["Property"] = ""
  487. if len(var.targets) >= 1:
  488. target1 = var.targets[0]
  489. if (var_data["Variable Type"] != 'SINGLE_PROP'):
  490. bone_target = var.targets[0].bone_target
  491. else: # figure it out by the data path string.
  492. target_string = var.targets[0].data_path
  493. bone_target = target_string.split("pose.bones[\"")[1]; bone_target = bone_target.split("\"]")[0]
  494. # we also need to get the property.
  495. p_string = fc.driver.variables[0].targets[0].data_path
  496. p_string = p_string.split("[\"")[-1]; p_string = p_string.split("\"]")[0]
  497. var_data["Property"] = p_string
  498. if (var_data["Variable Type"] == 'TRANSFORMS'):
  499. transform_channel_map = {
  500. "LOC_X" : ('location', 0),
  501. "LOC_Y" : ('location', 1),
  502. "LOC_Z" : ('location', 2),
  503. "ROT_X" : ('rotation', 0),
  504. "ROT_Y" : ('rotation', 1),
  505. "ROT_Z" : ('rotation', 2),
  506. "ROT_W" : ('rotation', 3),
  507. "SCALE_X" : ('scale', 0),
  508. "SCALE_Y" : ('scale', 1),
  509. "SCALE_Z" : ('scale', 2),
  510. "SCALE_AVG" : ('scale', 3), }
  511. # if (var.transform_type in transform_channel_map.keys()):
  512. # var_data["Property"], var_data["Property Index"] = transform_channel_map[var.transform_type]
  513. prRed("I am pretty sure this thing does not friggin work with whatever it is I commented above...")
  514. var_data["Evaluation Space"] = var.targets[0].transform_space
  515. var_data["Rotation Mode"] = var.targets[0].rotation_mode
  516. if len(var.targets) == 2:
  517. target2 = var.targets[1]
  518. bone_target2 = var.targets[1].bone_target
  519. # check if the variable already exists in the tree.
  520. target_node1, target_node2 = None, None
  521. if (target1 and bone_target):
  522. target_node1 = node_tree.nodes[bone_target]
  523. elif (target1 and not bone_target):
  524. target_node1 = node_tree.nodes[target1]
  525. if (target2 and bone_target2):
  526. target_node2 = node_tree.nodes[bone_target2]
  527. elif (target2 and not bone_target2):
  528. target_node2 = node_tree.nodes[target2]
  529. var_node = None
  530. for n in driver_vars:
  531. fail = False
  532. if (inp := n.inputs['xForm 1']).is_linked:
  533. if inp.links[0].from_node != target_node1:
  534. fail = True
  535. if (inp := n.inputs['xForm 2']).is_linked:
  536. if inp.links[0].from_node != target_node2:
  537. fail = True
  538. #
  539. if n.inputs[0].default_value != var_data["Variable Type"]:
  540. fail = True
  541. if n.inputs[1].default_value != var_data["Property"]:
  542. fail = True
  543. try:
  544. if n.inputs[2].default_value != var_data["Property Index"]:
  545. fail = True
  546. if n.inputs[3].default_value != var_data["Evaluation Space"]:
  547. fail = True
  548. if n.inputs[4].default_value != var_data["Rotation Mode"]:
  549. fail = True
  550. except KeyError:
  551. pass # this is a SCRIPTED node it seems
  552. if not fail:
  553. var_node = n
  554. prWhite("Variable Node Found %s!" % var_node )
  555. break # found it!
  556. else:
  557. var_node = node_tree.nodes.new("UtilityDriverVariable"); driver_vars.append(var_node)
  558. prRed("Creating Node: %s" % var_node.name)
  559. for key, value in var_data.items():
  560. try:
  561. var_node.inputs[key].default_value = value
  562. except TypeError as e: # maybe it is a variable\
  563. if key == "Variable Type":
  564. var_node.inputs[key].default_value = "SINGLE_PROP"
  565. else: raise e
  566. if (target1 and bone_target):
  567. node_tree.links.new(node_tree.nodes[bone_target].outputs['xForm Out'], var_node.inputs['xForm 1'])
  568. elif (target1 and not bone_target):
  569. node_tree.links.new(node_tree.nodes[target1].outputs['xForm Out'], var_node.inputs['xForm 1'])
  570. if (target2 and bone_target2):
  571. node_tree.links.new(node_tree.nodes[bone_target2].outputs['xForm Out'], var_node.inputs['xForm 2'])
  572. elif (target2 and not bone_target2):
  573. node_tree.links.new(node_tree.nodes[target2].outputs['xForm Out'], var_node.inputs['xForm 2'])
  574. var_nodes.append(var_node)
  575. num_vars+=1 # so the len(num_vars) will be correct
  576. # get the keyframes from the driver fCurve
  577. keys = {}
  578. from mathutils import Vector
  579. if len(fc.keyframe_points) > 0:
  580. # TODO: make this do more than co_ui
  581. for i, k in enumerate(fc.keyframe_points):
  582. keys[i] = {'co_ui':k.co_ui}
  583. # print (fc.data_path)
  584. # print (len(fc.keyframe_points))
  585. # raise NotImplementedError("Not needed for first milestone")
  586. else:
  587. # fc_ob = fCurve_node.fake_fcurve_ob
  588. # node_fc = fc_ob.animation_data.action.fcurves[0]
  589. # fc.keyframe_points.add(2)
  590. if ((len(fc.modifiers) == 0) or ((fc.evaluate(0) == 0) and (fc.evaluate(1) == 1))):
  591. keys[0] = {'co_ui':Vector((0, 0))}
  592. keys[1] = {'co_ui':Vector((1, 1))}
  593. elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  594. keys[0] = {'co_ui':Vector((0, 1))}
  595. keys[1] = {'co_ui':Vector((1, 0))}
  596. else:
  597. print ("Could not get keys!")
  598. # TODO find out why this happens
  599. # I HAVE NO IDEA
  600. pass
  601. # elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  602. # kf0 = fc.keyframe_points[0]; kf0.co_ui = (0, 1)
  603. # kf1 = fc.keyframe_points[1]; kf1.co_ui = (1, 0)
  604. # now get the fCurve
  605. fCurve_node = None
  606. for n in fcurves:
  607. fc_ob = n.fake_fcurve_ob; node_fc = fc_ob.animation_data.action.fcurves[0]
  608. node_keys = {}
  609. for i, k in enumerate(node_fc.keyframe_points):
  610. node_keys[i] = {'co_ui':k.co_ui}
  611. # now let's see if they are the same:
  612. if (keys != node_keys):
  613. continue
  614. fCurve_node = n
  615. break
  616. else:
  617. fCurve_node = node_tree.nodes.new("UtilityFCurve")
  618. # fc_ob = fCurve_node.fake_fcurve_ob
  619. # node_fc = fc_ob.animation_data.action.fcurves[0]
  620. # fcurves.append(fCurve_node)
  621. # while(node_fc.keyframe_points): # clear it, it has a default FC
  622. # node_fc.keyframe_points.remove(node_fc.keyframe_points[0], fast=True)
  623. # node_fc.update()
  624. # node_fc.keyframe_points.add(len(keys))
  625. # for k, v in keys.items():
  626. # node_fc.keyframe_points[k].co_ui = v['co_ui']
  627. # # todo eventually the other dict elements ofc
  628. for num_keys, (k, v) in enumerate(keys.items()):
  629. fCurve_node.inputs.new("KeyframeSocket", "Keyframe."+str(num_keys).zfill(3))
  630. kf_node = node_tree.nodes.new("UtilityKeyframe")
  631. kf_node.inputs[0].default_value = v['co_ui'][0]
  632. kf_node.inputs[1].default_value = v['co_ui'][1]
  633. node_tree.links.new(kf_node.outputs[0], fCurve_node.inputs[num_keys])
  634. # NOW the driver itself
  635. driver_node = None
  636. # checc for it...
  637. driver_node = node_tree.nodes.new("UtilityDriver")
  638. driver_node.inputs["Driver Type"].default_value = fc.driver.type
  639. driver_node.inputs["Expression"].default_value = fc.driver.expression.replace ('var', 'a')
  640. # HACK, fix the above with a more robust solution
  641. node_tree.links.new(fCurve_node.outputs[0], driver_node.inputs['fCurve'])
  642. for i, var_node in zip(range(num_vars), var_nodes):
  643. # TODO TODO BUG HACK
  644. with context.temp_override(node=driver_node):
  645. bpy.ops.mantis.driver_node_add_variable()
  646. # This causes an error when you run it from the console! DO NOT leave this
  647. node_tree.links.new(var_node.outputs[0], driver_node.inputs[-1])
  648. # HACK duplicated code from earlier...
  649. parameter = fc.data_path
  650. prWhite( "parameter: %s" % parameter)
  651. property = ''
  652. if len(parameter.split("[\"") ) == 3:
  653. property = parameter.split(".")[-1]
  654. if (property == 'mute'): # this is mapped to the 'Enable' socket...
  655. prop_in = out_node.inputs.get('Enable')
  656. else:
  657. prop_in = out_node.inputs.get(get_pretty_name(property))
  658. if not prop_in: # this is a HACK because my solution is terrible and also bad
  659. if property == "head_tail":
  660. prop_in = out_node.inputs.get("Head/Tail")
  661. # the socket should probably know what Blender thing is being mapped to it as a custom prop
  662. if not prop_in:
  663. # try one last thing:
  664. property = parameter.split("targets[")[-1]
  665. target_index = int(property[0])
  666. property = "targets[" + property # HACK lol
  667. # get the property by index...
  668. prop_in = out_node.inputs[target_index*2+6+1] # this is the weight, not the target
  669. if prop_in:
  670. prRed (" found: %s, %s, %s" % (property, out_node.label, out_node.name))
  671. node_tree.links.new(driver_node.outputs["Driver"], prop_in)
  672. else:
  673. prRed (" couldn't find: %s, %s, %s" % (property, out_node.label, out_node.name))
  674. elif len(parameter.split("[\"") ) == 2:
  675. # print (parameter.split("[\"") ); raise NotImplementedError
  676. property = parameter.split(".")[-1]
  677. else:
  678. prWhite( "parameter: %s" % parameter)
  679. prRed (" couldn't find: ", property, out_node.label, out_node.name)
  680. def do_generate_armature(context, node_tree):
  681. from time import time
  682. start = time()
  683. node_tree.do_live_update = False
  684. armOb = bpy.context.active_object
  685. #This will generate it in the current node tree and OVERWRITE!
  686. node_tree.nodes.clear()
  687. armature = node_tree.nodes.new("xFormArmatureNode")
  688. armature.location = ( 0, 0)
  689. do_after = []
  690. for root in armOb.data.bones:
  691. if root.parent is None:
  692. iter_start= time()
  693. lines = []
  694. lines = walk_edit_bone(armOb, root)
  695. lines.append([]) # add the root itself HACK ugly
  696. milestone=time()
  697. prPurple("got the bone paths", time() - milestone); milestone=time()
  698. # set up some properties:
  699. armature.inputs["Name"].default_value = armOb.name
  700. armature.name = armOb.name; armature.label = armOb.name
  701. # for getting parent nodes
  702. bone_inherit_node = {}
  703. # do short lines first bc longer lines rely on their results
  704. sort_by_len = lambda elem : len(elem)
  705. lines.sort(key=sort_by_len)
  706. for bone_path in lines:
  707. prGreen("for bone_path in lines", time() - milestone); milestone=time()
  708. # first go through the bone path and find relevant information
  709. bone = get_bone_from_path(root, bone_path)
  710. bone_node = node_tree.nodes.new("xFormBoneNode")
  711. bone_node.inputs["Name"].default_value = bone.name
  712. bone_node.name, bone_node.label = bone.name, bone.name
  713. matrix = bone.matrix_local.copy()
  714. bone_node.inputs["Matrix"].default_value = [
  715. matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
  716. matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
  717. matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], # last element is bone length, for mantis
  718. matrix[3][0], matrix[3][1], matrix[3][2], bone.length ] #matrix[3][3], ]
  719. x_distance, y_distance = 0, 0
  720. pb = armOb.pose.bones[bone.name]
  721. possible_parent_nodes = []
  722. if bone_path: # not a root
  723. x_distance, y_distance = len(bone_path), bone_path[-1]
  724. possible_parent_nodes = bone_inherit_node.get(bone.parent.name)
  725. # Set the parent
  726. parent_node = None
  727. if not (possible_parent_nodes):
  728. parent_node = create_inheritance_node(pb, bone.parent.name, bone_inherit_node, node_tree)
  729. else:
  730. for ppn in possible_parent_nodes:
  731. # check if it has the right connected, inherit scale, inherit rotation
  732. if ppn.inputs["Connected"].default_value != pb.bone.use_connect:
  733. continue
  734. if ppn.inputs["Inherit Scale"].default_value != pb.bone.inherit_scale:
  735. continue
  736. if ppn.inputs["Inherit Rotation"].default_value != pb.bone.use_inherit_rotation:
  737. continue
  738. parent_node = ppn; break
  739. else:
  740. parent_node = create_inheritance_node(pb, bone.parent.name, bone_inherit_node, node_tree)
  741. print("Got parent node", time() - milestone); milestone=time()
  742. if parent_node is None:
  743. raise RuntimeError("No parent node?")
  744. else: # This is a root
  745. prOrange("else this is a root",time() - milestone); milestone=time()
  746. parent_node = node_tree.nodes.new("linkInherit")
  747. # root_child = node_tree.nodes.new("linkInherit")
  748. node_tree.links.new(parent_node.outputs["Inheritance"], bone_node.inputs['Relationship'])
  749. # node_tree.links.new(bone_node.outputs["xForm Out"], root_child.inputs['Parent'])
  750. node_tree.links.new(armature.outputs["xForm Out"], parent_node.inputs['Parent'])
  751. parent_node.inputs["Inherit Rotation"].default_value = True
  752. parent_node.location = (200, 0)
  753. bone_node.location = (400, 0)
  754. # root_child.location = (600, 0)
  755. # bone_inherit_node[bone_node.name]=[root_child]
  756. bone_node.inputs["Lock Location"].default_value = pb.lock_location
  757. bone_node.inputs["Lock Rotation"].default_value = pb.lock_rotation
  758. bone_node.inputs["Lock Scale"].default_value = pb.lock_scale
  759. setup_custom_properties(bone_node, pb)
  760. setup_ik_settings(bone_node, pb)
  761. setup_vp_settings(bone_node, pb, do_after, node_tree)
  762. setup_df_settings(bone_node, pb)
  763. # BBONES
  764. bone_node.inputs["BBone X Size"].default_value = pb.bone.bbone_x
  765. bone_node.inputs["BBone Z Size"].default_value = pb.bone.bbone_z
  766. bone_node.inputs["BBone Segments"].default_value = pb.bone.bbone_segments
  767. if pb.bone.bbone_mapping_mode == "CURVED":
  768. bone_node.inputs["BBone HQ Deformation"].default_value = True
  769. bone_node.inputs["BBone Start Handle Type"].default_value = pb.bone.bbone_handle_type_start
  770. bone_node.inputs["BBone End Handle Type"].default_value = pb.bone.bbone_handle_type_end
  771. bone_node.inputs["BBone Custom Start Handle"].default_value = pb.bone.bbone_handle_type_start
  772. bone_node.inputs["BBone Custom End Handle"].default_value = pb.bone.bbone_handle_type_end
  773. bone_node.inputs["BBone X Curve-In"].default_value = pb.bone.bbone_curveinx
  774. bone_node.inputs["BBone Z Curve-In"].default_value = pb.bone.bbone_curveinz
  775. bone_node.inputs["BBone X Curve-Out"].default_value = pb.bone.bbone_curveoutx
  776. bone_node.inputs["BBone Z Curve-Out"].default_value = pb.bone.bbone_curveoutz
  777. prRed("BBone Implementation is not complete, expect errors and missing features for now")
  778. #
  779. for c in pb.constraints:
  780. prWhite("constraint %s for %s" % (c.name, pb.name), time() - milestone); milestone=time()
  781. # make relationship nodes and set up links...
  782. if ( c_node := create_relationship_node_for_constraint(node_tree, c)):
  783. c_node.label = c.name
  784. # this node definitely has a parent inherit node.
  785. c_node.location = parent_node.location; c_node.location.x += 200
  786. try:
  787. node_tree.links.new(parent_node.outputs["Inheritance"], c_node.inputs['Input Relationship'])
  788. except KeyError: # not a inherit node anymore
  789. node_tree.links.new(parent_node.outputs["Output Relationship"], c_node.inputs['Input Relationship'])
  790. parent_node = c_node
  791. #Target Tasks:
  792. if (hasattr(c, "target") and not hasattr(c, "subtarget")):
  793. do_after.append( ("Object Target", c_node.name , c.target.name ) )
  794. if (hasattr(c, "subtarget")):
  795. if c.target and c.subtarget: # this node has a target, find the node associated with it...
  796. do_after.append( ("Target", c_node.name , c.subtarget ) )
  797. else:
  798. do_after.append( ("Object Target", c_node.name , c.target.name ) )
  799. if (hasattr(c, "pole_subtarget")):
  800. if c.pole_target and c.pole_subtarget: # this node has a pole target, find the node associated with it...
  801. do_after.append( ("Pole Target", c_node.name , c.pole_subtarget ) )
  802. fill_parameters(c_node, c, context)
  803. if (hasattr(c, "targets")): # Armature Modifier, annoying.
  804. for i in range(len(c.targets)):
  805. if (c.targets[i].subtarget):
  806. do_after.append( ("Target."+str(i).zfill(3), c_node.name , c.targets[i].subtarget ) )
  807. # Driver Tasks
  808. if armOb.animation_data:
  809. for fc in armOb.animation_data.drivers:
  810. pb_string = fc.data_path.split("[\"")[1]; pb_string = pb_string.split("\"]")[0]
  811. try:
  812. c_string = fc.data_path.split("[\"")[2]; c_string = c_string.split("\"]")[0]
  813. do_after.append ( ("driver", bone_node.name, c_node.name) )
  814. except IndexError: # the above expects .pose.bones["some name"].constraints["some constraint"]
  815. do_after.append ( ("driver", bone_node.name, bone_node.name) ) # it's a property I guess
  816. try:
  817. node_tree.links.new(parent_node.outputs["Inheritance"], bone_node.inputs['Relationship'])
  818. except KeyError: # may have changed, see above
  819. node_tree.links.new(parent_node.outputs["Output Relationship"], bone_node.inputs['Relationship'])
  820. bone_node.location = (400 + parent_node.location.x, -200*y_distance + parent_node.location.y)
  821. prPurple("iteration: ", time() - iter_start)
  822. finished_drivers = set()
  823. switches, driver_vars, fcurves, drivers = [],[],[],[]
  824. # Now do the tasks.
  825. for (task, in_node_name, out_node_name) in do_after:
  826. prOrange(task, in_node_name, out_node_name)
  827. prPurple(len(node_tree.nodes))
  828. if task in ['Object Target']:
  829. in_node = node_tree.nodes[ in_node_name ]
  830. out_node= node_tree.nodes.new("InputExistingGeometryObject")
  831. out_node.inputs["Name"].default_value=out_node_name
  832. node_tree.links.new(out_node.outputs["Object"], in_node.inputs["Target"])
  833. if task in ['Target', 'Pole Target']:
  834. in_node = node_tree.nodes[ in_node_name ]
  835. try:
  836. out_node = node_tree.nodes[ out_node_name ]
  837. except KeyError:
  838. prRed (f"Failed to find node: {out_node_name} as pole target for node: {in_node_name} and input {task}")
  839. #
  840. node_tree.links.new(out_node.outputs["xForm Out"], in_node.inputs[task])
  841. elif (task[:6] == 'Target'):
  842. in_node = node_tree.nodes[ in_node_name ]
  843. out_node = node_tree.nodes[ out_node_name ]
  844. #
  845. node_tree.links.new(out_node.outputs["xForm Out"], in_node.inputs[task])
  846. elif task in ["Custom Object xForm Override"]:
  847. shape_xform_n = None
  848. for n in node_tree.nodes:
  849. if n.name == out_node_name:
  850. shape_xform_n = n
  851. node_tree.links.new(shape_xform_n.outputs["xForm Out"], node_tree.nodes[in_node_name].inputs['Custom Object xForm Override'])
  852. break
  853. else: # make it a task
  854. prRed("Cannot set custom object transform override for %s to %s" % (in_node_name, out_node_name))
  855. elif task in ["driver"]:
  856. create_driver(in_node_name, out_node_name, armOb, finished_drivers, switches, driver_vars, fcurves, drivers, node_tree, context)
  857. # annoyingly, Rigify uses f-modifiers to setup its fcurves
  858. # I do not intend to support fcurve modifiers in Mantis at this time
  859. for node in node_tree.nodes:
  860. node.select = False
  861. prGreen("Finished generating %d nodes in %f seconds." % (len(node_tree.nodes), time() - start))
  862. #bpy.ops.node.cleanup()
  863. node_tree.do_live_update = True
  864. class GenerateMantisTree(Operator):
  865. """Generate Mantis Tree From Selected"""
  866. bl_idname = "mantis.generate_tree"
  867. bl_label = "Generate Mantis Tree from Selected"
  868. @classmethod
  869. def poll(cls, context):
  870. return (mantis_poll_op(context))
  871. def execute(self, context):
  872. space = context.space_data
  873. path = space.path
  874. node_tree = space.path[len(path)-1].node_tree
  875. do_profile=False
  876. import cProfile
  877. from os import environ
  878. print (environ.get("DOPROFILE"))
  879. if environ.get("DOPROFILE"):
  880. do_profile=True
  881. if do_profile:
  882. cProfile.runctx("do_generate_armature(context, node_tree)", None, locals())
  883. else:
  884. do_generate_armature(context, node_tree)
  885. return {"FINISHED"}
  886. return {"FINISHED"}