readtree.py 36 KB

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