schema_solve.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. from .utilities import (prRed, prGreen, prPurple, prWhite,
  2. prOrange,
  3. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  4. wrapOrange,)
  5. from .utilities import init_connections, init_dependencies, get_link_in_out
  6. from .base_definitions import SchemaUINode, custom_props_types, MantisNodeGroup, SchemaGroup, replace_types
  7. from .node_container_common import setup_custom_props_from_np
  8. # a class that solves Schema nodes
  9. from bpy.types import NodeGroupInput, NodeGroupOutput
  10. from .readtree import execution_error_cleanup
  11. class SchemaSolver:
  12. def __init__(self, schema_dummy, nodes, prototype, signature=None, error_popups=False):
  13. self.all_nodes = nodes # this is the parsed tree from Mantis
  14. self.node = schema_dummy
  15. self.tree = prototype.node_tree
  16. self.uuid = self.node.uuid
  17. self.error_popups = error_popups
  18. if signature:
  19. self.signature = signature
  20. else:
  21. self.signature = self.node.signature
  22. self.schema_nodes={}
  23. self.solved_nodes = {}
  24. self.incoming_connections = {}
  25. self.outgoing_connections = {}
  26. self.constant_in = {}
  27. self.constant_out = {}
  28. self.array_input_connections = {}
  29. self.array_output_connections = {}
  30. self.nested_schemas = {}
  31. self.autogenerated_nodes = {}
  32. self.held_links = []
  33. self.tree_path_names = [*self.node.signature] # same tree as the schema node
  34. self.autogen_path_names = ['SCHEMA_AUTOGENERATED', *self.node.signature[1:]]
  35. self.is_node_group = False
  36. if self.node.prototype.bl_idname == "MantisNodeGroup":
  37. self.is_node_group = True
  38. if self.node.inputs['Schema Length'].links:
  39. self.index_link = self.node.inputs['Schema Length'].links[0]
  40. else:
  41. self.index_link = None
  42. # this should never happen, but it's OK to check.
  43. if self.node.inputs["Schema Length"].is_linked:
  44. if (other := self.node.inputs['Schema Length'].links[0].from_node).prepared == False:
  45. raise RuntimeError(f"Schema Length cannot be determined for {self.node} because {other} is not prepared.")
  46. self.solve_length = self.node.evaluate_input("Schema Length")
  47. # I'm making this a property of the solver because the solver's data is modified as it solves each iteration
  48. self.index = 0
  49. self.init_schema_links()
  50. self.set_index_strings()
  51. # Sort the multi-input nodes in reverse order of ID, this ensures that they are
  52. # read in the order they were created
  53. for inp in self.node.inputs.values():
  54. inp.links.sort(key=lambda a : -a.multi_input_sort_id)
  55. for ui_node in self.tree.nodes:
  56. # first we need to fill the parameters of the schema nodes.
  57. # we use the bl_idname because all schema nodes should be single-instance
  58. signature = (*self.tree_path_names, ui_node.bl_idname)
  59. if isinstance(ui_node, SchemaUINode):
  60. # We use the schema node's "natural signature" here because it represents
  61. # the "original" signature of the schema UI group node since this schema
  62. # solver may be in a nested schema, and its node's signature may have
  63. # uuid/index attached.
  64. get_sig = (*self.node.ui_signature, ui_node.bl_idname)
  65. if not (mantis_node := self.all_nodes.get(get_sig)): raise RuntimeError(wrapRed(f"Not found: {get_sig}"))
  66. self.schema_nodes[signature] = mantis_node
  67. mantis_node.fill_parameters(ui_node)
  68. # HACK to make Group Nodes work
  69. if ui_node.bl_idname == "NodeGroupInput":
  70. from .schema_containers import SchemaConstInput
  71. mantis_node = SchemaConstInput(signature=signature, base_tree=self.node.base_tree, parent_schema_node=self.node)
  72. self.schema_nodes[signature] = mantis_node
  73. mantis_node.fill_parameters(ui_node)
  74. if ui_node.bl_idname == "NodeGroupOutput":
  75. from .schema_containers import SchemaConstOutput
  76. mantis_node = SchemaConstOutput(signature=signature, base_tree=self.node.base_tree, parent_schema_node=self.node)
  77. self.schema_nodes[signature] = mantis_node
  78. mantis_node.fill_parameters(ui_node)
  79. def set_index_strings(self):
  80. self.index_str = lambda : '.'+str(self.uuid)+'.'+str(self.index).zfill(4)
  81. self.prev_index_str = lambda : '.'+str(self.uuid)+'.'+str(self.index-1).zfill(4)
  82. if self.is_node_group:
  83. self.index_str=lambda : ''
  84. self.prev_index_str=lambda : ''
  85. def init_schema_links(self,):
  86. """ Sort and store the links to/from the Schema group node."""
  87. for item in self.tree.interface.items_tree:
  88. if item.item_type == 'PANEL': continue
  89. parent_name='Constant'
  90. if item.parent.name != '': # in an "prphan" item this is left blank , it is not None or an AttributeError.
  91. parent_name = item.parent.name
  92. match parent_name:
  93. case 'Connection':
  94. if item.in_out == 'INPUT':
  95. if incoming_links := self.node.inputs[item.identifier].links:
  96. self.incoming_connections[item.name] = incoming_links[0]
  97. else:
  98. self.incoming_connections[item.name] = None
  99. else: # OUTPUT
  100. if outgoing_links := self.node.outputs[item.identifier].links:
  101. self.outgoing_connections[item.name] = outgoing_links.copy()
  102. else:
  103. self.outgoing_connections[item.name] = []
  104. case 'Constant':
  105. if item.in_out == 'INPUT':
  106. if constant_in_links := self.node.inputs[item.identifier].links:
  107. self.constant_in[item.name] = constant_in_links[0]
  108. else:
  109. self.constant_in[item.name] = None
  110. else: # OUTPUT
  111. if constant_out_links := self.node.outputs[item.identifier].links:
  112. self.constant_out[item.name] = constant_out_links.copy()
  113. else:
  114. self.constant_out[item.name] = []
  115. case 'Array':
  116. if item.in_out == 'INPUT':
  117. if item.identifier not in self.array_input_connections.keys():
  118. self.array_input_connections[item.identifier]=[]
  119. if in_links := self.node.inputs[item.identifier].links:
  120. self.array_input_connections[item.identifier]=in_links.copy()
  121. # I am tempted to put a check here, but it is sufficient to
  122. # rely on hierarchy links ensuring the arrays are prepared.
  123. # and testing here for un-prepared arrays will mess up schema
  124. # relationships in non-hierarchy situations.
  125. # Still, I'd like to have an easier time catching these problems.
  126. else: # OUTPUT
  127. if item.identifier not in self.array_output_connections.keys():
  128. self.array_output_connections[item.identifier]=[]
  129. if out_links := self.node.outputs[item.identifier].links:
  130. self.array_output_connections[item.identifier] = out_links.copy()
  131. def gen_solve_iteration_mantis_nodes(self, frame_mantis_nodes, unprepared):
  132. for prototype_ui_node in self.tree.nodes:
  133. mantis_node_name = prototype_ui_node.name
  134. index_str = self.index_str()
  135. mContext=self.node.mContext
  136. if isinstance(prototype_ui_node, SchemaUINode):
  137. continue # IGNORE the schema interface nodes, we already made them in __init__()
  138. # they are reused for each iteration.
  139. elif prototype_ui_node.bl_idname in ['NodeFrame', 'NodeReroute']:
  140. continue # IGNORE stuff that is purely UI - frames, reroutes.
  141. elif prototype_ui_node.bl_idname in ['NodeGroupInput', 'NodeGroupOutput']:
  142. continue # we converted these to Schema Nodes because they represent a Group input.
  143. signature = (*self.autogen_path_names, mantis_node_name+index_str)
  144. ui_signature=(*self.signature, mantis_node_name)
  145. prototype_mantis_node = self.all_nodes[ui_signature]
  146. # the prototype_mantis_node was generated inside the schema when we parsed the tree.
  147. # it is the prototype of the mantis node which we make for this iteration
  148. # for Schema sub-nodes ... they need a prototype to init.
  149. if prototype_mantis_node.node_type in ['DUMMY', 'DUMMY_SCHEMA']:
  150. # We stored the prototype ui_node when creating the Mantis node.
  151. ui_node = prototype_mantis_node.prototype
  152. # if prototype_mantis_node is a group or schema: TODO changes are needed elsewhere to make this easier to read. LEGIBILITY
  153. if ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  154. mantis_node = prototype_mantis_node.__class__(
  155. signature, prototype_mantis_node.base_tree, prototype=ui_node,
  156. ui_signature = prototype_mantis_node.signature)
  157. # now let's copy the links from the prototype node
  158. if ui_node.bl_idname in ["MantisNodeGroup"]:
  159. mantis_node.prepared = False
  160. mantis_node.node_type = 'DUMMY_SCHEMA' # we promote it to a schema for now
  161. mantis_node.inputs.init_sockets(['Schema Length']) # add a Schema Length socket
  162. mantis_node.parameters['Schema Length'] = 1 # set the length to 1 since it is a single group instance
  163. # we'll make the autogenerated nodes for constant inputs. It doesn't matter that there is technically
  164. # a prototype available for each one -- these are cheap and I want this to be easy.
  165. from .readtree import make_connections_to_ng_dummy
  166. make_connections_to_ng_dummy(self.node.base_tree, self.autogen_path_names, frame_mantis_nodes, self.all_nodes, mantis_node)
  167. else:
  168. mantis_node = prototype_mantis_node.__class__(signature, prototype_mantis_node.base_tree, prototype=ui_node)
  169. else:
  170. mantis_node = prototype_mantis_node.__class__(signature, prototype_mantis_node.base_tree)
  171. frame_mantis_nodes[mantis_node.signature] = mantis_node
  172. mantis_node.ui_signature=ui_signature # set the natural signature to ensure we can access from the UI
  173. if mantis_node.prepared == False:
  174. unprepared.append(mantis_node)
  175. if mantis_node.__class__.__name__ in custom_props_types:
  176. setup_custom_props_from_np(mantis_node, prototype_ui_node)
  177. mantis_node.fill_parameters(prototype_ui_node)
  178. # be sure to pass on the Mantis Context to them
  179. mantis_node.mContext=mContext
  180. def handle_link_from_index_input(self, index, frame_mantis_nodes, ui_link):
  181. _from_name, to_name = get_link_in_out(ui_link)
  182. to_node = frame_mantis_nodes[ (*self.autogen_path_names, to_name+self.index_str()) ]
  183. if to_node.node_type in ['DUMMY', 'DUMMY_SCHEMA']:
  184. from .utilities import gen_nc_input_for_data
  185. nc_cls = gen_nc_input_for_data(ui_link.from_socket)
  186. if (nc_cls): #HACK
  187. unique_name = "".join([
  188. ui_link.to_socket.node.name+self.index_str(),
  189. ui_link.from_socket.name,
  190. ui_link.from_socket.identifier,
  191. "==>",
  192. ui_link.to_socket.name,
  193. ui_link.to_socket.identifier,
  194. ])
  195. sig = ("MANTIS_AUTOGENERATED", *self.tree_path_names[1:-1], unique_name)
  196. nc_from = frame_mantis_nodes.get(sig)
  197. if not nc_from:
  198. nc_from = nc_cls(sig, self.node.base_tree)
  199. # ugly! maybe even a HACK!
  200. nc_from.inputs = {}
  201. from .base_definitions import NodeSocket
  202. nc_from.outputs = {ui_link.from_socket.name:NodeSocket(name = ui_link.from_socket.name, node=nc_from)}
  203. nc_from.parameters = {ui_link.from_socket.name:index}
  204. frame_mantis_nodes[sig]=nc_from
  205. nc_from.execution_prepared=True
  206. from_node = nc_from
  207. self.solved_nodes[sig]=from_node
  208. _connection = from_node.outputs[ui_link.from_socket.name].connect(node=to_node, socket=ui_link.to_socket.identifier)
  209. return
  210. # Since the index is already determined, it is safe to remove the socket and just keep the value.
  211. to_node.parameters[ui_link.to_socket.name] = index
  212. del to_node.inputs[ui_link.to_socket.name]
  213. def handle_link_from_schema_length_input(self, frame_mantis_nodes, ui_link):
  214. # see, here I can just use the schema node
  215. _from_name, to_name = get_link_in_out(ui_link)
  216. if to_name in replace_types:
  217. to_node = self.schema_nodes[(*self.autogen_path_names, to_name)]
  218. else:
  219. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  220. # this self.index_link is only used here?
  221. if self.index_link is None:
  222. # this should be impossible because the Schema gets an auto-generated Int input.
  223. raise NotImplementedError("This code should be unreachable. Please report this as a bug!")
  224. if (self.index_link.from_node):
  225. connection = self.index_link.from_node.outputs[self.index_link.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  226. # otherwise we can autogen an int input I guess...?
  227. else:
  228. raise RuntimeError("I was expecting there to be an incoming connection here for Schema Length")
  229. def handle_link_from_incoming_connection_input(self, frame_mantis_nodes, ui_link):
  230. incoming = self.incoming_connections[ui_link.from_socket.name]
  231. if incoming is not None:
  232. from_node = incoming.from_node
  233. _from_name, to_name = get_link_in_out(ui_link)
  234. to_node = frame_mantis_nodes[ (*self.autogen_path_names, to_name+self.index_str()) ]
  235. socket_name=ui_link.to_socket.name
  236. if to_node.node_type in [ 'DUMMY_SCHEMA' ]:
  237. socket_name=ui_link.to_socket.identifier
  238. connection = from_node.outputs[incoming.from_socket].connect(node=to_node, socket=socket_name)
  239. init_connections(from_node)
  240. def handle_link_to_outgoing_connection_output(self, frame_mantis_nodes, ui_link,):
  241. mantis_incoming_node = self.schema_nodes[*self.tree_path_names, 'SchemaIncomingConnection']
  242. for mantis_link in mantis_incoming_node.outputs[ui_link.to_socket.name].links:
  243. to_mantis_node, to_mantis_socket = mantis_link.to_node, mantis_link.to_socket
  244. from_name = get_link_in_out(ui_link)[0]
  245. from_mantis_node = self.solved_nodes[ (*self.autogen_path_names, from_name+self.prev_index_str()) ]
  246. to_mantis_node = frame_mantis_nodes[ (*self.autogen_path_names, to_mantis_node.signature[-1]+self.index_str()) ]
  247. from_socket_name = ui_link.from_socket.name
  248. if from_mantis_node.node_type in ['DUMMY_SCHEMA']:
  249. from_socket_name = ui_link.from_socket.identifier
  250. connection = from_mantis_node.outputs[from_socket_name].connect(node=to_mantis_node, socket=to_mantis_socket)
  251. # We want to delete the links from the tree into the schema node.
  252. # TODO: this is not robust enough and I do not feel sure this is doing the right thing.
  253. if existing_link := self.incoming_connections[ui_link.to_socket.name]:
  254. if existing_link.to_node == self.node:
  255. print ("INFO: Deleting...", existing_link)
  256. if self.node.signature[-1] in existing_link.to_node.signature:
  257. existing_link.die()
  258. # BUG may exist here.
  259. self.incoming_connections[ui_link.to_socket.name] = connection
  260. def handle_link_from_constant_input(self, frame_mantis_nodes, ui_link, to_ui_node):
  261. incoming = self.constant_in[ui_link.from_socket.name]
  262. from_node = incoming.from_node
  263. to_name = get_link_in_out(ui_link)[1]
  264. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  265. to_socket=ui_link.to_socket.name
  266. from .base_definitions import MantisNodeGroup, SchemaGroup
  267. if isinstance(to_ui_node, (SchemaGroup, MantisNodeGroup)):
  268. to_socket=ui_link.to_socket.identifier
  269. connection = from_node.outputs[incoming.from_socket].connect(node=to_node, socket=to_socket)
  270. init_connections(from_node)
  271. def handle_link_to_array_input_get(self, frame_mantis_nodes, ui_link, index):
  272. raise NotImplementedError("This node is not supported.")
  273. def handle_link_from_array_input(self, frame_mantis_nodes, ui_link, index):
  274. get_index = index
  275. try:
  276. incoming = self.array_input_connections[ui_link.from_socket.identifier][get_index]
  277. except IndexError:
  278. if len(self.array_input_connections[ui_link.from_socket.identifier]) > 0:
  279. incoming = self.array_input_connections[ui_link.from_socket.identifier][0]
  280. # prOrange(incoming.from_node.node_type)
  281. if incoming.from_node.node_type not in ['DUMMY_SCHEMA']:
  282. raise NotImplementedError(wrapRed("dev: make it so Mantis checks if there are enough Array inputs."))
  283. else: # do nothing
  284. return
  285. else:
  286. raise RuntimeError(wrapRed("make it so Mantis checks if there are enough Array inputs!"))
  287. to_name = get_link_in_out(ui_link)[1]
  288. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  289. connection = incoming.from_node.outputs[incoming.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  290. init_connections(incoming.from_node)
  291. def handle_link_from_array_input_all(self, frame_mantis_nodes, ui_link):
  292. all_links = self.array_input_connections[ui_link.from_socket.identifier]
  293. to_name = get_link_in_out(ui_link)[1]
  294. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  295. # connection = incoming.from_node.outputs[incoming.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  296. for l in all_links:
  297. # we need to copy the link with the new from-node info
  298. from .base_definitions import NodeLink
  299. to_socket_name=ui_link.to_socket.name
  300. if to_node.node_type in ['DUMMY_SCHEMA']:
  301. to_socket_name=ui_link.to_socket.identifier
  302. connection = NodeLink(l.from_node, l.from_socket, to_node, to_socket_name, l.multi_input_sort_id)
  303. to_node.flush_links()
  304. def handle_link_to_constant_output(self, frame_mantis_nodes, index, ui_link, to_ui_node):
  305. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)]
  306. expose_when = to_node.evaluate_input('Expose when N==')
  307. from_name = get_link_in_out(ui_link)[0]
  308. from bpy.types import NodeSocket
  309. #use it directly if it is a mantis node; this happens when the previous node was a Schema
  310. if isinstance( ui_link.from_socket, NodeSocket): # normal
  311. from_node = frame_mantis_nodes[(*self.autogen_path_names, from_name+self.index_str()) ]
  312. else: # it's a mantis socket, set manually while looping though prepped links
  313. from_node = ui_link.from_socket.node
  314. from_socket_name = ui_link.from_socket.name
  315. if from_node.node_type == 'DUMMY_SCHEMA':
  316. from_socket_name = ui_link.from_socket.identifier
  317. # HACK here to force it to work with ordinary node groups, which don't seem to set this value correctly.
  318. if to_ui_node.bl_idname == "NodeGroupOutput":
  319. expose_when = index # just set it directly since it is getting set to None somewhere (I should find out where tho)
  320. # end HACK
  321. if index == expose_when:
  322. for outgoing in self.constant_out[ui_link.to_socket.name]:
  323. to_node = outgoing.to_node
  324. connection = from_node.outputs[from_socket_name].connect(node=to_node, socket=outgoing.to_socket)
  325. def handle_link_from_subschema_to_output(self, frame_mantis_nodes, ui_link, to_ui_node):
  326. # wire the schema node itself to the output so it will push the connections when solving
  327. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)]
  328. from_name = get_link_in_out(ui_link)[0]
  329. from_node = frame_mantis_nodes[ (*self.autogen_path_names, from_name+self.index_str()) ]
  330. connection = from_node.outputs[ui_link.from_socket.identifier].connect(node=to_node, socket=ui_link.to_socket.name)
  331. # WTF is even happening here?? TODO BUG HACK
  332. def handle_link_to_array_output(self, frame_mantis_nodes, index, ui_link, to_ui_node, from_ui_node):# if this duplicated code works, dedupe!
  333. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)] # get it by [], we want a KeyError if this fails
  334. from_name = get_link_in_out(ui_link)[0]
  335. from bpy.types import NodeSocket
  336. #use it directly if it is a mantis node; this happens when the previous node was a Schema
  337. if isinstance( ui_link.from_socket, NodeSocket): # normal
  338. from_node = frame_mantis_nodes[(*self.autogen_path_names, from_name+self.index_str()) ]
  339. else: # it's a mantis socket, set manually while looping though prepped links
  340. from_node = ui_link.from_socket.node
  341. from_socket_name = ui_link.from_socket.name
  342. for outgoing in self.array_output_connections[ui_link.to_socket.identifier]:
  343. if not from_node:
  344. from_node = self.schema_nodes[(*self.tree_path_names, from_ui_node.bl_idname)]
  345. to_node = outgoing.to_node
  346. from .schema_containers import SchemaIndex
  347. if isinstance(from_node, SchemaIndex): # I think I need to dedup this stuff
  348. # print("INDEX")
  349. from .utilities import gen_nc_input_for_data
  350. nc_cls = gen_nc_input_for_data(ui_link.from_socket)
  351. if (nc_cls): #HACK
  352. sig = ("MANTIS_AUTOGENERATED", *self.tree_path_names[1:-1], self.index_str(), ui_link.from_socket.name, ui_link.from_socket.identifier)
  353. nc_from = nc_cls(sig, self.node.base_tree)
  354. nc_from.execution_prepared=True
  355. # ugly! maybe even a HACK!
  356. nc_from.inputs = {}
  357. from .node_container_common import NodeSocket
  358. nc_from.outputs = {ui_link.from_socket.name:NodeSocket(name = ui_link.from_socket.name, node=nc_from)}
  359. from .node_container_common import get_socket_value
  360. if ui_link.from_socket.name in ['Index']:
  361. nc_from.parameters = {ui_link.from_socket.name:index}
  362. else:
  363. nc_from.parameters = {ui_link.from_socket.name:self.solve_length}
  364. frame_mantis_nodes[sig]=nc_from
  365. from_node = nc_from
  366. self.solved_nodes[sig]=from_node
  367. elif from_node.node_type == 'DUMMY_SCHEMA':
  368. from_socket_name = ui_link.from_socket.identifier
  369. # I have a feeling that something bad will happen if both of these conditions (above and below) are true
  370. if to_node.node_type == 'DUMMY_SCHEMA' and to_node.prepared:
  371. other_stem = ('SCHEMA_AUTOGENERATED', *to_node.signature[1:])
  372. from .utilities import get_node_prototype
  373. other_schema_np = get_node_prototype(to_node.signature, to_node.base_tree)
  374. other_schema_tree = other_schema_np.node_tree
  375. for n in other_schema_tree.nodes:
  376. if n.bl_idname not in ["SchemaArrayInput", "SchemaArrayInputGet"]:
  377. continue
  378. out = n.outputs[outgoing.to_socket]
  379. for l in out.links:
  380. other_index_str = lambda : '.'+str(to_node.uuid)+'.'+str(index).zfill(4)
  381. # get it by [], we want a KeyError if this fails
  382. try:
  383. out_node = self.all_nodes[(*other_stem, l.to_node.name+other_index_str())]
  384. except KeyError as e:
  385. for n in self.all_nodes:
  386. if len(n) > len(other_stem)+1: break
  387. for elem in other_stem:
  388. if elem not in n: break
  389. else:
  390. print(n)
  391. raise e
  392. connection = from_node.outputs[from_socket_name].connect(node=out_node, socket=l.to_socket.name)
  393. else:
  394. connection = from_node.outputs[from_socket_name].connect(node=to_node, socket=outgoing.to_socket)
  395. def handle_link_from_array_input_get(self, frame_mantis_nodes, index, ui_link, from_ui_node ):
  396. get_index = index
  397. from_node = self.schema_nodes[(*self.tree_path_names, from_ui_node.bl_idname)]
  398. from .utilities import cap, wrap
  399. get_index = from_node.evaluate_input("Index", index)
  400. oob = from_node.evaluate_input("OoB Behaviour")
  401. # we must assume that the array has sent the correct number of links
  402. if oob == 'WRAP':
  403. get_index = wrap(get_index, len(self.array_input_connections[ui_link.from_socket.identifier])-1, 0)
  404. if oob == 'HOLD':
  405. get_index = cap(get_index, len(self.array_input_connections[ui_link.from_socket.identifier])-1)
  406. try:
  407. incoming = self.array_input_connections[ui_link.from_socket.identifier][get_index]
  408. except IndexError:
  409. raise RuntimeError(wrapRed("Dummy! You need to make it so Mantis checks if there are enough Array inputs! It should probably have a Get Index!"))
  410. to_name = get_link_in_out(ui_link)[1]
  411. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  412. connection = incoming.from_node.outputs[incoming.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  413. init_connections(incoming.from_node)
  414. def spoof_link_for_subschema_to_output_edge_case(self, ui_link, ):
  415. to_ui_node = ui_link.to_socket.node
  416. # ui_link is the link between the Schema & the output but we have mantis_links
  417. # connected up correctly. between the output and the schema's generated nodes.
  418. # so seek BACK from the output node and grab the from-node that is connected to
  419. # the link. then modify the ui_link to point to that node.
  420. from .base_definitions import DummyLink
  421. if not isinstance(ui_link, DummyLink): # make it a Dummy so i can modify it
  422. ui_link = DummyLink(ui_link.from_socket, ui_link.to_socket,
  423. multi_input_sort_id=ui_link.multi_input_sort_id)
  424. to_node = self.schema_nodes[(*self.node.ui_signature, to_ui_node.bl_idname)]
  425. for inp in to_node.inputs:
  426. if inp.name == ui_link.to_socket.name: # the most recent one is from
  427. l = inp.links[-1]; break # <---- this index of the outer schema
  428. ui_link.from_nc = l.from_node; ui_link.from_socket = l.from_node.outputs[l.from_socket]
  429. return ui_link
  430. def test_is_sub_schema(self, other):
  431. for i in range(len(other.ui_signature)-1): # -1, we don't want to check this node, obviously
  432. if self.node.ui_signature[:i+1]:
  433. return False
  434. return True
  435. def prepare_nodes(self, unprepared):
  436. # At this point, we've already run a pretty exhaustive preperation phase to prep the schema's dependencies
  437. # So we should not need to add any new dependencies unless there is a bug elsewhere.
  438. # and in fact, I could skip this in some cases, and should investigate if profiling reveals a slowdown here.
  439. forbidden=set()
  440. # forbid some nodes - they aren't necessary to solve the schema & cause problems.
  441. while unprepared:
  442. nc = unprepared.pop()
  443. if sum([dep.prepared for dep in nc.hierarchy_dependencies]) == len(nc.hierarchy_dependencies):
  444. try:
  445. nc.bPrepare()
  446. except Exception as e:
  447. e = execution_error_cleanup(nc, e, show_error = self.error_popups)
  448. raise e # always raise so that we don't enter an infinite loop.
  449. if nc.node_type == 'DUMMY_SCHEMA':
  450. self.solve_nested_schema(nc)
  451. elif nc.node_type == 'DUMMY_SCHEMA' and not self.test_is_sub_schema(nc):
  452. forbidden.add(nc)
  453. continue # do NOT add this as a dependency.
  454. else: # Keeping this for-loop as a fallback, it should never add dependencies though
  455. can_add_me = True
  456. for dep in nc.hierarchy_dependencies:
  457. if not dep.prepared and dep not in unprepared:
  458. if dep in forbidden:
  459. can_add_me=False
  460. forbidden.add(nc) # forbid the parent, too
  461. continue
  462. prOrange(f"Adding dependency... {dep}")
  463. unprepared.appendleft(dep)
  464. if can_add_me:
  465. unprepared.appendleft(nc) # just rotate them until they are ready.
  466. def solve_iteration(self):
  467. """ Solve an iteration of the schema.
  468. - 1 Create the Mantis Node instances that represent this iteration of the schema
  469. - 2 Connect the links from the entrypoint or previous iteration.
  470. - 3 Connect the constant and array links, and any link between nodes entirely within the tree
  471. - 4 Prepare the nodes that modify data (in case of e.g. array get index or nested schema length input)
  472. - 5 Connect the final prepared nodes
  473. and return the nodes that were created in this schema iteration (frame).
  474. This function also adds to held_links to pass data between iterations.
  475. """
  476. from .schema_definitions import (SchemaIndex,
  477. SchemaArrayInput,
  478. SchemaArrayInputGet,
  479. SchemaArrayInputAll,
  480. SchemaArrayOutput,
  481. SchemaConstInput,
  482. SchemaConstOutput,
  483. SchemaOutgoingConnection,
  484. SchemaIncomingConnection,)
  485. from .utilities import clear_reroutes, link_node_containers
  486. self.set_index_strings()
  487. frame_mantis_nodes = {}
  488. # Later we have to run bPrepare() on these guys, so we make the deque and fill it now.
  489. from collections import deque
  490. unprepared= deque()
  491. self.gen_solve_iteration_mantis_nodes(frame_mantis_nodes, unprepared)
  492. # This is where we handle node connections BETWEEN frames
  493. while(self.held_links):
  494. ui_link = self.held_links.pop()
  495. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  496. if isinstance(to_ui_node, SchemaOutgoingConnection):
  497. self.handle_link_to_outgoing_connection_output(frame_mantis_nodes, ui_link)
  498. # Get the rerouted links from the graph. We don't really need to do this every iteration.
  499. # TODO: use profiling to determine if this is slow; if so: copy & reuse the data, refactor the pop()'s out.
  500. ui_links = clear_reroutes(list(self.tree.links))
  501. # Now we handle ui_links in the current frame, including those ui_links between Schema nodes and "real" nodes
  502. awaiting_prep_stage = []
  503. for ui_link in ui_links:
  504. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  505. if isinstance(from_ui_node, SchemaIndex):
  506. if ui_link.from_socket.name == "Index":
  507. self.handle_link_from_index_input(self.index, frame_mantis_nodes, ui_link)
  508. elif ui_link.from_socket.name == "Schema Length":
  509. self.handle_link_from_schema_length_input(frame_mantis_nodes, ui_link)
  510. continue
  511. if isinstance(from_ui_node, SchemaIncomingConnection):
  512. if ui_link.from_socket.name in self.incoming_connections.keys():
  513. self.handle_link_from_incoming_connection_input(frame_mantis_nodes, ui_link)
  514. continue
  515. if isinstance(from_ui_node, (SchemaConstInput, NodeGroupInput)):
  516. if ui_link.from_socket.name in self.constant_in.keys():
  517. self.handle_link_from_constant_input( frame_mantis_nodes, ui_link, to_ui_node)
  518. continue
  519. if isinstance(to_ui_node, SchemaArrayInputGet):
  520. self.handle_link_to_array_input_get( frame_mantis_nodes, ui_link, self.index)
  521. continue
  522. if isinstance(from_ui_node, SchemaArrayInput):
  523. self.handle_link_from_array_input(frame_mantis_nodes, ui_link, self.index)
  524. continue
  525. if isinstance(from_ui_node, SchemaArrayInputAll):
  526. self.handle_link_from_array_input_all(frame_mantis_nodes, ui_link)
  527. continue
  528. # HOLD these links to the next iteration:
  529. if isinstance(to_ui_node, SchemaOutgoingConnection):
  530. if isinstance(from_ui_node, (MantisNodeGroup, SchemaGroup)):
  531. e = NotImplementedError(
  532. "You have connected a Node Group or Schema directly into an Outgoing Connection node"
  533. " inside another Schema. This is not currently supported. Try using a Constant Output" \
  534. f" instead. Affected node: {from_ui_node.name}"
  535. )
  536. e = execution_error_cleanup(self.node, e, show_error=self.error_popups)
  537. raise e # always raise this error because it is not implemented.
  538. self.handle_link_from_subschema_to_output(frame_mantis_nodes, ui_link, to_ui_node)
  539. self.held_links.append(ui_link)
  540. continue
  541. # HOLD these links until prep is done a little later
  542. if isinstance(to_ui_node, (SchemaConstOutput, NodeGroupOutput)) or isinstance(to_ui_node, SchemaArrayOutput):
  543. if isinstance(from_ui_node, (MantisNodeGroup, SchemaGroup)):
  544. self.handle_link_from_subschema_to_output(frame_mantis_nodes, ui_link, to_ui_node)
  545. # both links are desirable to create, so don't continue here
  546. awaiting_prep_stage.append(ui_link)
  547. continue
  548. if isinstance(from_ui_node, SchemaArrayInputGet):
  549. e = DeprecationWarning("This node is deprecated. Use an Entire Array Input and Array Get node instead.")
  550. from_name, to_name = get_link_in_out(ui_link)
  551. from_nc = frame_mantis_nodes[(*self.autogen_path_names, from_name+self.index_str())]
  552. # always raise this because it is deprecated.
  553. raise execution_error_cleanup(from_nc, e, show_error=self.error_popups)
  554. # for any of the special cases, we hit a 'continue' block. So this connection is not special, and is made here.
  555. connection = link_node_containers(self.autogen_path_names, ui_link, frame_mantis_nodes, from_suffix=self.index_str(), to_suffix=self.index_str())
  556. for signature, node in frame_mantis_nodes.items():
  557. self.solved_nodes[signature]=node
  558. if node.node_type == "DUMMY_SCHEMA":
  559. # make sure to add the nodes to the group's sockets if the user set them directly
  560. from .readtree import make_connections_to_ng_dummy
  561. make_connections_to_ng_dummy(
  562. self.node.base_tree,
  563. self.autogen_path_names,
  564. {}, # just pass an empty dict, this argument is not needed in this context
  565. self.all_nodes,
  566. node)
  567. from .utilities import init_schema_dependencies
  568. init_schema_dependencies(node, self.all_nodes)
  569. else:
  570. init_dependencies(node) # it is hard to overstate how important this single line of code is
  571. self.prepare_nodes(unprepared)
  572. while(awaiting_prep_stage):
  573. ui_link = awaiting_prep_stage.pop()
  574. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  575. # ugly workaround here in a very painful edge case...
  576. if isinstance(from_ui_node, (MantisNodeGroup, SchemaGroup)):
  577. ui_link=self.spoof_link_for_subschema_to_output_edge_case(ui_link)
  578. if isinstance(to_ui_node, (SchemaConstOutput, NodeGroupOutput)):
  579. self.handle_link_to_constant_output(frame_mantis_nodes, self.index, ui_link, to_ui_node)
  580. if isinstance(to_ui_node, SchemaArrayOutput):
  581. self.handle_link_to_array_output(frame_mantis_nodes, self.index, ui_link, to_ui_node, from_ui_node)
  582. if isinstance(from_ui_node, SchemaArrayInputGet):
  583. self.handle_link_from_array_input_get(frame_mantis_nodes, self.index, ui_link, from_ui_node )
  584. # end seciton
  585. return frame_mantis_nodes
  586. def solve_nested_schema(self, schema_nc):
  587. """ Solves all schema node groups found in this Schema. This is a recursive function, which will
  588. solve all levels of nested schema - since this function is called by solver.solve().
  589. """
  590. solver=None
  591. if schema_nc.prepared == False:
  592. all_nodes = self.all_nodes.copy()
  593. ui_node = schema_nc.prototype
  594. length = schema_nc.evaluate_input("Schema Length")
  595. tree = ui_node.node_tree
  596. if schema_nc.prototype.bl_idname == "MantisNodeGroup":
  597. prOrange(f"Expanding Node Group {tree.name} in node {schema_nc}.")
  598. else:
  599. prOrange(f"Expanding schema {tree.name} in node {schema_nc} with length {length}.")
  600. solver = SchemaSolver(schema_nc, all_nodes, ui_node, schema_nc.ui_signature, error_popups=self.error_popups)
  601. solved_nodes = solver.solve()
  602. schema_nc.prepared = True
  603. for k,v in solved_nodes.items():
  604. self.solved_nodes[k]=v
  605. return solver
  606. def finalize(self, frame_nc):
  607. from .schema_definitions import (SchemaOutgoingConnection,)
  608. for i in range(len(self.held_links)):
  609. link = self.held_links.pop()
  610. to_np = link.to_socket.node; from_np = link.from_socket.node
  611. if isinstance(to_np, SchemaOutgoingConnection):
  612. if link.to_socket.name in self.outgoing_connections.keys():
  613. if (outgoing_links := self.outgoing_connections[link.to_socket.name]) is None: continue
  614. for outgoing in outgoing_links:
  615. if outgoing:
  616. to_node = outgoing.to_node
  617. from_node =frame_nc[(*self.autogen_path_names, from_np.name+self.index_str()) ]
  618. from_socket_name = link.from_socket.name
  619. if from_node.node_type in ['DUMMY_SCHEMA']:
  620. from_socket_name = link.from_socket.identifier
  621. connection = from_node.outputs[from_socket_name].connect(node=to_node, socket=outgoing.to_socket)
  622. # we need to kill the link between the Schema itself and the next node and update the deps. Otherwise:confusing bugs.
  623. outgoing.die(); init_dependencies(to_node)
  624. # else: # the node just isn't connected out this socket.
  625. # # solve all unsolved nested schemas...
  626. for schema_sig, schema_nc in self.nested_schemas.items():
  627. self.solve_nested_schema(schema_nc)
  628. for n in self.autogenerated_nodes.values():
  629. init_connections(n)
  630. for c in n.connections:
  631. init_dependencies(c)
  632. all_outgoing_links = []
  633. for conn in self.outgoing_connections.values():
  634. for outgoing in conn:
  635. all_outgoing_links.append(outgoing)
  636. for conn in self.constant_out.values():
  637. for outgoing in conn:
  638. all_outgoing_links.append(outgoing)
  639. for conn in self.array_output_connections.values():
  640. for outgoing in conn:
  641. all_outgoing_links.append(outgoing)
  642. for outgoing in all_outgoing_links:
  643. to_node = outgoing.to_node
  644. for l in to_node.inputs[outgoing.to_socket].links:
  645. if self.node == l.from_node:
  646. l.die()
  647. for inp in self.node.inputs.values():
  648. for l in inp.links:
  649. init_connections(l.from_node) # to force it to have hierarchy connections with the new nodes.
  650. def solve(self):
  651. if self.solve_length < 1:
  652. from .base_definitions import GraphError
  653. for o in self.node.outputs:
  654. if o.is_linked:
  655. raise GraphError(f"ERROR: Schema {self} has a length"
  656. " of 0 but other nodes depend on it.")
  657. print (f"WARN: Schema {self} has a length of 0 or less and will not expand.")
  658. return {} # just don't do anything - it's OK to have a noop schema if it doesn't have dependencies.
  659. for index in range(self.solve_length):
  660. self.index = index
  661. frame_mantis_nodes = self.solve_iteration()
  662. for sig, nc in frame_mantis_nodes.items():
  663. if nc.node_type == 'DUMMY_SCHEMA':
  664. self.nested_schemas[sig] = nc
  665. self.finalize(frame_mantis_nodes)
  666. self.node.solver = self
  667. self.node.prepared = True
  668. return self.solved_nodes