base_definitions.py 49 KB

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