base_definitions.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. #Mantis Nodes Base
  2. import bpy
  3. from bpy.props import (BoolProperty, StringProperty, EnumProperty, CollectionProperty, \
  4. IntProperty, IntVectorProperty, PointerProperty, BoolVectorProperty)
  5. from . import ops_nodegroup
  6. from bpy.types import NodeTree, Node, PropertyGroup, Operator, UIList, Panel
  7. from .utilities import (prRed, prGreen, prPurple, prWhite,
  8. prOrange,
  9. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  10. wrapOrange,)
  11. from .utilities import get_socket_maps, relink_socket_map, do_relink
  12. FLOAT_EPSILON=0.0001 # used to check against floating point inaccuracy
  13. def TellClasses():
  14. #Why use a function to do this? Because I don't need every class to register.
  15. return [ MantisTree,
  16. SchemaTree,
  17. MantisNodeGroup,
  18. SchemaGroup,
  19. ]
  20. def error_popup_draw(self, context):
  21. self.layout.label(text="Error executing tree. See Console.")
  22. mantis_root = ".".join(__name__.split('.')[:-1]) # absolute HACK
  23. # https://docs.blender.org/api/master/bpy.types.NodeTree.html#bpy.types.NodeTree.valid_socket_type
  24. # thank you, Sverchok
  25. def valid_interface_types(cls : NodeTree, socket_idname : str):
  26. from .socket_definitions import tell_valid_bl_idnames, TellClasses
  27. #TODO: do the versioning code to handle this so it can be in all versions
  28. if bpy.app.version <= (4,4,0): # should work in 4.4.1
  29. return socket_idname in [cls.bl_idname for cls in TellClasses()]
  30. else: # once versioning is finished this will be unnecesary.
  31. return socket_idname in tell_valid_bl_idnames()
  32. class MantisTree(NodeTree):
  33. '''A custom node tree type that will show up in the editor type list'''
  34. bl_idname = 'MantisTree'
  35. bl_label = "Rigging Nodes"
  36. bl_icon = 'OUTLINER_OB_ARMATURE'
  37. tree_valid:BoolProperty(default=False)
  38. do_live_update:BoolProperty(default=True) # use this to disable updates for e.g. scripts
  39. num_links:IntProperty(default=-1)
  40. filepath:StringProperty(default="", subtype='FILE_PATH')
  41. is_executing:BoolProperty(default=False)
  42. is_exporting:BoolProperty(default=False)
  43. execution_id:StringProperty(default='')
  44. mantis_version:IntVectorProperty(default=[0,9,2])
  45. # this prevents the node group from executing on the next depsgraph update
  46. # because I don't always have control over when the dg update happens.
  47. prevent_next_exec:BoolProperty(default=False)
  48. parsed_tree={}
  49. if (bpy.app.version < (4, 4, 0)): # in 4.4 this leads to a crash
  50. @classmethod
  51. def valid_socket_type(cls : NodeTree, socket_idname: str):
  52. return valid_interface_types(cls, socket_idname)
  53. def update_tree(self, context = None):
  54. if self.is_exporting:
  55. return
  56. # return
  57. self.is_executing = True
  58. from . import readtree
  59. prGreen("Validating Tree: %s" % self.name)
  60. try:
  61. self.parsed_tree = readtree.parse_tree(self)
  62. if context:
  63. self.display_update(context)
  64. self.is_executing = False
  65. self.tree_valid = True
  66. except GraphError as e:
  67. prRed("Failed to update node tree due to error.")
  68. self.tree_valid = False
  69. self.is_executing = False
  70. raise e
  71. finally:
  72. self.is_executing = False
  73. def display_update(self, context):
  74. if self.is_exporting:
  75. return
  76. self.is_executing = True
  77. current_tree = bpy.context.space_data.path[-1].node_tree
  78. for node in current_tree.nodes:
  79. if hasattr(node, "display_update"):
  80. try:
  81. node.display_update(self.parsed_tree, context)
  82. except Exception as e:
  83. print("Node \"%s\" failed to update display with error: %s" %(wrapGreen(node.name), wrapRed(e)))
  84. self.is_executing = False
  85. # TODO: deal with invalid links properly.
  86. # - Non-hierarchy links should be ignored in the circle-check and so the links should be marked valid in such a circle
  87. # - hierarchy-links should be marked invalid and prevent the tree from executing.
  88. def execute_tree(self,context, error_popups = False):
  89. self.prevent_next_exec = False
  90. if self.is_exporting:
  91. return
  92. # return
  93. prGreen("Executing Tree: %s" % self.name)
  94. self.is_executing = True
  95. from . import readtree
  96. try:
  97. readtree.execute_tree(self.parsed_tree, self, context, error_popups)
  98. except RecursionError as e:
  99. prRed("Recursion error while parsing tree.")
  100. finally:
  101. self.is_executing = False
  102. class SchemaTree(NodeTree):
  103. '''A node tree representing a schema to generate a Mantis tree'''
  104. bl_idname = 'SchemaTree'
  105. bl_label = "Rigging Nodes Schema"
  106. bl_icon = 'RIGID_BODY_CONSTRAINT'
  107. # these are only needed for consistent interface, but should not be used
  108. do_live_update:BoolProperty(default=True) # default to true so that updates work
  109. is_executing:BoolProperty(default=False)
  110. is_exporting:BoolProperty(default=False)
  111. mantis_version:IntVectorProperty(default=[0,9,2])
  112. if (bpy.app.version < (4, 4, 0)): # in 4.4 this leads to a crash
  113. @classmethod
  114. def valid_socket_type(cls : NodeTree, socket_idname: str):
  115. return valid_interface_types(cls, socket_idname)
  116. #TODO: do a better job explaining how MantisNode and MantisUINode relate.
  117. class MantisUINode:
  118. """
  119. This class contains the common user-interface features of Mantis nodes.
  120. MantisUINode objects will spawn one or more MantisNode objects when the graph is evaluated.
  121. The MantisNode objects will pull the data from the UI node and use it to generate the graph.
  122. """
  123. mantis_node_library=''
  124. mantis_node_class_name=''
  125. mantis_class=None
  126. @classmethod
  127. def poll(cls, ntree):
  128. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  129. @classmethod
  130. def set_mantis_class(self):
  131. from importlib import import_module
  132. # do not catch errors, they should cause a failure.
  133. try:
  134. module = import_module(self.mantis_node_library, package=mantis_root)
  135. self.mantis_class=getattr(module, self.mantis_node_class_name)
  136. except Exception as e:
  137. print(self)
  138. raise e
  139. def insert_link(self, link):
  140. if (bpy.app.version < (4, 4, 0)):
  141. return # this causes a crasah due to a bug.
  142. context = bpy.context
  143. if context.space_data:
  144. node_tree = context.space_data.path[0].node_tree
  145. if node_tree.do_live_update:
  146. node_tree.update_tree(context)
  147. if (link.to_socket.is_linked == False):
  148. node_tree.num_links+=1
  149. elif (link.to_socket.is_multi_input):
  150. node_tree.num_links+=1
  151. class SchemaUINode(MantisUINode):
  152. mantis_node_library='.schema_containers'
  153. @classmethod
  154. def poll(cls, ntree):
  155. return (ntree.bl_idname in ['SchemaTree'])
  156. class LinkNode(MantisUINode):
  157. mantis_node_library='.link_containers'
  158. @classmethod
  159. def poll(cls, ntree):
  160. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  161. class xFormNode(MantisUINode):
  162. mantis_node_library='.xForm_containers'
  163. @classmethod
  164. def poll(cls, ntree):
  165. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  166. class DeformerNode(MantisUINode):
  167. mantis_node_library='.deformer_containers'
  168. @classmethod
  169. def poll(cls, ntree):
  170. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  171. def poll_node_tree(self, object):
  172. if isinstance(object, MantisTree):
  173. return True
  174. return False
  175. # TODO: try to check identifiers instead of name.
  176. def node_group_update(node, force = False):
  177. if not force:
  178. if (node.id_data.do_live_update == False) or (node.id_data.is_executing == True):
  179. return
  180. # note: if (node.id_data.is_exporting == True) I need to be able to update so I can make links.
  181. toggle_update = node.id_data.do_live_update
  182. node.id_data.do_live_update = False
  183. identifiers_in={socket.identifier:socket for socket in node.inputs}
  184. identifiers_out={socket.identifier:socket for socket in node.outputs}
  185. indices_in,indices_out={},{} # check by INDEX to see if the socket's name/type match.
  186. for collection, map in [(node.inputs, indices_in), (node.outputs, indices_out)]:
  187. for i, socket in enumerate(collection):
  188. map[socket.identifier]=i
  189. if node.node_tree is None:
  190. node.inputs.clear(); node.outputs.clear()
  191. node.id_data.do_live_update = toggle_update
  192. return
  193. found_in, found_out = [], []
  194. update_input, update_output = False, False
  195. for item in node.node_tree.interface.items_tree:
  196. if item.item_type != "SOCKET": continue
  197. if item.in_out == 'OUTPUT':
  198. if s:= identifiers_out.get(item.identifier): # if the requested output doesn't exist, update
  199. found_out.append(item.identifier)
  200. if (indices_out[s.identifier]!=item.index): update_output=True; continue
  201. if update_output: continue
  202. if s.bl_idname != item.socket_type: update_output = True; continue
  203. else: update_output = True; continue
  204. else:
  205. if s:= identifiers_in.get(item.identifier): # if the requested input doesn't exist, update
  206. found_in.append(item.identifier)
  207. if (indices_in[s.identifier]!=item.index): update_input=True; continue
  208. if update_input: continue # done here
  209. if s.bl_idname != item.socket_type: update_input = True; continue
  210. else: update_input = True; continue
  211. # Schema has an extra input for Length and for Extend.
  212. if node.bl_idname == 'MantisSchemaGroup':
  213. found_in.extend(['Schema Length', ''])
  214. # if we have too many elements, just get rid of the ones we don't need
  215. if len(node.inputs) > len(found_in):#
  216. for inp in node.inputs:
  217. if inp.identifier in found_in: continue
  218. node.inputs.remove(inp)
  219. if len(node.outputs) > len(found_out):
  220. for out in node.outputs:
  221. if out.identifier in found_out: continue
  222. node.outputs.remove(out)
  223. #
  224. if len(node.inputs) > 0 and (inp := node.inputs[-1]).bl_idname == 'WildcardSocket' and inp.is_linked:
  225. update_input = True
  226. if len(node.outputs) > 0 and (out := node.outputs[-1]).bl_idname == 'WildcardSocket' and out.is_linked:
  227. update_output = True
  228. #
  229. if not (update_input or update_output):
  230. node.id_data.do_live_update = toggle_update
  231. return
  232. if update_input or update_output:
  233. socket_maps = get_socket_maps(node)
  234. if socket_maps is None:
  235. node.id_data.do_live_update = toggle_update
  236. return
  237. socket_map_in, socket_map_out = socket_maps
  238. if update_input :
  239. if node.bl_idname == 'MantisSchemaGroup':
  240. schema_length=0
  241. if sl := node.inputs.get("Schema Length"):
  242. schema_length = sl.default_value
  243. # sometimes this isn't available yet # TODO not happy about this solution
  244. node.inputs.clear()
  245. if node.bl_idname == 'MantisSchemaGroup':
  246. node.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  247. node.inputs['Schema Length'].default_value = schema_length
  248. if update_output: node.outputs.clear()
  249. for item in node.node_tree.interface.items_tree:
  250. if item.item_type != "SOCKET": continue
  251. if (item.in_out == 'INPUT' and update_input):
  252. relink_socket_map(node, node.inputs, socket_map_in, item)
  253. if (item.in_out == 'OUTPUT' and update_output):
  254. relink_socket_map(node, node.outputs, socket_map_out, item)
  255. # at this point there is no wildcard socket
  256. if '__extend__' in socket_map_in.keys():
  257. do_relink(node, None, socket_map_in, in_out='INPUT', parent_name='Constant' )
  258. node.id_data.do_live_update = toggle_update
  259. def node_tree_prop_update(self, context):
  260. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  261. return # so we check if an update is currently running.
  262. self.is_updating = True
  263. node_group_update(self)
  264. self.is_updating = False
  265. if self.bl_idname in ['MantisSchemaGroup'] and self.node_tree is not None:
  266. if len(self.inputs) == 0:
  267. self.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  268. if self.inputs[-1].bl_idname != "WildcardSocket":
  269. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  270. from bpy.types import NodeCustomGroup
  271. class MantisNodeGroup(Node, MantisUINode):
  272. bl_idname = "MantisNodeGroup"
  273. bl_label = "Node Group"
  274. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree, update=node_tree_prop_update,)
  275. is_updating:BoolProperty(default=False)
  276. def update(self):
  277. live_update = self.id_data.do_live_update
  278. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  279. return # so we check if an update is currently running.
  280. try:
  281. self.is_updating = True
  282. node_group_update(self)
  283. self.is_updating = False
  284. finally: # we need to reset this regardless of whether or not the operation succeeds!
  285. self.is_updating = False
  286. self.id_data.do_live_update = live_update # ensure this remains the same
  287. def draw_buttons(self, context, layout):
  288. row = layout.row(align=True)
  289. row.prop(self, "node_tree", text="")
  290. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  291. class GraphError(Exception):
  292. pass
  293. def get_signature_from_edited_tree(node, context):
  294. sig_path=[None,]
  295. for item in context.space_data.path[:-1]:
  296. sig_path.append(item.node_tree.nodes.active.name)
  297. return tuple(sig_path+[node.name])
  298. def poll_node_tree_schema(self, object):
  299. if isinstance(object, SchemaTree):
  300. return True
  301. return False
  302. # TODO tiny UI problem - inserting new links into the tree will not place them in the right place.
  303. class SchemaGroup(Node, MantisUINode):
  304. bl_idname = "MantisSchemaGroup"
  305. bl_label = "Node Schema"
  306. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree_schema, update=node_tree_prop_update,)
  307. is_updating:BoolProperty(default=False)
  308. def draw_buttons(self, context, layout):
  309. row = layout.row(align=True)
  310. row.prop(self, "node_tree", text="")
  311. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  312. def update(self):
  313. live_update = self.id_data.do_live_update
  314. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  315. return # so we check if an update is currently running.
  316. self.is_updating = True
  317. try:
  318. node_group_update(self)
  319. # reset things if necessary:
  320. if self.node_tree:
  321. if len(self.inputs) == 0:
  322. self.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  323. if self.inputs[-1].bl_idname != "WildcardSocket":
  324. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  325. finally: # we need to reset this regardless of whether or not the operation succeeds!
  326. self.is_updating = False
  327. self.id_data.do_live_update = live_update # ensure this remains the same
  328. NODES_REMOVED=["xFormRootNode"]
  329. # Node bl_idname, # Socket Name
  330. SOCKETS_REMOVED=[("UtilityDriverVariable", "Transform Channel"),
  331. ("xFormRootNode","World Out"),
  332. ("UtilitySwitch","xForm"),
  333. ("LinkDrivenParameter", "Enable")]
  334. # Node Class #Prior bl_idname # prior name # new bl_idname # new name, # Multi
  335. SOCKETS_RENAMED=[ ("LinkDrivenParameter", "DriverSocket", "Driver", "FloatSocket", "Value", False)]
  336. # NODE CLASS NAME IN_OUT SOCKET TYPE SOCKET NAME INDEX MULTI DEFAULT
  337. SOCKETS_ADDED=[("DeformerMorphTargetDeform", 'INPUT', 'BooleanSocket', "Use Shape Key", 1, False, False),
  338. ("DeformerMorphTargetDeform", 'INPUT', 'BooleanSocket', "Use Offset", 2, False, True),
  339. ("UtilityFCurve", 'INPUT', "eFCrvExtrapolationMode", "Extrapolation Mode", 0, False, 'CONSTANT')]
  340. # replace names with bl_idnames for reading the tree and solving schemas.
  341. replace_types = ["NodeGroupInput", "NodeGroupOutput", "SchemaIncomingConnection",
  342. "SchemaArrayInput", "SchemaConstInput", "SchemaConstOutput", "SchemaIndex",
  343. "SchemaOutgoingConnection", "SchemaConstantOutput", "SchemaArrayOutput",
  344. "SchemaArrayInputGet",]
  345. # anything that gets properties added in the graph... this is a clumsy approach but I need to watch for this
  346. # in schema generation and this is the easiest way to do it for now.
  347. custom_props_types = ["LinkArmature", "UtilityKeyframe", "UtilityFCurve", "UtilityDriver", "xFormBone"]
  348. # filters for determining if a link is a hierarchy link or a non-hierarchy (cyclic) link.
  349. from_name_filter = ["Driver",]
  350. to_name_filter = [
  351. "Custom Object xForm Override",
  352. "Custom Object",
  353. "Deform Bones",
  354. ]
  355. class MantisNode:
  356. """
  357. This class contains the basic interface for a Mantis Node.
  358. A MantisNode is used internally by Mantis to represent the final evaluated node graph.
  359. It gets generated with data from a MantisUINode when the graph is read.
  360. """
  361. def __init__(self, signature, base_tree):
  362. self.base_tree=base_tree
  363. self.signature = signature
  364. self.inputs = MantisNodeSocketCollection(node=self, is_input=True)
  365. self.outputs = MantisNodeSocketCollection(node=self, is_input=False)
  366. self.parameters = {}
  367. self.drivers = {}
  368. self.node_type='UNINITIALIZED'
  369. self.hierarchy_connections, self.connections = [], []
  370. self.hierarchy_dependencies, self.dependencies = [], []
  371. self.prepared = False
  372. self.executed = False
  373. def init_parameters(self, additional_parameters = {}):
  374. for socket in self.inputs:
  375. self.parameters[socket.name] = None
  376. for socket in self.outputs:
  377. self.parameters[socket.name] = None
  378. for key, value in additional_parameters.items():
  379. self.parameters[key]=value
  380. def set_traverse(self, traversal_pairs = [(str, str)]):
  381. for (a, b) in traversal_pairs:
  382. self.inputs[a].set_traverse_target(self.outputs[b])
  383. self.outputs[b].set_traverse_target(self.inputs[a])
  384. def flush_links(self):
  385. for inp in self.inputs.values():
  386. inp.flush_links()
  387. for out in self.outputs.values():
  388. out.flush_links()
  389. def evaluate_input(self, input_name, index=0):
  390. from .node_container_common import trace_single_line
  391. if not (self.inputs.get(input_name)): # get the named parameter if there is no input
  392. return self.parameters.get(input_name) # this will return None if the parameter does not exist.
  393. # this trace() should give a key error if there is a problem
  394. # it is NOT handled here because it should NOT happen - so I want the error message.
  395. trace = trace_single_line(self, input_name, index)
  396. prop = trace[0][-1].parameters[trace[1].name] #trace[0] = the list of traced nodes; read its parameters
  397. return prop
  398. def fill_parameters(self, ui_node=None):
  399. from .utilities import get_node_prototype
  400. from .node_container_common import get_socket_value
  401. if not ui_node:
  402. if ( (self.signature[0] in ["MANTIS_AUTOGENERATED", "SCHEMA_AUTOGENERATED" ]) or
  403. (self.signature[-1] in ["NodeGroupOutput", "NodeGroupInput"]) ): # I think this is harmless
  404. return None
  405. else:
  406. ui_node = get_node_prototype(self.signature, self.base_tree)
  407. if not ui_node:
  408. raise RuntimeError(wrapRed("No node prototype found for... %s" % ( [self.base_tree] + list(self.signature[1:]) ) ) )
  409. for key in self.parameters.keys():
  410. node_socket = ui_node.inputs.get(key)
  411. if self.parameters[key] is not None: # the parameters are usually initialized as None.
  412. continue # will be filled by the node itself
  413. if not node_socket: #maybe the node socket has no name
  414. if ( ( len(ui_node.inputs) == 0) and ( len(ui_node.outputs) == 1) ):
  415. # this is a simple input node.
  416. node_socket = ui_node.outputs[0]
  417. elif key == 'Name': # for Links we just use the Node Label, or if there is no label, the name.
  418. self.parameters[key] = ui_node.label if ui_node.label else ui_node.name
  419. continue
  420. else:
  421. pass
  422. if node_socket:
  423. if node_socket.bl_idname in ['RelationshipSocket', 'xFormSocket']:
  424. continue
  425. elif node_socket.is_linked and (not node_socket.is_output):
  426. pass # we will get the value from the link, because this is a linked input port.
  427. # very importantly, we do not pass linked outputs- fill these because they are probably Input nodes.
  428. elif hasattr(node_socket, "default_value"):
  429. if (value := get_socket_value(node_socket)) is not None:
  430. self.parameters[key] = value
  431. # TODO: try and remove the input if it is not needed (for performance speed)
  432. else:
  433. raise RuntimeError(wrapRed("No value found for " + self.__repr__() + " when filling out node parameters for " + ui_node.name + "::"+node_socket.name))
  434. else:
  435. pass
  436. def call_on_all_ancestors(self, *args, **kwargs):
  437. """Resolve the dependencies of this node with the named method and its arguments.
  438. First, dependencies are discovered by walking backwards through the tree. Once the root
  439. nodes are discovered, the method is called by each node in dependency order.
  440. The first argument MUST be the name of the method as a string.
  441. """
  442. prGreen(self)
  443. if args[0] == 'call_on_all_ancestors': raise RuntimeError("Very funny!")
  444. from .utilities import get_all_dependencies
  445. from collections import deque
  446. # get all dependencies by walking backward through the tree.
  447. all_dependencies = get_all_dependencies(self)
  448. # get just the roots
  449. can_solve = deque(filter(lambda a : len(a.hierarchy_connections) == 0, all_dependencies))
  450. solved = set()
  451. while can_solve:
  452. node = can_solve.pop()
  453. print(node)
  454. method = getattr(node, args[0])
  455. method(*args[0:], **kwargs)
  456. solved.add(node)
  457. can_solve.extendleft(filter(lambda a : a in all_dependencies, node.hierarchy_connections))
  458. # prPurple(can_solve)
  459. if self in solved:
  460. break
  461. # else:
  462. # for dep in all_dependencies:
  463. # if dep not in solved:
  464. # prOrange(dep)
  465. return
  466. def bPrepare(self, bContext=None):
  467. return
  468. def bExecute(self, bContext=None):
  469. return
  470. def bFinalize(self, bContext=None):
  471. return
  472. def __repr__(self):
  473. return self.signature.__repr__()
  474. # do I need this and the link class above?
  475. class DummyLink:
  476. #gonna use this for faking links to keep the interface consistent
  477. def __init__(self, from_socket, to_socket, nc_from=None, nc_to=None, original_from=None, multi_input_sort_id=0):
  478. self.from_socket = from_socket
  479. self.to_socket = to_socket
  480. self.nc_from = nc_from
  481. self.nc_to = nc_to
  482. self.multi_input_sort_id = multi_input_sort_id
  483. # self.from_node = from_socket.node
  484. # self.to_node = to_socket.node
  485. if (original_from):
  486. self.original_from = original_from
  487. else:
  488. self.original_from = self.from_socket
  489. def __repr__(self):
  490. return(self.nc_from.__repr__()+":"+self.from_socket.name + " -> " + self.nc_to.__repr__()+":"+self.to_socket.name)
  491. class NodeLink:
  492. from_node = None
  493. from_socket = None
  494. to_node = None
  495. to_socket = None
  496. def __init__(self, from_node, from_socket, to_node, to_socket, multi_input_sort_id=0):
  497. if from_node.signature == to_node.signature:
  498. raise RuntimeError("Cannot connect a node to itself.")
  499. self.from_node = from_node
  500. self.from_socket = from_socket
  501. self.to_node = to_node
  502. self.to_socket = to_socket
  503. self.from_node.outputs[self.from_socket].links.append(self)
  504. # it is the responsibility of the node that uses these links to sort them correctly based on the sort_id
  505. self.multi_input_sort_id = multi_input_sort_id
  506. self.to_node.inputs[self.to_socket].links.append(self)
  507. from .node_container_common import detect_hierarchy_link
  508. self.is_hierarchy = detect_hierarchy_link(from_node, from_socket, to_node, to_socket,)
  509. self.is_alive = True
  510. def __repr__(self):
  511. return self.from_node.outputs[self.from_socket].__repr__() + " --> " + self.to_node.inputs[self.to_socket].__repr__()
  512. # link_string = # if I need to colorize output for debugging.
  513. # if self.is_hierarchy:
  514. # return wrapOrange(link_string)
  515. # else:
  516. # return wrapWhite(link_string)
  517. def die(self):
  518. self.is_alive = False
  519. self.to_node.inputs[self.to_socket].flush_links()
  520. self.from_node.outputs[self.from_socket].flush_links()
  521. def insert_node(self, middle_node, middle_node_in, middle_node_out, re_init_hierarchy = True):
  522. to_node = self.to_node
  523. to_socket = self.to_socket
  524. self.to_node = middle_node
  525. self.to_socket = middle_node_in
  526. middle_node.outputs[middle_node_out].connect(to_node, to_socket)
  527. if re_init_hierarchy:
  528. from .utilities import init_connections, init_dependencies
  529. init_connections(self.from_node)
  530. init_connections(middle_node)
  531. init_dependencies(middle_node)
  532. init_dependencies(to_node)
  533. class NodeSocket:
  534. # @property # this is a read-only property.
  535. # def is_linked(self):
  536. # return bool(self.links)
  537. def __init__(self, is_input = False,
  538. node = None, name = None,
  539. traverse_target = None):
  540. self.can_traverse = False # to/from the other side of the parent node
  541. self.traverse_target = None
  542. self.node = node
  543. self.name = name
  544. self.is_input = is_input
  545. self.links = []
  546. self.is_linked = False
  547. if (traverse_target):
  548. self.can_traverse = True
  549. def connect(self, node, socket, sort_id=0):
  550. if (self.is_input):
  551. to_node = self.node; from_node = node
  552. to_socket = self.name; from_socket = socket
  553. else:
  554. from_node = self.node; to_node = node
  555. from_socket = self.name; to_socket = socket
  556. from_node.outputs[from_socket].is_linked = True
  557. to_node.inputs[to_socket].is_linked = True
  558. for l in from_node.outputs[from_socket].links:
  559. if l.to_node==to_node and l.to_socket==to_socket:
  560. return None
  561. new_link = NodeLink(
  562. from_node,
  563. from_socket,
  564. to_node,
  565. to_socket,
  566. sort_id)
  567. return new_link
  568. def set_traverse_target(self, traverse_target):
  569. self.traverse_target = traverse_target
  570. self.can_traverse = True
  571. def flush_links(self):
  572. """ Removes dead links from this socket."""
  573. self.links = [l for l in self.links if l.is_alive]
  574. self.is_linked = bool(self.links)
  575. @property
  576. def is_connected(self):
  577. return len(self.links)>0
  578. def __repr__(self):
  579. return self.node.__repr__() + "::" + self.name
  580. class MantisNodeSocketCollection(dict):
  581. def __init__(self, node, is_input=False):
  582. self.is_input = is_input
  583. self.node = node
  584. def init_sockets(self, sockets):
  585. for socket in sockets:
  586. if not isinstance(socket, str): raise RuntimeError("NodeSocketCollection keys must be str.")
  587. self[socket] = NodeSocket(is_input=self.is_input, name=socket, node=self.node)
  588. def __delitem__(self, key):
  589. """Deletes a node socket by name, and all its links."""
  590. socket = self[key]
  591. for l in socket.links:
  592. l.die()
  593. super().__delitem__(key)
  594. def __iter__(self):
  595. """Makes the class iterable"""
  596. return iter(self.values())
  597. # The Mantis Solver class is used to store the execution-specific variables that are used
  598. # when executing the tree
  599. class MantisSolver():
  600. pass
  601. # GOAL: make the switch to "group overlay" paradigm