readtree.py 38 KB

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