readtree.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. from .utilities import prRed, prGreen, prPurple, prWhite, prOrange, \
  2. wrapRed, wrapGreen, wrapPurple, wrapWhite, wrapOrange
  3. def grp_node_reroute_common(nc, nc_to, all_nc):
  4. # we need to do this: go to the to-node
  5. # then reroute the link in the to_node all the way to the beginning
  6. # so that the number of links in "real" nodes is unchanged
  7. # then the links in the dummy nodes need to be deleted
  8. for inp_name, inp in nc.inputs.items():
  9. # assume each input socket only has one input for now
  10. if inp.is_connected:
  11. while (inp.links):
  12. in_link = inp.links.pop()
  13. from_nc = in_link.from_node
  14. from_socket = in_link.from_socket
  15. links = []
  16. from_links = from_nc.outputs[from_socket].links.copy()
  17. while(from_links):
  18. from_link = from_links.pop()
  19. if from_link == in_link:
  20. from_link.die()
  21. continue # DELETE the dummy node link
  22. links.append(from_link)
  23. from_nc.outputs[from_socket].links = links
  24. down = nc_to.outputs[inp_name]
  25. for downlink in down.links:
  26. downlink.from_node = from_nc
  27. downlink.from_socket = from_socket
  28. from_nc.outputs[from_socket].links.append(downlink)
  29. if hasattr(downlink.to_node, "reroute_links"):
  30. downlink.to_node.reroute_links(downlink.to_node, all_nc)
  31. in_link.die()
  32. def reroute_links_grp(nc, all_nc):
  33. if nc.inputs:
  34. if (nc_to := all_nc.get( ( *nc.signature, "NodeGroupInput") )):
  35. grp_node_reroute_common(nc, nc_to, all_nc)
  36. else:
  37. raise RuntimeError("internal error: failed to enter a node group ")
  38. def reroute_links_grpout(nc, all_nc):
  39. if (nc_to := all_nc.get( ( *nc.signature[:-1],) )):
  40. grp_node_reroute_common(nc, nc_to, all_nc)
  41. else:
  42. raise RuntimeError("error leaving a node group (maybe you are running the tree from inside a node group?)")
  43. # FIXME I don't think these signatures are unique.
  44. def insert_lazy_parents(nc):
  45. from .link_containers import LinkInherit
  46. from .base_definitions import NodeLink
  47. inherit_nc = None
  48. if nc.inputs["Relationship"].is_connected:
  49. link = nc.inputs["Relationship"].links[0]
  50. # print(nc)
  51. from_nc = link.from_node
  52. if from_nc.node_type in ["XFORM"] and link.from_socket in ["xForm Out"]:
  53. inherit_nc = LinkInherit(("MANTIS_AUTOGENERATED", *nc.signature[1:], "LAZY_INHERIT"), nc.base_tree)
  54. for from_link in from_nc.outputs["xForm Out"].links:
  55. if from_link.to_node == nc and from_link.to_socket == "Relationship":
  56. break # this is it
  57. from_link.to_node = inherit_nc; from_link.to_socket="Parent"
  58. from_link.to_node.inputs[from_link.to_socket].is_linked=True
  59. links=[]
  60. while (nc.inputs["Relationship"].links):
  61. to_link = nc.inputs["Relationship"].links.pop()
  62. if to_link.from_node == from_nc and to_link.from_socket == "xForm Out":
  63. continue # don't keep this one
  64. links.append(to_link)
  65. to_link.from_node.outputs[from_link.from_socket].is_linked=True
  66. nc.inputs["Relationship"].links=links
  67. link=NodeLink(from_node=inherit_nc, from_socket="Inheritance", to_node=nc, to_socket="Relationship")
  68. inherit_nc.inputs["Parent"].links.append(from_link)
  69. inherit_nc.parameters = {
  70. "Parent":None,
  71. "Inherit Rotation":True,
  72. "Inherit Scale":'FULL',
  73. "Connected":False,
  74. }
  75. # because the from node may have already been done.
  76. init_connections(from_nc)
  77. init_dependencies(from_nc)
  78. init_connections(inherit_nc)
  79. init_dependencies(inherit_nc)
  80. return inherit_nc
  81. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  82. # DATA FROM NODES #
  83. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  84. from .base_definitions import replace_types, NodeSocket
  85. def autogen_node(base_tree, ui_socket, signature, mContext):
  86. mantis_node=None
  87. from .utilities import gen_nc_input_for_data
  88. nc_cls = gen_nc_input_for_data(ui_socket)
  89. if (nc_cls):
  90. mantis_node = nc_cls(signature, base_tree)
  91. mantis_node.mContext = mContext
  92. mantis_node.execution_prepared=True
  93. mantis_node.outputs.init_sockets([ui_socket.name])
  94. return mantis_node
  95. # TODO: investigate whether I can set the properties in the downstream nodes directly.
  96. # I am doing this in Schema Solver and it seems to work quite efficiently.
  97. def make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, nc_to):
  98. np = nc_to.prototype
  99. for inp in np.inputs:
  100. nc_from = None
  101. if inp.bl_idname in ['WildcardSocket']:
  102. continue # it isn't a real input so I don't think it is good to check it.
  103. to_s = inp.identifier
  104. if not inp.is_linked: # make an autogenerated NC for the inputs of the group node
  105. signature = ("MANTIS_AUTOGENERATED", *tree_path_names, np.name, inp.name, inp.identifier)
  106. nc_from = autogen_node(base_tree, inp, signature, nc_to.mContext)
  107. if nc_from:
  108. from .node_container_common import get_socket_value
  109. nc_from.parameters = {inp.name:get_socket_value(inp)}
  110. local_nc[signature] = nc_from; all_nc[signature] = nc_from
  111. nc_from.outputs[inp.name].connect(node=nc_to, socket=to_s, sort_id=0)
  112. else:
  113. prRed("No available auto-generated class for input", *tree_path_names, inp.name, np.name)
  114. def gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, schema_nodes ):
  115. from .internal_containers import DummyNode
  116. for ui_node in current_tree.nodes:
  117. # HACK I found that this isn't being set sometimes. I wonder why? It makes the most sense to do this here.
  118. if hasattr(ui_node, 'initialized'): ui_node.initialized=True
  119. # end HACK. TODO: find out why this is not set sometimes. This is only needed for UI socket change updates.
  120. if ui_node.bl_idname in ["NodeFrame", "NodeReroute"]:
  121. continue # not a Mantis Node
  122. if ui_node.bl_idname in ["NodeGroupInput", "NodeGroupOutput"]:
  123. # we only want ONE dummy in/out per tree_path, so use the bl_idname to make a Dummy node
  124. sig = (None, *tree_path_names, ui_node.bl_idname)
  125. ui_sig = (None, *tree_path_names, ui_node.name)
  126. if not local_nc.get(sig):
  127. nc = DummyNode( signature=sig , base_tree=base_tree, prototype=ui_node, ui_signature=ui_sig )
  128. local_nc[sig] = nc; all_nc[sig] = nc; dummy_nodes[sig] = nc
  129. if ui_node.bl_idname in ["NodeGroupOutput"]:
  130. nc.reroute_links = reroute_links_grpout
  131. elif ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  132. nc = DummyNode( signature= (sig := (None, *tree_path_names, ui_node.name) ), base_tree=base_tree, prototype=ui_node )
  133. local_nc[sig] = nc; all_nc[sig] = nc; dummy_nodes[sig] = nc
  134. make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, nc)
  135. if ui_node.bl_idname == "MantisNodeGroup":
  136. group_nodes.append(nc)
  137. nc.reroute_links = reroute_links_grp
  138. else:
  139. group_nodes.append(nc)
  140. schema_nodes[sig] = nc
  141. # if it wasn't the types we ignore or the types we make a Dummy for, use this to catch all non-special cases.
  142. elif (nc_cls := ui_node.mantis_class):
  143. sig = (None, *tree_path_names, ui_node.name)
  144. if ui_node.bl_idname in replace_types:
  145. sig = (None, *tree_path_names, ui_node.bl_idname)
  146. if local_nc.get(sig):
  147. continue # already made
  148. nc = nc_cls( sig , base_tree)
  149. local_nc[sig] = nc; all_nc[sig] = nc
  150. nc.ui_signature = (*nc.ui_signature[:-1], ui_node.name) # just to ensure it points to a real node.
  151. else:
  152. nc = None
  153. prRed(f"Can't make nc for.. {ui_node.bl_idname}")
  154. # this should be done at init
  155. if nc.signature[0] not in ['MANTIS_AUTOGENERATED'] and nc.node_type not in ['SCHEMA', 'DUMMY', 'DUMMY_SCHEMA']:
  156. nc.fill_parameters()
  157. def data_from_tree(base_tree, tree_path, dummy_nodes, all_nc, all_schema):#
  158. # TODO: it should be relatively easy to make this use a while loop instead of recursion.
  159. local_nc, group_nodes = {}, []
  160. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  161. if tree_path[-1]:
  162. current_tree = tree_path[-1].node_tree # this may be None.
  163. else:
  164. current_tree = base_tree
  165. #
  166. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  167. from .utilities import clear_reroutes
  168. links = clear_reroutes(list(current_tree.links))
  169. gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, all_schema)
  170. from .utilities import link_node_containers
  171. for link in links:
  172. link_node_containers((None, *tree_path_names), link, local_nc)
  173. # Now, descend into the Node Groups and recurse
  174. for nc in group_nodes:
  175. data_from_tree(base_tree, tree_path+[nc.prototype], dummy_nodes, all_nc, all_schema)
  176. return dummy_nodes, all_nc, all_schema
  177. from .utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  178. def is_signature_in_other_signature(parent_signature, child_signature):
  179. # If the other signature is shorter, it isn't a child node
  180. if len(parent_signature) > len(child_signature):
  181. return False
  182. return parent_signature[0:] == child_signature[:len(parent_signature)]
  183. def solve_schema_to_tree(nc, all_nc, roots=[], error_popups=False):
  184. from .utilities import get_node_prototype
  185. np = get_node_prototype(nc.signature, nc.base_tree)
  186. from .schema_solve import SchemaSolver
  187. solver = SchemaSolver(nc, all_nc, np, error_popups=error_popups)
  188. try:
  189. solved_nodes = solver.solve()
  190. except Exception as e:
  191. # # the schema will run the error cleanup code, we just need to raise or not
  192. solved_nodes = {}
  193. nc.base_tree.hash=''
  194. raise execution_error_cleanup(nc, e, show_error=error_popups)
  195. # maybe this should be done in schema solver. TODO invesitigate a more efficient way
  196. del_me = []
  197. for k, v in all_nc.items():
  198. # delete all the schema's internal nodes. The links have already been deleted by the solver.
  199. if v.signature[0] not in ['MANTIS_AUTOGENERATED'] and is_signature_in_other_signature(nc.signature, k):
  200. del_me.append(k)
  201. for k in del_me:
  202. del all_nc[k]
  203. for k,v in solved_nodes.items():
  204. all_nc[k]=v
  205. init_connections(v)
  206. check_and_add_root(v, roots, include_non_hierarchy=True)
  207. return solved_nodes
  208. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  209. # PARSE NODE TREE #
  210. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  211. schema_bl_idnames = [ "SchemaIndex",
  212. "SchemaArrayInput",
  213. "SchemaArrayInputGet",
  214. "SchemaArrayInputAll",
  215. "SchemaArrayOutput",
  216. "SchemaConstInput",
  217. "SchemaConstOutput",
  218. "SchemaOutgoingConnection",
  219. "SchemaIncomingConnection",
  220. ]
  221. from .utilities import get_all_dependencies
  222. def get_schema_length_dependencies(node, all_nodes={}):
  223. """ Get a list of all dependencies for the given node's length or array properties.
  224. This function will also recursively search for dependencies in its sub-trees.
  225. """
  226. deps = []
  227. prepare_links_to = ['Schema Length', 'Array', 'Index']
  228. def extend_dependencies_from_inputs(node):
  229. for inp in node.inputs.values():
  230. for l in inp.links:
  231. if not l.from_node in node.hierarchy_dependencies:
  232. continue
  233. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  234. deps.extend([l.from_node]) # why we need this lol
  235. if inp.name in prepare_links_to:
  236. deps.append(l.from_node)
  237. deps.extend(get_all_dependencies(l.from_node))
  238. def deps_filter(dep): # remove any nodes inside the schema
  239. if len(dep.signature) > len(node.signature):
  240. for i in range(len(node.signature)):
  241. dep_sig_elem, node_sig_elem = dep.signature[i], node.signature[i]
  242. if dep_sig_elem != node_sig_elem: break # they don't match, it isn't an inner-node
  243. else: # remove this, it didn't break, meaning it shares signature with outer node
  244. return False # this is an inner-node
  245. return True
  246. # this way we can handle Schema and Array Get nodes with one function
  247. extend_dependencies_from_inputs(node)
  248. if node.node_type == 'DUMMY_SCHEMA':
  249. trees = [(node.prototype.node_tree, node.signature)] # this is UI data
  250. while trees:
  251. tree, tree_signature = trees.pop()
  252. for sub_ui_node in tree.nodes:
  253. if sub_ui_node.bl_idname in ['NodeReroute', 'NodeFrame']:
  254. continue
  255. if sub_ui_node.bl_idname in schema_bl_idnames:
  256. sub_node = all_nodes[(*tree_signature, sub_ui_node.bl_idname)]
  257. else:
  258. sub_node = all_nodes[(*tree_signature, sub_ui_node.name)]
  259. if sub_node.node_type == 'DUMMY_SCHEMA':
  260. extend_dependencies_from_inputs(sub_node)
  261. trees.append((sub_node.prototype.node_tree, sub_node.signature))
  262. return list(filter(deps_filter, deps))
  263. def parse_tree(base_tree, error_popups=False):
  264. from uuid import uuid4
  265. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  266. from .base_definitions import MantisExecutionContext
  267. mContext = MantisExecutionContext(base_tree=base_tree)
  268. import time
  269. data_start_time = time.time()
  270. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  271. # then they stick around because the function definition inits them once and keeps a reference
  272. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  273. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  274. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(base_tree, tree_path = [None], dummy_nodes = {}, all_nc = {}, all_schema={})
  275. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  276. if (hasattr(dummy, "reroute_links")):
  277. dummy.reroute_links(dummy, all_mantis_nodes)
  278. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  279. start_time = time.time()
  280. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  281. roots, array_nodes = [], []
  282. from collections import deque
  283. unsolved_schema = deque()
  284. from .base_definitions import array_output_types, GraphError
  285. for mantis_node in all_mantis_nodes.values():
  286. # add the Mantis Context here, so that it available during parsing.
  287. mantis_node.mContext = mContext
  288. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  289. if mantis_node.prototype.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  290. continue
  291. # Initialize the dependencies and connections (from/to links) for each node.
  292. # we record & store it because using a getter is much slower (according to profiling)
  293. init_dependencies(mantis_node); init_connections(mantis_node)
  294. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  295. # Array nodes need a little special treatment, they're quasi-schemas
  296. if mantis_node.__class__.__name__ in array_output_types:
  297. solve_only_these.append(mantis_node)
  298. array_nodes.append(mantis_node)
  299. from itertools import chain
  300. for schema in chain(all_schema.values(), array_nodes):
  301. # We must remove the schema/array nodes that are inside a schema tree.
  302. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  303. if parent := all_schema.get(schema.signature[:i+1]):
  304. # This will be solved along with its parent schema.
  305. solve_only_these.remove(schema)
  306. break
  307. for schema in all_schema.values():
  308. if schema not in solve_only_these: continue
  309. init_schema_dependencies(schema, all_mantis_nodes)
  310. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  311. unsolved_schema.append(schema)
  312. for array in array_nodes:
  313. if array not in solve_only_these: continue
  314. solve_only_these.extend(get_schema_length_dependencies(array))
  315. solve_only_these.extend(array_nodes)
  316. schema_solve_done = set()
  317. solve_only_these = set(solve_only_these)
  318. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  319. while(solve_layer):
  320. n = solve_layer.pop()
  321. if n not in solve_only_these:
  322. continue
  323. if n.signature in all_schema.keys():
  324. for dep in n.hierarchy_dependencies:
  325. if dep not in schema_solve_done and (dep in solve_only_these):
  326. if dep.prepared:
  327. continue
  328. solve_layer.appendleft(n)
  329. break
  330. else:
  331. try:
  332. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots, error_popups=error_popups)
  333. except Exception as e:
  334. e = execution_error_cleanup(n, e, show_error=error_popups)
  335. solved_nodes = {}
  336. if error_popups == False:
  337. raise e
  338. return # break out of this function regardless.
  339. unsolved_schema.remove(n)
  340. schema_solve_done.add(n)
  341. for node in solved_nodes.values():
  342. init_dependencies(node); init_connections(node)
  343. solve_layer.appendleft(node)
  344. schema_solve_done.add(node) # CRITICAL to prevent freezes.
  345. for conn in n.hierarchy_connections:
  346. if conn not in schema_solve_done and conn not in solve_layer:
  347. solve_layer.appendleft(conn)
  348. continue
  349. else:
  350. for dep in n.hierarchy_dependencies:
  351. if dep not in schema_solve_done:
  352. break
  353. else:
  354. try:
  355. n.bPrepare()
  356. except Exception as e:
  357. e = execution_error_cleanup(n, e, show_error=error_popups)
  358. if error_popups == False:
  359. raise e
  360. schema_solve_done.add(n)
  361. for conn in n.hierarchy_connections:
  362. if conn not in schema_solve_done and conn not in solve_layer:
  363. solve_layer.appendleft(conn)
  364. continue
  365. if unsolved_schema:
  366. raise RuntimeError("Failed to resolve all schema declarations")
  367. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  368. all_mantis_nodes = list(all_mantis_nodes.values())
  369. kept_nc = {}
  370. while (all_mantis_nodes):
  371. nc = all_mantis_nodes.pop()
  372. if nc in array_nodes:
  373. continue
  374. if nc.node_type in ["DUMMY"]:
  375. continue
  376. # cleanup autogen nodes
  377. if nc.signature[0] == "MANTIS_AUTOGENERATED" and len(nc.inputs) == 0 and len(nc.outputs) == 1:
  378. from .base_definitions import can_remove_socket_for_autogen
  379. output=list(nc.outputs.values())[0]
  380. value=list(nc.parameters.values())[0] # IDEA modify the dependecy get function to exclude these nodes completely
  381. keep_me = False
  382. for l in output.links:
  383. to_node = l.to_node; to_socket = l.to_socket
  384. # do not remove the socket if it is a custom property.
  385. if not can_remove_socket_for_autogen(to_node, to_socket):
  386. keep_me = True; continue
  387. l.die()
  388. to_node.parameters[to_socket] = value
  389. del to_node.inputs[to_socket]
  390. init_dependencies(to_node) # to remove the autogen node we no longer need.
  391. if not keep_me:
  392. continue
  393. init_connections(nc) # because we have removed many connections.
  394. if (nc.node_type in ['XFORM']) and ("Relationship" in nc.inputs.keys()):
  395. if (new_nc := insert_lazy_parents(nc)):
  396. kept_nc[new_nc.signature]=new_nc
  397. # be sure to add the Mantis context.
  398. new_nc.mContext =mContext
  399. kept_nc[nc.signature]=nc
  400. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  401. prWhite("Number of Nodes: %s" % (len(kept_nc)))
  402. return kept_nc
  403. def switch_mode(mode='OBJECT', objects = []):
  404. active = None
  405. if objects:
  406. from bpy import context, ops
  407. active = objects[-1]
  408. context.view_layer.objects.active = active
  409. if (active):
  410. with context.temp_override(**{'active_object':active, 'selected_objects':objects}):
  411. ops.object.mode_set(mode=mode)
  412. return active
  413. def execution_error_cleanup(node, exception, switch_objects = [], show_error=False ):
  414. from bpy import context
  415. ui_sig = None
  416. if show_error: # show a popup and select the relevant nodes
  417. if node:
  418. ui_sig = node.ui_signature
  419. # TODO: see about zooming-to-node.
  420. base_tree = node.base_tree
  421. tree = base_tree
  422. try:
  423. pass
  424. space = context.space_data
  425. for name in ui_sig[1:]:
  426. for n in tree.nodes: n.select = False
  427. n = tree.nodes[name]
  428. n.select = True
  429. tree.nodes.active = n
  430. if hasattr(n, "node_tree"):
  431. tree = n.node_tree
  432. except AttributeError: # not being run in node graph
  433. pass
  434. finally:
  435. def error_popup_draw(self, context):
  436. self.layout.label(text=f"Error: {exception}")
  437. self.layout.label(text=f"see node: {ui_sig[1:]}.")
  438. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  439. switch_mode(mode='OBJECT', objects=switch_objects)
  440. for ob in switch_objects:
  441. ob.data.pose_position = 'POSE'
  442. prRed(f"Error: {exception} in node {ui_sig}")
  443. return exception
  444. def execute_tree(nodes, base_tree, context, error_popups = False):
  445. import bpy
  446. from time import time
  447. from .node_container_common import GraphError
  448. original_active = context.view_layer.objects.active
  449. start_execution_time = time()
  450. mContext = None
  451. from collections import deque
  452. xForm_pass = deque()
  453. for nc in nodes.values():
  454. if not mContext: # just grab one of these. this is a silly way to do this.
  455. mContext = nc.mContext
  456. mContext.b_objects = {} # clear the objects and recreate them
  457. nc.reset_execution()
  458. check_and_add_root(nc, xForm_pass)
  459. executed = []
  460. # check for cycles here by keeping track of the number of times a node has been visited.
  461. visited={}
  462. check_max_len=len(nodes)**2 # seems too high but safe. In a well-ordered graph, I guess this number should be less than the number of nodes.
  463. max_iterations = len(nodes)**2
  464. i = 0
  465. switch_me = [] # switch the mode on these objects
  466. active = None # only need it for switching modes
  467. select_me = []
  468. execution_failed=False
  469. try:
  470. while(xForm_pass):
  471. if execution_failed: break
  472. if i >= max_iterations:
  473. execution_failed = True
  474. raise GraphError("There is probably a cycle somewhere in the graph. "
  475. "Or a connection missing in a Group/Schema Input")
  476. i+=1
  477. n = xForm_pass.pop()
  478. if visited.get(n.signature) is not None:
  479. visited[n.signature]+=1
  480. else:
  481. visited[n.signature]=0
  482. if visited[n.signature] > check_max_len:
  483. execution_failed = True
  484. raise GraphError("There is a probably a cycle in the graph somewhere. "
  485. "Or a connection missing in a Group/Schema Input")
  486. # we're trying to solve the halting problem at this point.. don't do that.
  487. # TODO find a better way! there are algo's for this but they will require using a different solving algo, too
  488. if n.execution_prepared:
  489. continue
  490. if n.node_type not in ['XFORM', 'UTILITY']:
  491. for dep in n.hierarchy_dependencies:
  492. if not dep.execution_prepared:
  493. xForm_pass.appendleft(n) # hold it
  494. break
  495. else:
  496. n.execution_prepared=True
  497. executed.append(n)
  498. for conn in n.hierarchy_connections:
  499. if not conn.execution_prepared:
  500. xForm_pass.appendleft(conn)
  501. else:
  502. for dep in n.hierarchy_dependencies:
  503. if not dep.execution_prepared:
  504. break
  505. else:
  506. try:
  507. if not n.prepared:
  508. n.bPrepare(context)
  509. if not n.executed:
  510. n.bExecute(context)
  511. if (n.__class__.__name__ == "xFormArmature" ):
  512. ob = n.bGetObject()
  513. switch_me.append(ob)
  514. active = ob
  515. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  516. ob = n.bGetObject()
  517. if isinstance(ob, bpy.types.Object):
  518. select_me.append(ob)
  519. except Exception as e:
  520. e = execution_error_cleanup(n, e, show_error=error_popups)
  521. if error_popups == False:
  522. raise e
  523. execution_failed = True; break
  524. n.execution_prepared=True
  525. executed.append(n)
  526. for conn in n.hierarchy_connections:
  527. if not conn.execution_prepared:
  528. xForm_pass.appendleft(conn)
  529. switch_mode(mode='POSE', objects=switch_me)
  530. if (active):
  531. with context.temp_override(**{'active_object':active, 'selected_objects':switch_me}):
  532. bpy.ops.object.mode_set(mode='POSE')
  533. for n in executed:
  534. try:
  535. if not n.prepared:
  536. n.bPrepare(context)
  537. if not n.executed:
  538. n.bExecute(context)
  539. except Exception as e:
  540. e = execution_error_cleanup(n, e, show_error=error_popups)
  541. if error_popups == False:
  542. raise e
  543. execution_failed = True; break
  544. switch_mode(mode='OBJECT', objects=switch_me)
  545. for ob in switch_me:
  546. ob.data.pose_position = 'POSE'
  547. # switch to pose mode here so that the nodes can use the final pose data
  548. # this will require them to update the depsgraph.
  549. for n in executed:
  550. try:
  551. n.bFinalize(context)
  552. except Exception as e:
  553. e = execution_error_cleanup(n, e, show_error=error_popups)
  554. if error_popups == False:
  555. raise e
  556. execution_failed = True; break
  557. tot_time = (time() - start_execution_time)
  558. if not execution_failed:
  559. prGreen(f"Executed tree of {len(executed)} nodes in {tot_time} seconds")
  560. if (original_active):
  561. context.view_layer.objects.active = original_active
  562. original_active.select_set(True)
  563. except Exception as e:
  564. e = execution_error_cleanup(None, e, switch_me, show_error=error_popups)
  565. if error_popups == False:
  566. raise e
  567. prRed(f"Failed to execute tree.")
  568. finally:
  569. context.view_layer.objects.active = active
  570. # clear the selection first.
  571. from itertools import chain
  572. for ob in context.selected_objects:
  573. try:
  574. ob.select_set(False)
  575. except RuntimeError: # it isn't in the view layer
  576. pass
  577. for ob in chain(select_me, mContext.b_objects.values()):
  578. try:
  579. ob.select_set(True)
  580. except RuntimeError: # it isn't in the view layer
  581. pass