readtree.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. from ..utilities.utilities import prRed, prGreen, prPurple, prWhite, prOrange, \
  2. wrapRed, wrapGreen, wrapPurple, wrapWhite, wrapOrange
  3. # FIXME I don't think these signatures are unique.
  4. # TODO this is a really silly and bad and also really dumb way to do this
  5. def insert_lazy_parents(mantis_node):
  6. from ..link_nodes import LinkInherit
  7. inherit_node = None
  8. if mantis_node.inputs["Relationship"].is_connected:
  9. from ..utilities.node_common import trace_single_line_safe
  10. # BUG this line can create infinite loops
  11. node_line, last_socket = trace_single_line_safe(mantis_node, 'Relationship')
  12. # if last_socket is from a valid XFORM, it is the relationship in
  13. # because it was traversed from the xForm Out... so get the traverse target.
  14. if last_socket.traverse_target is None:
  15. return # this is not a valid lazy parent.
  16. for other_node in node_line[1:]: # skip the first one, it is the same node
  17. if other_node.node_type == 'LINK':
  18. return # this one has a realtionship connection.
  19. elif other_node.node_type == 'XFORM':
  20. break
  21. if other_node.node_type in ["XFORM"] and last_socket.traverse_target.name in ["xForm Out"]:
  22. for link in other_node.outputs['xForm Out'].links:
  23. if link.to_node == mantis_node: link.die()
  24. inherit_node = LinkInherit(("MANTIS_AUTOGENERATED", *mantis_node.signature[1:], "LAZY_INHERIT"), mantis_node.base_tree)
  25. l = other_node.outputs['xForm Out'].connect(inherit_node, 'Parent')
  26. l1 = inherit_node.outputs['Inheritance'].connect(mantis_node, 'Relationship')
  27. inherit_node.parameters = { "Parent":None,
  28. "Inherit Rotation":True,
  29. "Inherit Scale":'FULL',
  30. "Connected":False, }
  31. # because the from node may have already been done.
  32. init_connections(other_node); init_dependencies(other_node)
  33. init_connections(inherit_node); init_dependencies(inherit_node)
  34. return inherit_node
  35. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  36. # DATA FROM NODES #
  37. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  38. from ..base_definitions import replace_types, NodeSocket
  39. def autogen_node(base_tree, ui_socket, signature, mContext):
  40. mantis_node=None
  41. from ..internal_nodes import AutoGenNode
  42. mantis_node = AutoGenNode(signature, base_tree)
  43. mantis_node.mContext = mContext
  44. mantis_node.outputs.init_sockets([ui_socket.name])
  45. mantis_node.ui_signature = None # does not exist in the UI
  46. return mantis_node
  47. # TODO: investigate whether I can set the properties in the downstream nodes directly.
  48. # I am doing this in Schema Solver and it seems to work quite efficiently.
  49. def make_connections_to_ng_dummy(base_tree, tree_path_names, local_mantis_nodes, all_mantis_nodes, to_mantis_node):
  50. from ..socket_definitions import no_default_value
  51. for inp in to_mantis_node.ui_node.inputs:
  52. if inp.bl_idname in no_default_value:
  53. continue
  54. from_mantis_node = None
  55. to_s = inp.identifier
  56. if not inp.is_linked: # make an autogenerated NC for the inputs of the group node
  57. # This can be run inside schema. Make it unique with uuid() to be safe.
  58. from uuid import uuid4
  59. signature = ("MANTIS_AUTOGENERATED", *tree_path_names, to_mantis_node.ui_signature[-1], inp.name, inp.identifier, str(uuid4()))
  60. from_mantis_node = all_mantis_nodes.get(signature) # creating this without checking and
  61. # using UUID signature leads to TERRIBLE CONFUSING BUGS.
  62. if from_mantis_node is None:
  63. from_mantis_node = autogen_node(base_tree, inp, signature, to_mantis_node.mContext)
  64. from ..utilities.node_common import get_socket_value
  65. if from_mantis_node: # autogen can fail and we should catch it.
  66. from_mantis_node.parameters = {inp.name:get_socket_value(inp)}
  67. local_mantis_nodes[signature] = from_mantis_node; all_mantis_nodes[signature] = from_mantis_node
  68. from_mantis_node.outputs[inp.name].connect(node=to_mantis_node, socket=to_s, sort_id=0)
  69. else:
  70. prRed("No available auto-generated class for input %s in %s" % (inp.name, np.name))
  71. def gen_mantis_nodes(base_tree, current_tree, tree_path_names, mContext, all_mantis_nodes, local_mantis_nodes, dummy_nodes, group_nodes, schema_nodes ):
  72. from ..internal_nodes import DummyNode
  73. for ui_node in current_tree.nodes:
  74. if ui_node.bl_idname in ["NodeFrame", "NodeReroute"]:
  75. continue # not a Mantis Node
  76. if ui_node.bl_idname in ["NodeGroupInput", "NodeGroupOutput"]:
  77. # we only want ONE dummy in/out per tree_path, so use the bl_idname to make a Dummy node
  78. sig = (None, *tree_path_names, ui_node.bl_idname)
  79. ui_sig = (None, *tree_path_names, ui_node.name)
  80. if not local_mantis_nodes.get(sig):
  81. mantis_node = DummyNode( signature=sig , base_tree=base_tree, ui_node=ui_node, ui_signature=ui_sig )
  82. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node; dummy_nodes[sig] = mantis_node
  83. if ui_node.bl_idname in ["NodeGroupOutput"]:
  84. mantis_node.reroute_links_type = 'out'
  85. elif ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  86. mantis_node = DummyNode( signature= (sig := (None, *tree_path_names, ui_node.name) ), base_tree=base_tree, ui_node=ui_node )
  87. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node; dummy_nodes[sig] = mantis_node
  88. make_connections_to_ng_dummy(base_tree, tree_path_names, local_mantis_nodes, all_mantis_nodes, mantis_node)
  89. group_nodes.append(mantis_node)
  90. if ui_node.bl_idname == "MantisNodeGroup":
  91. mantis_node.reroute_links_type = 'group'
  92. else:
  93. mantis_node.reroute_links_type = 'schema'
  94. schema_nodes[sig] = mantis_node
  95. # if it wasn't the types we ignore or the types we make a Dummy for, use this to catch all non-special cases.
  96. elif (mantis_class := ui_node.mantis_class):
  97. sig = (None, *tree_path_names, ui_node.name)
  98. if ui_node.bl_idname in replace_types:
  99. sig = (None, *tree_path_names, ui_node.bl_idname)
  100. if local_mantis_nodes.get(sig):
  101. continue # already made
  102. mantis_node = mantis_class( sig , base_tree)
  103. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node
  104. mantis_node.ui_signature = (*mantis_node.ui_signature[:-1], ui_node.name) # just to ensure it points to a real node.
  105. else:
  106. mantis_node = None
  107. prRed(f"Can't make mantis_node for.. {ui_node.bl_idname}")
  108. # this should be done at init
  109. mantis_node.mContext = mContext
  110. if mantis_node.signature[0] not in ['MANTIS_AUTOGENERATED'] and mantis_node.node_type not in ['SCHEMA', 'DUMMY', 'DUMMY_SCHEMA']:
  111. mantis_node.fill_parameters()
  112. def data_from_tree(base_tree, tree_path, mContext, dummy_nodes, all_mantis_nodes, all_schema):#
  113. # TODO: it should be relatively easy to make this use a while loop instead of recursion.
  114. local_mantis_nodes, group_nodes = {}, []
  115. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  116. if tree_path[-1]:
  117. current_tree = tree_path[-1].node_tree # this may be None.
  118. else:
  119. current_tree = base_tree
  120. #
  121. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  122. from ..utilities.utilities import clear_reroutes
  123. links = clear_reroutes(list(current_tree.links))
  124. gen_mantis_nodes(base_tree, current_tree, tree_path_names, mContext, all_mantis_nodes, local_mantis_nodes, dummy_nodes, group_nodes, all_schema)
  125. from ..utilities.utilities import link_mantis_nodes
  126. for link in links:
  127. link_mantis_nodes((None, *tree_path_names), link, local_mantis_nodes)
  128. if current_tree == base_tree:
  129. # in the base tree, we need to auto-gen the default values in a slightly different way to node groups.
  130. insert_default_values_base_tree(base_tree, all_mantis_nodes)
  131. # Now, descend into the Node Groups and recurse
  132. for mantis_node in group_nodes:
  133. data_from_tree(base_tree, tree_path+[mantis_node.ui_node], mContext, dummy_nodes, all_mantis_nodes, all_schema)
  134. return dummy_nodes, all_mantis_nodes, all_schema
  135. STRING_PADDING = 4
  136. overlay_valid_socket_types = [
  137. "FloatSocket", "FloatPositiveSocket", "FloatFactorSocket",
  138. "FloatAngleSocket", "UnsignedIntSocket", "IntSocket", "StringSocket",
  139. ]
  140. # Do not use these input names as overlay keys:
  141. forbidden_key_names = ["",]
  142. forbidden_in_key_name = ['$',]
  143. def node_scan_overlays(node, socket_id,):
  144. from ..utilities.node_common import GraphError
  145. interface_nodes = node.mContext.interface_nodes
  146. from ..utilities.utilities import get_ui_node
  147. ui_node = get_ui_node(node.ui_signature, node.base_tree)
  148. # we'll assume that the overlay tag system checked if this is linked.
  149. # First let's check if it is a simple input node, by checking outputs that are marked "input"
  150. for socket in ui_node.outputs:
  151. # weird edge case for simple input nodes with unnamed sockets
  152. # the socket.identifier is not used by Mantis but it defaults to 'socket'\
  153. if socket.identifier == socket_id and socket.input == True: break
  154. else:
  155. for socket in ui_node.inputs:
  156. if socket.identifier == socket_id: break
  157. else:
  158. raise KeyError(f"Socket not found by ID {socket_id} in node {node.ui_signature}\n"
  159. f"Candidates: {[socket.identifier for socket in ui_node.inputs]}")
  160. value = socket.default_value # get the ACTUAL UI value
  161. if not isinstance(value, str): return
  162. # First step: get the interface nodes and the overlay keys
  163. # this should only check interfaces that are ancestors of this node
  164. my_interfaces = []
  165. for index in range(len(node.signature)-1):
  166. if index == 0: continue # root
  167. interface_signature = (*node.signature[:index+1], "InputInterface")
  168. my_interfaces.append( interface_nodes[interface_signature] )
  169. # the my_interfaces list is sorted in REVERSE order of importance
  170. # Next, get all the overlay providers.
  171. name_to_id_map = {}
  172. name_to_type_map = {} # Just for printing reasonable error messages
  173. overlay_keys = set()
  174. root_overlay_values = {}
  175. # First, we'll get the base tree's default inputs
  176. for interface_item in node.mContext.base_tree.interface.items_tree:
  177. if interface_item.item_type != "SOCKET": continue
  178. if interface_item.in_out != "INPUT": continue
  179. # NOTE this will need to change if overlays extend to other data types
  180. if hasattr(interface_item, "default_string"):
  181. # NOTE that there may be duplicate names. Too bad!
  182. root_overlay_values[interface_item.name] = interface_item.default_string
  183. elif hasattr(interface_item, "default_int"):
  184. root_overlay_values[interface_item.name] = str(interface_item.default_int).zfill(STRING_PADDING)
  185. elif hasattr(interface_item, "default_float"):
  186. root_overlay_values[interface_item.name] = str(interface_item.default_float).zfill(STRING_PADDING)
  187. overlay_keys.add(interface_item.name)
  188. name_to_id_map[interface_item.name] = None # don't worry about it
  189. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  190. for interface_node in interface_nodes.values():
  191. # problem: the interface node stores socket identifiers as keys
  192. # so in reality we need to get the group UI node and ask for its input names
  193. # if there is a duplicate name, too bad!
  194. group_ui_node = get_ui_node(interface_node.ui_signature[:-1], node.base_tree)
  195. for interface_item in group_ui_node.node_tree.interface.items_tree:
  196. if interface_item.item_type != 'SOCKET': continue
  197. if interface_item.in_out != 'INPUT': continue
  198. if interface_item.name in forbidden_key_names: continue
  199. for substr in forbidden_in_key_name:
  200. if substr in interface_item.name:
  201. break
  202. else: # if we do not find a bad substr
  203. name_to_id_map[interface_item.name]=interface_item.identifier
  204. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  205. overlay_keys.add(interface_item.name)
  206. # sort by reverse length so we find "CatsAndFrogs" before "Cats"
  207. overlay_keys = sorted(overlay_keys, key= lambda a :-1*len(a))
  208. # First I need to break it into substrings based on quotation marks
  209. from ..utilities.utilities import split_quoted_substrings_to_strings
  210. quoted_substrings = split_quoted_substrings_to_strings(value)
  211. overlay_tries = []
  212. for quoted_substring in quoted_substrings:
  213. overlay_tries.extend(quoted_substring.split("$"))
  214. result = overlay_tries[0] # the 0th element is always before the split character
  215. # the reason for the difference between overlay_try and key is because
  216. # we don't actually know if the $text part has a key in it
  217. for overlay_try in overlay_tries[1:]:
  218. if not overlay_try: continue # some of these are empty
  219. overlay_resolved_value = "$" + overlay_try
  220. for key in overlay_keys:
  221. if key in overlay_try:
  222. overlay_resolved_value = "$" + key
  223. for interface in reversed(my_interfaces): # since this is reversed when we build it
  224. if interface.inputs.get(actual_key := name_to_id_map.get(key)):
  225. overlay_value = None
  226. try:
  227. overlay_value = interface.evaluate_input(actual_key)
  228. except KeyError:
  229. if (socket_type := name_to_type_map.get(key) or 'NOT FOUND') in overlay_valid_socket_types:
  230. raise GraphError(f"Error: Variable {key} is not supported because it has "
  231. f"an invalid input in the node group: {interface.signature[:-1]}.")
  232. raise GraphError( f"Error: Variable {key} is not supported because it is "
  233. f"type {socket_type}" )
  234. continue
  235. # NOTE that the above can also be caused by any BUG occuring in node group update
  236. # because it causes the interface to be invalid for the UI node that spawns the interface node.
  237. if isinstance(overlay_value, (float, int)):
  238. overlay_value = str(overlay_value).zfill(STRING_PADDING)
  239. assert (isinstance(overlay_value, str)), f"Error: Variable {key} is not supported because it is type {type(overlay_value)}"
  240. overlay_resolved_value = overlay_try.replace(key, overlay_value)
  241. break
  242. else: # we'll try the base tree
  243. if base_tree_result := root_overlay_values.get(overlay_try):
  244. overlay_resolved_value = base_tree_result
  245. else:
  246. prOrange(f"WARN: no overlay value applied for {node.ui_signature} for key {key}")
  247. break # we found the key and are done here. One found Key per overlay-try
  248. result += overlay_resolved_value
  249. # Simple Input sockets with unnamed sockets assign this ID automatically
  250. # But Mantis uses the name instead. Usually the name and ID are the same.
  251. if socket_id == 'socket' and ui_node.outputs[0].name == "":
  252. socket_id = ''
  253. node.parameters[socket_id] = result
  254. return result # because sometimes I need to get the result, too
  255. from ..utilities.utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  256. def is_signature_in_other_signature(parent_signature, child_signature):
  257. # If the other signature is shorter, it isn't a child node
  258. if len(parent_signature) > len(child_signature):
  259. return False
  260. return parent_signature[0:] == child_signature[:len(parent_signature)]
  261. def solve_schema_to_tree(mantis_node, all_mantis_nodes, roots=[], error_popups=False):
  262. from ..utilities.utilities import get_ui_node
  263. np = get_ui_node(mantis_node.signature, mantis_node.base_tree)
  264. from .schema_solve import SchemaSolver
  265. solver = SchemaSolver(mantis_node, all_mantis_nodes.copy(), np, error_popups=error_popups)
  266. try:
  267. solved_nodes = solver.solve()
  268. except Exception as e:
  269. # # the schema will run the error cleanup code, we just need to raise or not
  270. solved_nodes = {}
  271. mantis_node.base_tree.hash=''
  272. raise execution_error_cleanup(mantis_node, e, show_error=error_popups)
  273. # maybe this should be done in schema solver. TODO invesitigate a more efficient way
  274. del_me = []
  275. for k, v in all_mantis_nodes.items():
  276. # delete all the schema's ui_node and interface nodes. The links have already been deleted by the solver.
  277. if v.signature[0] not in ['MANTIS_AUTOGENERATED'] and is_signature_in_other_signature(mantis_node.signature, k):
  278. del_me.append(k)
  279. for k in del_me:
  280. del all_mantis_nodes[k]
  281. for k,v in solved_nodes.items():
  282. all_mantis_nodes[k]=v
  283. init_connections(v)
  284. check_and_add_root(v, roots, include_non_hierarchy=True)
  285. return solved_nodes
  286. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  287. # PARSE NODE TREE #
  288. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  289. schema_bl_idnames = [ "SchemaIndex",
  290. "SchemaArrayInput",
  291. "SchemaArrayInputGet",
  292. "SchemaArrayInputAll",
  293. "SchemaArrayOutput",
  294. "SchemaConstInput",
  295. "SchemaConstOutput",
  296. "SchemaOutgoingConnection",
  297. "SchemaIncomingConnection",
  298. ]
  299. from ..utilities.utilities import get_all_dependencies
  300. def get_schema_length_dependencies(node, all_nodes={}):
  301. """ Get a list of all dependencies for the given node's length or array properties.
  302. This function will also recursively search for dependencies in its sub-trees.
  303. """
  304. deps = []
  305. prepare_links_to = ['Schema Length', 'Array', 'Index']
  306. def extend_dependencies_from_inputs(node):
  307. for inp in node.inputs.values():
  308. for l in inp.links:
  309. if not l.from_node in node.hierarchy_dependencies:
  310. continue
  311. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  312. deps.extend([l.from_node]) # why we need this lol
  313. if inp.name in prepare_links_to:
  314. deps.append(l.from_node)
  315. deps.extend(get_all_dependencies(l.from_node))
  316. def deps_filter(dep): # remove any nodes inside the schema
  317. if len(dep.signature) > len(node.signature):
  318. for i in range(len(node.signature)):
  319. dep_sig_elem, node_sig_elem = dep.signature[i], node.signature[i]
  320. if dep_sig_elem != node_sig_elem: break # they don't match, it isn't an inner-node
  321. else: # remove this, it didn't break, meaning it shares signature with outer node
  322. return False # this is an inner-node
  323. return True
  324. # this way we can handle Schema and Array Get nodes with one function
  325. extend_dependencies_from_inputs(node)
  326. if node.node_type == 'DUMMY_SCHEMA':
  327. trees = [(node.ui_node.node_tree, node.signature)] # this is UI data
  328. while trees:
  329. tree, tree_signature = trees.pop()
  330. for sub_ui_node in tree.nodes:
  331. if sub_ui_node.bl_idname in ['NodeReroute', 'NodeFrame']:
  332. continue
  333. if sub_ui_node.bl_idname in schema_bl_idnames:
  334. sub_node = all_nodes[(*tree_signature, sub_ui_node.bl_idname)]
  335. else:
  336. sub_node = all_nodes[(*tree_signature, sub_ui_node.name)]
  337. if sub_node.node_type == 'DUMMY_SCHEMA':
  338. extend_dependencies_from_inputs(sub_node)
  339. trees.append((sub_node.ui_node.node_tree, sub_node.signature))
  340. return list(filter(deps_filter, deps))
  341. def insert_default_values_base_tree(base_tree, all_mantis_nodes):
  342. # we can get this by name because group inputs are gathered to the bl_idname
  343. InputNode = all_mantis_nodes.get((None, 'NodeGroupInput'))
  344. if InputNode is None: return # nothing to do here.
  345. ui_node = InputNode.ui_node
  346. for i, output in enumerate(InputNode.outputs):
  347. ui_output = ui_node.outputs[i] # I need this for the error messages to make sense
  348. assert ui_output.identifier == output.name, "Cannot find UI Socket for Default Value"
  349. for interface_item in base_tree.interface.items_tree:
  350. if interface_item.item_type == 'PANEL': continue
  351. if interface_item.identifier == output.name: break
  352. else:
  353. raise RuntimeError(f"Default value {ui_output.name} does not exist in {base_tree.name} ")
  354. if interface_item.item_type == "PANEL":
  355. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  356. default_value = None
  357. from bpy.types import bpy_prop_array
  358. from mathutils import Vector
  359. val_type = None
  360. if hasattr(ui_output, 'default_value'):
  361. val_type = type(ui_output.default_value) # why tf can't I match/case here?
  362. if val_type is bool: default_value = interface_item.default_bool
  363. elif val_type is int: default_value = interface_item.default_int
  364. elif val_type is float: default_value = interface_item.default_float
  365. elif val_type is Vector: default_value = interface_item.default_vector
  366. elif val_type is str: default_value = interface_item.default_string
  367. elif val_type is bpy_prop_array: default_value = interface_item.default_bool_vector
  368. elif interface_item.bl_socket_idname == "xFormSocket":
  369. if interface_item.default_xForm == 'ARMATURE':
  370. default_value = 'MANTIS_DEFAULT_ARMATURE'
  371. else:
  372. raise RuntimeError(f"No xForm connected for {ui_output.name} in {base_tree.name}.")
  373. else:
  374. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  375. output_name = output.name
  376. if interface_item.bl_socket_idname not in ['xFormSocket']:
  377. signature = ("MANTIS_AUTOGENERATED", f"Default Value {output.name}",)
  378. autogen_mantis_node = all_mantis_nodes.get(signature)
  379. if autogen_mantis_node is None:
  380. autogen_mantis_node = autogen_node(base_tree, output, signature, InputNode.mContext)
  381. autogen_mantis_node.parameters[output_name]=default_value
  382. elif interface_item.bl_socket_idname == 'xFormSocket' \
  383. and default_value == 'MANTIS_DEFAULT_ARMATURE':
  384. signature = ("MANTIS_AUTOGENERATED", "MANTIS_DEFAULT_ARMATURE",)
  385. autogen_mantis_node = all_mantis_nodes.get(signature)
  386. if autogen_mantis_node is None:
  387. from ..xForm_nodes import xFormArmature
  388. autogen_mantis_node = xFormArmature(signature, base_tree)
  389. autogen_mantis_node.parameters['Name']=base_tree.name+'_MANTIS_AUTOGEN'
  390. autogen_mantis_node.mContext = InputNode.mContext
  391. from mathutils import Matrix
  392. autogen_mantis_node.parameters['Matrix'] = Matrix.Identity(4)
  393. output_name = 'xForm Out'
  394. while output.links:
  395. l = output.links.pop()
  396. to_node = l.to_node; to_socket = l.to_socket
  397. l.die()
  398. autogen_mantis_node.outputs[output_name].connect(to_node, to_socket)
  399. init_connections(l.from_node); init_dependencies(l.from_node)
  400. all_mantis_nodes[autogen_mantis_node.signature]=autogen_mantis_node
  401. def parse_tree(base_tree, error_popups=False):
  402. from uuid import uuid4
  403. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  404. from ..base_definitions import MantisExecutionContext
  405. mContext = MantisExecutionContext(base_tree=base_tree)
  406. import time
  407. data_start_time = time.time()
  408. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  409. # then they stick around because the function definition inits them once and keeps a reference
  410. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  411. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  412. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(base_tree, tree_path = [None], mContext=mContext, dummy_nodes = {}, all_mantis_nodes = {}, all_schema={})
  413. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  414. dummy.reroute_links(all_mantis_nodes)
  415. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  416. start_time = time.time()
  417. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  418. roots, array_nodes = [], []
  419. from collections import deque
  420. unsolved_schema = deque()
  421. from ..base_definitions import array_output_types, GraphError
  422. for mantis_node in all_mantis_nodes.values():
  423. # TODO I still need to assign mContext here because of autogen_node
  424. # so I have to do a deeper refactor to ensure autogen nodes get this at creation time.
  425. mantis_node.mContext = mContext
  426. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  427. if mantis_node.ui_node.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  428. continue
  429. # Initialize the dependencies and connections (from/to links) for each node.
  430. # we record & store it because using a getter is much slower (according to profiling)
  431. init_dependencies(mantis_node); init_connections(mantis_node)
  432. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  433. # Array nodes need a little special treatment, they're quasi-schemas
  434. if mantis_node.__class__.__name__ in array_output_types:
  435. solve_only_these.append(mantis_node)
  436. array_nodes.append(mantis_node)
  437. if mantis_node.node_type == 'INTERFACE':
  438. mContext.interface_nodes[mantis_node.signature] = mantis_node
  439. from itertools import chain
  440. for schema in chain(all_schema.values(), array_nodes):
  441. # We must remove the schema/array nodes that are inside a schema tree.
  442. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  443. if parent := all_schema.get(schema.signature[:i+1]):
  444. # This will be solved along with its parent schema.
  445. solve_only_these.remove(schema)
  446. break
  447. for schema in all_schema.values():
  448. if schema not in solve_only_these: continue
  449. init_schema_dependencies(schema, all_mantis_nodes)
  450. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  451. unsolved_schema.append(schema)
  452. for array in array_nodes:
  453. if array not in solve_only_these: continue
  454. solve_only_these.extend(get_schema_length_dependencies(array))
  455. solve_only_these.extend(array_nodes)
  456. schema_solve_done = set()
  457. solve_only_these = set(solve_only_these)
  458. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  459. while(solve_layer):
  460. n = solve_layer.pop()
  461. if n not in solve_only_these:
  462. continue
  463. if n.signature in all_schema.keys():
  464. for dep in n.hierarchy_dependencies:
  465. if dep not in schema_solve_done and (dep in solve_only_these):
  466. if dep.prepared:
  467. continue
  468. solve_layer.appendleft(n)
  469. break
  470. else:
  471. try:
  472. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots, error_popups=error_popups)
  473. except Exception as e:
  474. e = execution_error_cleanup(n, e, show_error=error_popups)
  475. solved_nodes = {}
  476. if error_popups == False:
  477. raise e
  478. return # it is not possible to parse the tree.
  479. unsolved_schema.remove(n)
  480. schema_solve_done.add(n)
  481. for node in solved_nodes.values():
  482. init_dependencies(node); init_connections(node)
  483. solve_layer.appendleft(node)
  484. schema_solve_done.add(node) # CRITICAL to prevent freezes.
  485. for conn in n.hierarchy_connections:
  486. if conn not in schema_solve_done and conn not in solve_layer:
  487. solve_layer.appendleft(conn)
  488. continue
  489. else:
  490. for dep in n.hierarchy_dependencies:
  491. if dep not in schema_solve_done:
  492. break
  493. else:
  494. try:
  495. n.bPrepare()
  496. except Exception as e:
  497. e = execution_error_cleanup(n, e, show_error=error_popups)
  498. if error_popups == False:
  499. raise e
  500. schema_solve_done.add(n)
  501. for conn in n.hierarchy_connections:
  502. if conn not in schema_solve_done and conn not in solve_layer:
  503. solve_layer.appendleft(conn)
  504. continue
  505. if unsolved_schema:
  506. raise RuntimeError("Failed to resolve all schema declarations")
  507. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  508. all_mantis_nodes = list(all_mantis_nodes.values())
  509. kept_mantis_node = {}
  510. while (all_mantis_nodes):
  511. mantis_node = all_mantis_nodes.pop()
  512. if mantis_node.node_type in ["DUMMY", 'SCHEMA', 'DUMMY_SCHEMA']:
  513. continue # screen out the ui_node schema nodes, group in/out, and group placeholders
  514. # cleanup autogen nodes
  515. if mantis_node.signature[0] == "MANTIS_AUTOGENERATED" and len(mantis_node.inputs) == 0 and len(mantis_node.outputs) == 1:
  516. from ..base_definitions import can_remove_socket_for_autogen
  517. output=list(mantis_node.outputs.values())[0]
  518. value=list(mantis_node.parameters.values())[0]
  519. # We can remove this node if it is safe to push it into the other node's socket.
  520. keep_me = False
  521. for l in output.links:
  522. to_node = l.to_node; to_socket = l.to_socket
  523. # do not remove the socket if it is a custom property.
  524. if not can_remove_socket_for_autogen(to_node, to_socket):
  525. keep_me = True; continue
  526. l.die()
  527. to_node.parameters[to_socket] = value
  528. del to_node.inputs[to_socket]
  529. init_dependencies(to_node) # to remove the autogen node we no longer need.
  530. if not keep_me:
  531. continue
  532. init_connections(mantis_node) # because we have removed many connections.
  533. if (mantis_node.node_type in ['XFORM']) and ("Relationship" in mantis_node.inputs.keys()):
  534. from ..utilities.node_common import GraphError
  535. try:
  536. if (new_mantis_node := insert_lazy_parents(mantis_node)):
  537. kept_mantis_node[new_mantis_node.signature]=new_mantis_node
  538. # be sure to add the Mantis context.
  539. new_mantis_node.mContext =mContext
  540. except GraphError as e:
  541. e = execution_error_cleanup(mantis_node, e, show_error=error_popups)
  542. if error_popups == False:
  543. raise e
  544. return # it is not possible to parse the tree.
  545. kept_mantis_node[mantis_node.signature]=mantis_node
  546. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  547. prWhite("Number of Nodes: %s" % (len(kept_mantis_node)))
  548. return kept_mantis_node
  549. from ..utilities.utilities import switch_mode
  550. def error_popup_draw_inner(layout, exception, ui_sig):
  551. message = f"Error: {exception}\n" \
  552. f"See node: {ui_sig[1:]}."
  553. lines = message.splitlines()
  554. for line in lines:
  555. layout.label(text=line)
  556. def execution_error_cleanup(node, exception, switch_objects = [], show_error=False ):
  557. from bpy import context
  558. ui_sig = None
  559. if show_error: # show a popup and select the relevant nodes
  560. if node:
  561. if node.mContext:
  562. if node.mContext.execution_failed==True:
  563. # already have an error, pass it to avoid printing
  564. return # a second error (it's confusing to users.)
  565. node.mContext.execution_failed=True
  566. ui_sig = node.ui_signature
  567. # TODO: see about zooming-to-node.
  568. base_tree = node.base_tree
  569. tree = base_tree
  570. try:
  571. for name in ui_sig[1:]:
  572. for n in tree.nodes: n.select = False
  573. n = tree.nodes[name]
  574. n.select = True
  575. tree.nodes.active = n
  576. if hasattr(n, "node_tree"):
  577. tree = n.node_tree
  578. except AttributeError: # not being run in node graph
  579. pass
  580. finally:
  581. def error_popup_draw(self, context):
  582. error_popup_draw_inner(self.layout, exception, ui_sig)
  583. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  584. switch_mode(mode='OBJECT', objects=switch_objects)
  585. for ob in switch_objects:
  586. ob.data.pose_position = 'POSE'
  587. prRed(f"Error: {exception} in node {ui_sig}")
  588. return exception
  589. def print_cycle(nodes):
  590. ret_str = ""
  591. for node in nodes:
  592. ret_str+= node.__repr__() + '\n'
  593. return ret_str
  594. def sort_execution(nodes, error_popups):
  595. from ..utilities.node_common import GraphError
  596. from collections import deque
  597. xForm_pass = deque()
  598. execution_failed = False
  599. sorted_nodes = []
  600. # initialize the hierarchy dependency count. We'll use this to ensure there
  601. # are no cycles (using Kahn's algorithm).
  602. for mantis_node in nodes.values():
  603. mantis_node.unmet_hierarchy_dependency_count = len(mantis_node.hierarchy_dependencies)
  604. if mantis_node.unmet_hierarchy_dependency_count == 0 :
  605. xForm_pass.append(mantis_node)
  606. processed_count = 0
  607. while(xForm_pass):
  608. n = xForm_pass.pop()
  609. # if n.execution_prepared: continue
  610. n.execution_prepared = True
  611. sorted_nodes.append(n)
  612. processed_count+=1
  613. for child in n.hierarchy_connections:
  614. child.unmet_hierarchy_dependency_count-= 1
  615. if child.unmet_hierarchy_dependency_count == 0:
  616. xForm_pass.append(child)
  617. if processed_count < len(nodes):
  618. cycle = []
  619. for n in nodes.values():
  620. if n.execution_prepared == False:
  621. cycle.append(n)
  622. execution_failed = True
  623. e = GraphError("Detected a cycle in the tree, containing at "
  624. "least one of the following nodes: " + print_cycle(cycle))
  625. e = execution_error_cleanup(cycle[-1], e, show_error=error_popups)
  626. raise e
  627. return sorted_nodes, execution_failed
  628. def execute_tree(nodes, base_tree, context, error_popups = False, profile=False):
  629. assert nodes is not None, "Failed to parse tree."
  630. assert len(nodes) > 0, "No parsed nodes for execution."\
  631. " Mantis probably failed to parse the tree."
  632. import bpy
  633. from time import time
  634. original_active = context.view_layer.objects.active
  635. start_execution_time = time()
  636. mContext = None
  637. for mantis_node in nodes.values():
  638. if not mContext: # just grab one of these. this is a silly way to do this.
  639. mContext = mantis_node.mContext
  640. mContext.b_objects = {} # clear the objects and recreate them
  641. mantis_node.reset_execution()
  642. mContext.execution_failed = False
  643. interface_nodes = {}
  644. from ..internal_nodes import GroupInterface
  645. for node in nodes.values():
  646. if isinstance(node, GroupInterface):
  647. interface_nodes[node.signature] = node
  648. overlay_tagged_nodes = {}
  649. for node_signature, socket_id in mContext.tagged_for_overlay:
  650. if overlay_tagged_nodes.get(node_signature):
  651. overlay_tagged_nodes[node_signature].append(socket_id)
  652. else:
  653. overlay_tagged_nodes[node_signature] = [socket_id]
  654. def check_and_apply_overlay(n):
  655. if overlays_for_this_node := overlay_tagged_nodes.get(n.signature):
  656. for socket_id in overlays_for_this_node:
  657. node_scan_overlays(n, socket_id,)
  658. select_me, switch_me = [], [] # switch the mode on these objects
  659. active = None # only need it for switching modes
  660. select_me = []
  661. profiler = None
  662. if profile:
  663. from ..dev_helpers.profile_nodes import NodeProfiler
  664. profiler = NodeProfiler()
  665. profiler.new_session(mContext.execution_id)
  666. sort_key = 'total'
  667. try:
  668. sorted_nodes, execution_failed = sort_execution(nodes, error_popups=error_popups)
  669. except Exception as e:
  670. # We'll fire the popup in sort_execution because it has the node in scope
  671. if error_popups == False:
  672. raise e
  673. execution_failed = True
  674. try:
  675. for n in sorted_nodes:
  676. if execution_failed: break
  677. try:
  678. check_and_apply_overlay(n)
  679. if not n.prepared:
  680. if profiler: profiler.record(n, "bPrepare", context)
  681. else: n.bPrepare(context)
  682. if not n.executed:
  683. if profiler: profiler.record(n, "bTransformPass", context)
  684. else: n.bTransformPass(context)
  685. if (n.__class__.__name__ == "xFormArmature" ):
  686. ob = n.bGetObject()
  687. switch_me.append(ob)
  688. active = ob
  689. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  690. ob = n.bGetObject()
  691. if isinstance(ob, bpy.types.Object):
  692. select_me.append(ob)
  693. except Exception as e:
  694. e = execution_error_cleanup(n, e, show_error=error_popups)
  695. if error_popups == False:
  696. raise e
  697. execution_failed = True; break
  698. switch_mode(mode='POSE', objects=switch_me)
  699. for n in sorted_nodes:
  700. try:
  701. check_and_apply_overlay(n)
  702. if not n.prepared:
  703. if profiler: profiler.record(n, "bPrepare", context)
  704. else: n.bPrepare(context)
  705. if not n.executed:
  706. if profiler: profiler.record(n, "bRelationshipPass", context)
  707. else: n.bRelationshipPass(context)
  708. except Exception as e:
  709. e = execution_error_cleanup(n, e, show_error=error_popups)
  710. if error_popups == False:
  711. raise e
  712. execution_failed = True; break
  713. switch_mode(mode='OBJECT', objects=switch_me)
  714. # switch to pose mode here so that the nodes can use the final pose data
  715. # this will require them to update the depsgraph.
  716. for ob in switch_me:
  717. ob.data.pose_position = 'POSE'
  718. for n in sorted_nodes:
  719. try:
  720. if profiler: profiler.record(n, "bFinalize", context)
  721. else: n.bFinalize(context)
  722. except Exception as e:
  723. e = execution_error_cleanup(n, e, show_error=error_popups)
  724. if error_popups == False:
  725. raise e
  726. execution_failed = True; break
  727. # REST pose for deformer bind, so everything is in the rest position
  728. for ob in switch_me:
  729. ob.data.pose_position = 'REST'
  730. # finally, apply modifiers and bind stuff
  731. for n in sorted_nodes:
  732. try:
  733. if profiler: profiler.record(n, "bModifierApply", context)
  734. else: n.bModifierApply(context)
  735. except Exception as e:
  736. e = execution_error_cleanup(n, e, show_error=error_popups)
  737. if error_popups == False:
  738. raise e
  739. execution_failed = True; break
  740. for ob in switch_me:
  741. ob.data.pose_position = 'POSE'
  742. tot_time = (time() - start_execution_time)
  743. if not execution_failed:
  744. prGreen(f"Executed tree of {len(sorted_nodes)} nodes in {tot_time} seconds")
  745. if profiler:
  746. from ..dev_helpers.profile_nodes import summarize_profile
  747. summarize_profile(profiler._current, pass_name='bPrepare', sort_key = sort_key)
  748. summarize_profile(profiler._current, pass_name='bTransformPass', sort_key = sort_key)
  749. summarize_profile(profiler._current, pass_name='bRelationshipPass', sort_key = sort_key)
  750. summarize_profile(profiler._current, pass_name='bFinalize', sort_key = sort_key)
  751. summarize_profile(profiler._current, pass_name='bModifierApply', sort_key = sort_key)
  752. if (original_active):
  753. context.view_layer.objects.active = original_active
  754. original_active.select_set(True)
  755. except Exception as e:
  756. e = execution_error_cleanup(None, e, switch_me, show_error=error_popups)
  757. if error_popups == False:
  758. raise e
  759. prRed(f"Failed to execute tree.")
  760. finally:
  761. context.view_layer.objects.active = active
  762. # clear the selection first.
  763. from itertools import chain
  764. for ob in context.selected_objects:
  765. try:
  766. ob.select_set(False)
  767. except RuntimeError: # it isn't in the view layer
  768. pass
  769. for ob in chain(select_me, mContext.b_objects.values()):
  770. try:
  771. ob.select_set(True)
  772. except RuntimeError: # it isn't in the view layer
  773. pass