schema_solve.py 34 KB

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