base_definitions.py 51 KB

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