readtree.py 45 KB

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