readtree.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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. # Do not use these input names as overlay keys:
  202. forbidden_key_names = ["",]
  203. forbidden_in_key_name = ['$',]
  204. def node_scan_overlays(node, socket_id,):
  205. interface_nodes = node.mContext.interface_nodes
  206. from .utilities.utilities import get_ui_node
  207. ui_node = get_ui_node(node.ui_signature, node.base_tree)
  208. # we'll assume that the overlay tag system checked if this is linked.
  209. # First let's check if it is a simple input node, by checking outputs that are marked "input"
  210. for socket in ui_node.outputs:
  211. # weird edge case for simple input nodes with unnamed sockets
  212. # the socket.identifier is not used by Mantis but it defaults to 'socket'\
  213. if socket.identifier == socket_id and socket.input == True: break
  214. else:
  215. for socket in ui_node.inputs:
  216. if socket.identifier == socket_id: break
  217. else:
  218. raise KeyError(f"Socket not found by ID {socket_id} in node {node.ui_signature}\n"
  219. f"Candidates: {[socket.identifier for socket in ui_node.inputs]}")
  220. value = socket.default_value # get the ACTUAL UI value
  221. if not isinstance(value, str): return
  222. # First step: get the interface nodes and the overlay keys
  223. # this should only check interfaces that are ancestors of this node
  224. my_interfaces = []
  225. for index in range(len(node.signature)-1):
  226. if index == 0: continue # root
  227. interface_signature = (*node.signature[:index+1], "InputInterface")
  228. my_interfaces.append( interface_nodes[interface_signature] )
  229. # the my_interfaces list is sorted in REVERSE order of importance
  230. # Next, get all the overlay providers.
  231. name_to_id_map = {}
  232. overlay_keys = set()
  233. root_overlay_values = {}
  234. # First, we'll get the base tree's default inputs
  235. for interface_item in node.mContext.base_tree.interface.items_tree:
  236. if interface_item.item_type != "SOCKET": continue
  237. if interface_item.in_out != "INPUT": continue
  238. # NOTE this will need to change if overlays extend to other data types
  239. if not hasattr(interface_item, "default_string"): continue
  240. # NOTE that there may be duplicate names. Too bad!
  241. root_overlay_values[interface_item.name] = interface_item.default_string
  242. overlay_keys.add(interface_item.name)
  243. name_to_id_map[interface_item.name] = None # don't worry about it
  244. for interface_node in interface_nodes.values():
  245. # problem: the interface node stores socket identifiers as keys
  246. # so in reality we need to get the group UI node and ask for its input names
  247. # if there is a duplicate name, too bad!
  248. group_ui_node = get_ui_node(interface_node.ui_signature[:-1], node.base_tree)
  249. for input in group_ui_node.inputs:
  250. if input.name in forbidden_key_names: continue
  251. for substr in forbidden_in_key_name:
  252. if substr in input.name:
  253. break
  254. else: # if we do not find a bad substr
  255. name_to_id_map[input.name]=input.identifier
  256. overlay_keys.add(input.name)
  257. # sort by reverse length so we find "CatsAndFrogs" before "Cats"
  258. overlay_keys = sorted(overlay_keys, key= lambda a :-1*len(a))
  259. overlay_tries = value.split("$")
  260. result = overlay_tries[0] # the 0th element is always before the split character
  261. # the reason for the difference between overlay_try and key is because
  262. # we don't actually know if the $text part has a key in it
  263. for overlay_try in overlay_tries[1:]:
  264. overlay_resolved_value = "$" + overlay_try
  265. for key in overlay_keys:
  266. if key in overlay_try:
  267. overlay_resolved_value = "$" + key
  268. for interface in reversed(my_interfaces): # since this is reversed when we build it
  269. if interface.inputs.get(actual_key := name_to_id_map.get(key)):
  270. overlay_resolved_value = overlay_try.replace(key, interface.evaluate_input(actual_key))
  271. break
  272. else: # we'll try the base tree
  273. if base_tree_result := root_overlay_values.get(overlay_try):
  274. overlay_resolved_value = base_tree_result
  275. else:
  276. prOrange(f"WARN: no overlay value applied for {node.ui_signature} for key {key}")
  277. break # we found the key and are done here. One found Key per overlay-try
  278. result += overlay_resolved_value
  279. # Simple Input sockets with unnamed sockets assign this ID automatically
  280. # But Mantis uses the name instead. Usually the name and ID are the same.
  281. if socket_id == 'socket' and ui_node.outputs[0].name == "":
  282. socket_id = ''
  283. node.parameters[socket_id] = result
  284. return result # because sometimes I need to get the result, too
  285. from .utilities.utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  286. def is_signature_in_other_signature(parent_signature, child_signature):
  287. # If the other signature is shorter, it isn't a child node
  288. if len(parent_signature) > len(child_signature):
  289. return False
  290. return parent_signature[0:] == child_signature[:len(parent_signature)]
  291. def solve_schema_to_tree(mantis_node, all_mantis_nodes, roots=[], error_popups=False):
  292. from .utilities.utilities import get_ui_node
  293. np = get_ui_node(mantis_node.signature, mantis_node.base_tree)
  294. from .schema_solve import SchemaSolver
  295. solver = SchemaSolver(mantis_node, all_mantis_nodes.copy(), np, error_popups=error_popups)
  296. try:
  297. solved_nodes = solver.solve()
  298. except Exception as e:
  299. # # the schema will run the error cleanup code, we just need to raise or not
  300. solved_nodes = {}
  301. mantis_node.base_tree.hash=''
  302. raise execution_error_cleanup(mantis_node, e, show_error=error_popups)
  303. # maybe this should be done in schema solver. TODO invesitigate a more efficient way
  304. del_me = []
  305. for k, v in all_mantis_nodes.items():
  306. # delete all the schema's ui_node and interface nodes. The links have already been deleted by the solver.
  307. if v.signature[0] not in ['MANTIS_AUTOGENERATED'] and is_signature_in_other_signature(mantis_node.signature, k):
  308. del_me.append(k)
  309. for k in del_me:
  310. del all_mantis_nodes[k]
  311. for k,v in solved_nodes.items():
  312. all_mantis_nodes[k]=v
  313. init_connections(v)
  314. check_and_add_root(v, roots, include_non_hierarchy=True)
  315. return solved_nodes
  316. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  317. # PARSE NODE TREE #
  318. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  319. schema_bl_idnames = [ "SchemaIndex",
  320. "SchemaArrayInput",
  321. "SchemaArrayInputGet",
  322. "SchemaArrayInputAll",
  323. "SchemaArrayOutput",
  324. "SchemaConstInput",
  325. "SchemaConstOutput",
  326. "SchemaOutgoingConnection",
  327. "SchemaIncomingConnection",
  328. ]
  329. from .utilities.utilities import get_all_dependencies
  330. def get_schema_length_dependencies(node, all_nodes={}):
  331. """ Get a list of all dependencies for the given node's length or array properties.
  332. This function will also recursively search for dependencies in its sub-trees.
  333. """
  334. deps = []
  335. prepare_links_to = ['Schema Length', 'Array', 'Index']
  336. def extend_dependencies_from_inputs(node):
  337. for inp in node.inputs.values():
  338. for l in inp.links:
  339. if not l.from_node in node.hierarchy_dependencies:
  340. continue
  341. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  342. deps.extend([l.from_node]) # why we need this lol
  343. if inp.name in prepare_links_to:
  344. deps.append(l.from_node)
  345. deps.extend(get_all_dependencies(l.from_node))
  346. def deps_filter(dep): # remove any nodes inside the schema
  347. if len(dep.signature) > len(node.signature):
  348. for i in range(len(node.signature)):
  349. dep_sig_elem, node_sig_elem = dep.signature[i], node.signature[i]
  350. if dep_sig_elem != node_sig_elem: break # they don't match, it isn't an inner-node
  351. else: # remove this, it didn't break, meaning it shares signature with outer node
  352. return False # this is an inner-node
  353. return True
  354. # this way we can handle Schema and Array Get nodes with one function
  355. extend_dependencies_from_inputs(node)
  356. if node.node_type == 'DUMMY_SCHEMA':
  357. trees = [(node.ui_node.node_tree, node.signature)] # this is UI data
  358. while trees:
  359. tree, tree_signature = trees.pop()
  360. for sub_ui_node in tree.nodes:
  361. if sub_ui_node.bl_idname in ['NodeReroute', 'NodeFrame']:
  362. continue
  363. if sub_ui_node.bl_idname in schema_bl_idnames:
  364. sub_node = all_nodes[(*tree_signature, sub_ui_node.bl_idname)]
  365. else:
  366. sub_node = all_nodes[(*tree_signature, sub_ui_node.name)]
  367. if sub_node.node_type == 'DUMMY_SCHEMA':
  368. extend_dependencies_from_inputs(sub_node)
  369. trees.append((sub_node.ui_node.node_tree, sub_node.signature))
  370. return list(filter(deps_filter, deps))
  371. def insert_default_values_base_tree(base_tree, all_mantis_nodes):
  372. # we can get this by name because group inputs are gathered to the bl_idname
  373. InputNode = all_mantis_nodes.get((None, 'NodeGroupInput'))
  374. if InputNode is None: return # nothing to do here.
  375. ui_node = InputNode.ui_node
  376. for i, output in enumerate(InputNode.outputs):
  377. ui_output = ui_node.outputs[i] # I need this for the error messages to make sense
  378. assert ui_output.identifier == output.name, "Cannot find UI Socket for Default Value"
  379. for interface_item in base_tree.interface.items_tree:
  380. if interface_item.item_type == 'PANEL': continue
  381. if interface_item.identifier == output.name: break
  382. else:
  383. raise RuntimeError(f"Default value {ui_output.name} does not exist in {base_tree.name} ")
  384. if interface_item.item_type == "PANEL":
  385. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  386. default_value = None
  387. from bpy.types import bpy_prop_array
  388. from mathutils import Vector
  389. val_type = None
  390. if hasattr(ui_output, 'default_value'):
  391. val_type = type(ui_output.default_value) # why tf can't I match/case here?
  392. if val_type is bool: default_value = interface_item.default_bool
  393. elif val_type is int: default_value = interface_item.default_int
  394. elif val_type is float: default_value = interface_item.default_float
  395. elif val_type is Vector: default_value = interface_item.default_vector
  396. elif val_type is str: default_value = interface_item.default_string
  397. elif val_type is bpy_prop_array: default_value = interface_item.default_bool_vector
  398. elif interface_item.bl_socket_idname == "xFormSocket":
  399. if interface_item.default_xForm == 'ARMATURE':
  400. default_value = 'MANTIS_DEFAULT_ARMATURE'
  401. else:
  402. raise RuntimeError(f"No xForm connected for {ui_output.name} in {base_tree.name}.")
  403. else:
  404. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  405. output_name = output.name
  406. if interface_item.bl_socket_idname not in ['xFormSocket']:
  407. signature = ("MANTIS_AUTOGENERATED", f"Default Value {output.name}",)
  408. autogen_mantis_node = all_mantis_nodes.get(signature)
  409. if autogen_mantis_node is None:
  410. autogen_mantis_node = autogen_node(base_tree, output, signature, InputNode.mContext)
  411. autogen_mantis_node.parameters[output_name]=default_value
  412. elif interface_item.bl_socket_idname == 'xFormSocket' \
  413. and default_value == 'MANTIS_DEFAULT_ARMATURE':
  414. signature = ("MANTIS_AUTOGENERATED", "MANTIS_DEFAULT_ARMATURE",)
  415. autogen_mantis_node = all_mantis_nodes.get(signature)
  416. if autogen_mantis_node is None:
  417. from .xForm_nodes import xFormArmature
  418. autogen_mantis_node = xFormArmature(signature, base_tree)
  419. autogen_mantis_node.parameters['Name']=base_tree.name+'_MANTIS_AUTOGEN'
  420. autogen_mantis_node.mContext = InputNode.mContext
  421. from mathutils import Matrix
  422. autogen_mantis_node.parameters['Matrix'] = Matrix.Identity(4)
  423. output_name = 'xForm Out'
  424. while output.links:
  425. l = output.links.pop()
  426. to_node = l.to_node; to_socket = l.to_socket
  427. l.die()
  428. autogen_mantis_node.outputs[output_name].connect(to_node, to_socket)
  429. init_connections(l.from_node); init_dependencies(l.from_node)
  430. all_mantis_nodes[autogen_mantis_node.signature]=autogen_mantis_node
  431. def parse_tree(base_tree, error_popups=False):
  432. from uuid import uuid4
  433. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  434. from .base_definitions import MantisExecutionContext
  435. mContext = MantisExecutionContext(base_tree=base_tree)
  436. import time
  437. data_start_time = time.time()
  438. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  439. # then they stick around because the function definition inits them once and keeps a reference
  440. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  441. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  442. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(base_tree, tree_path = [None], mContext=mContext, dummy_nodes = {}, all_mantis_nodes = {}, all_schema={})
  443. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  444. if (hasattr(dummy, "reroute_links")):
  445. dummy.reroute_links(dummy, all_mantis_nodes)
  446. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  447. start_time = time.time()
  448. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  449. roots, array_nodes = [], []
  450. from collections import deque
  451. unsolved_schema = deque()
  452. from .base_definitions import array_output_types, GraphError
  453. for mantis_node in all_mantis_nodes.values():
  454. # TODO I still need to assign mContext here because of autogen_node
  455. # so I have to do a deeper refactor to ensure autogen nodes get this at creation time.
  456. mantis_node.mContext = mContext
  457. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  458. if mantis_node.ui_node.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  459. continue
  460. # Initialize the dependencies and connections (from/to links) for each node.
  461. # we record & store it because using a getter is much slower (according to profiling)
  462. init_dependencies(mantis_node); init_connections(mantis_node)
  463. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  464. # Array nodes need a little special treatment, they're quasi-schemas
  465. if mantis_node.__class__.__name__ in array_output_types:
  466. solve_only_these.append(mantis_node)
  467. array_nodes.append(mantis_node)
  468. if mantis_node.node_type == 'INTERFACE':
  469. mContext.interface_nodes[mantis_node.signature] = mantis_node
  470. from itertools import chain
  471. for schema in chain(all_schema.values(), array_nodes):
  472. # We must remove the schema/array nodes that are inside a schema tree.
  473. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  474. if parent := all_schema.get(schema.signature[:i+1]):
  475. # This will be solved along with its parent schema.
  476. solve_only_these.remove(schema)
  477. break
  478. for schema in all_schema.values():
  479. if schema not in solve_only_these: continue
  480. init_schema_dependencies(schema, all_mantis_nodes)
  481. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  482. unsolved_schema.append(schema)
  483. for array in array_nodes:
  484. if array not in solve_only_these: continue
  485. solve_only_these.extend(get_schema_length_dependencies(array))
  486. solve_only_these.extend(array_nodes)
  487. schema_solve_done = set()
  488. solve_only_these = set(solve_only_these)
  489. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  490. while(solve_layer):
  491. n = solve_layer.pop()
  492. if n not in solve_only_these:
  493. continue
  494. if n.signature in all_schema.keys():
  495. for dep in n.hierarchy_dependencies:
  496. if dep not in schema_solve_done and (dep in solve_only_these):
  497. if dep.prepared:
  498. continue
  499. solve_layer.appendleft(n)
  500. break
  501. else:
  502. try:
  503. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots, error_popups=error_popups)
  504. except Exception as e:
  505. e = execution_error_cleanup(n, e, show_error=error_popups)
  506. solved_nodes = {}
  507. if error_popups == False:
  508. raise e
  509. return # break out of this function regardless.
  510. unsolved_schema.remove(n)
  511. schema_solve_done.add(n)
  512. for node in solved_nodes.values():
  513. init_dependencies(node); init_connections(node)
  514. solve_layer.appendleft(node)
  515. schema_solve_done.add(node) # CRITICAL to prevent freezes.
  516. for conn in n.hierarchy_connections:
  517. if conn not in schema_solve_done and conn not in solve_layer:
  518. solve_layer.appendleft(conn)
  519. continue
  520. else:
  521. for dep in n.hierarchy_dependencies:
  522. if dep not in schema_solve_done:
  523. break
  524. else:
  525. try:
  526. n.bPrepare()
  527. except Exception as e:
  528. e = execution_error_cleanup(n, e, show_error=error_popups)
  529. if error_popups == False:
  530. raise e
  531. schema_solve_done.add(n)
  532. for conn in n.hierarchy_connections:
  533. if conn not in schema_solve_done and conn not in solve_layer:
  534. solve_layer.appendleft(conn)
  535. continue
  536. if unsolved_schema:
  537. raise RuntimeError("Failed to resolve all schema declarations")
  538. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  539. all_mantis_nodes = list(all_mantis_nodes.values())
  540. kept_mantis_node = {}
  541. while (all_mantis_nodes):
  542. mantis_node = all_mantis_nodes.pop()
  543. if mantis_node.node_type in ["DUMMY", 'SCHEMA', 'DUMMY_SCHEMA']:
  544. continue # screen out the ui_node schema nodes, group in/out, and group placeholders
  545. # cleanup autogen nodes
  546. if mantis_node.signature[0] == "MANTIS_AUTOGENERATED" and len(mantis_node.inputs) == 0 and len(mantis_node.outputs) == 1:
  547. from .base_definitions import can_remove_socket_for_autogen
  548. output=list(mantis_node.outputs.values())[0]
  549. value=list(mantis_node.parameters.values())[0]
  550. # We can remove this node if it is safe to push it into the other node's socket.
  551. keep_me = False
  552. for l in output.links:
  553. to_node = l.to_node; to_socket = l.to_socket
  554. # do not remove the socket if it is a custom property.
  555. if not can_remove_socket_for_autogen(to_node, to_socket):
  556. keep_me = True; continue
  557. l.die()
  558. to_node.parameters[to_socket] = value
  559. del to_node.inputs[to_socket]
  560. init_dependencies(to_node) # to remove the autogen node we no longer need.
  561. if not keep_me:
  562. continue
  563. init_connections(mantis_node) # because we have removed many connections.
  564. if (mantis_node.node_type in ['XFORM']) and ("Relationship" in mantis_node.inputs.keys()):
  565. if (new_mantis_node := insert_lazy_parents(mantis_node)):
  566. kept_mantis_node[new_mantis_node.signature]=new_mantis_node
  567. # be sure to add the Mantis context.
  568. new_mantis_node.mContext =mContext
  569. kept_mantis_node[mantis_node.signature]=mantis_node
  570. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  571. prWhite("Number of Nodes: %s" % (len(kept_mantis_node)))
  572. return kept_mantis_node
  573. from .utilities.utilities import switch_mode
  574. def execution_error_cleanup(node, exception, switch_objects = [], show_error=False ):
  575. from bpy import context
  576. ui_sig = None
  577. if show_error: # show a popup and select the relevant nodes
  578. if node:
  579. if node.mContext:
  580. if node.mContext.execution_failed==True:
  581. # already have an error, pass it to avoid printing
  582. return # a second error (it's confusing to users.)
  583. node.mContext.execution_failed=True
  584. ui_sig = node.ui_signature
  585. # TODO: see about zooming-to-node.
  586. base_tree = node.base_tree
  587. tree = base_tree
  588. try:
  589. for name in ui_sig[1:]:
  590. for n in tree.nodes: n.select = False
  591. n = tree.nodes[name]
  592. n.select = True
  593. tree.nodes.active = n
  594. if hasattr(n, "node_tree"):
  595. tree = n.node_tree
  596. except AttributeError: # not being run in node graph
  597. pass
  598. finally:
  599. def error_popup_draw(self, context):
  600. self.layout.label(text=f"Error: {exception}")
  601. self.layout.label(text=f"see node: {ui_sig[1:]}.")
  602. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  603. switch_mode(mode='OBJECT', objects=switch_objects)
  604. for ob in switch_objects:
  605. ob.data.pose_position = 'POSE'
  606. prRed(f"Error: {exception} in node {ui_sig}")
  607. return exception
  608. def sort_execution(nodes):
  609. from .utilities.node_common import GraphError
  610. from collections import deque
  611. xForm_pass = deque()
  612. execution_failed = False
  613. sorted_nodes = []
  614. # initialize the hierarchy dependency count. We'll use this to ensure there
  615. # are no cycles (using Kahn's algorithm).
  616. for mantis_node in nodes.values():
  617. mantis_node.unmet_hierarchy_dependency_count = len(mantis_node.hierarchy_dependencies)
  618. if mantis_node.unmet_hierarchy_dependency_count == 0 :
  619. xForm_pass.append(mantis_node)
  620. processed_count = 0
  621. while(xForm_pass):
  622. n = xForm_pass.pop()
  623. # if n.execution_prepared: continue
  624. n.execution_prepared = True
  625. sorted_nodes.append(n)
  626. processed_count+=1
  627. for child in n.hierarchy_connections:
  628. child.unmet_hierarchy_dependency_count-= 1
  629. if child.unmet_hierarchy_dependency_count == 0:
  630. xForm_pass.append(child)
  631. if processed_count < len(nodes):
  632. execution_failed = True
  633. raise GraphError("detected a cycle in the tree")
  634. return sorted_nodes, execution_failed
  635. def execute_tree(nodes, base_tree, context, error_popups = False, profile=False):
  636. assert nodes is not None, "Failed to parse tree."
  637. assert len(nodes) > 0, "No parsed nodes for execution."\
  638. " Mantis probably failed to parse the tree."
  639. import bpy
  640. from time import time
  641. original_active = context.view_layer.objects.active
  642. start_execution_time = time()
  643. mContext = None
  644. for mantis_node in nodes.values():
  645. if not mContext: # just grab one of these. this is a silly way to do this.
  646. mContext = mantis_node.mContext
  647. mContext.b_objects = {} # clear the objects and recreate them
  648. mantis_node.reset_execution()
  649. mContext.execution_failed = False
  650. interface_nodes = {}
  651. from .internal_nodes import GroupInterface
  652. for node in nodes.values():
  653. if isinstance(node, GroupInterface):
  654. interface_nodes[node.signature] = node
  655. overlay_tagged_nodes = {}
  656. for node_signature, socket_id in mContext.tagged_for_overlay:
  657. if overlay_tagged_nodes.get(node_signature):
  658. overlay_tagged_nodes[node_signature].append(socket_id)
  659. else:
  660. overlay_tagged_nodes[node_signature] = [socket_id]
  661. def check_and_apply_overlay(n):
  662. if overlays_for_this_node := overlay_tagged_nodes.get(n.signature):
  663. for socket_id in overlays_for_this_node:
  664. node_scan_overlays(n, socket_id,)
  665. select_me, switch_me = [], [] # switch the mode on these objects
  666. active = None # only need it for switching modes
  667. select_me = []
  668. profiler = None
  669. if profile:
  670. from .dev_helpers.profile_nodes import NodeProfiler
  671. profiler = NodeProfiler()
  672. profiler.new_session(mContext.execution_id)
  673. sort_key = 'total'
  674. try:
  675. sorted_nodes, execution_failed = sort_execution(nodes)
  676. for n in sorted_nodes:
  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