base_definitions.py 28 KB

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