base_definitions.py 51 KB

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