readtree.py 38 KB

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