node_common.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. from .utilities import (prRed, prGreen, prPurple, prWhite,
  2. prOrange,
  3. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  4. wrapOrange,)
  5. from ..base_definitions import GraphError, NodeSocket, MantisNode
  6. from collections.abc import Callable
  7. # BE VERY CAREFUL
  8. # the x_containers files import * from this file
  9. # so all the top-level imports are carried over
  10. from bpy.app import version as bpy_version
  11. #TODO: refactor the socket definitions so this becomes unnecessary.
  12. def get_socket_value(node_socket):
  13. value = None
  14. if hasattr(node_socket, "default_value"):
  15. value = node_socket.default_value
  16. if node_socket.bl_idname == 'MatrixSocket':
  17. value = node_socket.TellValue()
  18. return value
  19. # TODO: modify this to work with multi-input nodes
  20. def trace_single_line(mantis_node, input_name, link_index=0):
  21. # DO: refactor this for new link class
  22. """Traces a line to its input."""
  23. nodes = [mantis_node]
  24. # Trace a single line
  25. if (socket := mantis_node.inputs.get(input_name) ):
  26. while (socket.is_linked):
  27. link = socket.links[link_index]; link_index = 0
  28. if (socket := link.from_node.outputs.get(link.from_socket)):
  29. nodes.append(socket.node)
  30. if socket.can_traverse:
  31. socket = socket.traverse_target
  32. else: # this is an output.
  33. break
  34. else:
  35. break
  36. return nodes, socket
  37. # this is same as the other, just flip from/to and in/out
  38. def trace_single_line_up(mantis_node, output_name,):
  39. """I use this to get the xForm from a link node."""
  40. nodes = [mantis_node]
  41. if hasattr(mantis_node, "outputs"):
  42. # Trace a single line
  43. if (socket := mantis_node.outputs.get(output_name) ):
  44. while (socket.is_linked):
  45. # This is bad, but it's efficient for nodes that only expect
  46. # one path along the given line
  47. link = socket.links[0] # TODO: find out if this is wise.
  48. other = link.to_node.inputs.get(link.to_socket)
  49. if (other):
  50. socket = other
  51. if socket.can_traverse:
  52. socket = socket.traverse_target
  53. nodes.append(socket.node)
  54. else: # this is an input.
  55. nodes.append(socket.node)
  56. break
  57. else:
  58. break
  59. return nodes, socket
  60. def trace_line_up_branching(mantis_node : MantisNode, output_name : str,
  61. break_condition : Callable = lambda mantis_node : False):
  62. """ Returns all leaf nodes at the ends of branching lines from an output."""
  63. leaf_nodes = []
  64. if hasattr(mantis_node, "outputs"):
  65. # Trace a single line
  66. if (socket := mantis_node.outputs.get(output_name) ):
  67. check_sockets={socket}
  68. while (check_sockets):
  69. # This is bad, but it's efficient for nodes that only expect
  70. # one path along the given line
  71. socket = check_sockets.pop()
  72. for link in socket.links:
  73. other = link.to_node.inputs.get(link.to_socket)
  74. if (other):
  75. socket = other
  76. if break_condition(socket.node):
  77. leaf_nodes.append(socket.node)
  78. elif socket.is_input and socket.can_traverse:
  79. check_sockets.add(socket.traverse_target)
  80. else: # this is an input.
  81. leaf_nodes.append(socket.node)
  82. return leaf_nodes
  83. # this function exists to walk back to the first ancestor node of XFORM or LINK without
  84. # breaking the traverse behaviour which I still need for various reasons.
  85. def get_parent_xForm_info(mantis_node, socket_name = 'Relationship'):
  86. from ..mantis_dataclasses import xForm_info
  87. # we re-implement the trace logic here for performance.
  88. # because this kind of connection has traversal (for Links to find their children), we must
  89. # simply seek back to the first available xForm or Link and get its xForm info.\
  90. parent_node = None
  91. if (socket := mantis_node.inputs.get(socket_name) ):
  92. while (socket.is_linked):
  93. link = socket.links[0]
  94. if (socket := link.from_node.outputs.get(link.from_socket)):
  95. if socket.node.node_type in ['LINK', 'XFORM']:
  96. parent_node = socket.node; break
  97. if socket.can_traverse:
  98. socket = socket.traverse_target
  99. else: # this is an output.
  100. break
  101. else:
  102. break
  103. parent_xForm_info = None
  104. if parent_node:
  105. if parent_node.node_type == 'XFORM':
  106. parent_xForm_info = parent_node.parameters['xForm Out']
  107. else:
  108. if 'Output Relationship' in parent_node.parameters.keys():
  109. parent_xForm_info = parent_node.parameters['Output Relationship']
  110. else: # TODO refactor Inherit Node to have the same output as the other link nodes.
  111. parent_xForm_info = parent_node.parameters['Inheritance']
  112. if parent_xForm_info is None: parent_xForm_info = xForm_info() # default to empty
  113. return parent_xForm_info
  114. def setup_custom_property_inputs_outputs(mantis_node):
  115. from .utilities import get_ui_node
  116. if mantis_node.signature[0] == 'SCHEMA_AUTOGENERATED':
  117. from ..base_definitions import custom_props_types
  118. if mantis_node.__class__.__name__ not in custom_props_types:
  119. raise RuntimeError(wrapRed(f"Custom Properties not allowed for class {mantis_node.__class__.__name__}"))
  120. return
  121. else:
  122. ui_node = get_ui_node(mantis_node.ui_signature, mantis_node.base_tree)
  123. if ui_node:
  124. setup_custom_props_from_np(mantis_node, ui_node)
  125. else:
  126. prRed(f"Failed to setup custom properties for: {mantis_node.ui_signature}")
  127. def setup_custom_props_from_np(mantis_node, ui_node):
  128. for inp in ui_node.inputs:
  129. if inp.identifier == "__extend__": continue
  130. if not (inp.name in mantis_node.inputs.keys()) :
  131. socket = NodeSocket(is_input = True, name = inp.name, node = mantis_node,)
  132. mantis_node.inputs[inp.name] = socket
  133. mantis_node.parameters[inp.name] = None
  134. for attr_name in ["min", "max", "soft_min", "soft_max", "description"]:
  135. try:
  136. setattr(socket, attr_name, getattr(inp, attr_name))
  137. except AttributeError:
  138. pass
  139. for out in ui_node.outputs:
  140. if out.identifier == "__extend__": continue
  141. if not (out.name in mantis_node.outputs.keys()) :
  142. mantis_node.outputs[out.name] = NodeSocket(is_input = False, name = out.name, node = mantis_node,)
  143. def prepare_parameters(mantis_node):
  144. # some nodes add new parameters at runtime, e.g. Drivers
  145. # so we need to take that stuff from the mantis_nodes that have
  146. # been executed prior to this node.
  147. for s_name, sock in mantis_node.inputs.items():
  148. if not (sock.is_linked):
  149. continue
  150. if (sock.name in sock.links[0].from_node.parameters.keys()):
  151. mantis_node.parameters[s_name] = sock.links[0].from_node.parameters[sock.name]
  152. # should work, this is ugly.
  153. def check_for_driver(mantis_node, input_name, value_index = None, array_index = 0, combo_property=False):
  154. prop = mantis_node.evaluate_input(input_name, array_index)
  155. if (value_index is not None):
  156. try:
  157. prop = prop[value_index]
  158. except KeyError: # We'll try to use the driver for all three channels.
  159. pass
  160. # TODO an Index or Key error here should have a reasonable error message
  161. return (prop.__class__.__name__ == 'MantisDriver')
  162. def print_driver_item(mantis_node, b_object, original_prop):
  163. if mantis_node.node_type in ['LINK',]:
  164. printname = wrapOrange(b_object.id_data.name)
  165. elif mantis_node.node_type in ['XFORM',]:
  166. printname = wrapOrange(mantis_node.bGetObject().name)
  167. else:
  168. printname = wrapOrange(mantis_node)
  169. print("Adding driver %s to %s in %s" % (wrapPurple(original_prop), wrapWhite(mantis_node.signature[-1]), printname))
  170. # HACK This is the most hideous voodoo black magic fucntion in the entire program
  171. # but everything depends on it and it works
  172. def evaluate_sockets(mantis_node, b_object, props_sockets,):
  173. # this is neccesary because some things use dict properties for dynamic properties and setattr doesn't work
  174. def safe_setattr(ob, att_name, val):
  175. if ob.__class__.__name__ in ["NodesModifier"]:
  176. ob[att_name]=val
  177. elif b_object.__class__.__name__ in ["Key"]:
  178. if not val: val=0
  179. ob.key_blocks[att_name].value=val
  180. elif "]." in att_name:
  181. # it is of the form prop[int].prop2
  182. prop=att_name.split('[')[0]
  183. prop1=att_name.split('.')[1]
  184. get_index = int(att_name.split('[')[1][0])
  185. setattr(getattr(b_object, prop)[get_index], prop1, val)
  186. else:
  187. try:
  188. setattr(ob, att_name, val)
  189. except Exception as e:
  190. print ("ob, att_name, val")
  191. prRed(ob, att_name, val)
  192. raise e
  193. for prop, filler_item in props_sockets.items():
  194. if isinstance(filler_item, tuple):
  195. raise NotImplementedError(mantis_node)
  196. sock = filler_item.socket_name
  197. default = filler_item.default_value
  198. value_index = filler_item.value_index
  199. array_index = filler_item.array_index
  200. combo_property = filler_item.combo_property
  201. driver_key = (sock, value_index, array_index)
  202. if (check_for_driver(mantis_node, sock, value_index, array_index, combo_property)):
  203. original_prop = prop
  204. # TODO: deduplicate this terrible hack
  205. if ("." in prop) and not b_object.__class__.__name__ in ["Key"]: # this is a property of a property...
  206. sub_props = [b_object]
  207. while ("." in prop):
  208. split_prop = prop.split(".")
  209. prop = split_prop[1]
  210. sub_prop = (split_prop[0])
  211. if ("[" in sub_prop):
  212. sub_prop, sub_index = sub_prop.split("[")
  213. sub_prop_index = int(sub_index[0])
  214. sub_props.append(getattr(sub_props[-1], sub_prop)[sub_prop_index])
  215. else:
  216. sub_props.append(getattr(sub_props[-1], sub_prop))
  217. safe_setattr(sub_props[-1], prop, default)
  218. # this is really stupid
  219. else:
  220. safe_setattr(b_object, prop, default)
  221. print_driver_item( mantis_node, b_object, original_prop)
  222. if b_object.__class__.__name__ in ["NodesModifier"]:
  223. mantis_node.drivers[driver_key] = "[\""+original_prop+"\"]" # lol. It is a dict element not a "true" property
  224. elif b_object.__class__.__name__ in ["Key"]:
  225. mantis_node.drivers[driver_key] = "key_blocks[\""+original_prop+"\"].value"
  226. else:
  227. mantis_node.drivers[driver_key] = original_prop
  228. else: # here we can do error checking for the socket if needed
  229. if (value_index is not None):
  230. safe_setattr(b_object, prop, mantis_node.evaluate_input(sock)[value_index])
  231. else: # 'mute' is better than 'enabled'
  232. # UGLY HACK # because it is available in older
  233. if (prop == 'mute'): # Blenders.
  234. safe_setattr(b_object, prop, not bool(mantis_node.evaluate_input(sock)))
  235. elif (prop == 'hide'): # this will not cast it for me, annoying.
  236. safe_setattr(b_object, prop, bool(mantis_node.evaluate_input(sock)))
  237. else:
  238. try:
  239. # just wanna see if we are dealing with some collection
  240. # check hasattr in case it is one of those ["such-and-such"] props, and ignore those
  241. if hasattr(b_object, prop) and (not isinstance(getattr(b_object, prop), str)) and hasattr(getattr(b_object, prop), "__getitem__"):
  242. # prGreen("Doing the thing")
  243. for val_index, value in enumerate(mantis_node.evaluate_input(sock)):
  244. # assume this will work, both because val should have the right number of elements, and because this should be the right data type.
  245. from .drivers import MantisDriver
  246. if isinstance(value, MantisDriver):
  247. getattr(b_object,prop)[val_index] = default[val_index]
  248. print("Adding driver %s to %s in %s" % (wrapPurple(prop), wrapWhite(mantis_node.signature[-1]), mantis_node))
  249. try:
  250. mantis_node.drivers[sock].append((prop, val_index))
  251. except:
  252. mantis_node.drivers[sock] = [(prop, val_index)]
  253. else:
  254. getattr(b_object,prop)[val_index] = value
  255. else:
  256. safe_setattr(b_object, prop, mantis_node.evaluate_input(sock))
  257. except Exception as e:
  258. prRed(b_object, mantis_node, prop, sock, mantis_node.evaluate_input(sock))
  259. raise e
  260. def finish_driver(mantis_node, b_object, driver_item, prop):
  261. try:
  262. driver_sock = driver_item[0]; index = driver_item[1]; array_index =driver_item[2]
  263. except Exception as e:
  264. print (wrapGreen(mantis_node), wrapOrange(b_object), wrapRed(driver_item), wrapWhite(prop),)
  265. raise e
  266. driver_trace = trace_single_line(mantis_node, driver_sock, array_index)
  267. driver_provider, driver_socket = driver_trace[0][-1], driver_trace[1]
  268. combo_property = False
  269. # try to detect combo properties
  270. if mantis_node.socket_templates:
  271. for st in mantis_node.socket_templates:
  272. if st.name == driver_sock:
  273. if isinstance(st.blender_property, tuple):
  274. combo_property = True
  275. break
  276. if index is not None:
  277. try:
  278. driver = driver_provider.parameters[driver_socket.name][index].copy()
  279. except KeyError as e: # try single driver, it should still work fine.
  280. if combo_property:
  281. driver = driver_provider.parameters[driver_socket.name].copy()
  282. else:
  283. raise e
  284. # this is harmless and necessary for the weird ones where the property is a vector too
  285. if not combo_property:
  286. driver["ind"] = index
  287. else:
  288. driver = driver_provider.parameters[driver_socket.name].copy()
  289. if driver:
  290. socket_template = None
  291. if mantis_node.socket_templates:
  292. for socket_template in mantis_node.socket_templates:
  293. if socket_template.name == driver_sock: break
  294. if socket_template:
  295. if socket_template.is_animatable == False:
  296. raise RuntimeError(f"Driver is not allowed for {driver_sock} in node {mantis_node}")
  297. if ("." in prop) and mantis_node.__class__.__name__ != "DeformerMorphTargetDeform": # this is a property of a property...
  298. sub_props = [b_object]
  299. while ("." in prop):
  300. split_prop = prop.split(".")
  301. prop = split_prop[1]
  302. sub_prop = (split_prop[0])
  303. if ("[" in sub_prop):
  304. sub_prop, index = sub_prop.split("[")
  305. index = int(index[0])
  306. sub_props.append(getattr(sub_props[-1], sub_prop)[index])
  307. else:
  308. sub_props.append(getattr(sub_props[-1], sub_prop))
  309. driver["owner"] = sub_props[-1]
  310. elif mantis_node.node_type in ['XFORM',] and mantis_node.__class__.__name__ in ['xFormBone']:
  311. # TODO: I really shouldn't have to hardcode this. Look into better solutions.
  312. # NOTE: VERSIONING in Blender 5.0 we have to use pose bone for this, too.
  313. # default to pose bone, it's usually what we want
  314. bone_col = mantis_node.bGetParentArmature().pose.bones
  315. from ..xForm_socket_templates import attributes_shared_by_bone_and_pose_bone
  316. if socket_template.prop_owner_group == 'bone':
  317. bone_col = mantis_node.bGetParentArmature().data.bones
  318. # this is a little bit clumsy. TODO clean up here
  319. if prop in attributes_shared_by_bone_and_pose_bone:
  320. # we want to use the pose bone for this...only if it has a driver
  321. bone_col = mantis_node.bGetParentArmature().pose.bones
  322. driver["owner"] = bone_col[b_object] # we use "unsafe" brackets instead of get() because we want to see any errors that occur
  323. # HACK having special cases here is indicitave of a deeper problem that should be refactored
  324. elif mantis_node.__class__.__name__ in ['xFormCurvePin'] and \
  325. prop in ['offset_factor', 'forward_axis', 'up_axis']:
  326. driver["owner"] = b_object.constraints['Curve Pin']
  327. else:
  328. driver["owner"] = b_object
  329. driver["prop"] = prop
  330. return driver
  331. else:
  332. prOrange("Provider", driver_provider)
  333. prGreen("socket", driver_socket)
  334. print (index)
  335. prPurple(driver_provider.parameters[driver_socket.name])
  336. prRed("Failed to create driver for %s" % prop)
  337. return None
  338. def finish_drivers(mantis_node):
  339. drivers = []
  340. if not hasattr(mantis_node, "drivers"):
  341. return # HACK
  342. for driver_item, prop in mantis_node.drivers.items():
  343. b_objects = [mantis_node.bObject]
  344. if mantis_node.node_type == 'LINK':
  345. b_objects = mantis_node.bObject # this is already a list
  346. for b_object in b_objects:
  347. # Mutating the driver_item here is the WORST THING I HAVE EVER SEEN
  348. # HACK UGLY BUG TERRIBLE BAD CODE
  349. if isinstance(prop, list):
  350. for sub_item in prop:
  351. drivers.append(finish_driver(mantis_node, b_object, (driver_item, sub_item[1], 0), sub_item[0]))
  352. else:
  353. drivers.append(finish_driver(mantis_node, b_object, (driver_item, sub_item[1], 0), sub_item[0]))
  354. else:
  355. drivers.append(finish_driver(mantis_node, b_object, driver_item, prop))
  356. from .drivers import CreateDrivers
  357. CreateDrivers(drivers)