readtree.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. from .utilities import prRed, prGreen, prPurple, prWhite, prOrange, \
  2. wrapRed, wrapGreen, wrapPurple, wrapWhite, wrapOrange
  3. from .utilities import get_node_prototype, class_for_mantis_prototype_node, \
  4. gen_nc_input_for_data
  5. # BAD NAMES ahead, as these have nothing to do with NodeReroute nodes.
  6. def reroute_common(nc, nc_to, all_nc):
  7. # we need to do this: go to the to-node
  8. # then reroute the link in the to_node all the way to the beginning
  9. # so that the number of links in "real" nodes is unchanged
  10. # then the links in the dummy nodes need to be deleted
  11. # watch=False
  12. # if nc.signature[-1] == 'NodeGroupOutput': watch=True
  13. for inp_name, inp in nc.inputs.items():
  14. # assume each input socket only has one input for now
  15. if inp.is_connected:
  16. while (inp.links):
  17. in_link = inp.links.pop()
  18. from_nc = in_link.from_node
  19. from_socket = in_link.from_socket
  20. links = []
  21. from_links = from_nc.outputs[from_socket].links.copy()
  22. while(from_links): # This is a weird way to do this HACK
  23. from_link = from_links.pop()
  24. if from_link == in_link:
  25. from_link.die()
  26. continue # DELETE the dummy node link
  27. links.append(from_link)
  28. from_nc.outputs[from_socket].links = links
  29. down = nc_to.outputs[inp_name]
  30. for downlink in down.links:
  31. downlink.from_node = from_nc
  32. downlink.from_socket = from_socket
  33. from_nc.outputs[from_socket].links.append(downlink)
  34. if hasattr(downlink.to_node, "reroute_links"):
  35. downlink.to_node.reroute_links(downlink.to_node, all_nc)
  36. in_link.die()
  37. def reroute_links_grp(nc, all_nc):
  38. if nc.inputs:
  39. if (nc_to := all_nc.get( ( *nc.signature, "NodeGroupInput") )):
  40. reroute_common(nc, nc_to, all_nc)
  41. else:
  42. raise RuntimeError("internal error: failed to enter a node group ")
  43. def reroute_links_grpout(nc, all_nc):
  44. if (nc_to := all_nc.get( ( *nc.signature[:-1],) )):
  45. reroute_common(nc, nc_to, all_nc)
  46. else:
  47. raise RuntimeError("error leaving a node group (maybe you are running the tree from inside a node group?)")
  48. def reroute_links_grpin(nc, all_nc):
  49. pass
  50. # FIXME I don't think these signatures are unique.
  51. def insert_lazy_parents(nc):
  52. from .link_containers import LinkInherit
  53. from .xForm_containers import xFormArmature
  54. from .node_container_common import NodeLink
  55. inherit_nc = None
  56. if nc.inputs["Relationship"].is_connected:
  57. link = nc.inputs["Relationship"].links[0]
  58. # print(nc)
  59. from_nc = link.from_node
  60. if from_nc.node_type in ["XFORM"] and link.from_socket in ["xForm Out"]:
  61. inherit_nc = LinkInherit(("MANTIS_AUTOGENERATED", *nc.signature[1:], "LAZY_INHERIT"), nc.base_tree)
  62. for from_link in from_nc.outputs["xForm Out"].links:
  63. if from_link.to_node == nc and from_link.to_socket == "Relationship":
  64. break # this is it
  65. from_link.to_node = inherit_nc; from_link.to_socket="Parent"
  66. links=[]
  67. while (nc.inputs["Relationship"].links):
  68. to_link = nc.inputs["Relationship"].links.pop()
  69. if to_link.from_node == from_nc and to_link.from_socket == "xForm Out":
  70. continue # don't keep this one
  71. links.append(to_link)
  72. nc.inputs["Relationship"].links=links
  73. link=NodeLink(from_node=inherit_nc, from_socket="Inheritance", to_node=nc, to_socket="Relationship")
  74. inherit_nc.inputs["Parent"].links.append(from_link)
  75. inherit_nc.parameters = {
  76. "Parent":None,
  77. "Inherit Rotation":True,
  78. "Inherit Scale":'FULL',
  79. "Connected":False,
  80. }
  81. # because the from node may have already been done.
  82. init_connections(from_nc)
  83. init_dependencies(from_nc)
  84. init_connections(inherit_nc)
  85. init_dependencies(inherit_nc)
  86. return inherit_nc
  87. from_name_filter = ["Driver", ]
  88. to_name_filter = [
  89. "Custom Object xForm Override",
  90. "Custom Object",
  91. "Deform Bones"
  92. ]
  93. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  94. # DATA FROM NODES #
  95. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  96. from .base_definitions import replace_types
  97. # TODO: investigate whether I can set the properties in the downstream nodes directly.
  98. # I am doing this in Schema Solver and it seems to work quite efficiently.
  99. def make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, np):
  100. from .node_container_common import NodeSocket
  101. nc_to = local_nc[(None, *tree_path_names, np.name)]
  102. for inp in np.inputs:
  103. nc_from = None
  104. if inp.bl_idname in ['WildcardSocket']:
  105. continue # it isn't a real input so I don't think it is good to check it.
  106. to_s = inp.identifier
  107. if not inp.is_linked: # make an autogenerated NC for the inputs of the group node
  108. if inp.bl_idname in ['xFormSocket']:
  109. continue
  110. from .node_container_common import get_socket_value
  111. nc_cls = gen_nc_input_for_data(inp)
  112. if (nc_cls):
  113. sig = ("MANTIS_AUTOGENERATED", *tree_path_names, np.name, inp.name, inp.identifier)
  114. nc_from = nc_cls(sig, base_tree)
  115. # ugly! maybe even a HACK!
  116. nc_from.inputs = {}
  117. nc_from.outputs = {inp.name:NodeSocket(name = inp.name, node=nc_from)}
  118. nc_from.parameters = {inp.name:get_socket_value(inp)}
  119. #
  120. local_nc[sig] = nc_from; all_nc[sig] = nc_from
  121. from_s = inp.name
  122. else:
  123. prRed("No available auto-generated class for input", *tree_path_names, np.name, inp.name)
  124. nc_from.outputs[from_s].connect(node=nc_to, socket=to_s, sort_id=0)
  125. def gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, schema_nodes ):
  126. from .internal_containers import DummyNode
  127. from .base_definitions import SchemaNode
  128. for np in current_tree.nodes:
  129. # TODO: find out why I had to add this in. these should be taken care of already? BUG
  130. if np.bl_idname in ["NodeFrame", "NodeReroute"]:
  131. continue # not a Mantis Node
  132. if (nc_cls := class_for_mantis_prototype_node(np)):
  133. sig = (None, *tree_path_names, np.name)
  134. # but I will probably choose to handle this elsewhere
  135. # if isinstance(np, SchemaNode):
  136. # continue # we won't do this one here.
  137. if np.bl_idname in replace_types:
  138. # prPurple(np.bl_idname)
  139. sig = (None, *tree_path_names, np.bl_idname)
  140. if local_nc.get(sig):
  141. continue # already made
  142. nc = nc_cls( sig , base_tree)
  143. local_nc[sig] = nc; all_nc[sig] = nc
  144. # if np.bl_idname in ['UtilityMatricesFromCurve', 'UtilityBreakArray']:
  145. # schema_nodes[sig]=nc
  146. elif np.bl_idname in ["NodeGroupInput", "NodeGroupOutput"]: # make a Dummy Node
  147. # we only want ONE dummy in/out per tree_path, so use the bl_idname
  148. sig = (None, *tree_path_names, np.bl_idname)
  149. if not local_nc.get(sig):
  150. nc = DummyNode( signature=sig , base_tree=base_tree, prototype=np )
  151. local_nc[sig] = nc; all_nc[sig] = nc; dummy_nodes[sig] = nc
  152. if np.bl_idname in ["NodeGroupOutput"]:
  153. nc.reroute_links = reroute_links_grpout
  154. if np.bl_idname in ["NodeGroupInput"]:
  155. nc.reroute_links = reroute_links_grpin
  156. # else:
  157. # nc = local_nc.get(sig)
  158. elif np.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  159. nc = DummyNode( signature= (sig := (None, *tree_path_names, np.name) ), base_tree=base_tree, prototype=np )
  160. local_nc[sig] = nc; all_nc[sig] = nc; dummy_nodes[sig] = nc
  161. make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, np)
  162. if np.bl_idname == "MantisNodeGroup":
  163. group_nodes.append(nc)
  164. nc.reroute_links = reroute_links_grp
  165. else:
  166. group_nodes.append(nc)
  167. schema_nodes[sig] = nc
  168. else:
  169. nc = None
  170. prRed(f"Can't make nc for.. {np.bl_idname}")
  171. # this should be done at init
  172. if nc.signature[0] not in ['MANTIS_AUTOGENERATED'] and nc.node_type not in ['SCHEMA', 'DUMMY', 'DUMMY_SCHEMA']:
  173. nc.fill_parameters()
  174. def data_from_tree(base_tree, tree_path, dummy_nodes, all_nc, all_schema):
  175. # TODO: it should be realtively easy to make this use a while loop instead of recursion.
  176. local_nc, group_nodes = {}, []
  177. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  178. if tree_path[-1]:
  179. current_tree = tree_path[-1].node_tree # this may be None.
  180. else:
  181. current_tree = base_tree
  182. #
  183. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  184. from .utilities import clear_reroutes
  185. links = clear_reroutes(list(current_tree.links))
  186. gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, all_schema)
  187. from .utilities import link_node_containers
  188. for link in links:
  189. link_node_containers((None, *tree_path_names), link, local_nc)
  190. # Now, descend into the Node Groups and recurse
  191. for nc in group_nodes:
  192. # ng = get_node_prototype(nc.signature, base_tree)
  193. data_from_tree(base_tree, tree_path+[nc.prototype], dummy_nodes, all_nc, all_schema)
  194. return dummy_nodes, all_nc, all_schema
  195. from .utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  196. def delete_nc(nc):
  197. return
  198. # this doesn't seem to work actually
  199. for socket in nc.inputs.values():
  200. for l in socket.links:
  201. if l is not None:
  202. l.__del__()
  203. for socket in nc.outputs.values():
  204. for l in socket.links:
  205. if l is not None:
  206. l.__del__()
  207. def is_signature_in_other_signature(sig_a, sig_b):
  208. # this is the easiest but not the best way to do this:
  209. # this function is hideous but it does not seem to have any significant effect on timing
  210. # tested it with profiling on a full character rig.
  211. # OK. Had another test in a more extreme situation and this one came out on top for time spent and calls
  212. # gotta optimize this one.
  213. sig_a = list(sig_a)
  214. sig_a = ['MANTIS_NONE' if val is None else val for val in sig_a]
  215. sig_b = list(sig_b)
  216. sig_b = ['MANTIS_NONE' if val is None else val for val in sig_b]
  217. string_a = "".join(sig_a)
  218. string_b = "".join(sig_b)
  219. return string_a in string_b
  220. def solve_schema_to_tree(nc, all_nc, roots=[]):
  221. from .utilities import get_node_prototype
  222. np = get_node_prototype(nc.signature, nc.base_tree)
  223. # if not hasattr(np, 'node_tree'):
  224. # nc.bPrepare()
  225. # nc.prepared=True
  226. # return {}
  227. from .schema_solve import SchemaSolver
  228. length = nc.evaluate_input("Schema Length")
  229. tree = np.node_tree
  230. prOrange(f"Expanding schema {tree.name} in node {nc} with length {length}.")
  231. for inp in nc.inputs.values():
  232. inp.links.sort(key=lambda a : -a.multi_input_sort_id)
  233. solver = SchemaSolver(nc, all_nc, np)
  234. solved_nodes = solver.solve(length)
  235. # prGreen(f"Finished solving schema {tree.name} in node {nc}.")
  236. prWhite(f"Schema declared {len(solved_nodes)} nodes.")
  237. nc.prepared = True
  238. # TODO this should be handled by the schema's finalize() function
  239. del_me = []
  240. for k, v in all_nc.items():
  241. # delete all the schema's internal nodes. The links have already been deleted by the solver.
  242. if v.signature[0] not in ['MANTIS_AUTOGENERATED'] and is_signature_in_other_signature(nc.signature, k):
  243. # print (wrapOrange("Culling: ")+wrapRed(v))
  244. delete_nc(v)
  245. del_me.append(k)
  246. for k in del_me:
  247. del all_nc[k]
  248. for k,v in solved_nodes.items():
  249. all_nc[k]=v
  250. init_connections(v)
  251. check_and_add_root(v, roots, include_non_hierarchy=True)
  252. # end TODO
  253. return solved_nodes
  254. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  255. # PARSE NODE TREE #
  256. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  257. from .utilities import get_all_dependencies
  258. def get_schema_length_dependencies(node):
  259. """ Find all of the nodes that the Schema Length input depends on. """
  260. # the deps recursively from the from_nodes connected to Schema Length
  261. deps = []
  262. # return get_all_dependencies(node)
  263. inp = node.inputs.get("Schema Length")
  264. if not inp:
  265. inp = node.inputs.get("Array")
  266. # this way we can handle Schema and Array Get nodes with one function
  267. # ... since I may add more in the future this is not a robust solution HACK
  268. for l in inp.links:
  269. deps.extend(get_all_dependencies(l.from_node))
  270. if inp := node.inputs.get("Index"):
  271. for l in inp.links:
  272. deps.extend(get_all_dependencies(l.from_node))
  273. # now get the auto-generated simple inputs. These should not really be there but I haven't figured out how to set things directly yet lol
  274. for inp in node.inputs.values():
  275. for l in inp.links:
  276. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  277. # l.from_node.bPrepare() # try this...
  278. # l.from_node.prepared = True; l.from_node.executed = True
  279. deps.extend([l.from_node]) # why we need this lol
  280. return deps
  281. def parse_tree(base_tree):
  282. from uuid import uuid4 # do this here?
  283. base_tree.execution_id = uuid4().__str__() # set this, it may be used by nodes during execution
  284. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  285. # then they stick around because the function definition inits them once and keeps a reference
  286. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  287. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  288. import time
  289. data_start_time = time.time()
  290. dummy_nodes, all_nc, all_schema = data_from_tree(base_tree, tree_path = [None], dummy_nodes = {}, all_nc = {}, all_schema={})
  291. # return
  292. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  293. for sig, dummy in dummy_nodes.items():
  294. if (hasattr(dummy, "reroute_links")):
  295. dummy.reroute_links(dummy, all_nc)
  296. # TODO
  297. # MODIFY BELOW to use hierarchy_dependencies instead
  298. # SCHEMA DUMMY nodes will need to gather the hierarchy and non-hierarchy dependencies
  299. # so SCHEMA DUMMY will not make their dependencies all hierarchy
  300. # since they will need to be able to send drivers and such
  301. start_time = time.time()
  302. sig_check = (None, 'Node Group.001', 'switch_thigh')
  303. roots = []
  304. arrays = []
  305. from .misc_containers import UtilityArrayGet
  306. for nc in all_nc.values():
  307. # clean up the groups
  308. if nc.node_type in ["DUMMY"]:
  309. if nc.prototype.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  310. continue
  311. from .base_definitions import from_name_filter, to_name_filter
  312. init_dependencies(nc)
  313. init_connections(nc)
  314. check_and_add_root(nc, roots, include_non_hierarchy=True)
  315. if isinstance(nc, UtilityArrayGet):
  316. arrays.append(nc)
  317. from collections import deque
  318. unsolved_schema = deque()
  319. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  320. for schema in all_schema.values():
  321. # so basically we need to check every parent node if it is a schema
  322. # this is a fairly slapdash solution but it works and I won't change it
  323. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  324. if parent := all_schema.get(schema.signature[:i+1]):
  325. solve_only_these.remove(schema)
  326. break
  327. else:
  328. init_schema_dependencies(schema, all_nc)
  329. solve_only_these.extend(get_schema_length_dependencies(schema))
  330. unsolved_schema.append(schema)
  331. for array in arrays:
  332. solve_only_these.extend(get_schema_length_dependencies(array))
  333. solve_only_these.extend(arrays)
  334. schema_solve_done = set()
  335. solve_only_these = set(solve_only_these)
  336. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  337. while(solve_layer):
  338. n = solve_layer.pop()
  339. if n not in solve_only_these: # removes the unneeded node from the solve-layer
  340. continue
  341. if n.signature in all_schema.keys():
  342. for dep in n.hierarchy_dependencies:
  343. if dep not in schema_solve_done and (dep in solve_only_these):
  344. solve_layer.appendleft(n)
  345. break
  346. else:
  347. solved_nodes = solve_schema_to_tree(n, all_nc, roots)
  348. unsolved_schema.remove(n)
  349. schema_solve_done.add(n)
  350. for node in solved_nodes.values():
  351. #
  352. init_dependencies(node)
  353. init_connections(node)
  354. #
  355. solve_layer.appendleft(node)
  356. for conn in n.hierarchy_connections:
  357. if conn not in schema_solve_done and conn not in solve_layer:
  358. solve_layer.appendleft(conn)
  359. else:
  360. for dep in n.hierarchy_dependencies:
  361. if dep not in schema_solve_done:
  362. break
  363. else:
  364. n.bPrepare()
  365. schema_solve_done.add(n)
  366. for conn in n.hierarchy_connections:
  367. if conn not in schema_solve_done and conn not in solve_layer:
  368. solve_layer.appendleft(conn)
  369. if unsolved_schema:
  370. raise RuntimeError("Failed to resolve all schema declarations")
  371. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  372. all_nc = list(all_nc.values()).copy()
  373. kept_nc = {}
  374. while (all_nc):
  375. nc = all_nc.pop()
  376. if nc in arrays:
  377. continue
  378. if nc.node_type in ["DUMMY"]:
  379. continue
  380. # cleanup autogen nodes
  381. if nc.signature[0] == "MANTIS_AUTOGENERATED" and len(nc.inputs) == 0 and len(nc.outputs) == 1:
  382. output=list(nc.outputs.values())[0]
  383. value=list(nc.parameters.values())[0] # TODO modify the dependecy get function to exclude these nodes completely
  384. for l in output.links:
  385. to_node = l.to_node; to_socket = l.to_socket
  386. l.die()
  387. to_node.parameters[to_socket] = value
  388. del to_node.inputs[to_socket]
  389. init_dependencies(to_node)
  390. # init_connections(from_node) # this is unnecesary
  391. continue
  392. if (nc.node_type in ['XFORM']) and ("Relationship" in nc.inputs.keys()):
  393. if (new_nc := insert_lazy_parents(nc)):
  394. kept_nc[new_nc.signature]=new_nc
  395. kept_nc[nc.signature]=nc
  396. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  397. prWhite("Number of Nodes: %s" % (len(kept_nc)))
  398. return kept_nc
  399. def switch_mode(mode='OBJECT', objects = []):
  400. active = None
  401. if objects:
  402. from bpy import context, ops
  403. active = objects[-1]
  404. context.view_layer.objects.active = active
  405. if (active):
  406. with context.temp_override(**{'active_object':active, 'selected_objects':objects}):
  407. ops.object.mode_set(mode=mode)
  408. return active
  409. def execution_error_cleanup(node, exception, switch_objects = [] ):
  410. from bpy import context
  411. if node:
  412. # this stuff that is commented out is good and useful but I fear to enable it by default.
  413. # TODO: see about this zoom-to-node stuff.
  414. base_tree = node.base_tree
  415. tree = base_tree
  416. try:
  417. pass
  418. space = context.space_data
  419. # path = space.path
  420. # path.clear()
  421. # path.start(base_tree)
  422. for name in node.signature[1:]:
  423. for n in tree.nodes: n.select = False
  424. n = tree.nodes[name]
  425. n.select = True
  426. tree.nodes.active = n
  427. if hasattr(n, "node_tree"):
  428. tree = n.node_tree
  429. # path.append(tree, node=n)
  430. except AttributeError: # not being run in node graph
  431. pass
  432. finally:
  433. def error_popup_draw(self, context):
  434. self.layout.label(text=f"Error: {exception}")
  435. self.layout.label(text=f"see node: {node.signature[1:]}.")
  436. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  437. switch_mode(mode='OBJECT', objects=switch_objects)
  438. for ob in switch_objects:
  439. ob.data.pose_position = 'POSE'
  440. prRed(f"Error: {exception} in node {node}")
  441. return exception
  442. #execute tree is really slow overall, but still completes 1000s of nodes in only
  443. def execute_tree(nodes, base_tree, context, error_popups = False):
  444. # return
  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. from collections import deque
  451. xForm_pass = deque()
  452. for nc in nodes.values():
  453. nc.prepared = False
  454. nc.executed = False
  455. check_and_add_root(nc, xForm_pass)
  456. executed = []
  457. # check for cycles here by keeping track of the number of times a node has been visited.
  458. visited={}
  459. 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.
  460. max_iterations = len(nodes)**2
  461. i = 0
  462. switch_me = [] # switch the mode on these objects
  463. active = None # only need it for switching modes
  464. select_me = []
  465. try:
  466. while(xForm_pass):
  467. if i >= max_iterations:
  468. raise GraphError("There is probably a cycle somewhere in the graph.")
  469. i+=1
  470. n = xForm_pass.pop()
  471. if visited.get(n.signature):
  472. visited[n.signature]+=1
  473. else:
  474. visited[n.signature]=0
  475. if visited[n.signature] > check_max_len:
  476. raise GraphError("There is a probably a cycle in the graph somewhere. Fix it!")
  477. # we're trying to solve the halting problem at this point.. don't do that.
  478. # TODO find a better way! there are algo's for this but they will require using a different solving algo, too
  479. if n.prepared:
  480. continue
  481. if n.node_type not in ['XFORM', 'UTILITY']:
  482. for dep in n.hierarchy_dependencies:
  483. if not dep.prepared:
  484. xForm_pass.appendleft(n) # hold it
  485. break
  486. else:
  487. n.prepared=True
  488. executed.append(n)
  489. for conn in n.hierarchy_connections:
  490. if not conn.prepared:
  491. xForm_pass.appendleft(conn)
  492. else:
  493. for dep in n.hierarchy_dependencies:
  494. if not dep.prepared:
  495. break
  496. else:
  497. try:
  498. n.bPrepare(context)
  499. if not n.executed:
  500. n.bExecute(context)
  501. if (n.__class__.__name__ == "xFormArmature" ):
  502. ob = n.bGetObject()
  503. switch_me.append(ob)
  504. active = ob
  505. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  506. ob = n.bGetObject()
  507. if isinstance(ob, bpy.types.Object):
  508. select_me.append(ob)
  509. except Exception as e:
  510. if error_popups:
  511. raise execution_error_cleanup(n, e,)
  512. else:
  513. raise e
  514. n.prepared=True
  515. executed.append(n)
  516. for conn in n.hierarchy_connections:
  517. if not conn.prepared:
  518. xForm_pass.appendleft(conn)
  519. switch_mode(mode='POSE', objects=switch_me)
  520. if (active):
  521. with context.temp_override(**{'active_object':active, 'selected_objects':switch_me}):
  522. bpy.ops.object.mode_set(mode='POSE')
  523. for n in executed:
  524. try:
  525. n.bPrepare(context)
  526. if not n.executed:
  527. n.bExecute(context)
  528. except Exception as e:
  529. if error_popups:
  530. raise execution_error_cleanup(n, e,)
  531. else:
  532. raise e
  533. for n in executed:
  534. try:
  535. n.bFinalize(context)
  536. except Exception as e:
  537. if error_popups:
  538. raise execution_error_cleanup(n, e,)
  539. else:
  540. raise e
  541. switch_mode(mode='OBJECT', objects=switch_me)
  542. for ob in switch_me:
  543. ob.data.pose_position = 'POSE'
  544. tot_time = (time() - start_execution_time)
  545. prGreen(f"Executed tree of {len(executed)} nodes in {tot_time} seconds")
  546. if (original_active):
  547. context.view_layer.objects.active = original_active
  548. original_active.select_set(True)
  549. except Exception as e:
  550. execution_error_cleanup(None, e, switch_me)
  551. if error_popups == False:
  552. raise e
  553. finally:
  554. context.view_layer.objects.active = active
  555. # clear the selection first.
  556. for ob in context.selected_objects:
  557. try:
  558. ob.select_set(False)
  559. except RuntimeError: # it isn't in the view layer
  560. pass
  561. for ob in select_me:
  562. try:
  563. ob.select_set(True)
  564. except RuntimeError: # it isn't in the view layer
  565. pass