base_definitions.py 50 KB

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