readtree.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. from ..utilities.utilities import prRed, prGreen, prPurple, prWhite, prOrange, \
  2. wrapRed, wrapGreen, wrapPurple, wrapWhite, wrapOrange
  3. # FIXME I don't think these signatures are unique.
  4. # TODO this is a really silly and bad and also really dumb way to do this
  5. def insert_lazy_parents(mantis_node):
  6. from ..link_nodes import LinkInherit
  7. inherit_node = None
  8. if mantis_node.inputs["Relationship"].is_connected:
  9. from ..utilities.node_common import trace_single_line_safe
  10. # BUG this line can create infinite loops
  11. node_line, last_socket = trace_single_line_safe(mantis_node, 'Relationship')
  12. # if last_socket is from a valid XFORM, it is the relationship in
  13. # because it was traversed from the xForm Out... so get the traverse target.
  14. if last_socket.traverse_target is None:
  15. return # this is not a valid lazy parent.
  16. for other_node in node_line[1:]: # skip the first one, it is the same node
  17. if other_node.node_type == 'LINK':
  18. return # this one has a realtionship connection.
  19. elif other_node.node_type == 'XFORM':
  20. break
  21. if other_node.node_type in ["XFORM"] and last_socket.traverse_target.name in ["xForm Out"]:
  22. for link in other_node.outputs['xForm Out'].links:
  23. if link.to_node == mantis_node: link.die()
  24. inherit_node = LinkInherit(("MANTIS_AUTOGENERATED", *mantis_node.signature[1:], "LAZY_INHERIT"), mantis_node.base_tree)
  25. l = other_node.outputs['xForm Out'].connect(inherit_node, 'Parent')
  26. l1 = inherit_node.outputs['Inheritance'].connect(mantis_node, 'Relationship')
  27. inherit_node.parameters = { "Parent":None,
  28. "Inherit Rotation":True,
  29. "Inherit Scale":'FULL',
  30. "Connected":False, }
  31. # because the from node may have already been done.
  32. init_connections(other_node); init_dependencies(other_node)
  33. init_connections(inherit_node); init_dependencies(inherit_node)
  34. return inherit_node
  35. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  36. # DATA FROM NODES #
  37. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  38. from ..base_definitions import replace_types, NodeSocket
  39. def autogen_node(base_tree, ui_socket, signature, mContext):
  40. mantis_node=None
  41. from ..internal_nodes import AutoGenNode
  42. mantis_node = AutoGenNode(signature, base_tree)
  43. mantis_node.mContext = mContext
  44. mantis_node.outputs[ui_socket.name] = NodeSocket(is_input=False, name=ui_socket.name, node=mantis_node)
  45. mantis_node.ui_signature = None # does not exist in the UI
  46. return mantis_node
  47. # TODO: investigate whether I can set the properties in the downstream nodes directly.
  48. # I am doing this in Schema Solver and it seems to work quite efficiently.
  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. if from_mantis_node: # autogen can fail and we should catch it.
  65. from mathutils import Matrix
  66. from_mantis_node.parameters = {inp.name:
  67. Matrix(( tuple(inp.default_value[0:4]), \
  68. tuple(inp.default_value[4:8]), \
  69. tuple(inp.default_value[8:12]), \
  70. tuple(inp.default_value[12:16]) )) if inp.bl_idname == 'MatrixSocket' \
  71. else inp.default_value}
  72. local_mantis_nodes[signature] = from_mantis_node; all_mantis_nodes[signature] = from_mantis_node
  73. from_mantis_node.outputs[inp.name].connect(node=to_mantis_node, socket=to_s, sort_id=0)
  74. else:
  75. prRed("No available auto-generated class for input %s in %s" % (inp.name, np.name))
  76. 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 ):
  77. from ..internal_nodes import DummyNode
  78. for ui_node in current_tree.nodes:
  79. mantis_node = None
  80. if ui_node.bl_idname in ["NodeFrame", "NodeReroute"]:
  81. continue # not a Mantis Node
  82. if ui_node.bl_idname in ["NodeGroupInput", "NodeGroupOutput"]:
  83. # we only want ONE dummy in/out per tree_path, so use the bl_idname to make a Dummy node
  84. sig = (None, *tree_path_names, ui_node.bl_idname)
  85. ui_sig = (None, *tree_path_names, ui_node.name)
  86. if not local_mantis_nodes.get(sig):
  87. mantis_node = DummyNode( signature=sig , base_tree=base_tree, ui_node=ui_node, ui_signature=ui_sig )
  88. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node; dummy_nodes[sig] = mantis_node
  89. if ui_node.bl_idname in {"NodeGroupOutput"}:
  90. mantis_node.reroute_links_type = 'out'
  91. elif ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  92. mantis_node = DummyNode( signature= (sig := (None, *tree_path_names, ui_node.name) ), base_tree=base_tree, ui_node=ui_node )
  93. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node; dummy_nodes[sig] = mantis_node
  94. make_connections_to_ng_dummy(base_tree, tree_path_names, local_mantis_nodes, all_mantis_nodes, mantis_node)
  95. group_nodes.append(mantis_node)
  96. if ui_node.bl_idname == "MantisNodeGroup":
  97. mantis_node.reroute_links_type = 'group'
  98. else:
  99. schema_nodes[sig] = mantis_node
  100. # if it wasn't the types we ignore or the types we make a Dummy for, use this to catch all non-special cases.
  101. elif (mantis_class := ui_node.mantis_class):
  102. sig = (None, *tree_path_names, ui_node.name)
  103. if ui_node.bl_idname in replace_types:
  104. sig = (None, *tree_path_names, ui_node.bl_idname)
  105. if local_mantis_nodes.get(sig):
  106. continue # already made
  107. mantis_node = mantis_class( sig , base_tree)
  108. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node
  109. mantis_node.ui_signature = (*mantis_node.ui_signature[:-1], ui_node.name) # just to ensure it points to a real node.
  110. else:
  111. mantis_node = None
  112. prRed(f"Can't make mantis_node for.. {ui_node.bl_idname}")
  113. if mantis_node is not None:
  114. # this should be done at init
  115. mantis_node.mContext = mContext
  116. if mantis_node.signature[0] != 'MANTIS_AUTOGENERATED' and mantis_node.node_type not in {'SCHEMA', 'DUMMY', 'DUMMY_SCHEMA'}:
  117. mantis_node.fill_parameters(ui_node)
  118. mantis_node.is_schema_prototype = in_schema
  119. def data_from_tree(base_tree, tree_path, mContext, dummy_nodes, all_mantis_nodes, all_schema, in_schema):#
  120. # TODO: it should be relatively easy to make this use a while loop instead of recursion.
  121. local_mantis_nodes, group_nodes = {}, []
  122. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  123. if tree_path[-1]:
  124. current_tree = tree_path[-1].node_tree # this may be None.
  125. else:
  126. current_tree = base_tree
  127. #
  128. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  129. if not in_schema:
  130. in_schema = current_tree.bl_idname in ['SchemaTree']
  131. from ..utilities.utilities import clear_reroutes
  132. links = clear_reroutes(list(current_tree.links))
  133. 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)
  134. from ..utilities.utilities import link_mantis_nodes
  135. for link in links:
  136. link_mantis_nodes((None, *tree_path_names), link, local_mantis_nodes)
  137. if current_tree == base_tree:
  138. # in the base tree, we need to auto-gen the default values in a slightly different way to node groups.
  139. insert_default_values_base_tree(base_tree, all_mantis_nodes)
  140. # Now, descend into the Node Groups and recurse
  141. for mantis_node in group_nodes:
  142. data_from_tree(base_tree, tree_path+[mantis_node.ui_node], mContext, dummy_nodes, all_mantis_nodes, all_schema, in_schema)
  143. return dummy_nodes, all_mantis_nodes, all_schema
  144. STRING_PADDING = 4
  145. overlay_valid_socket_types = [
  146. "FloatSocket", "FloatPositiveSocket", "FloatFactorSocket",
  147. "FloatAngleSocket", "UnsignedIntSocket", "IntSocket", "StringSocket",
  148. ]
  149. # Do not use these input names as overlay keys:
  150. forbidden_key_names = ["",]
  151. forbidden_in_key_name = ['$',]
  152. def node_scan_overlays(node, socket_id,):
  153. from ..misc_nodes import SimpleInputNode
  154. overlay_data_type = str
  155. if isinstance(node, SimpleInputNode):
  156. overlay_data_type = type(node.parameters[list(node.outputs.values())[0].name])
  157. else:
  158. match node.inputs[socket_id].socket_type:
  159. case "IntSocket" | "UnsignedIntSocket":
  160. overlay_data_type = int
  161. case "FloatSocket" | "FloatPositiveSocket" | "FloatFactorSocket" | "FloatAngleSocket":
  162. overlay_data_type = float
  163. from ..utilities.node_common import GraphError
  164. interface_nodes = node.mContext.interface_nodes
  165. from ..utilities.utilities import get_ui_node
  166. ui_node = get_ui_node(node.ui_signature, node.base_tree)
  167. # we'll assume that the overlay tag system checked if this is linked.
  168. # TODO this is probably redundant with the check above this
  169. # First let's check if it is a simple input node, by checking outputs that are marked "input"
  170. for socket in ui_node.outputs:
  171. # weird edge case for simple input nodes with unnamed sockets
  172. # the socket.identifier is not used by Mantis but it defaults to 'socket'\
  173. if socket.identifier == socket_id and socket.input == True: break
  174. else:
  175. for socket in ui_node.inputs:
  176. if socket.identifier == socket_id: break
  177. else:
  178. raise KeyError(f"Socket not found by ID {socket_id} in node {node.ui_signature}\n"
  179. f"Candidates: {[socket.identifier for socket in ui_node.inputs]}")
  180. value = socket.default_value # get the ACTUAL UI value
  181. if hasattr(socket, 'overlay_text'): # TODO this is all wrong but for now
  182. value = "$"+socket.overlay_text # I am not implementing the Parser feature
  183. if not isinstance(value, str): return
  184. # First step: get the interface nodes and the overlay keys
  185. # this should only check interfaces that are ancestors of this node
  186. my_interfaces = []
  187. for index in range(len(node.signature)-1):
  188. if index == 0: continue # root
  189. # we add one here because the node inside the schema references the schema's interface...
  190. current_schema_interface_index = node.generated_at_schema_index[index+1]
  191. if current_schema_interface_index < 0: # this indicates that it is not in a schema
  192. interface = interface_nodes.get(
  193. interface_signature := (*node.signature[:index+1], "InputInterface"))
  194. else: # First we get the interface that enters the schema (index 0)
  195. interface = interface_nodes.get(
  196. interface_signature := (*node.signature[:index+1],
  197. "InputInterface."+str( 0 ).zfill(4)))
  198. if interface not in my_interfaces: my_interfaces.append(interface)
  199. if current_schema_interface_index == 0: continue # just did it
  200. # we need to get the schema of the current index
  201. interface = interface_nodes.get(
  202. interface_signature := (*node.signature[:index+1],
  203. "InputInterface."+str(current_schema_interface_index).zfill(4)))
  204. my_interfaces.append( interface )
  205. # the my_interfaces list is sorted in REVERSE order of importance
  206. # Next, get all the overlay providers.
  207. name_to_id_map = {}
  208. name_to_type_map = {} # Just for printing reasonable error messages
  209. overlay_keys = set()
  210. root_overlay_values = {}
  211. # First, we'll get the base tree's default inputs
  212. for interface_item in node.mContext.base_tree.interface.items_tree:
  213. if interface_item.item_type != "SOCKET": continue
  214. if interface_item.in_out != "INPUT": continue
  215. # NOTE this will need to change if overlays extend to other data types
  216. if hasattr(interface_item, "default_string"):
  217. # NOTE that there may be duplicate names. Too bad!
  218. root_overlay_values[interface_item.name] = interface_item.default_string
  219. elif hasattr(interface_item, "default_int"):
  220. root_overlay_values[interface_item.name] = str(interface_item.default_int).zfill(STRING_PADDING)
  221. elif hasattr(interface_item, "default_float"):
  222. root_overlay_values[interface_item.name] = str(interface_item.default_float).zfill(STRING_PADDING)
  223. overlay_keys.add(interface_item.name)
  224. name_to_id_map[interface_item.name] = None # don't worry about it
  225. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  226. # BUG? should this be my_interfaces ? why bother with interfaces this may not be a part of?
  227. for interface_node in interface_nodes.values():
  228. # problem: the interface node stores socket identifiers as keys
  229. # so in reality we need to get the group UI node and ask for its input names
  230. # if there is a duplicate name, too bad!
  231. group_ui_node = get_ui_node(interface_node.ui_signature[:-1], node.base_tree)
  232. for interface_item in group_ui_node.node_tree.interface.items_tree:
  233. if interface_item.item_type != 'SOCKET': continue
  234. if interface_item.in_out != 'INPUT': continue
  235. if interface_item.name in forbidden_key_names: continue
  236. for substr in forbidden_in_key_name:
  237. if substr in interface_item.name:
  238. break
  239. else: # if we do not find a bad substr
  240. name_to_id_map[interface_item.name]=interface_item.identifier
  241. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  242. overlay_keys.add(interface_item.name)
  243. # For schema interfaces, we also need to get the length and index.
  244. if 'Index' in interface.outputs:
  245. overlay_keys.add('Index'); overlay_keys.add('Length')
  246. if 'Index' in overlay_keys:
  247. name_to_id_map['Index']='Index'
  248. name_to_type_map['Index']= "IntSocket"
  249. name_to_id_map['Length']='Length'
  250. name_to_type_map['Length']= "IntSocket"
  251. # sort by reverse length so we find "CatsAndFrogs" before "Cats"
  252. overlay_keys = sorted(overlay_keys, key= lambda a :-1*len(a))
  253. # First I need to break it into substrings based on quotation marks
  254. from ..utilities.utilities import split_quoted_substrings_to_strings
  255. quoted_substrings = split_quoted_substrings_to_strings(value)
  256. overlay_tries = []
  257. for quoted_substring in quoted_substrings:
  258. overlay_tries.extend(quoted_substring.split("$"))
  259. if overlay_data_type == str:
  260. result = overlay_tries[0] # the 0th element is always before the split character
  261. else: # TODO HACK later use the parser feature
  262. result = 0
  263. # the reason for the difference between overlay_try and key is because
  264. # we don't actually know if the $text part has a key in it
  265. for overlay_try in overlay_tries[1:]:
  266. if not overlay_try: continue # some of these are empty
  267. overlay_resolved_value = "$" + overlay_try
  268. for key in overlay_keys:
  269. if key in overlay_try:
  270. overlay_resolved_value = "$" + key
  271. for interface in reversed(my_interfaces): # since this is reversed when we build it
  272. actual_key = name_to_id_map.get(key)
  273. socket = interface.inputs.get(actual_key)
  274. if key in ['Index', 'Length']:
  275. socket = interface.outputs.get(actual_key)
  276. if socket:
  277. overlay_value = None
  278. try:
  279. overlay_value = interface.evaluate_input(actual_key)
  280. except KeyError:
  281. if (socket_type := name_to_type_map.get(key) or 'NOT FOUND') in overlay_valid_socket_types:
  282. raise GraphError(f"Error: Variable {key} is not supported because it has "
  283. f"an invalid input in the node group: {interface.signature[:-1]}.")
  284. raise GraphError( f"Error: Variable {key} is not supported because it is "
  285. f"type {socket_type}" )
  286. # NOTE that the above can also be caused by any BUG occuring in node group update
  287. # because it causes the interface to be invalid for the UI node that spawns the interface node.
  288. if overlay_data_type == str:
  289. if isinstance(overlay_value, (float, int)):
  290. overlay_value = str(overlay_value).zfill(STRING_PADDING)
  291. assert (isinstance(overlay_value, str)), f"Error: Variable {key} is not supported because it is type {type(overlay_value)}"
  292. overlay_resolved_value = overlay_try.replace(key, overlay_value)
  293. else:
  294. overlay_resolved_value = overlay_value
  295. break
  296. else: # we'll try the base tree
  297. if base_tree_result := root_overlay_values.get(overlay_try):
  298. overlay_resolved_value = base_tree_result
  299. else:
  300. prOrange(f"WARN: no overlay value applied for {node.ui_signature} for key {key}")
  301. break # we found the key and are done here. One found Key per overlay-try
  302. result += overlay_resolved_value
  303. # Simple Input sockets with unnamed sockets assign this ID automatically
  304. # But Mantis uses the name instead. Usually the name and ID are the same.
  305. if socket_id == 'socket' and ui_node.outputs[0].name == "":
  306. socket_id = ''
  307. node.parameters[socket_id] = result
  308. return result # because sometimes I need to get the result, too
  309. from ..utilities.utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  310. def solve_schema_to_tree(mantis_node, all_mantis_nodes, roots=[], error_popups=False):
  311. from ..utilities.utilities import get_ui_node
  312. np = get_ui_node(mantis_node.signature, mantis_node.base_tree)
  313. from .schema_solve import SchemaSolver
  314. solver = SchemaSolver(mantis_node, all_mantis_nodes.copy(), np, error_popups=error_popups)
  315. try:
  316. solved_nodes = solver.solve()
  317. except Exception as e:
  318. # # the schema will run the error cleanup code, we just need to raise or not
  319. solved_nodes = {}
  320. mantis_node.base_tree.hash_recursive=''
  321. raise execution_error_cleanup(mantis_node, e, show_error=error_popups)
  322. for k,v in solved_nodes.items():
  323. all_mantis_nodes[k]=v
  324. init_connections(v)
  325. check_and_add_root(v, roots, include_non_hierarchy=True)
  326. return solved_nodes
  327. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  328. # PARSE NODE TREE #
  329. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  330. schema_bl_idnames = [ "SchemaIndex",
  331. "SchemaArrayInput",
  332. "SchemaArrayInputGet",
  333. "SchemaArrayInputAll",
  334. "SchemaArrayOutput",
  335. "SchemaConstInput",
  336. "SchemaConstOutput",
  337. "SchemaOutgoingConnection",
  338. "SchemaIncomingConnection",
  339. ]
  340. from ..utilities.utilities import get_all_dependencies, read_schema_type
  341. def get_schema_length_dependencies(node, all_nodes={}):
  342. """ Get a list of all dependencies for the given node's length or array properties.
  343. This function will also recursively search for dependencies in its sub-trees.
  344. """
  345. deps = []
  346. prepare_links_to = ['Schema Length', 'Array', 'Index']
  347. def extend_dependencies_from_inputs(node):
  348. for inp in node.inputs.values():
  349. for l in inp.links:
  350. if not l.from_node in node.hierarchy_dependencies:
  351. continue
  352. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  353. deps.extend([l.from_node]) # why we need this lol
  354. if inp.name in prepare_links_to:
  355. deps.append(l.from_node)
  356. deps.extend(get_all_dependencies(l.from_node))
  357. # we also always need to prepare these inputs because they create links.
  358. # HACK below until I can be less stupid and solve this the right way
  359. if l.from_node.__class__.__name__ in 'UtilityMatricesFromCurve':
  360. deps.append(l.from_node)
  361. deps.extend(get_all_dependencies(l.from_node))
  362. def deps_filter(dep): # remove any nodes inside the schema
  363. if len(dep.signature) > len(node.signature):
  364. for i in range(len(node.signature)):
  365. dep_sig_elem, node_sig_elem = dep.signature[i], node.signature[i]
  366. if dep_sig_elem != node_sig_elem: break # they don't match, it isn't an inner-node
  367. else: # remove this, it didn't break, meaning it shares signature with outer node
  368. return False # this is an inner-node
  369. return True
  370. # this way we can handle Schema and Array Get nodes with one function
  371. extend_dependencies_from_inputs(node)
  372. if node.node_type == 'DUMMY_SCHEMA':
  373. trees = [(node.ui_node.node_tree, node.signature)] # this is UI data
  374. while trees:
  375. tree, tree_signature = trees.pop()
  376. for sub_ui_node in tree.nodes:
  377. if sub_ui_node.bl_idname in ['NodeReroute', 'NodeFrame']:
  378. continue
  379. if sub_ui_node.bl_idname in schema_bl_idnames:
  380. sub_node = all_nodes[(*tree_signature, sub_ui_node.bl_idname)]
  381. else:
  382. sub_node = all_nodes[(*tree_signature, sub_ui_node.name)]
  383. if sub_node.node_type == 'DUMMY_SCHEMA':
  384. extend_dependencies_from_inputs(sub_node)
  385. trees.append((sub_node.ui_node.node_tree, sub_node.signature))
  386. return list(filter(deps_filter, deps))
  387. def insert_default_values_base_tree(base_tree, all_mantis_nodes):
  388. # we can get this by name because group inputs are gathered to the bl_idname
  389. InputNode = all_mantis_nodes.get((None, 'NodeGroupInput'))
  390. if InputNode is None: return # nothing to do here.
  391. ui_node = InputNode.ui_node
  392. for i, output in enumerate(InputNode.outputs):
  393. ui_output = ui_node.outputs[i] # I need this for the error messages to make sense
  394. assert ui_output.identifier == output.name, "Cannot find UI Socket for Default Value"
  395. for interface_item in base_tree.interface.items_tree:
  396. if interface_item.item_type == 'PANEL': continue
  397. if interface_item.identifier == output.name: break
  398. else:
  399. raise RuntimeError(f"Default value {ui_output.name} does not exist in {base_tree.name} ")
  400. if interface_item.item_type == "PANEL":
  401. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  402. default_value = None
  403. from bpy.types import bpy_prop_array
  404. from mathutils import Vector
  405. val_type = None
  406. if hasattr(ui_output, 'default_value'):
  407. val_type = type(ui_output.default_value) # why tf can't I match/case here?
  408. if val_type is bool: default_value = interface_item.default_bool
  409. elif val_type is int: default_value = interface_item.default_int
  410. elif val_type is float: default_value = interface_item.default_float
  411. elif val_type is Vector: default_value = interface_item.default_vector
  412. elif val_type is str: default_value = interface_item.default_string
  413. elif val_type is bpy_prop_array: default_value = interface_item.default_bool_vector
  414. elif interface_item.bl_socket_idname == "xFormSocket":
  415. if interface_item.default_xForm == 'ARMATURE':
  416. default_value = 'MANTIS_DEFAULT_ARMATURE'
  417. else:
  418. raise RuntimeError(f"No xForm connected for {ui_output.name} in {base_tree.name}.")
  419. else:
  420. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  421. output_name = output.name
  422. if interface_item.bl_socket_idname not in ['xFormSocket']:
  423. signature = ("MANTIS_AUTOGENERATED", f"Default Value {output.name}",)
  424. autogen_mantis_node = all_mantis_nodes.get(signature)
  425. if autogen_mantis_node is None:
  426. autogen_mantis_node = autogen_node(base_tree, output, signature, InputNode.mContext)
  427. autogen_mantis_node.parameters[output_name]=default_value
  428. elif interface_item.bl_socket_idname == 'xFormSocket' \
  429. and default_value == 'MANTIS_DEFAULT_ARMATURE':
  430. signature = ("MANTIS_AUTOGENERATED", "MANTIS_DEFAULT_ARMATURE",)
  431. autogen_mantis_node = all_mantis_nodes.get(signature)
  432. if autogen_mantis_node is None:
  433. from ..xForm_nodes import xFormArmature
  434. autogen_mantis_node = xFormArmature(signature, base_tree)
  435. autogen_mantis_node.parameters['Name']=base_tree.name+'_MANTIS_AUTOGEN'
  436. autogen_mantis_node.mContext = InputNode.mContext
  437. from mathutils import Matrix
  438. autogen_mantis_node.parameters['Matrix'] = Matrix.Identity(4)
  439. output_name = 'xForm Out'
  440. while output.links:
  441. l = output.links.pop()
  442. to_node = l.to_node; to_socket = l.to_socket
  443. l.die()
  444. autogen_mantis_node.outputs[output_name].connect(to_node, to_socket)
  445. init_connections(l.from_node); init_dependencies(l.from_node)
  446. all_mantis_nodes[autogen_mantis_node.signature]=autogen_mantis_node
  447. def parse_tree(base_tree, error_popups=False):
  448. from uuid import uuid4
  449. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  450. from ..base_definitions import MantisExecutionContext
  451. from ..utilities.node_common import GraphError
  452. mContext = MantisExecutionContext(base_tree=base_tree)
  453. import time
  454. data_start_time = time.time()
  455. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  456. # then they stick around because the function definition inits them once and keeps a reference
  457. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  458. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  459. try:
  460. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(
  461. base_tree,
  462. tree_path = [None],
  463. mContext=mContext,
  464. dummy_nodes = {},
  465. all_mantis_nodes = {},
  466. all_schema={},
  467. in_schema=False
  468. )
  469. except GraphError as e:
  470. base_tree.tree_valid = False; base_tree.hash_recursive=""
  471. if error_popups:
  472. from bpy import context
  473. def error_popup_draw(self, context):
  474. error_popup_draw_inner(self.layout, e, ())
  475. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  476. else: raise e
  477. return # it is not possible to parse the tree until GraphErrors are resolved.
  478. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  479. dummy.reroute_links(all_mantis_nodes)
  480. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  481. start_time = time.time()
  482. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  483. roots, array_nodes = [], []
  484. from collections import deque
  485. unsolved_schema = deque()
  486. from ..base_definitions import array_output_types, GraphError
  487. for mantis_node in all_mantis_nodes.values():
  488. # TODO I still need to assign mContext here because of autogen_node
  489. # so I have to do a deeper refactor to ensure autogen nodes get this at creation time.
  490. mantis_node.mContext = mContext
  491. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  492. if mantis_node.ui_node.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  493. continue
  494. # Initialize the dependencies and connections (from/to links) for each node.
  495. # we record & store it because using a getter is much slower (according to profiling)
  496. init_dependencies(mantis_node); init_connections(mantis_node)
  497. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  498. # Array nodes need a little special treatment, they're quasi-schemas
  499. if mantis_node.__class__.__name__ in array_output_types:
  500. solve_only_these.append(mantis_node)
  501. array_nodes.append(mantis_node)
  502. if mantis_node.node_type == 'INTERFACE':
  503. mContext.interface_nodes[mantis_node.signature] = mantis_node
  504. from itertools import chain
  505. for schema in chain(all_schema.values(), array_nodes):
  506. # We must remove the schema/array nodes that are inside a schema tree.
  507. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  508. if parent := all_schema.get(schema.signature[:i+1]):
  509. # This will be solved along with its parent schema.
  510. solve_only_these.remove(schema)
  511. break
  512. for schema in all_schema.values():
  513. if schema not in solve_only_these: continue
  514. init_schema_dependencies(schema, all_mantis_nodes)
  515. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  516. unsolved_schema.append(schema)
  517. for array in array_nodes:
  518. if array not in solve_only_these: continue
  519. solve_only_these.extend(get_schema_length_dependencies(array))
  520. solve_only_these.extend(array_nodes)
  521. schema_solve_done = set()
  522. solve_only_these = set(solve_only_these)
  523. overlay_tagged_nodes = {}
  524. for node_signature, socket_id in mContext.tagged_for_overlay:
  525. if overlay_tagged_nodes.get(node_signature):
  526. overlay_tagged_nodes[node_signature].append(socket_id)
  527. else:
  528. overlay_tagged_nodes[node_signature] = [socket_id]
  529. def check_and_apply_overlay(n):
  530. if overlays_for_this_node := overlay_tagged_nodes.get(n.signature):
  531. for socket_id in overlays_for_this_node:
  532. node_scan_overlays(n, socket_id,)
  533. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  534. while(solve_layer):
  535. n = solve_layer.pop()
  536. if n not in solve_only_these:
  537. continue
  538. if n.signature in all_schema.keys():
  539. prOrange(n)
  540. for dep in n.hierarchy_dependencies:
  541. if dep not in schema_solve_done and (dep in solve_only_these):
  542. if dep.prepared:
  543. continue
  544. solve_layer.appendleft(n)
  545. break
  546. else:
  547. try:
  548. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots, error_popups=error_popups)
  549. except Exception as e:
  550. e = execution_error_cleanup(n, e, show_error=error_popups)
  551. solved_nodes = {}
  552. if error_popups == False:
  553. raise e
  554. return # it is not possible to parse the tree.
  555. unsolved_schema.remove(n)
  556. schema_solve_done.add(n)
  557. for node in solved_nodes.values():
  558. init_dependencies(node); init_connections(node)
  559. solve_layer.appendleft(node)
  560. schema_solve_done.add(node) # CRITICAL to prevent freezes.
  561. for conn in n.hierarchy_connections:
  562. if conn not in schema_solve_done and conn not in solve_layer:
  563. solve_layer.appendleft(conn)
  564. continue
  565. else:
  566. for dep in n.hierarchy_dependencies:
  567. if dep not in schema_solve_done:
  568. break
  569. else:
  570. check_and_apply_overlay(n)
  571. try:
  572. n.bPrepare()
  573. except Exception as e:
  574. e = execution_error_cleanup(n, e, show_error=error_popups)
  575. if error_popups == False:
  576. raise e
  577. schema_solve_done.add(n)
  578. for conn in n.hierarchy_connections:
  579. if conn not in schema_solve_done and conn not in solve_layer:
  580. solve_layer.appendleft(conn)
  581. continue
  582. if unsolved_schema:
  583. raise RuntimeError("Failed to resolve all schema declarations")
  584. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  585. all_mantis_nodes = list(all_mantis_nodes.values())
  586. kept_mantis_node = {}
  587. while (all_mantis_nodes):
  588. mantis_node = all_mantis_nodes.pop()
  589. if mantis_node.node_type in ["DUMMY", 'SCHEMA', 'DUMMY_SCHEMA']:
  590. continue # screen out the ui_node schema nodes, group in/out, and group placeholders
  591. # cleanup autogen nodes
  592. if mantis_node.signature[0] == "MANTIS_AUTOGENERATED" and len(mantis_node.inputs) == 0 and len(mantis_node.outputs) == 1:
  593. from ..base_definitions import can_remove_socket_for_autogen
  594. output=list(mantis_node.outputs.values())[0]
  595. value=list(mantis_node.parameters.values())[0]
  596. # We can remove this node if it is safe to push it into the other node's socket.
  597. keep_me = False
  598. for l in output.links:
  599. to_node = l.to_node; to_socket = l.to_socket
  600. # do not remove the socket if it is a custom property.
  601. if not can_remove_socket_for_autogen(to_node, to_socket):
  602. keep_me = True; continue
  603. l.die()
  604. to_node.parameters[to_socket] = value
  605. del to_node.inputs[to_socket]
  606. init_dependencies(to_node) # to remove the autogen node we no longer need.
  607. if not keep_me:
  608. continue
  609. init_connections(mantis_node) # because we have removed many connections.
  610. if (mantis_node.node_type in ['XFORM']) and ("Relationship" in mantis_node.inputs.keys()):
  611. from ..utilities.node_common import GraphError
  612. try:
  613. if (new_mantis_node := insert_lazy_parents(mantis_node)):
  614. kept_mantis_node[new_mantis_node.signature]=new_mantis_node
  615. # be sure to add the Mantis context.
  616. new_mantis_node.mContext =mContext
  617. except GraphError as e:
  618. e = execution_error_cleanup(mantis_node, e, show_error=error_popups)
  619. if error_popups == False:
  620. raise e
  621. return # it is not possible to parse the tree.
  622. kept_mantis_node[mantis_node.signature]=mantis_node
  623. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  624. prWhite("Number of Nodes: %s" % (len(kept_mantis_node)))
  625. return kept_mantis_node
  626. from ..utilities.utilities import switch_mode
  627. def error_popup_draw_inner(layout, exception, ui_sig = ()):
  628. node_string = f"See node: {ui_sig[1:]}." if ui_sig else ""
  629. message = f"Error: {exception}\n" + node_string
  630. lines = message.splitlines()
  631. for line in lines:
  632. layout.label(text=line)
  633. def execution_error_cleanup(node, exception, switch_objects = [], show_error=False ):
  634. from bpy import context
  635. ui_sig = None
  636. if show_error: # show a popup and select the relevant nodes
  637. if node:
  638. if node.mContext:
  639. if node.mContext.execution_failed==True:
  640. # already have an error, pass it to avoid printing
  641. return # a second error (it's confusing to users.)
  642. node.mContext.execution_failed=True
  643. ui_sig = node.ui_signature
  644. # TODO: see about zooming-to-node.
  645. base_tree = node.base_tree
  646. tree = base_tree
  647. try:
  648. for name in ui_sig[1:]:
  649. for n in tree.nodes: n.select = False
  650. n = tree.nodes[name]
  651. n.select = True
  652. tree.nodes.active = n
  653. if hasattr(n, "node_tree"):
  654. tree = n.node_tree
  655. except AttributeError: # not being run in node graph
  656. pass
  657. finally:
  658. def error_popup_draw(self, context):
  659. error_popup_draw_inner(self.layout, exception, ui_sig)
  660. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  661. switch_mode(mode='OBJECT', objects=switch_objects)
  662. for ob in switch_objects:
  663. ob.data.pose_position = 'POSE'
  664. prRed(f"Error: {exception} in node {ui_sig}")
  665. return exception
  666. def print_cycle(nodes):
  667. ret_str = ""
  668. for node in nodes:
  669. ret_str+= node.__repr__() + '\n'
  670. return ret_str
  671. def sort_execution(nodes, error_popups):
  672. from ..utilities.node_common import GraphError
  673. from collections import deque
  674. xForm_pass = deque()
  675. execution_failed = False
  676. sorted_nodes = []
  677. # initialize the hierarchy dependency count. We'll use this to ensure there
  678. # are no cycles (using Kahn's algorithm).
  679. expected_sort_quantity = len(nodes)
  680. for mantis_node in nodes.values():
  681. if mantis_node.node_type in ['DUMMY', 'DUMMY_SCHEMA', 'INTERFACE']:
  682. expected_sort_quantity -=1 ; continue
  683. if mantis_node.is_schema_prototype:
  684. expected_sort_quantity -= 1; continue
  685. mantis_node.unmet_hierarchy_dependency_count = len(mantis_node.hierarchy_dependencies)
  686. if mantis_node.unmet_hierarchy_dependency_count == 0 :
  687. xForm_pass.append(mantis_node)
  688. processed_count = 0
  689. while(xForm_pass):
  690. n = xForm_pass.popleft()
  691. # if n.execution_prepared: continue
  692. n.execution_prepared = True
  693. sorted_nodes.append(n)
  694. processed_count+=1
  695. for child in n.hierarchy_connections:
  696. child.unmet_hierarchy_dependency_count-= 1
  697. if child.unmet_hierarchy_dependency_count == 0:
  698. xForm_pass.append(child)
  699. if processed_count < expected_sort_quantity:
  700. cycle = []
  701. for n in nodes.values():
  702. if n.execution_prepared == False:
  703. cycle.append(n)
  704. execution_failed = True
  705. e = GraphError("Detected a cycle in the tree, containing at "
  706. "least one of the following nodes: " + print_cycle(cycle))
  707. e = execution_error_cleanup(cycle[-1], e, show_error=error_popups)
  708. prRed(processed_count, expected_sort_quantity)
  709. raise e
  710. return sorted_nodes, execution_failed
  711. def execute_tree(nodes, base_tree, context, error_popups = False, profile=False):
  712. assert nodes is not None, "Failed to parse tree."
  713. assert len(nodes) > 0, "No parsed nodes for execution."\
  714. " Mantis probably failed to parse the tree."
  715. from bpy.types import Object as bpy_object
  716. from time import time
  717. original_active = context.view_layer.objects.active
  718. start_execution_time = time()
  719. mContext = None
  720. for mantis_node in nodes.values():
  721. if not mContext: # just grab one of these. this is a silly way to do this.
  722. mContext = mantis_node.mContext
  723. mContext.b_objects = {} # clear the objects and recreate them
  724. mantis_node.reset_execution()
  725. mContext.execution_failed = False
  726. interface_nodes = {}
  727. from ..internal_nodes import GroupInterface
  728. for node in nodes.values():
  729. if isinstance(node, GroupInterface):
  730. interface_nodes[node.signature] = node
  731. overlay_tagged_nodes = {}
  732. for node_signature, socket_id in mContext.tagged_for_overlay:
  733. if overlay_tagged_nodes.get(node_signature):
  734. overlay_tagged_nodes[node_signature].append(socket_id)
  735. else:
  736. overlay_tagged_nodes[node_signature] = [socket_id]
  737. def check_and_apply_overlay(n):
  738. if overlays_for_this_node := overlay_tagged_nodes.get(n.signature):
  739. for socket_id in overlays_for_this_node:
  740. node_scan_overlays(n, socket_id,)
  741. select_me, switch_me = [], [] # switch the mode on these objects
  742. active = None # only need it for switching modes
  743. select_me = []
  744. profiler = None
  745. if profile:
  746. from ..dev_helpers.profile_nodes import NodeProfiler
  747. profiler = NodeProfiler()
  748. profiler.new_session(mContext.execution_id)
  749. sort_key = 'total'
  750. try:
  751. sorted_nodes, execution_failed = sort_execution(nodes, error_popups=error_popups)
  752. except Exception as e:
  753. # We'll fire the popup in sort_execution because it has the node in scope
  754. if error_popups == False:
  755. raise e
  756. execution_failed = True
  757. try:
  758. for n in sorted_nodes:
  759. if execution_failed: break
  760. try:
  761. check_and_apply_overlay(n)
  762. if not n.prepared and 'bPrepare' in n.passes:
  763. if profiler: profiler.record(n, "bPrepare", context)
  764. else: n.bPrepare(context)
  765. if not n.executed and 'bTransform' in n.passes:
  766. if profiler: profiler.record(n, "bTransformPass", context)
  767. else: n.bTransformPass(context)
  768. if (n.__class__.__name__ == "xFormArmature" ):
  769. ob = n.bGetObject()
  770. switch_me.append(ob)
  771. active = ob
  772. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  773. ob = n.bGetObject()
  774. if isinstance(ob, bpy_object):
  775. select_me.append(ob)
  776. except Exception as e:
  777. e = execution_error_cleanup(n, e, show_error=error_popups)
  778. if error_popups == False:
  779. raise e
  780. execution_failed = True; break
  781. switch_mode(mode='POSE', objects=switch_me)
  782. for n in sorted_nodes:
  783. try:
  784. check_and_apply_overlay(n)
  785. if not n.prepared and 'bPrepare' in n.passes:
  786. if profiler: profiler.record(n, "bPrepare", context)
  787. else: n.bPrepare(context)
  788. if not n.executed and 'bRelationship' in n.passes:
  789. if profiler: profiler.record(n, "bRelationshipPass", context)
  790. else: n.bRelationshipPass(context)
  791. except Exception as e:
  792. e = execution_error_cleanup(n, e, show_error=error_popups)
  793. if error_popups == False:
  794. raise e
  795. execution_failed = True; break
  796. switch_mode(mode='OBJECT', objects=switch_me)
  797. # switch to pose mode here so that the nodes can use the final pose data
  798. # this will require them to update the depsgraph.
  799. for ob in switch_me:
  800. ob.data.pose_position = 'POSE'
  801. for n in sorted_nodes:
  802. if 'bFinalize' in n.passes:
  803. try:
  804. if profiler: profiler.record(n, "bFinalize", context)
  805. else: n.bFinalize(context)
  806. except Exception as e:
  807. e = execution_error_cleanup(n, e, show_error=error_popups)
  808. if error_popups == False:
  809. raise e
  810. execution_failed = True; break
  811. # REST pose for deformer bind, so everything is in the rest position
  812. for ob in switch_me:
  813. ob.data.pose_position = 'REST'
  814. # finally, apply modifiers and bind stuff
  815. for n in sorted_nodes:
  816. if 'bModifierApply' in n.passes:
  817. try:
  818. if profiler: profiler.record(n, "bModifierApply", context)
  819. else: n.bModifierApply(context)
  820. except Exception as e:
  821. e = execution_error_cleanup(n, e, show_error=error_popups)
  822. if error_popups == False:
  823. raise e
  824. execution_failed = True; break
  825. for ob in switch_me:
  826. ob.data.pose_position = 'POSE'
  827. tot_time = (time() - start_execution_time)
  828. if not execution_failed:
  829. prGreen(f"Executed tree of {len(sorted_nodes)} nodes in {tot_time} seconds")
  830. if profiler:
  831. from ..dev_helpers.profile_nodes import summarize_profile
  832. summarize_profile(profiler._current, pass_name='bPrepare', sort_key = sort_key)
  833. summarize_profile(profiler._current, pass_name='bTransformPass', sort_key = sort_key)
  834. summarize_profile(profiler._current, pass_name='bRelationshipPass', sort_key = sort_key)
  835. summarize_profile(profiler._current, pass_name='bFinalize', sort_key = sort_key)
  836. summarize_profile(profiler._current, pass_name='bModifierApply', sort_key = sort_key)
  837. if (original_active):
  838. context.view_layer.objects.active = original_active
  839. original_active.select_set(True)
  840. except Exception as e:
  841. e = execution_error_cleanup(None, e, switch_me, show_error=error_popups)
  842. if error_popups == False:
  843. raise e
  844. prRed(f"Failed to execute tree.")
  845. finally:
  846. context.view_layer.objects.active = active
  847. # clear the selection first.
  848. from itertools import chain
  849. for ob in context.selected_objects:
  850. try:
  851. ob.select_set(False)
  852. except RuntimeError: # it isn't in the view layer
  853. pass
  854. for ob in chain(select_me, mContext.b_objects.values()):
  855. try:
  856. ob.select_set(True)
  857. except RuntimeError: # it isn't in the view layer
  858. pass