schema_solve.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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
  6. from .base_definitions import SchemaUINode, GraphError, replace_types, custom_props_types
  7. from .node_container_common import setup_custom_props_from_np
  8. # a class that solves Schema nodes
  9. class SchemaSolver:
  10. def __init__(self, schema_dummy, nodes, prototype, signature=None,):
  11. self.all_nodes = nodes # this is the parsed tree from Mantis
  12. self.node = schema_dummy
  13. self.tree = prototype.node_tree
  14. self.uuid = self.node.uuid
  15. if signature:
  16. self.signature = signature
  17. else:
  18. self.signature = self.node.signature
  19. self.schema_nodes={}
  20. self.solved_nodes = {}
  21. self.incoming_connections = {}
  22. self.outgoing_connections = {}
  23. self.constant_in = {}
  24. self.constant_out = {}
  25. self.array_input_connections = {}
  26. self.array_output_connections = {}
  27. self.nested_schemas = {}
  28. self.autogenerated_nodes = {}
  29. self.held_links = []
  30. self.tree_path_names = [*self.node.signature] # same tree as the schema node
  31. self.autogen_path_names = ['SCHEMA_AUTOGENERATED', *self.node.signature[1:]]
  32. self.index_link = self.node.inputs['Schema Length'].links[0]
  33. self.solve_length = self.node.evaluate_input("Schema Length")
  34. # I'm making this a property of the solver because the solver's data is modified as it solves each iteration
  35. self.index = 0
  36. self.init_schema_links()
  37. self.set_index_strings()
  38. # Sort the multi-input nodes in reverse order of ID, this ensures that they are
  39. # read in the order they were created
  40. for inp in self.node.inputs.values():
  41. inp.links.sort(key=lambda a : -a.multi_input_sort_id)
  42. for ui_node in self.tree.nodes:
  43. if isinstance(ui_node, SchemaUINode):
  44. # first we need to fill the parameters of the schema nodes.
  45. # we use the bl_idname because all schema nodes should be single-instance
  46. signature = (*self.tree_path_names, ui_node.bl_idname)
  47. # We use the solver's signature here because it represents the "original" signature of the schema UI group node
  48. # since this schema solver may be in a nested schema, and its node's signature may have uuid/index attached.
  49. get_sig = (*self.signature, ui_node.bl_idname)
  50. if not (mantis_node := self.all_nodes.get(get_sig)): raise RuntimeError(wrapRed(f"Not found: {get_sig}"))
  51. self.schema_nodes[signature] = mantis_node
  52. mantis_node.fill_parameters(ui_node)
  53. def set_index_strings(self):
  54. self.index_str = lambda : '.'+str(self.uuid)+'.'+str(self.index).zfill(4)
  55. self.prev_index_str = lambda : '.'+str(self.uuid)+'.'+str(self.index-1).zfill(4)
  56. def init_schema_links(self,):
  57. """ Sort and store the links to/from the Schema group node."""
  58. for item in self.tree.interface.items_tree:
  59. if item.item_type == 'PANEL': continue
  60. if not item.parent:
  61. raise GraphError("ERROR: Schema tree has inputs that are not in categories. This is not supported")
  62. match item.parent.name:
  63. case 'Connection':
  64. if item.in_out == 'INPUT':
  65. if incoming_links := self.node.inputs[item.identifier].links:
  66. self.incoming_connections[item.name] = incoming_links[0]
  67. else:
  68. self.incoming_connections[item.name] = None
  69. else: # OUTPUT
  70. if outgoing_links := self.node.outputs[item.identifier].links:
  71. self.outgoing_connections[item.name] = outgoing_links.copy()
  72. else:
  73. self.outgoing_connections[item.name] = []
  74. case 'Constant':
  75. if item.in_out == 'INPUT':
  76. if constant_in_links := self.node.inputs[item.identifier].links:
  77. self.constant_in[item.name] = constant_in_links[0]
  78. else:
  79. self.constant_in[item.name] = None
  80. else: # OUTPUT
  81. if constant_out_links := self.node.outputs[item.identifier].links:
  82. self.constant_out[item.name] = constant_out_links.copy()
  83. else:
  84. self.constant_out[item.name] = []
  85. case 'Array':
  86. if item.in_out == 'INPUT':
  87. if item.identifier not in self.array_input_connections.keys():
  88. self.array_input_connections[item.identifier]=[]
  89. if in_links := self.node.inputs[item.identifier].links:
  90. self.array_input_connections[item.identifier]=in_links.copy()
  91. else: # OUTPUT
  92. if item.identifier not in self.array_output_connections.keys():
  93. self.array_output_connections[item.identifier]=[]
  94. if out_links := self.node.outputs[item.identifier].links:
  95. self.array_output_connections[item.identifier] = out_links.copy()
  96. def gen_solve_iteration_mantis_nodes(self, frame_mantis_nodes, unprepared):
  97. for prototype_ui_node in self.tree.nodes:
  98. if isinstance(prototype_ui_node, SchemaUINode):
  99. continue # IGNORE the schema interface nodes, we already made them in __init__()
  100. # they are reused for each iteration.
  101. elif prototype_ui_node.bl_idname in ['NodeFrame', 'NodeReroute']:
  102. continue # IGNORE stuff that is purely UI - frames, reroutes.
  103. signature = (*self.autogen_path_names, prototype_ui_node.name+self.index_str())
  104. prototype_mantis_node = self.all_nodes[(*self.signature, prototype_ui_node.name)]
  105. # the prototype_mantis_node was generated inside the schema when we parsed the tree.
  106. # it is the prototype of the mantis node which we make for this iteration
  107. # for Schema sub-nodes ... they need a prototype to init.
  108. if prototype_mantis_node.node_type in ['DUMMY', 'DUMMY_SCHEMA']:
  109. from .utilities import get_node_prototype
  110. ui_node = get_node_prototype(prototype_mantis_node.signature, prototype_mantis_node.base_tree)
  111. if prototype_mantis_node.node_type == 'DUMMY_SCHEMA':
  112. mantis_node = prototype_mantis_node.__class__(
  113. signature, prototype_mantis_node.base_tree, prototype=ui_node,
  114. natural_signature = (*self.node.signature, ui_node.name) )
  115. else:
  116. mantis_node = prototype_mantis_node.__class__(signature, prototype_mantis_node.base_tree, prototype=ui_node)
  117. else:
  118. mantis_node = prototype_mantis_node.__class__(signature, prototype_mantis_node.base_tree)
  119. frame_mantis_nodes[mantis_node.signature] = mantis_node
  120. if mantis_node.prepared == False:
  121. unprepared.append(mantis_node)
  122. if mantis_node.__class__.__name__ in custom_props_types:
  123. setup_custom_props_from_np(mantis_node, prototype_ui_node)
  124. mantis_node.fill_parameters(prototype_ui_node)
  125. def handle_link_from_index_input(self, index, frame_mantis_nodes, ui_link):
  126. from .utilities import get_link_in_out
  127. _from_name, to_name = get_link_in_out(ui_link)
  128. to_node = frame_mantis_nodes[ (*self.autogen_path_names, to_name+self.index_str()) ]
  129. if to_node.node_type in ['DUMMY', 'DUMMY_SCHEMA']:
  130. from .utilities import gen_nc_input_for_data
  131. nc_cls = gen_nc_input_for_data(ui_link.from_socket)
  132. if (nc_cls): #HACK
  133. sig = ("MANTIS_AUTOGENERATED", *self.tree_path_names[1:-1], self.index_str(), ui_link.from_socket.name, ui_link.from_socket.identifier)
  134. nc_from = nc_cls(sig, self.node.base_tree)
  135. # ugly! maybe even a HACK!
  136. nc_from.inputs = {}
  137. from .base_definitions import NodeSocket
  138. nc_from.outputs = {ui_link.from_socket.name:NodeSocket(name = ui_link.from_socket.name, node=nc_from)}
  139. from .node_container_common import get_socket_value
  140. nc_from.parameters = {ui_link.from_socket.name:index}
  141. frame_mantis_nodes[sig]=nc_from
  142. from_node = nc_from
  143. self.solved_nodes[sig]=from_node
  144. _connection = from_node.outputs[ui_link.from_socket.name].connect(node=to_node, socket=ui_link.to_socket.identifier)
  145. return
  146. # Since the index is already determined, it is safe to remove the socket and just keep the value.
  147. to_node.parameters[ui_link.to_socket.name] = index
  148. del to_node.inputs[ui_link.to_socket.name]
  149. def handle_link_from_schema_length_input(self, frame_mantis_nodes, ui_link):
  150. from .utilities import get_link_in_out
  151. # see, here I can just use the schema node
  152. _from_name, to_name = get_link_in_out(ui_link)
  153. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  154. # this self.index_link is only used here?
  155. if (self.index_link.from_node):
  156. connection = self.index_link.from_node.outputs[self.index_link.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  157. # otherwise we can autogen an int input I guess...?
  158. else:
  159. raise RuntimeError("I was expecting there to be an incoming connection here for Schema Length")
  160. def handle_link_from_incoming_connection_input(self, frame_mantis_nodes, ui_link):
  161. from .utilities import get_link_in_out
  162. incoming = self.incoming_connections[ui_link.from_socket.name]
  163. from_node = incoming.from_node
  164. _from_name, to_name = get_link_in_out(ui_link)
  165. to_node = frame_mantis_nodes[ (*self.autogen_path_names, to_name+self.index_str()) ]
  166. connection = from_node.outputs[incoming.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  167. init_connections(from_node)
  168. def handle_link_from_constant_input(self, frame_mantis_nodes, ui_link, to_ui_node):
  169. from .utilities import get_link_in_out
  170. incoming = self.constant_in[ui_link.from_socket.name]
  171. from_node = incoming.from_node
  172. to_name = get_link_in_out(ui_link)[1]
  173. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  174. to_socket=ui_link.to_socket.name
  175. from .base_definitions import MantisNodeGroup, SchemaGroup
  176. if isinstance(to_ui_node, (SchemaGroup, MantisNodeGroup)):
  177. to_socket=ui_link.to_socket.identifier
  178. connection = from_node.outputs[incoming.from_socket].connect(node=to_node, socket=to_socket)
  179. init_connections(from_node)
  180. def handle_link_to_array_input_get(self, frame_mantis_nodes, ui_link, index):
  181. from .utilities import get_link_in_out
  182. from_name, to_name = get_link_in_out(ui_link)
  183. from_nc = frame_mantis_nodes[(*self.autogen_path_names, from_name+self.index_str())]
  184. to_nc = self.schema_nodes[(*self.tree_path_names, to_name)]
  185. # this only needs to be done once:
  186. if index == 0: # BUG? HACK? TODO find out what is going on here.
  187. # Kill the link between the schema node group and the node connecting to it
  188. old_nc = self.all_nodes[(*self.tree_path_names, from_name)]
  189. # I am not sure about this!
  190. existing_link = old_nc.outputs[ui_link.from_socket.name].links[0]
  191. existing_link.die()
  192. #
  193. connection = from_nc.outputs[ui_link.from_socket.name].connect(node=to_nc, socket=ui_link.to_socket.name)
  194. def handle_link_from_array_input(self, frame_mantis_nodes, ui_link, index):
  195. from .utilities import get_link_in_out
  196. get_index = index
  197. try:
  198. incoming = self.array_input_connections[ui_link.from_socket.identifier][get_index]
  199. except IndexError:
  200. if len(self.array_input_connections[ui_link.from_socket.identifier]) > 0:
  201. incoming = self.array_input_connections[ui_link.from_socket.identifier][0]
  202. # prOrange(incoming.from_node.node_type)
  203. if incoming.from_node.node_type not in ['DUMMY_SCHEMA']:
  204. raise NotImplementedError(wrapRed("dev: make it so Mantis checks if there are enough Array inputs."))
  205. else: # do nothing
  206. return
  207. else:
  208. raise RuntimeError(wrapRed("make it so Mantis checks if there are enough Array inputs!"))
  209. to_name = get_link_in_out(ui_link)[1]
  210. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  211. connection = incoming.from_node.outputs[incoming.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  212. init_connections(incoming.from_node)
  213. def handle_link_to_constant_output(self, frame_mantis_nodes, index, ui_link, to_ui_node):
  214. from .utilities import get_link_in_out
  215. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)]
  216. expose_when = to_node.evaluate_input('Expose when N==')
  217. if index == expose_when:
  218. for outgoing in self.constant_out[ui_link.to_socket.name]:
  219. to_node = outgoing.to_node
  220. from_name = get_link_in_out(ui_link)[0]
  221. from_node = frame_mantis_nodes[(*self.autogen_path_names, from_name+self.index_str()) ]
  222. connection = from_node.outputs[ui_link.from_socket.name].connect(node=to_node, socket=outgoing.to_socket)
  223. # WTF is even happening here?? TODO BUG HACK
  224. 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!
  225. from .utilities import get_link_in_out
  226. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)] # get it by [], we want a KeyError if this fails
  227. for outgoing in self.array_output_connections[ui_link.to_socket.identifier]:
  228. # print (type(outgoing))
  229. from .schema_containers import SchemaIndex
  230. from_name = get_link_in_out(ui_link)[0]
  231. from_node = frame_mantis_nodes[ (*self.autogen_path_names, from_name+self.index_str()) ]
  232. if not from_node:
  233. from_node = self.schema_nodes[(*self.tree_path_names, from_ui_node.bl_idname)]
  234. to_node = outgoing.to_node
  235. if isinstance(from_node, SchemaIndex): # I think I need to dedup this stuff
  236. # print("INDEX")
  237. from .utilities import gen_nc_input_for_data
  238. nc_cls = gen_nc_input_for_data(ui_link.from_socket)
  239. if (nc_cls): #HACK
  240. sig = ("MANTIS_AUTOGENERATED", *self.tree_path_names[1:-1], self.index_str(), ui_link.from_socket.name, ui_link.from_socket.identifier)
  241. nc_from = nc_cls(sig, self.node.base_tree)
  242. # ugly! maybe even a HACK!
  243. nc_from.inputs = {}
  244. from .node_container_common import NodeSocket
  245. nc_from.outputs = {ui_link.from_socket.name:NodeSocket(name = ui_link.from_socket.name, node=nc_from)}
  246. from .node_container_common import get_socket_value
  247. if ui_link.from_socket.name in ['Index']:
  248. nc_from.parameters = {ui_link.from_socket.name:index}
  249. else:
  250. nc_from.parameters = {ui_link.from_socket.name:self.solve_length}
  251. frame_mantis_nodes[sig]=nc_from
  252. from_node = nc_from
  253. self.solved_nodes[sig]=from_node
  254. # I have a feeling that something bad will happen if both of these conditions (above and below) are true
  255. if to_node.node_type == 'DUMMY_SCHEMA' and to_node.prepared:
  256. other_stem = ('SCHEMA_AUTOGENERATED', *to_node.signature[1:])
  257. from .utilities import get_node_prototype
  258. other_schema_np = get_node_prototype(to_node.signature, to_node.base_tree)
  259. other_schema_tree = other_schema_np.node_tree
  260. for n in other_schema_tree.nodes:
  261. if n.bl_idname not in ["SchemaArrayInput", "SchemaArrayInputGet"]:
  262. continue
  263. out = n.outputs[outgoing.to_socket]
  264. for l in out.links:
  265. other_index_str = lambda : '.'+str(to_node.uuid)+'.'+str(index).zfill(4)
  266. # get it by [], we want a KeyError if this fails
  267. try:
  268. out_node = self.all_nodes[(*other_stem, l.to_node.name+other_index_str())]
  269. except KeyError as e:
  270. for n in self.all_nodes:
  271. if len(n) > len(other_stem)+1: break
  272. for elem in other_stem:
  273. if elem not in n: break
  274. else:
  275. print(n)
  276. raise e
  277. connection = from_node.outputs[ui_link.from_socket.name].connect(node=out_node, socket=l.to_socket.name)
  278. else:
  279. connection = from_node.outputs[ui_link.from_socket.name].connect(node=to_node, socket=outgoing.to_socket)
  280. def handle_link_from_array_input_get(self, frame_mantis_nodes, index, ui_link, from_ui_node ):
  281. from .utilities import get_link_in_out
  282. get_index = index
  283. from_node = self.schema_nodes[(*self.tree_path_names, from_ui_node.bl_idname)]
  284. from .utilities import cap, wrap
  285. get_index = from_node.evaluate_input("Index", index)
  286. oob = from_node.evaluate_input("OoB Behaviour")
  287. # we must assume that the array has sent the correct number of links
  288. if oob == 'WRAP':
  289. get_index = wrap(get_index, len(self.array_input_connections[ui_link.from_socket.identifier])-1, 0)
  290. if oob == 'HOLD':
  291. get_index = cap(get_index, len(self.array_input_connections[ui_link.from_socket.identifier])-1)
  292. try:
  293. incoming = self.array_input_connections[ui_link.from_socket.identifier][get_index]
  294. except IndexError:
  295. 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!"))
  296. to_name = get_link_in_out(ui_link)[1]
  297. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  298. connection = incoming.from_node.outputs[incoming.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  299. init_connections(incoming.from_node)
  300. def prepare_nodes(self, unprepared):
  301. # At this point, we've already run a pretty exhaustive preperation phase to prep the schema's dependencies
  302. # So we should not need to add any new dependencies unless there is a bug elsewhere.
  303. # and in fact, I could skip this in some cases, and should investigate if profiling reveals a slowdown here.
  304. while unprepared:
  305. nc = unprepared.pop()
  306. if sum([dep.prepared for dep in nc.hierarchy_dependencies]) == len(nc.hierarchy_dependencies):
  307. nc.bPrepare()
  308. if nc.node_type == 'DUMMY_SCHEMA':
  309. self.solve_nested_schema(nc)
  310. else: # Keeping this for-loop as a fallback, it should never add dependencies though
  311. for dep in nc.hierarchy_dependencies:
  312. if not dep.prepared and dep not in unprepared:
  313. prOrange(f"Adding dependency... {dep}")
  314. unprepared.appendleft(dep)
  315. unprepared.appendleft(nc) # just rotate them until they are ready.
  316. def solve_iteration(self):
  317. """ Solve an iteration of the schema.
  318. - 1 Create the Mantis Node instances that represent this iteration of the schema
  319. - 2 Connect the links from the entrypoint or previous iteration.
  320. - 3 Connect the constant and array links, and any link between nodes entirely within the tree
  321. - 4 Prepare the nodes that modify data (in case of e.g. array get index or nested schema length input)
  322. - 5 Connect the final prepared nodes
  323. and return the nodes that were created in this schema iteration (frame).
  324. This function also adds to held_links to pass data between iterations.
  325. """
  326. from .schema_definitions import (SchemaIndex,
  327. SchemaArrayInput,
  328. SchemaArrayInputGet,
  329. SchemaArrayOutput,
  330. SchemaConstInput,
  331. SchemaConstOutput,
  332. SchemaOutgoingConnection,
  333. SchemaIncomingConnection,)
  334. from .utilities import clear_reroutes
  335. from .utilities import get_link_in_out, link_node_containers
  336. self.set_index_strings()
  337. frame_mantis_nodes = {}
  338. # Later we have to run bPrepare() on these guys, so we make the deque and fill it now.
  339. from collections import deque
  340. unprepared= deque()
  341. self.gen_solve_iteration_mantis_nodes(frame_mantis_nodes, unprepared)
  342. # This is where we handle node connections BETWEEN frames
  343. while(self.held_links):
  344. ui_link = self.held_links.pop()
  345. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  346. if isinstance(to_ui_node, SchemaOutgoingConnection):
  347. mantis_incoming_node = self.schema_nodes[*self.tree_path_names, 'SchemaIncomingConnection']
  348. for mantis_link in mantis_incoming_node.outputs[ui_link.to_socket.name].links:
  349. to_mantis_node, to_mantis_socket = mantis_link.to_node, mantis_link.to_socket
  350. from_name = get_link_in_out(ui_link)[0]
  351. from_mantis_node = self.solved_nodes[ (*self.autogen_path_names, from_name+self.prev_index_str()) ]
  352. to_mantis_node = frame_mantis_nodes[ (*self.autogen_path_names, to_mantis_node.signature[-1]+self.index_str()) ]
  353. connection = from_mantis_node.outputs[ui_link.from_socket.name].connect(node=to_mantis_node, socket=to_mantis_socket)
  354. # We want to delete the links from the tree into the schema node.
  355. # TODO: this is not robust enough and I do not feel sure this is doing the right thing.
  356. if existing_link := self.incoming_connections[ui_link.to_socket.name]:
  357. if existing_link.to_node == self.node:
  358. print ("Deleting...", existing_link)
  359. if self.node.signature[-1] in existing_link.to_node.signature:
  360. existing_link.die()
  361. # BUG may exist here.
  362. self.incoming_connections[ui_link.to_socket.name] = connection
  363. # Get the rerouted links from the graph. We don't really need to do this every iteration.
  364. # TODO: use profiling to determine if this is slow; if so: copy & reuse the data, refactor the pop()'s out.
  365. ui_links = clear_reroutes(list(self.tree.links))
  366. # Now we handle ui_links in the current frame, including those ui_links between Schema nodes and "real" nodes
  367. awaiting_prep_stage = []
  368. for ui_link in ui_links:
  369. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  370. if isinstance(from_ui_node, SchemaIndex):
  371. if ui_link.from_socket.name == "Index":
  372. self.handle_link_from_index_input(self.index, frame_mantis_nodes, ui_link)
  373. elif ui_link.from_socket.name == "Schema Length":
  374. self.handle_link_from_schema_length_input(frame_mantis_nodes, ui_link)
  375. continue
  376. if isinstance(from_ui_node, SchemaIncomingConnection):
  377. if ui_link.from_socket.name in self.incoming_connections.keys():
  378. self.handle_link_from_incoming_connection_input(frame_mantis_nodes, ui_link)
  379. continue
  380. if isinstance(from_ui_node, SchemaConstInput):
  381. if ui_link.from_socket.name in self.constant_in.keys():
  382. self.handle_link_from_constant_input( frame_mantis_nodes, ui_link, to_ui_node)
  383. continue
  384. if isinstance(to_ui_node, SchemaArrayInputGet):
  385. self.handle_link_to_array_input_get( frame_mantis_nodes, ui_link, self.index)
  386. continue
  387. if isinstance(from_ui_node, SchemaArrayInput):
  388. self.handle_link_from_array_input(frame_mantis_nodes, ui_link, self.index)
  389. continue
  390. # HOLD these links to the next iteration:
  391. if isinstance(to_ui_node, SchemaOutgoingConnection):
  392. self.held_links.append(ui_link)
  393. continue
  394. # HOLD these links until prep is done a little later
  395. if isinstance(to_ui_node, SchemaConstOutput) or isinstance(to_ui_node, SchemaArrayOutput) or \
  396. isinstance(from_ui_node, SchemaArrayInputGet):
  397. awaiting_prep_stage.append(ui_link)
  398. continue
  399. # for any of the special cases, we hit a 'continue' block. So this connection is not special, and is made here.
  400. connection = link_node_containers(self.autogen_path_names, ui_link, frame_mantis_nodes, from_suffix=self.index_str(), to_suffix=self.index_str())
  401. for k,v in frame_mantis_nodes.items():
  402. self.solved_nodes[k]=v
  403. init_dependencies(v) # it is hard to overstate how important this single line of code is
  404. self.prepare_nodes(unprepared)
  405. while(awaiting_prep_stage):
  406. ui_link = awaiting_prep_stage.pop()
  407. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  408. if isinstance(to_ui_node, SchemaConstOutput):
  409. self.handle_link_to_constant_output(frame_mantis_nodes, self.index, ui_link, to_ui_node)
  410. if isinstance(to_ui_node, SchemaArrayOutput):
  411. self.handle_link_to_array_output(frame_mantis_nodes, self.index, ui_link, to_ui_node, from_ui_node)
  412. if isinstance(from_ui_node, SchemaArrayInputGet):
  413. self.handle_link_from_array_input_get(frame_mantis_nodes, self.index, ui_link, from_ui_node )
  414. # end seciton
  415. return frame_mantis_nodes
  416. def solve_nested_schema(self, schema_nc):
  417. """ Solves all schema node groups found in this Schema. This is a recursive function, which will
  418. solve all levels of nested schema - since this function is called by solver.solve().
  419. """
  420. if schema_nc.prepared == False:
  421. all_nodes = self.all_nodes.copy()
  422. ui_node = schema_nc.prototype
  423. length = schema_nc.evaluate_input("Schema Length")
  424. tree = ui_node.node_tree
  425. prOrange(f"Expanding schema {tree.name} in node {schema_nc} with length {length}.")
  426. solver = SchemaSolver(schema_nc, all_nodes, ui_node, schema_nc.natural_signature)
  427. solved_nodes = solver.solve()
  428. schema_nc.prepared = True
  429. for k,v in solved_nodes.items():
  430. self.solved_nodes[k]=v
  431. def finalize(self, frame_nc):
  432. from .schema_definitions import (SchemaOutgoingConnection,)
  433. for i in range(len(self.held_links)):
  434. link = self.held_links.pop()
  435. to_np = link.to_socket.node; from_np = link.from_socket.node
  436. if isinstance(to_np, SchemaOutgoingConnection):
  437. if link.to_socket.name in self.outgoing_connections.keys():
  438. if (outgoing_links := self.outgoing_connections[link.to_socket.name]) is None: continue
  439. for outgoing in outgoing_links:
  440. if outgoing:
  441. to_node = outgoing.to_node
  442. from_node =frame_nc[(*self.autogen_path_names, from_np.name+self.index_str()) ]
  443. connection = from_node.outputs[link.from_socket.name].connect(node=to_node, socket=outgoing.to_socket)
  444. # we need to kill the link between the Schema itself and the next node and update the deps. Otherwise:confusing bugs.
  445. outgoing.die(); init_dependencies(to_node)
  446. # else: # the node just isn't connected out this socket.
  447. # # solve all unsolved nested schemas...
  448. for schema_sig, schema_nc in self.nested_schemas.items():
  449. self.solve_nested_schema(schema_nc)
  450. for n in self.autogenerated_nodes.values():
  451. init_connections(n)
  452. for c in n.connections:
  453. init_dependencies(c)
  454. all_outgoing_links = []
  455. for conn in self.outgoing_connections.values():
  456. for outgoing in conn:
  457. all_outgoing_links.append(outgoing)
  458. for conn in self.constant_out.values():
  459. for outgoing in conn:
  460. all_outgoing_links.append(outgoing)
  461. for conn in self.array_output_connections.values():
  462. for outgoing in conn:
  463. all_outgoing_links.append(outgoing)
  464. for outgoing in all_outgoing_links:
  465. to_node = outgoing.to_node
  466. for l in to_node.inputs[outgoing.to_socket].links:
  467. if self.node == l.from_node:
  468. l.die()
  469. for inp in self.node.inputs.values():
  470. for l in inp.links:
  471. init_connections(l.from_node) # to force it to have hierarchy connections with the new nodes.
  472. def solve(self):
  473. for index in range(self.solve_length):
  474. self.index = index
  475. frame_mantis_nodes = self.solve_iteration()
  476. for sig, nc in frame_mantis_nodes.items():
  477. if nc.node_type == 'DUMMY_SCHEMA':
  478. self.nested_schemas[sig] = nc
  479. self.finalize(frame_mantis_nodes)
  480. self.node.solver = self
  481. self.node.prepared = True
  482. return self.solved_nodes