base_definitions.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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. from .mantis_dataclasses import MantisSocketTemplate
  13. FLOAT_EPSILON=0.0001 # used to check against floating point inaccuracy
  14. links_sort_key= lambda a : (-a.multi_input_sort_id, -a.sub_sort_id)
  15. def TellClasses():
  16. #Why use a function to do this? Because I don't need every class to register.
  17. return [ MantisTree,
  18. SchemaTree,
  19. MantisNodeGroup,
  20. SchemaGroup,
  21. ]
  22. def error_popup_draw(self, context):
  23. self.layout.label(text="Error executing tree. See Console.")
  24. mantis_root = ".".join(__name__.split('.')[:-1]) # absolute HACK
  25. from os import environ
  26. # https://docs.blender.org/api/master/bpy.types.NodeTree.html#bpy.types.NodeTree.valid_socket_type
  27. # thank you, Sverchok
  28. def valid_interface_types(cls : NodeTree, socket_idname : str):
  29. from .socket_definitions import tell_valid_bl_idnames, TellClasses
  30. #TODO: do the versioning code to handle this so it can be in all versions
  31. if bpy.app.version <= (4,4,0): # should work in 4.4.1
  32. return socket_idname in [cls.bl_idname for cls in TellClasses()]
  33. elif bpy.app.version == (4,5,0): # workaround for a BUG
  34. return ['NodeSocketGeometry']
  35. else: # once versioning is finished this will be unnecesary.
  36. return socket_idname in tell_valid_bl_idnames()
  37. def fix_reroute_colors(tree):
  38. context = bpy.context
  39. if any((tree.is_executing, tree.is_exporting, tree.do_live_update==False, context.space_data is None) ):
  40. return
  41. from collections import deque
  42. from .utilities import socket_seek
  43. from .socket_definitions import MantisSocket
  44. reroutes_without_color = deque()
  45. for n in tree.nodes:
  46. if n.bl_idname=='NodeReroute' and n.inputs[0].bl_idname == "NodeSocketColor":
  47. reroutes_without_color.append(n)
  48. try:
  49. while reroutes_without_color:
  50. rr = reroutes_without_color.pop()
  51. if rr.inputs[0].is_linked:
  52. link = rr.inputs[0].links[0]
  53. socket = socket_seek(link, tree.links)
  54. if isinstance(socket, MantisSocket):
  55. rr.socket_idname = socket.bl_idname
  56. except Exception as e:
  57. print(wrapOrange("WARN: Updating reroute color failed with exception: ")+wrapWhite(f"{e.__class__.__name__}"))
  58. #functions to identify the state of the system using hashes
  59. # this function runs a lot so it should be optimized as well as possible.
  60. def hash_tree(tree):
  61. trees=set(); links=[]; hash_data=""
  62. for node in tree.nodes:
  63. hash_data+=str(node.name)
  64. if hasattr(node, 'node_tree') and node.node_tree:
  65. trees.add(node.node_tree)
  66. for other_tree in trees:
  67. hash_data+=str(hash_tree(other_tree))
  68. for link in tree.links:
  69. links.append( link.from_node.name+link.from_socket.name+
  70. link.to_node.name+link.to_socket.name+
  71. str(link.multi_input_sort_id) )
  72. links.sort(); hash_data+=''.join(links)
  73. return hash(hash_data)
  74. MANTIS_VERSION_MAJOR=0
  75. MANTIS_VERSION_MINOR=12
  76. MANTIS_VERSION_SUB=27
  77. class MantisTree(NodeTree):
  78. '''A custom node tree type that will show up in the editor type list'''
  79. bl_idname = 'MantisTree'
  80. bl_label = "Rigging Nodes"
  81. bl_icon = 'OUTLINER_OB_ARMATURE'
  82. tree_valid:BoolProperty(default=False)
  83. hash:StringProperty(default='')
  84. do_live_update:BoolProperty(default=True) # use this to disable updates for e.g. scripts
  85. num_links:IntProperty(default=-1)
  86. # operator settings for re-exporting the tree.
  87. filepath:StringProperty(default="", subtype='FILE_PATH')
  88. export_all_subtrees_together:BoolProperty(default=True)
  89. #
  90. is_executing:BoolProperty(default=False)
  91. is_exporting:BoolProperty(default=False)
  92. execution_id:StringProperty(default='')
  93. # prev_execution_id:StringProperty(default='')
  94. mantis_version:IntVectorProperty(default=[
  95. MANTIS_VERSION_MAJOR, MANTIS_VERSION_MINOR, MANTIS_VERSION_SUB])
  96. # this prevents the node group from executing on the next depsgraph update
  97. # because I don't always have control over when the dg upadte happens.
  98. prevent_next_exec:BoolProperty(default=False)
  99. #added to work around a bug in 4.5.0 LTS
  100. interface_helper : StringProperty(default='')
  101. parsed_tree={}
  102. if (bpy.app.version < (4, 4, 0) or bpy.app.version >= (4,5,0)): # in 4.4 this leads to a crash
  103. @classmethod
  104. def valid_socket_type(cls : NodeTree, socket_idname: str):
  105. return valid_interface_types(cls, socket_idname)
  106. def update(self): # set the reroute colors
  107. if (bpy.app.version >= (4,4,0)):
  108. fix_reroute_colors(self)
  109. def update_tree(self, context = None, force=False, error_popups=False):
  110. if self.is_exporting:
  111. return
  112. my_hash = str( hash_tree(self) )
  113. if (my_hash != self.hash) or force:
  114. self.hash = my_hash
  115. self.is_executing = True
  116. from . import readtree
  117. prGreen("Validating Tree: %s" % self.name)
  118. try:
  119. import bpy # I am importing here so that the context passed in
  120. # is used for display update... but I always want to do this
  121. scene = bpy.context.scene
  122. scene.render.use_lock_interface = True
  123. self.parsed_tree = readtree.parse_tree(self, error_popups)
  124. if context:
  125. self.display_update(context)
  126. self.tree_valid = True
  127. except Exception as e:
  128. prRed("Failed to update node tree due to error.")
  129. self.tree_valid = False
  130. self.hash='' # unset the hash to mark the tree as un-parsed.
  131. raise e
  132. finally:
  133. scene.render.use_lock_interface = False
  134. self.is_executing = False
  135. def display_update(self, context):
  136. if self.is_exporting:
  137. return
  138. self.is_executing = True
  139. current_tree = bpy.context.space_data.path[-1].node_tree
  140. for node in current_tree.nodes:
  141. if hasattr(node, "display_update"):
  142. try:
  143. node.display_update(self.parsed_tree, context)
  144. except Exception as e:
  145. print("Node \"%s\" failed to update display with error: %s" %(wrapGreen(node.name), wrapRed(e)))
  146. self.is_executing = False
  147. # TODO: deal with invalid links properly.
  148. # - Non-hierarchy links should be ignored in the circle-check and so the links should be marked valid in such a circle
  149. # - hierarchy-links should be marked invalid and prevent the tree from executing.
  150. def execute_tree(self,context, error_popups = False, profile=False):
  151. self.prevent_next_exec = False
  152. if not self.hash:
  153. return
  154. if self.is_exporting or self.is_executing:
  155. return
  156. prGreen("Executing Tree: %s" % self.name)
  157. self.is_executing = True
  158. from . import readtree
  159. try:
  160. context.scene.render.use_lock_interface = True
  161. readtree.execute_tree(self.parsed_tree, self, context, error_popups, profile=profile)
  162. except RecursionError as e:
  163. prRed("Recursion error while parsing tree.")
  164. finally:
  165. context.scene.render.use_lock_interface = False
  166. self.is_executing = False
  167. class SchemaTree(NodeTree):
  168. '''A node tree representing a schema to generate a Mantis tree'''
  169. bl_idname = 'SchemaTree'
  170. bl_label = "Rigging Nodes Schema"
  171. bl_icon = 'RIGID_BODY_CONSTRAINT'
  172. # these are only needed for consistent interface, but should not be used
  173. do_live_update:BoolProperty(default=True) # default to true so that updates work
  174. is_executing:BoolProperty(default=False)
  175. is_exporting:BoolProperty(default=False)
  176. mantis_version:IntVectorProperty(default=[
  177. MANTIS_VERSION_MAJOR, MANTIS_VERSION_MINOR, MANTIS_VERSION_SUB])
  178. # see the note in MantisTree
  179. interface_helper : StringProperty(default='')
  180. if (bpy.app.version < (4, 4, 0) or bpy.app.version >= (4,5,0)): # in 4.4 this leads to a crash
  181. @classmethod
  182. def valid_socket_type(cls : NodeTree, socket_idname: str):
  183. return valid_interface_types(cls, socket_idname)
  184. def update(self): # set the reroute colors
  185. if (bpy.app.version >= (4,4,0)):
  186. fix_reroute_colors(self)
  187. #TODO: do a better job explaining how MantisNode and MantisUINode relate.
  188. class MantisUINode:
  189. """
  190. This class contains the common user-interface features of Mantis nodes.
  191. MantisUINode objects will spawn one or more MantisNode objects when the graph is evaluated.
  192. The MantisNode objects will pull the data from the UI node and use it to generate the graph.
  193. """
  194. mantis_node_library=''
  195. mantis_node_class_name=''
  196. mantis_class=None
  197. @classmethod
  198. def poll(cls, ntree):
  199. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  200. @classmethod
  201. def set_mantis_class(self):
  202. from importlib import import_module
  203. # do not catch errors, they should cause a failure.
  204. try:
  205. module = import_module(self.mantis_node_library, package=mantis_root)
  206. self.mantis_class=getattr(module, self.mantis_node_class_name)
  207. except Exception as e:
  208. print(self)
  209. raise e
  210. def insert_link(self, link):
  211. if (bpy.app.version >= (4, 4, 0)):
  212. return # this causes a crash due to a bug.
  213. context = bpy.context
  214. if context.space_data:
  215. node_tree = context.space_data.path[0].node_tree
  216. if node_tree.do_live_update:
  217. node_tree.update_tree(context)
  218. if (link.to_socket.is_linked == False):
  219. node_tree.num_links+=1
  220. elif (link.to_socket.is_multi_input):
  221. node_tree.num_links+=1
  222. def init_sockets(self, socket_templates : tuple[MantisSocketTemplate]):
  223. for template in socket_templates:
  224. collection = self.outputs
  225. if template.is_input:
  226. collection = self.inputs
  227. identifier = template.name
  228. if template.identifier:
  229. identifier = template.identifier
  230. use_multi_input = template.use_multi_input if template.is_input else False
  231. socket = collection.new(
  232. template.bl_idname,
  233. template.name,
  234. identifier=identifier,
  235. use_multi_input=use_multi_input
  236. )
  237. socket.hide= template.hide
  238. if template.category:
  239. # a custom property for the UI functions to use.
  240. socket.category = template.category
  241. if template.default_value is not None:
  242. socket.default_value = template.default_value
  243. # this can throw a TypeError - it is the caller's
  244. # responsibility to send the right type.
  245. if template.use_multi_input: # this is an array
  246. socket.display_shape = 'SQUARE_DOT'
  247. class SchemaUINode(MantisUINode):
  248. mantis_node_library='.schema_nodes'
  249. is_updating:BoolProperty(default=False)
  250. @classmethod
  251. def poll(cls, ntree):
  252. return (ntree.bl_idname in ['SchemaTree'])
  253. class LinkNode(MantisUINode):
  254. mantis_node_library='.link_nodes'
  255. @classmethod
  256. def poll(cls, ntree):
  257. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  258. class xFormNode(MantisUINode):
  259. mantis_node_library='.xForm_nodes'
  260. @classmethod
  261. def poll(cls, ntree):
  262. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  263. class DeformerNode(MantisUINode):
  264. mantis_node_library='.deformer_nodes'
  265. @classmethod
  266. def poll(cls, ntree):
  267. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  268. def poll_node_tree(self, object):
  269. forbid = []
  270. context = bpy.context
  271. if context.space_data:
  272. if context.space_data.path:
  273. for path_item in context.space_data.path:
  274. forbid.append(path_item.node_tree.name)
  275. if isinstance(object, MantisTree) and object.name not in forbid:
  276. return True
  277. return False
  278. # TODO: try and remove the extra loop used here... but it is OK for now
  279. def should_remove_socket(node, socket):
  280. # a function to check if the socket is in the interface
  281. id_found = False
  282. for item in node.node_tree.interface.items_tree:
  283. if item.item_type != "SOCKET": continue
  284. if item.identifier == socket.identifier:
  285. id_found = True; break
  286. return not id_found
  287. # TODO: try to check identifiers instead of name.
  288. def node_group_update(node, force = False):
  289. if not node.is_updating:
  290. raise RuntimeError("Cannot update node while it is not marked as updating.")
  291. if not force:
  292. if (node.id_data.do_live_update == False) or \
  293. (node.id_data.is_executing == True) or \
  294. (node.id_data.is_exporting == True):
  295. return
  296. # note: if (node.id_data.is_exporting == True) I need to be able to update so I can make links.
  297. if node.node_tree is None:
  298. node.inputs.clear(); node.outputs.clear()
  299. return
  300. toggle_update = node.id_data.do_live_update
  301. node.id_data.do_live_update = False
  302. identifiers_in={socket.identifier:socket for socket in node.inputs}
  303. identifiers_out={socket.identifier:socket for socket in node.outputs}
  304. interface_names_in, interface_names_out = {}, {}
  305. for interface_item in node.node_tree.interface.items_tree:
  306. if interface_item.item_type != 'SOCKET': continue
  307. if interface_item.in_out == 'INPUT':
  308. interface_names_in[interface_item.identifier] = interface_item.name
  309. else:
  310. interface_names_out[interface_item.identifier] = interface_item.name
  311. indices_in,indices_out={},{} # check by INDEX to see if the socket's name/type match.
  312. for collection, map in [(node.inputs, indices_in), (node.outputs, indices_out)]:
  313. for i, socket in enumerate(collection):
  314. map[socket.identifier]=i
  315. if node.node_tree is None:
  316. node.inputs.clear(); node.outputs.clear()
  317. node.id_data.do_live_update = toggle_update
  318. return
  319. found_in, found_out = [], []
  320. update_input, update_output = False, False
  321. for item in node.node_tree.interface.items_tree:
  322. if item.item_type != "SOCKET": continue
  323. if item.in_out == 'OUTPUT':
  324. if s:= identifiers_out.get(item.identifier): # if the requested output doesn't exist, update
  325. if interface_names_out.get(item.identifier) != s.name: update_output = True; continue
  326. found_out.append(item.identifier)
  327. if (indices_out[s.identifier]!=item.index): update_output=True; continue
  328. if update_output: continue
  329. if s.bl_idname != item.bl_socket_idname: update_output = True; continue
  330. else: update_output = True; continue
  331. else:
  332. if s:= identifiers_in.get(item.identifier): # if the requested input doesn't exist, update
  333. if interface_names_in.get(item.identifier) != s.name: update_input = True; continue
  334. found_in.append(item.identifier)
  335. if (indices_in[s.identifier]!=item.index): update_input=True; continue
  336. if update_input: continue # done here
  337. if s.bl_idname != item.bl_socket_idname: update_input = True; continue
  338. else: update_input = True; continue
  339. # Schema has an extra input for Length and for Extend.
  340. if node.bl_idname == 'MantisSchemaGroup':
  341. found_in.extend(['Schema Length', ''])
  342. # get the socket maps before modifying stuff
  343. if update_input or update_output:
  344. socket_maps = get_socket_maps(node,)
  345. if socket_maps:
  346. socket_map_in, socket_map_out = socket_maps
  347. if node.bl_idname == "MantisSchemaGroup" and \
  348. len(node.inputs)+len(node.outputs)<=2 and\
  349. len(node.node_tree.interface.items_tree) > 0:
  350. socket_map_in, socket_map_out = None, None
  351. # We have to initialize the node because it only has its base inputs.
  352. elif socket_maps is None:
  353. node.id_data.do_live_update = toggle_update
  354. # if we have too many elements, just get rid of the ones we don't need
  355. if len(node.inputs) > len(found_in):#
  356. for inp in node.inputs:
  357. if inp.identifier in found_in: continue
  358. node.inputs.remove(inp)
  359. if len(node.outputs) > len(found_out):
  360. for out in node.outputs:
  361. if out.identifier in found_out: continue
  362. node.outputs.remove(out)
  363. #
  364. if len(node.inputs) > 0 and (inp := node.inputs[-1]).bl_idname == 'WildcardSocket' and inp.is_linked:
  365. update_input = True
  366. #
  367. if not (update_input or update_output):
  368. node.id_data.do_live_update = toggle_update
  369. return
  370. if update_input or update_output and (socket_maps is not None):
  371. if update_input :
  372. if node.bl_idname == 'MantisSchemaGroup':
  373. schema_length=0
  374. if sl := node.inputs.get("Schema Length"):
  375. schema_length = sl.default_value
  376. # sometimes this isn't available yet # TODO not happy about this solution
  377. remove_me=[]
  378. # remove all found map items but the Schema Length input (reuse it)
  379. for i, socket in enumerate(node.inputs):
  380. if socket.identifier == "Schema Length" and i == 0:
  381. continue
  382. elif (socket_map_in is None) or socket.identifier in socket_map_in.keys():
  383. remove_me.append(socket)
  384. elif should_remove_socket(node, socket):
  385. remove_me.append(socket)
  386. while remove_me:
  387. node.inputs.remove(remove_me.pop())
  388. if update_output:
  389. remove_me=[]
  390. for socket in node.outputs:
  391. if (socket_map_out is None) or socket.identifier in socket_map_out.keys():
  392. remove_me.append(socket)
  393. elif should_remove_socket(node, socket):
  394. remove_me.append(socket)
  395. while remove_me:
  396. node.inputs.remove(remove_me.pop())
  397. from .utilities import relink_socket_map_add_socket
  398. reorder_me_input = []; input_index = 0
  399. reorder_me_output = []; output_index = 0
  400. def update_group_sockets(interface_item, is_input):
  401. socket_map = socket_map_in if is_input else socket_map_out
  402. socket_collection = node.inputs if is_input else node.outputs
  403. counter = input_index if is_input else output_index
  404. reorder_collection = reorder_me_input if is_input else reorder_me_output
  405. if socket_map:
  406. if item.identifier in socket_map.keys():
  407. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  408. do_relink(node, socket, socket_map, item.in_out)
  409. else:
  410. for has_socket in socket_collection:
  411. if has_socket.bl_idname == item.bl_socket_idname and \
  412. has_socket.name == item.name:
  413. reorder_collection.append((has_socket, counter))
  414. break
  415. else:
  416. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  417. else:
  418. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  419. counter += 1
  420. # TODO: de-duplicate this hideous stuff
  421. for item in node.node_tree.interface.items_tree:
  422. if item.item_type != "SOCKET": continue
  423. if (item.in_out == 'INPUT' and update_input):
  424. # check and see if it exists... should only happen in curves on startup
  425. if item.bl_socket_idname in ['EnumCurveSocket']:
  426. for exists in node.inputs: # NOTE: check if the socket was not deleted
  427. if exists.identifier == item.identifier:
  428. # this happens for curve inputs because of some shennanigans with how
  429. # blender loads IDs - I can't set the ID until the file has loaded
  430. # so I have to avoid touching the socket until then...
  431. break
  432. else:
  433. update_group_sockets(item, True)
  434. else:
  435. update_group_sockets(item, True)
  436. input_index += 1
  437. if (item.in_out == 'OUTPUT' and update_output):
  438. if item.bl_socket_idname in ['EnumCurveSocket']: # LOOK up there at the comment!
  439. for exists in node.outputs:
  440. if exists.identifier == item.identifier:
  441. break
  442. else:
  443. update_group_sockets(item, False)
  444. else:
  445. update_group_sockets(item, False)
  446. output_index += 1
  447. both_reorders = zip([reorder_me_input, reorder_me_output], [node.inputs, node.outputs])
  448. for reorder_task, collection in both_reorders:
  449. for socket, position in reorder_task:
  450. for i, s in enumerate(collection): # get the index
  451. if s.identifier == socket.identifier: break
  452. else:
  453. prRed(f"WARN: could not reorder socket {socket.name}")
  454. to_index = position
  455. if (not socket.is_output) and node.bl_idname == "MantisSchemaGroup":
  456. to_index+=1
  457. collection.move(i, to_index)
  458. # at this point there is no wildcard socket
  459. if socket_map_in and '__extend__' in socket_map_in.keys():
  460. do_relink(node, None, socket_map_in, in_out='INPUT', parent_name='Constant' )
  461. node.id_data.do_live_update = toggle_update
  462. def node_tree_prop_update(self, context):
  463. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  464. return # so we check if an update is currently running.
  465. self.is_updating = True
  466. def init_schema(self, context):
  467. if len(self.inputs) == 0:
  468. self.inputs.new("UnsignedIntSocket", "Schema Length", identifier='Schema Length')
  469. if self.inputs[-1].bl_idname != "WildcardSocket":
  470. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  471. init_schema(self, context)
  472. try:
  473. node_group_update(self, force=True)
  474. finally: # ensure this line is run even if there is an error
  475. self.is_updating = False
  476. if self.bl_idname in ['MantisSchemaGroup'] and self.node_tree is not None:
  477. init_schema(self, context)
  478. from bpy.types import NodeCustomGroup
  479. def group_draw_buttons(self, context, layout):
  480. row = layout.row(align=True)
  481. row.prop(self, "node_tree", text="")
  482. if self.node_tree is None:
  483. row.operator("mantis.new_node_tree", text="", icon='PLUS', emboss=True)
  484. else:
  485. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  486. class MantisNodeGroup(Node, MantisUINode):
  487. bl_idname = "MantisNodeGroup"
  488. bl_label = "Node Group"
  489. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree, update=node_tree_prop_update,)
  490. is_updating:BoolProperty(default=False)
  491. def draw_label(self):
  492. if self.node_tree is None:
  493. return "Node Group"
  494. else:
  495. return self.node_tree.name
  496. def draw_buttons(self, context, layout):
  497. group_draw_buttons(self, context, layout)
  498. def update(self):
  499. if self.node_tree is None:
  500. return
  501. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  502. return # so we check if an update is currently running.
  503. live_update = self.id_data.do_live_update
  504. self.is_updating = True
  505. try:
  506. node_group_update(self)
  507. finally: # we need to reset this regardless of whether or not the operation succeeds!
  508. self.is_updating = False
  509. self.id_data.do_live_update = live_update # ensure this remains the same
  510. class GraphError(Exception):
  511. pass
  512. def get_signature_from_edited_tree(node, context):
  513. sig_path=[None,]
  514. for item in context.space_data.path[:-1]:
  515. sig_path.append(item.node_tree.nodes.active.name)
  516. return tuple(sig_path+[node.name])
  517. def poll_node_tree_schema(self, object):
  518. if isinstance(object, SchemaTree):
  519. return True
  520. return False
  521. # TODO tiny UI problem - inserting new links into the tree will not place them in the right place.
  522. class SchemaGroup(Node, MantisUINode):
  523. bl_idname = "MantisSchemaGroup"
  524. bl_label = "Node Schema"
  525. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree_schema, update=node_tree_prop_update,)
  526. is_updating:BoolProperty(default=False)
  527. def draw_buttons(self, context, layout):
  528. group_draw_buttons(self, context, layout)
  529. def draw_label(self):
  530. if self.node_tree is None:
  531. return "Schema Group"
  532. else:
  533. return self.node_tree.name
  534. def update(self):
  535. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  536. return # so we check if an update is currently running.
  537. if self.node_tree is None:
  538. return
  539. live_update = self.id_data.do_live_update
  540. self.is_updating = True
  541. try:
  542. node_group_update(self)
  543. # reset things if necessary:
  544. if self.node_tree:
  545. if len(self.inputs) == 0:
  546. self.inputs.new("UnsignedIntSocket", "Schema Length", identifier='Schema Length')
  547. if self.inputs[-1].identifier != "__extend__":
  548. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  549. finally: # we need to reset this regardless of whether or not the operation succeeds!
  550. self.is_updating = False
  551. self.id_data.do_live_update = live_update # ensure this remains the same
  552. # replace names with bl_idnames for reading the tree and solving schemas.
  553. replace_types = ["NodeGroupInput", "NodeGroupOutput", "SchemaIncomingConnection",
  554. "SchemaArrayInput", "SchemaArrayInputAll", "SchemaConstInput", "SchemaConstOutput",
  555. "SchemaIndex", "SchemaOutgoingConnection", "SchemaArrayOutput","SchemaArrayInputGet",
  556. ]
  557. # anything that gets properties added in the graph... this is a clumsy approach but I need to watch for this
  558. # in schema generation and this is the easiest way to do it for now.
  559. custom_props_types = ["LinkArmature", "UtilityKeyframe", "UtilityFCurve", "UtilityDriver", "xFormBone",
  560. "xFormArmature", "xFormGeometryObject", "xFormObjectInstance", "xFormCurvePin",]
  561. # filters for determining if a link is a hierarchy link or a non-hierarchy (cyclic) link.
  562. from_name_filter = ["Driver",]
  563. to_name_filter = [
  564. "Custom Object xForm Override",
  565. "Custom Object",
  566. "Deform Bones",
  567. ]
  568. # nodes that must be solved as if they were Schema because they send arrays out.
  569. array_output_types = [
  570. 'UtilityArrayGet', 'UtilityKDChoosePoint', 'UtilityKDChooseXForm',
  571. ]
  572. def can_remove_socket_for_autogen(node, socket) -> bool:
  573. """ Whether to enable socket removal optimization for the socket
  574. This should be disallowed if e.g. it is a custom property.
  575. """
  576. return False # for now! This doesn't seem to be working...
  577. # the problem is that Schema does this, and so does Readtree
  578. # and they can try and both do it. That's bad.
  579. if node.socket_templates:
  580. for s_template in node.socket_templates:
  581. if s_template.name == socket:
  582. # raise NotImplementedError
  583. return True
  584. elif node.node_type == 'UTILITY':
  585. return True # HACK because most utilities don't have socket templates yet
  586. return False
  587. # TODO:
  588. # - get the execution context in the execution code
  589. # - from there, begin to use it for stuff I can't do without it
  590. # - and slowly start transferring stuff to it
  591. # The Mantis Overlay class is used to store node-tree specific information
  592. # such as inputs and outputs
  593. # used for e.g. allowing strings to pass as $variables in node names
  594. class MantisOverlay():
  595. def __init__( self, parent, inputs, outputs, ):
  596. pass
  597. # The MantisExecutionContext class is used to store the execution-specific variables
  598. # that are used when executing the tree
  599. # Importantly, it is NOT used to store variables between solutions, these belong to the
  600. # tree itself.
  601. class MantisExecutionContext():
  602. def __init__(
  603. self,
  604. base_tree,
  605. ):
  606. self.base_tree = base_tree
  607. self.execution_id = base_tree.execution_id
  608. self.execution_failed=False
  609. self.b_objects={} # objects created by Mantis during execution
  610. from typing import Any
  611. class MantisNode:
  612. """
  613. This class contains the basic interface for a Mantis Node.
  614. A MantisNode is used internally by Mantis to represent the final evaluated node graph.
  615. It gets generated with data from a MantisUINode when the graph is read.
  616. """
  617. def __init__(self, signature : tuple,
  618. base_tree : bpy.types.NodeTree,
  619. socket_templates : list[MantisSocketTemplate]=[],):
  620. self.base_tree=base_tree
  621. self.signature = signature
  622. self.ui_signature = signature
  623. self.inputs = MantisNodeSocketCollection(node=self, is_input=True)
  624. self.outputs = MantisNodeSocketCollection(node=self, is_input=False)
  625. self.parameters, self.drivers = {}, {}; self.bObject=None
  626. self.node_type='UNINITIALIZED'
  627. self.hierarchy_connections, self.connections = [], []
  628. self.hierarchy_dependencies, self.dependencies = [], []
  629. self.prepared, self.executed = False, False
  630. self.execution_prepared = False
  631. # the above is for tracking prep state in execution, so that I can avoid preparing nodes
  632. # again without changing the readtree code much.
  633. self.socket_templates = socket_templates
  634. self.mContext = None # for now I am gonna set this at runtime
  635. # I know it isn't "beautiful OOP" or whatever, but it is just easier
  636. # code should be simple and do things in the simplest way.
  637. # in the future I can refactor it, but it will require changes to 100+
  638. # classes, instead of adding about 5 lines of code elsewhere.
  639. if self.socket_templates:
  640. self.init_sockets()
  641. @property
  642. def name(self):
  643. return self.ui_signature[-1]
  644. @property
  645. def bl_idname(self): # this and the above exist solely to maintain interface w/bpy.types.Node
  646. from .utilities import get_ui_node
  647. return get_ui_node(self.ui_signature, self.base_tree).bl_idname
  648. def reset_execution(self) -> None:
  649. """ Reset the node for additional execution without re-building the tree."""
  650. self.drivers={}; self.bObject=None
  651. self.executed = False
  652. self.execution_prepared = False
  653. def init_sockets(self) -> None:
  654. self.inputs.init_sockets(self.socket_templates)
  655. self.outputs.init_sockets(self.socket_templates)
  656. def init_parameters(self, additional_parameters = {}) -> None:
  657. for socket in self.inputs:
  658. self.parameters[socket.name] = None
  659. for socket in self.outputs:
  660. self.parameters[socket.name] = None
  661. for key, value in additional_parameters.items():
  662. self.parameters[key]=value
  663. def gen_property_socket_map(self) -> dict:
  664. props_sockets = {}
  665. for s_template in self.socket_templates:
  666. if not s_template.blender_property:
  667. continue
  668. if isinstance(s_template.blender_property, str):
  669. props_sockets[s_template.blender_property]=(s_template.name, s_template.default_value)
  670. elif isinstance(s_template.blender_property, (tuple, list)):
  671. for index, sub_prop in enumerate(s_template.blender_property):
  672. props_sockets[sub_prop]=( (s_template.name, index),s_template.default_value[index] )
  673. return props_sockets
  674. def set_traverse(self, traversal_pairs = [(str, str)]) -> None:
  675. for (a, b) in traversal_pairs:
  676. self.inputs[a].set_traverse_target(self.outputs[b])
  677. self.outputs[b].set_traverse_target(self.inputs[a])
  678. def clear_traverse(self, inputs = [str], outputs = [str]) -> None:
  679. for inp in inputs:
  680. self.inputs[inp].set_traverse(None)
  681. for out in outputs:
  682. self.inputs[out].set_traverse(None)
  683. def flush_links(self) -> None:
  684. for inp in self.inputs.values():
  685. inp.flush_links()
  686. for out in self.outputs.values():
  687. out.flush_links()
  688. def update_socket_value(self, blender_property, value) -> bool:
  689. change_handled=False
  690. if self.node_type == 'LINK':
  691. if len(self.bObject) == 0: # - there are no downstream xForms
  692. return True # so there is nothing to do here
  693. for b_ob in self.bObject:
  694. try:
  695. setattr(b_ob, blender_property, value)
  696. change_handled=True
  697. except Exception as e:
  698. print("Failed to update mantis socket because of %s" % e,
  699. "Updating tree instead.")
  700. else:
  701. try:
  702. b_ob = self.bObject
  703. if self.node_type == 'XFORM': # HACK
  704. b_ob = self.bGetObject()
  705. setattr(b_ob, blender_property, value)
  706. change_handled=True
  707. except Exception as e:
  708. print("Failed to update mantis socket because of %s" % e,
  709. "Updating tree instead.")
  710. return change_handled
  711. def ui_modify_socket(self, ui_socket, socket_name=None) -> bool:
  712. """ Handle changes in the node's UI. Updates the rig if possible."""
  713. # Always update the node's data
  714. change_handled=False
  715. if socket_name is None: socket_name = ui_socket.name
  716. value = ui_socket.default_value
  717. if socket_name == 'Enable': value = not value
  718. try:
  719. self.parameters[ui_socket.name]=value
  720. except KeyError:
  721. prRed(f"Unhandled change occured in socket {ui_socket.name} in node"
  722. f" {ui_socket.node.name} in tree {ui_socket.node.id_data.name}.")
  723. for s_template in self.socket_templates:
  724. if s_template.name==ui_socket.name:
  725. change_handled = True
  726. if not s_template.blender_property: return False
  727. elif isinstance(s_template.blender_property, str):
  728. change_handled &= self.update_socket_value(
  729. s_template.blender_property, value)
  730. else: # it is a tuple
  731. for i, prop in enumerate(s_template.blender_property):
  732. try:
  733. change_handled &= self.update_socket_value(
  734. prop, value[i])
  735. except IndexError:
  736. prRed(f"{ui_socket.name} does not have enough values to unpack"
  737. " to update the Mantis tree. Please report this as a bug.")
  738. change_handled=False
  739. break # we don't have to look through any more socket templates
  740. return change_handled
  741. # the goal here is to tag the node as unprepared
  742. # but some nodes are always prepared, so we have to kick it forward.
  743. def reset_execution_recursive(self):
  744. self.reset_execution()
  745. if self.prepared==False: return # all good from here
  746. for conn in self.hierarchy_connections:
  747. conn.reset_execution_recursive()
  748. def evaluate_input(self, input_name, index=0) -> Any:
  749. from .node_common import trace_single_line
  750. if not (self.inputs.get(input_name)): # get the named parameter if there is no input
  751. return self.parameters.get(input_name) # this will return None if the parameter does not exist.
  752. # this trace() should give a key error if there is a problem
  753. # it is NOT handled here because it should NOT happen - so I want the error message.
  754. trace = trace_single_line(self, input_name, index)
  755. prop = trace[0][-1].parameters[trace[1].name] #trace[0] = the list of traced nodes; read its parameters
  756. return prop
  757. def fill_parameters(self, ui_node=None) -> None:
  758. from .utilities import get_ui_node
  759. from .node_common import get_socket_value
  760. if not ui_node:
  761. if ( (self.signature[0] in ["MANTIS_AUTOGENERATED", "SCHEMA_AUTOGENERATED" ]) or
  762. (self.signature[-1] in ["NodeGroupOutput", "NodeGroupInput"]) ): # I think this is harmless
  763. return None
  764. else: # BUG shouldn't this use ui_signature??
  765. ui_node = get_ui_node(self.signature, self.base_tree)
  766. if not ui_node:
  767. raise RuntimeError(wrapRed("No UI Node found for... %s" % ( [self.base_tree] + list(self.signature[1:]) ) ) )
  768. for key in self.parameters.keys():
  769. node_socket = ui_node.inputs.get(key)
  770. if self.parameters[key] is not None: # the parameters are usually initialized as None.
  771. continue # will be filled by the node itself
  772. if not node_socket: #maybe the node socket has no name
  773. if ( ( len(ui_node.inputs) == 0) and ( len(ui_node.outputs) == 1) ):
  774. node_socket = ui_node.outputs[0] # this is a simple input node.
  775. elif key == 'Name': # for Links we just use the Node Label, or if there is no label, the name.
  776. self.parameters[key] = ui_node.label if ui_node.label else ui_node.name
  777. continue
  778. if node_socket:
  779. if node_socket.bl_idname in ['RelationshipSocket', 'xFormSocket']: continue
  780. elif node_socket.is_linked and (not node_socket.is_output): continue
  781. # we will get the value from the link, because this is a linked input port.
  782. # very importantly, we do not pass linked outputs
  783. # fill these because they are probably Input nodes.
  784. elif hasattr(node_socket, "default_value"):
  785. if (value := get_socket_value(node_socket)) is not None:
  786. self.parameters[key] = value
  787. else:
  788. raise RuntimeError(wrapRed("No value found for " + self.__repr__() + " when filling out node parameters for " + ui_node.name + "::"+node_socket.name))
  789. # I don't think this works! but I like the idea
  790. def call_on_all_ancestors(self, *args, **kwargs):
  791. """Resolve the dependencies of this node with the named method and its arguments.
  792. First, dependencies are discovered by walking backwards through the tree. Once the root
  793. nodes are discovered, the method is called by each node in dependency order.
  794. The first argument MUST be the name of the method as a string.
  795. """
  796. if args[0] == 'call_on_all_ancestors': raise RuntimeError("Very funny!")
  797. from .utilities import get_all_dependencies
  798. from collections import deque
  799. # get all dependencies by walking backward through the tree.
  800. all_dependencies = get_all_dependencies(self)
  801. # get just the roots
  802. can_solve = deque(filter(lambda a : len(a.hierarchy_connections) == 0, all_dependencies))
  803. solved = set()
  804. while can_solve:
  805. node = can_solve.pop()
  806. method = getattr(node, args[0])
  807. method(*args[0:], **kwargs)
  808. solved.add(node)
  809. can_solve.extendleft(filter(lambda a : a in all_dependencies, node.hierarchy_connections))
  810. if self in solved:
  811. break
  812. return
  813. # gets targets for constraints and deformers and should handle all cases
  814. def get_target_and_subtarget(self, constraint_or_deformer, input_name = "Target"):
  815. from bpy.types import PoseBone, Object, SplineIKConstraint
  816. subtarget = ''; target = self.evaluate_input(input_name)
  817. if target:
  818. if not hasattr(target, "bGetObject"):
  819. if hasattr(constraint_or_deformer, 'name'):
  820. name = constraint_or_deformer.name
  821. else:
  822. name = 'NAME NOT FOUND'
  823. prRed(f"No {input_name} target found for {name} in {self} because there is no connected node, or node is wrong type")
  824. return
  825. if (isinstance(target.bGetObject(), PoseBone)):
  826. subtarget = target.bGetObject().name
  827. target = target.bGetParentArmature()
  828. elif (isinstance(target.bGetObject(), Object) ):
  829. target = target.bGetObject()
  830. else:
  831. raise RuntimeError("Cannot interpret constraint or deformer target!")
  832. if (isinstance(constraint_or_deformer, SplineIKConstraint)):
  833. if target and target.type not in ["CURVE"]:
  834. raise GraphError(wrapRed("Error: %s requires a Curve input, not %s" %
  835. (self, type(target))))
  836. constraint_or_deformer.target = target# don't get a subtarget
  837. if (input_name == 'Pole Target'):
  838. constraint_or_deformer.pole_target, constraint_or_deformer.pole_subtarget = target, subtarget
  839. else:
  840. if hasattr(constraint_or_deformer, "target"):
  841. constraint_or_deformer.target = target
  842. if hasattr(constraint_or_deformer, "object"):
  843. constraint_or_deformer.object = target
  844. if hasattr(constraint_or_deformer, "subtarget"):
  845. constraint_or_deformer.subtarget = subtarget
  846. # PASSES DEFINED HERE!
  847. def bPrepare(self, bContext=None):
  848. return # This one runs BEFORE anything else
  849. def bTransformPass(self, bContext=None):
  850. return # This one runs in EDIT MODE
  851. def bRelationshipPass(self, bContext=None):
  852. return # This one runs in POSE MODE
  853. def bFinalize(self, bContext=None):
  854. return
  855. def bModifierApply(self, bContext=None):
  856. return
  857. if environ.get("DOERROR"):
  858. def __repr__(self):
  859. return self.signature.__repr__()
  860. else:
  861. def __repr__(self):
  862. return self.ui_signature.__repr__()
  863. # do I need this and the link class above?
  864. class DummyLink:
  865. #gonna use this for faking links to keep the interface consistent
  866. def __init__(self, from_socket, to_socket, from_mantis_node=None, to_mantis_node=None, original_from=None, multi_input_sort_id=0):
  867. self.from_socket = from_socket
  868. self.to_socket = to_socket
  869. self.from_mantis_node = from_mantis_node
  870. self.to_mantis_node = to_mantis_node
  871. self.multi_input_sort_id = multi_input_sort_id
  872. # self.from_node = from_socket.node
  873. # self.to_node = to_socket.node
  874. if (original_from):
  875. self.original_from = original_from
  876. else:
  877. self.original_from = self.from_socket
  878. def __repr__(self):
  879. return(self.from_mantis_node.__repr__()+":"+self.from_socket.name + " -> " + self.to_mantis_node.__repr__()+":"+self.to_socket.name)
  880. def detect_hierarchy_link(from_node, from_socket, to_node, to_socket,):
  881. if to_node.node_type in ['DUMMY_SCHEMA', 'SCHEMA']:
  882. return False #TODO: find out if filtering SCHEMA types is wise
  883. if (from_socket in from_name_filter) or (to_socket in to_name_filter):
  884. return False
  885. # if from_node.__class__.__name__ in ["UtilityCombineVector", "UtilityCombineThreeBool"]:
  886. # return False
  887. return True
  888. class NodeLink:
  889. from_node = None
  890. from_socket = None
  891. to_node = None
  892. to_socket = None
  893. def __init__(self, from_node, from_socket, to_node, to_socket, multi_input_sort_id=0, sub_sort_id=0):
  894. if from_node.signature == to_node.signature:
  895. raise RuntimeError("Cannot connect a node to itself.")
  896. self.from_node = from_node
  897. self.from_socket = from_socket
  898. self.to_node = to_node
  899. self.to_socket = to_socket
  900. self.from_node.outputs[self.from_socket].links.append(self)
  901. # it is the responsibility of the node that uses these links to sort them correctly based on the sort_id
  902. self.multi_input_sort_id = multi_input_sort_id # this is the sort_id of the link in the UI
  903. self.sub_sort_id = sub_sort_id # this is for sorting within a bundled link (one link in the UI)
  904. self.to_node.inputs[self.to_socket].links.append(self)
  905. self.is_hierarchy = detect_hierarchy_link(from_node, from_socket, to_node, to_socket,)
  906. self.is_alive = True
  907. def __repr__(self):
  908. return self.from_node.outputs[self.from_socket].__repr__() + " --> " + self.to_node.inputs[self.to_socket].__repr__()
  909. # link_string = # if I need to colorize output for debugging.
  910. # if self.is_hierarchy:
  911. # return wrapOrange(link_string)
  912. # else:
  913. # return wrapWhite(link_string)
  914. def die(self):
  915. self.is_alive = False
  916. self.to_node.inputs[self.to_socket].flush_links()
  917. self.from_node.outputs[self.from_socket].flush_links()
  918. def insert_node(self, middle_node, middle_node_in, middle_node_out, re_init_hierarchy = True):
  919. to_node = self.to_node
  920. to_socket = self.to_socket
  921. self.to_node = middle_node
  922. self.to_socket = middle_node_in
  923. middle_node.outputs[middle_node_out].connect(to_node, to_socket)
  924. if re_init_hierarchy:
  925. from .utilities import init_connections, init_dependencies
  926. init_connections(self.from_node)
  927. init_connections(middle_node)
  928. init_dependencies(middle_node)
  929. init_dependencies(to_node)
  930. class NodeSocket:
  931. # @property # this is a read-only property.
  932. # def is_linked(self):
  933. # return bool(self.links)
  934. def __init__(self, is_input = False,
  935. node = None, name = None,
  936. traverse_target = None):
  937. self.can_traverse = False # to/from the other side of the parent node
  938. self.traverse_target = None
  939. self.node = node
  940. self.name = name
  941. self.is_input = is_input
  942. self.links = []
  943. self.is_linked = False
  944. if (traverse_target):
  945. self.can_traverse = True
  946. def connect(self, node, socket, sort_id=0, sub_sort_id=0):
  947. if (self.is_input):
  948. to_node = self.node; from_node = node
  949. to_socket = self.name; from_socket = socket
  950. else:
  951. from_node = self.node; to_node = node
  952. from_socket = self.name; to_socket = socket
  953. from_node.outputs[from_socket].is_linked = True
  954. to_node.inputs[to_socket].is_linked = True
  955. # NOTE: I have removed a check for duplicate links here.
  956. # Schemas sometimes have valid duplicate links.
  957. # It is conceivable that this will lead to bugs, but I judge it unlikely.
  958. new_link = NodeLink(
  959. from_node,
  960. from_socket,
  961. to_node,
  962. to_socket,
  963. sort_id,
  964. sub_sort_id)
  965. return new_link
  966. def set_traverse_target(self, traverse_target):
  967. self.traverse_target = traverse_target
  968. if traverse_target: self.can_traverse = True
  969. else: self.can_traverse = False
  970. def flush_links(self):
  971. """ Removes dead links from this socket."""
  972. self.links = [l for l in self.links if l.is_alive]
  973. self.links.sort(key=links_sort_key)
  974. self.is_linked = bool(self.links)
  975. @property
  976. def is_connected(self):
  977. return len(self.links)>0
  978. def __repr__(self):
  979. return self.node.__repr__() + "::" + self.name
  980. class MantisNodeSocketCollection(dict):
  981. def __init__(self, node, is_input=False):
  982. self.is_input = is_input
  983. self.node = node
  984. def init_sockets(self, sockets):
  985. for socket in sockets:
  986. if isinstance(socket, str):
  987. self[socket] = NodeSocket(is_input=self.is_input, name=socket, node=self.node)
  988. elif isinstance(socket, MantisSocketTemplate):
  989. if socket.is_input != self.is_input: continue
  990. self[socket.name] = NodeSocket(is_input=self.is_input, name=socket.name, node=self.node)
  991. else:
  992. raise RuntimeError(f"NodeSocketCollection keys must be str or MantisSocketTemplate, not {type(socket)}")
  993. def __delitem__(self, key):
  994. """Deletes a node socket by name, and all its links."""
  995. socket = self[key]
  996. for l in socket.links:
  997. l.die()
  998. super().__delitem__(key)
  999. def __iter__(self):
  1000. """Makes the class iterable"""
  1001. return iter(self.values())