base_definitions.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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.utilities import (prRed, prGreen, prPurple, prWhite,
  8. prOrange,
  9. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  10. wrapOrange,)
  11. from .utilities.utilities import get_socket_maps, relink_socket_map, do_relink
  12. from .mantis_dataclasses import MantisSocketTemplate
  13. MANTIS_VERSION_MAJOR=0
  14. MANTIS_VERSION_MINOR=13
  15. MANTIS_VERSION_SUB=5
  16. FLOAT_EPSILON=0.0001 # used to check against floating point inaccuracy
  17. links_sort_key= lambda a : (-a.multi_input_sort_id, -a.sub_sort_id)
  18. selection_sync_node_to_object = {} # what objects a node spawns
  19. selection_sync_object_to_node = {} # what node an object comes from
  20. # The reroute cache is used to accelerate reading reroute nodes
  21. # it uses the tree name and hash to ensure reroutes are only updated when needed
  22. # reroutes recursively find their source and remember it
  23. reroute_cache = {}
  24. def TellClasses():
  25. #Why use a function to do this? Because I don't need every class to register.
  26. return [ MantisTree,
  27. SchemaTree,
  28. MantisNodeGroup,
  29. SchemaGroup,
  30. ]
  31. def error_popup_draw(self, context):
  32. self.layout.label(text="Error executing tree. See Console.")
  33. mantis_root = ".".join(__name__.split('.')[:-1]) # absolute HACK
  34. from os import environ
  35. # https://docs.blender.org/api/master/bpy.types.NodeTree.html#bpy.types.NodeTree.valid_socket_type
  36. # thank you, Sverchok
  37. def valid_interface_types(cls : NodeTree, socket_idname : str):
  38. from .socket_definitions import tell_valid_bl_idnames, TellClasses
  39. #TODO: do the versioning code to handle this so it can be in all versions
  40. if bpy.app.version <= (4,4,0): # should work in 4.4.1
  41. return socket_idname in [cls.bl_idname for cls in TellClasses()]
  42. elif bpy.app.version == (4,5,0): # workaround for a BUG
  43. return ['NodeSocketGeometry']
  44. else: # once versioning is finished this will be unnecesary.
  45. return socket_idname in tell_valid_bl_idnames()
  46. def fix_reroute_colors(tree):
  47. context = bpy.context
  48. if any((tree.is_executing, tree.is_exporting, tree.do_live_update==False, context.space_data is None) ):
  49. return
  50. from .utilities.utilities import find_reroute_start_socket
  51. from .socket_definitions import MantisSocket
  52. reroutes_without_color = []
  53. for n in tree.nodes:
  54. if n.bl_idname=='NodeReroute' and n.inputs[0].bl_idname == "NodeSocketColor":
  55. reroutes_without_color.append(n)
  56. try:
  57. while reroutes_without_color:
  58. rr = reroutes_without_color.pop()
  59. if rr.inputs[0].is_linked:
  60. link = rr.inputs[0].links[0]
  61. socket = find_reroute_start_socket(rr)
  62. if isinstance(socket, MantisSocket):
  63. rr.socket_idname = socket.bl_idname
  64. except Exception as e:
  65. print(wrapOrange("WARN: Updating reroute color failed with exception: ")+wrapWhite(f"{e.__class__.__name__}"))
  66. #functions to identify the state of the system using hashes
  67. # this function runs a lot so it should be optimized as well as possible.
  68. def hash_tree(tree, recurse=True):
  69. trees=set(); links=[]; hash_data=""
  70. for node in tree.nodes:
  71. hash_data+=str(node.name)
  72. if recurse and hasattr(node, 'node_tree') and node.node_tree:
  73. trees.add(node.node_tree)
  74. for other_tree in trees:
  75. hash_data+=str(hash_tree(other_tree))
  76. for link in tree.links:
  77. links.append( link.from_node.name+link.from_socket.name+
  78. link.to_node.name+link.to_socket.name+
  79. str(link.multi_input_sort_id) )
  80. links.sort(); hash_data+=''.join(links)
  81. return hash(hash_data)
  82. # TODO: I should see if I can make these work without every using NodeSocket.links
  83. # as that getter is very slow at scale
  84. # however with the cache in place it is probably negligible
  85. def update_reroute_cache_item_source_recursively(reroute, tree_cache, source):
  86. # find all the inputs to this reroute and update their destination sets
  87. # every reroute ancestor pushes to this destination... but not every recursive-child
  88. # of the root reroute necessarily does, so pushing back like this is right
  89. # since each reroute node only has one ancestor, this is easy
  90. from .mantis_dataclasses import RerouteCacheItem
  91. tree= reroute.id_data
  92. reroutes = {reroute}
  93. while(reroutes):
  94. reroute = reroutes.pop()
  95. # for making a new cache item
  96. if (cache_object := tree_cache.get(reroute.name)) is None:
  97. cache_object = RerouteCacheItem(
  98. reroute_name=reroute.name,
  99. reroute_tree_name=tree.name,
  100. )
  101. tree_cache[reroute.name] = cache_object
  102. cache_object.source = source
  103. if reroute.outputs[0].is_linked: # reroutes are always single-output
  104. for l in reroute.outputs[0].links: # with potentially many links
  105. if l.to_node.bl_idname == 'NodeReroute':
  106. reroutes.add(l.to_node)
  107. def update_reroute_cache_item_destination_recursively(reroute, tree_cache, destination):
  108. # find all the inputs to this reroute and update their destination sets
  109. # every reroute ancestor pushes to this destination... but not every recursive-child
  110. # of the root reroute necessarily does, so pushing back like this is right
  111. # since each reroute node only has one ancestor, this is easy
  112. from .mantis_dataclasses import RerouteCacheItem
  113. tree= reroute.id_data
  114. while(reroute):
  115. # for making a new cache item
  116. if (cache_object := tree_cache.get(reroute.name)) is None:
  117. cache_object = RerouteCacheItem(
  118. reroute_name=reroute.name,
  119. reroute_tree_name=tree.name,
  120. destinations= {destination},
  121. )
  122. tree_cache[reroute.name] = cache_object
  123. else:
  124. cache_object.destinations.add(destination)
  125. # Odd: if I check reroute.inputs[0].is_linked with live updates, CRASH.
  126. if rr_links := reroute.inputs[0].links:
  127. # reroutes are always single-input with at most 1 link
  128. if (l := rr_links[0]).from_node == 'NodeReroute':
  129. reroute = l.from_node
  130. continue
  131. reroute = None
  132. # Update the reroute cache from the link
  133. # NOTE this is updated as the user adds links by the node.insert_link() callback
  134. def reroute_cache_handle_link(tree, tree_cache, link):
  135. from .mantis_dataclasses import RerouteCacheItem
  136. # if it is a link to or from a reroute, add or update the cache item
  137. # first check if the cache item is stale
  138. # then try and fill the source and destination - make sure to recursively fill them
  139. # if it isn't connected to a source or destination, it's part of a network
  140. # We only need to check the ends, and we can do both the destination and source
  141. # passes simultaneously since they don't depend on each other.
  142. # NOTE that we use socket index to make things explicit and fast
  143. if link.from_node.bl_idname == 'NodeReroute' and link.to_node.bl_idname != 'NodeReroute':
  144. other_node = link.to_node
  145. other_socket = link.to_socket
  146. for socket_index, check_socket in enumerate(other_node.inputs):
  147. if check_socket.identifier == other_socket.identifier: break
  148. else:
  149. raise RuntimeError("Error, cannot make reroute cache for link: "
  150. f"{link.from_node.name}:{link.from_socket.name} ==>"
  151. f"{link.to_node.name}:{link.to_socket.name}")
  152. reroute = link.from_node
  153. destination = (other_node.name, socket_index)
  154. if (cache_object := tree_cache.get(reroute.name)) is None:
  155. cache_object = RerouteCacheItem(
  156. reroute_name=reroute.name,
  157. reroute_tree_name=tree.name,
  158. destinations= {destination},
  159. )
  160. tree_cache[reroute.name]=cache_object
  161. update_reroute_cache_item_destination_recursively(reroute, tree_cache,
  162. destination=destination)
  163. elif link.from_node.bl_idname != 'NodeReroute' and link.to_node.bl_idname == 'NodeReroute':
  164. other_node = link.from_node
  165. other_socket = link.from_socket
  166. for socket_index, check_socket in enumerate(other_node.outputs):
  167. if check_socket.identifier == other_socket.identifier: break
  168. else:
  169. raise RuntimeError("Error, cannot make reroute cache for link: "
  170. f"{link.from_node.name}:{link.from_socket.name} ==>"
  171. f"{link.to_node.name}:{link.to_socket.name}")
  172. reroute = link.to_node
  173. source = (link.from_node.name, socket_index)
  174. if (cache_object := tree_cache.get(reroute.name)) is None:
  175. cache_object = RerouteCacheItem(
  176. reroute_name=reroute.name,
  177. reroute_tree_name=tree.name,
  178. source = source,
  179. )
  180. tree_cache[reroute.name]=cache_object
  181. update_reroute_cache_item_source_recursively(reroute, tree_cache,
  182. source=source)
  183. def build_reroute_cache(tree, links):
  184. # we'll track this to know if a tree update should invalidate the hash on incremental update
  185. tree.number_of_reroute_links = 0
  186. # make sure to clear the previous cache or confusing things will happen
  187. tree_cache = {}; reroute_cache[tree.name] = tree_cache
  188. tree_cache['_MANTIS_RESERVED_TREE_HASH'] = tree.hash
  189. for link in links:
  190. if link.from_node.bl_idname == 'NodeReroute' or link.to_node.bl_idname == 'NodeReroute':
  191. tree.number_of_reroute_links += 1
  192. reroute_cache_handle_link(tree, tree_cache, link)
  193. def tree_update_common(tree): # set the reroute colors
  194. if tree.is_quitting: return
  195. if (bpy.app.version == (4,4,0)): # CTD bug in that version
  196. return
  197. fix_reroute_colors(tree)
  198. # intialize it if e.g the tree is new.
  199. if (tree_cache := reroute_cache.get(tree.name)) is None:
  200. tree_cache = {}; reroute_cache[tree.name] = tree_cache
  201. # events fire in this order:
  202. # - node.insert_link (one for each node)
  203. # - node.update (one for each node)
  204. # - tree.update
  205. # so if the node's insert_link handled things, we don't need to check
  206. tree.hash = str(hash_tree(tree, recurse=False))
  207. if tree.reroute_link_handled: # we can update the hash, it's still good.
  208. if tree_cache := reroute_cache.get(tree.name):
  209. tree_cache["_MANTIS_RESERVED_TREE_HASH"]=tree.hash
  210. tree.reroute_link_handled = False # always make sure to reset the flag
  211. else:
  212. reroute_links = []
  213. # set the UI tree hash for e.g. reroute cache
  214. for link in tree.links:
  215. if link.from_node.bl_idname == 'NodeReroute' or link.to_node.bl_idname == 'NodeReroute':
  216. reroute_links.append(link)
  217. if len(reroute_links) == tree.number_of_reroute_links:
  218. if tree_cache := reroute_cache.get(tree.name): # we can update the hash, it's still good.
  219. tree_cache["_MANTIS_RESERVED_TREE_HASH"] = tree.hash
  220. else: # there is no cache after all. How did that happen?
  221. build_reroute_cache(tree, reroute_links)
  222. # NOTE I put a lot of effort into catching deleted links but it just isn't practical
  223. # to catch this and it is almost free to rebuild the cache.
  224. else:
  225. build_reroute_cache(tree, reroute_links)
  226. # reset the count but do not update the hash.
  227. tree.number_of_reroute_links = len(reroute_links)
  228. class MantisTree(NodeTree):
  229. '''A custom node tree type that will show up in the editor type list'''
  230. bl_idname = 'MantisTree'
  231. bl_label = "Rigging Nodes"
  232. bl_icon = 'OUTLINER_OB_ARMATURE'
  233. tree_valid:BoolProperty(default=False)
  234. hash:StringProperty(default='') # use for UI updates, reroute cache
  235. hash_recursive:StringProperty(default='') # use for checking Mantis state
  236. do_live_update:BoolProperty(default=True) # use this to disable updates for e.g. scripts
  237. # operator settings for re-exporting the tree.
  238. filepath:StringProperty(default="", subtype='FILE_PATH')
  239. export_all_subtrees_together:BoolProperty(default=True)
  240. #
  241. is_executing:BoolProperty(default=False)
  242. is_exporting:BoolProperty(default=False)
  243. is_quitting:BoolProperty(default=False)
  244. execution_id:StringProperty(default='')
  245. # prev_execution_id:StringProperty(default='')
  246. mantis_version:IntVectorProperty(default=[
  247. MANTIS_VERSION_MAJOR, MANTIS_VERSION_MINOR-1, MANTIS_VERSION_SUB-1])
  248. # this prevents the node group from executing on the next depsgraph update
  249. # because I don't always have control over when the dg upadte happens.
  250. prevent_next_exec:BoolProperty(default=False)
  251. #added to work around a bug in 4.5.0 LTS
  252. interface_helper : StringProperty(default='')
  253. # for reroute cache, to check if it is still good
  254. number_of_reroute_links : IntProperty(default=0)
  255. # flag to indicate a link was already handled this update
  256. reroute_link_handled : BoolProperty(default=False)
  257. parsed_tree={}
  258. # NOTE that these are class properties that should be serialized
  259. # to per-instance bpy properties when switching trees.
  260. # The class properties should, however, be associated to specific
  261. # trees by name so that the user can edit multiple trees at once.
  262. # Selection Sync Dicts
  263. node_to_object_map = {}
  264. object_to_node_map = {}
  265. if (bpy.app.version < (4, 4, 0) or bpy.app.version >= (4,5,0)): # in 4.4 this leads to a crash
  266. @classmethod
  267. def valid_socket_type(cls : NodeTree, socket_idname: str):
  268. return valid_interface_types(cls, socket_idname)
  269. def update(self):
  270. tree_update_common(self)
  271. def update_tree(self, context = None, force=False, error_popups=False):
  272. if self.is_exporting:
  273. return
  274. my_hash = str( hash_tree(self) )
  275. my_ui_hash = str( hash_tree(self, recurse=False))
  276. tree_cache = reroute_cache.get(self.name)
  277. if tree_cache['_MANTIS_RESERVED_TREE_HASH'] != my_ui_hash:
  278. build_reroute_cache(self, self.links) # somehow it became invalid, rebuild it.
  279. if (my_hash != self.hash_recursive) or force:
  280. self.hash_recursive = my_hash
  281. self.is_executing = True
  282. from .execution import readtree
  283. prGreen("Validating Tree: %s" % self.name)
  284. try:
  285. import bpy # I am importing here so that the context passed in
  286. # is used for display update... but I always want to do this
  287. scene = bpy.context.scene
  288. scene.render.use_lock_interface = True
  289. self.parsed_tree = readtree.parse_tree(self, error_popups)
  290. if context:
  291. self.display_update(context)
  292. self.tree_valid = bool(self.parsed_tree)
  293. except Exception as e:
  294. prRed("Failed to update node tree due to error.")
  295. self.tree_valid = False
  296. self.hash_recursive='' # unset the hash to mark the tree as un-parsed.
  297. raise e
  298. finally:
  299. scene.render.use_lock_interface = False
  300. self.is_executing = False
  301. if self.parsed_tree is None:
  302. self.parsed_tree = {}
  303. return 1 # failure
  304. return 0 # success
  305. def display_update(self, context):
  306. if self.is_exporting:
  307. return
  308. self.is_executing = True
  309. try:
  310. current_tree = bpy.context.space_data.path[-1].node_tree
  311. for node in current_tree.nodes:
  312. if hasattr(node, "display_update"):
  313. try:
  314. node.display_update(self.parsed_tree, context)
  315. except Exception as e:
  316. print("Node \"%s\" failed to update display with error: %s" %(wrapGreen(node.name), wrapRed(e)))
  317. finally:
  318. self.is_executing = False
  319. # TODO: deal with invalid links properly.
  320. # - Non-hierarchy links should be ignored in the circle-check and so the links should be marked valid in such a circle
  321. # - hierarchy-links should be marked invalid and prevent the tree from executing.
  322. def execute_tree(self,context, error_popups = False, profile=False):
  323. self.prevent_next_exec = False
  324. if not self.hash_recursive:
  325. return
  326. if not self.parsed_tree:
  327. return
  328. if self.is_exporting or self.is_executing:
  329. return
  330. prGreen("Executing Tree: %s" % self.name)
  331. self.is_executing = True
  332. from .execution import readtree
  333. try:
  334. context.scene.render.use_lock_interface = True
  335. readtree.execute_tree(self.parsed_tree, self, context, error_popups, profile=profile)
  336. except RecursionError as e:
  337. prRed("Recursion error while parsing tree.")
  338. finally:
  339. context.scene.render.use_lock_interface = False
  340. self.is_executing = False
  341. class SchemaTree(NodeTree):
  342. '''A node tree representing a schema to generate a Mantis tree'''
  343. bl_idname = 'SchemaTree'
  344. bl_label = "Rigging Nodes Schema"
  345. bl_icon = 'RIGID_BODY_CONSTRAINT'
  346. # these are only needed for consistent interface, but should not be used
  347. do_live_update:BoolProperty(default=True) # default to true so that updates work
  348. is_executing:BoolProperty(default=False)
  349. is_exporting:BoolProperty(default=False)
  350. is_quitting:BoolProperty(default=False)
  351. mantis_version:IntVectorProperty(default=[
  352. MANTIS_VERSION_MAJOR, MANTIS_VERSION_MINOR, MANTIS_VERSION_SUB])
  353. # see the note in MantisTree
  354. interface_helper : StringProperty(default='')
  355. # for reroute cache, to check if it is still good
  356. number_of_reroute_links : IntProperty(default=0)
  357. # flag to indicate a link was already handled this update
  358. reroute_link_handled : BoolProperty(default=False)
  359. if (bpy.app.version < (4, 4, 0) or bpy.app.version >= (4,5,0)): # in 4.4 this leads to a crash
  360. @classmethod
  361. def valid_socket_type(cls : NodeTree, socket_idname: str):
  362. return valid_interface_types(cls, socket_idname)
  363. def update(self):
  364. tree_update_common(self)
  365. #TODO: do a better job explaining how MantisNode and MantisUINode relate.
  366. # TODO: I want to avoid doing any kind of class mutation at runtime
  367. # so in the future I will try to do this directly rather than
  368. # running this function once for each class while registering
  369. # however this is not very important for UI classes since they
  370. # are not a performance bottleneck.
  371. def mantis_class_from_library(library, class_name):
  372. from importlib import import_module
  373. return getattr(import_module(library, package=mantis_root), class_name)
  374. class MantisUINode:
  375. """
  376. This class contains the common user-interface features of Mantis nodes.
  377. MantisUINode objects will spawn one or more MantisNode objects when the graph is evaluated.
  378. The MantisNode objects will pull the data from the UI node and use it to generate the graph.
  379. """
  380. # blender stuff, I'll need to split this into a mixin class later
  381. bl_icon = 'NODE'
  382. initialized : bpy.props.BoolProperty(default = False)
  383. #
  384. mantis_node_class_name=''
  385. mantis_class=None
  386. socket_templates=None
  387. @classmethod
  388. def poll(cls, ntree):
  389. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  390. def init(self, context):
  391. self.init_sockets(self.socket_templates)
  392. self.initialized = True
  393. def init_sockets(self, socket_templates : tuple[MantisSocketTemplate]):
  394. for template in socket_templates:
  395. collection = self.outputs
  396. if template.is_input:
  397. collection = self.inputs
  398. identifier = template.name
  399. if template.identifier:
  400. identifier = template.identifier
  401. use_multi_input = template.use_multi_input if template.is_input else False
  402. socket = collection.new(
  403. template.bl_idname,
  404. template.name,
  405. identifier=identifier,
  406. use_multi_input=use_multi_input
  407. )
  408. socket.hide= template.hide
  409. if template.category:
  410. from . import DOERROR
  411. # a custom property for the UI functions to use.
  412. if hasattr(socket, "category"):
  413. socket.category = template.category
  414. elif DOERROR:
  415. print (f"WARN: socket type {socket.bl_idname} has no category attribute")
  416. if template.default_value is not None:
  417. socket.default_value = template.default_value
  418. # this can throw a TypeError - it is the caller's
  419. # responsibility to send the right type.
  420. if template.use_multi_input: # this is an array
  421. socket.display_shape = 'SQUARE_DOT'
  422. def insert_link(self, link):
  423. if (bpy.app.version == (4, 4, 0)):
  424. return # this causes a crash due to a bug.
  425. tree = self.id_data
  426. if tree.reroute_link_handled: return
  427. if ( link.from_node.bl_idname == 'NodeReroute' or
  428. link.to_node.bl_idname == 'NodeReroute' ):
  429. tree.number_of_reroute_links+=1
  430. reroute_cache_handle_link(tree=tree,
  431. tree_cache=reroute_cache.get(tree.name), link=link)
  432. tree.reroute_link_handled = True
  433. # NOTE
  434. # MantisUINode has no proper mantis libraryclass on its own, so:
  435. # register()'s are in SUBclasses; they have to run AFTER library is defined
  436. class SchemaUINode(MantisUINode):
  437. is_updating:BoolProperty(default=False)
  438. @classmethod
  439. def register(cls):
  440. cls.mantis_class = mantis_class_from_library('.schema_nodes', cls.mantis_node_class_name)
  441. class LinkNode(MantisUINode):
  442. mantis_node_library='.link_nodes'
  443. category_color=[0.5,0.5,0.5]
  444. @classmethod
  445. def register(cls):
  446. cls.mantis_class = mantis_class_from_library('.link_nodes', cls.mantis_node_class_name)
  447. def init(self, context):
  448. super().init(context)
  449. self.use_custom_color = True
  450. self.color = self.category_color
  451. class xFormNode(MantisUINode):
  452. @classmethod
  453. def register(cls):
  454. cls.mantis_class = mantis_class_from_library('.xForm_nodes', cls.mantis_node_class_name)
  455. def init(self, context):
  456. super().init(context)
  457. from mathutils import Color
  458. xFormColor = Color((0.093172, 0.047735, 0.028036)).from_scene_linear_to_srgb()
  459. self.use_custom_color = True
  460. self.color = xFormColor # must not have alpha
  461. class DeformerNode(MantisUINode):
  462. @classmethod
  463. def register(cls):
  464. cls.mantis_class = mantis_class_from_library('.deformer_nodes', cls.mantis_node_class_name)
  465. class GeometryPrimitiveNode(MantisUINode):
  466. @classmethod
  467. def register(cls):
  468. cls.mantis_class = mantis_class_from_library('.primitives_nodes', cls.mantis_node_class_name)
  469. class MantisMiscNode(MantisUINode):
  470. @classmethod
  471. def register(cls):
  472. cls.mantis_class = mantis_class_from_library('.misc_nodes', cls.mantis_node_class_name)
  473. class MantisMathUINode(MantisUINode):
  474. @classmethod
  475. def register(cls):
  476. cls.mantis_class = mantis_class_from_library('.math_nodes', cls.mantis_node_class_name)
  477. def poll_node_tree(self, object):
  478. forbid = []
  479. context = bpy.context
  480. if context.space_data:
  481. if context.space_data.path:
  482. for path_item in context.space_data.path:
  483. forbid.append(path_item.node_tree.name)
  484. if isinstance(object, MantisTree) and object.name not in forbid:
  485. return True
  486. return False
  487. # TODO: try and remove the extra loop used here... but it is OK for now
  488. def should_remove_socket(node, socket):
  489. # a function to check if the socket is in the interface
  490. id_found = False
  491. for item in node.node_tree.interface.items_tree:
  492. if item.item_type != "SOCKET": continue
  493. if item.identifier == socket.identifier:
  494. id_found = True; break
  495. return not id_found
  496. # TODO: try to check identifiers instead of name.
  497. def node_group_update(node, force = False):
  498. if not node.is_updating:
  499. raise RuntimeError("Cannot update node while it is not marked as updating.")
  500. if not force:
  501. if (node.id_data.do_live_update == False) or \
  502. (node.id_data.is_executing == True) or \
  503. (node.id_data.is_exporting == True):
  504. return
  505. # note: if (node.id_data.is_exporting == True) I need to be able to update so I can make links.
  506. if node.node_tree is None:
  507. node.inputs.clear(); node.outputs.clear()
  508. return
  509. toggle_update = node.id_data.do_live_update
  510. node.id_data.do_live_update = False
  511. identifiers_in={socket.identifier:socket for socket in node.inputs}
  512. identifiers_out={socket.identifier:socket for socket in node.outputs}
  513. interface_names_in, interface_names_out = {}, {}
  514. for interface_item in node.node_tree.interface.items_tree:
  515. if interface_item.item_type != 'SOCKET': continue
  516. if interface_item.in_out == 'INPUT':
  517. interface_names_in[interface_item.identifier] = interface_item.name
  518. else:
  519. interface_names_out[interface_item.identifier] = interface_item.name
  520. indices_in,indices_out={},{} # check by INDEX to see if the socket's name/type match.
  521. for collection, map in [(node.inputs, indices_in), (node.outputs, indices_out)]:
  522. for i, socket in enumerate(collection):
  523. map[socket.identifier]=i
  524. if node.node_tree is None:
  525. node.inputs.clear(); node.outputs.clear()
  526. node.id_data.do_live_update = toggle_update
  527. return
  528. found_in, found_out = [], []
  529. update_input, update_output = False, False
  530. for item in node.node_tree.interface.items_tree:
  531. if item.item_type != "SOCKET": continue
  532. if item.in_out == 'OUTPUT':
  533. if s:= identifiers_out.get(item.identifier): # if the requested output doesn't exist, update
  534. if interface_names_out.get(item.identifier) != s.name: update_output = True; continue
  535. found_out.append(item.identifier)
  536. if (indices_out[s.identifier]!=item.index): update_output=True; continue
  537. if update_output: continue
  538. if s.bl_idname != item.bl_socket_idname: update_output = True; continue
  539. else: update_output = True; continue
  540. else:
  541. if s:= identifiers_in.get(item.identifier): # if the requested input doesn't exist, update
  542. if interface_names_in.get(item.identifier) != s.name: update_input = True; continue
  543. found_in.append(item.identifier)
  544. if (indices_in[s.identifier]!=item.index): update_input=True; continue
  545. if update_input: continue # done here
  546. if s.bl_idname != item.bl_socket_idname: update_input = True; continue
  547. else: update_input = True; continue
  548. # Schema has an extra input for Length and for Extend.
  549. if node.bl_idname == 'MantisSchemaGroup':
  550. found_in.extend(['Schema Length', ''])
  551. # get the socket maps before modifying stuff
  552. if update_input or update_output:
  553. socket_maps = get_socket_maps(node,)
  554. if socket_maps:
  555. socket_map_in, socket_map_out = socket_maps
  556. if node.bl_idname == "MantisSchemaGroup" and \
  557. len(node.inputs)+len(node.outputs)<=2 and\
  558. len(node.node_tree.interface.items_tree) > 0:
  559. socket_map_in, socket_map_out = None, None
  560. # We have to initialize the node because it only has its base inputs.
  561. elif socket_maps is None:
  562. node.id_data.do_live_update = toggle_update
  563. # if we have too many elements, just get rid of the ones we don't need
  564. if len(node.inputs) > len(found_in):#
  565. for inp in node.inputs:
  566. if inp.identifier in found_in: continue
  567. node.inputs.remove(inp)
  568. if len(node.outputs) > len(found_out):
  569. for out in node.outputs:
  570. if out.identifier in found_out: continue
  571. node.outputs.remove(out)
  572. #
  573. if len(node.inputs) > 0 and (inp := node.inputs[-1]).bl_idname == 'WildcardSocket' and inp.is_linked:
  574. update_input = True
  575. #
  576. if not (update_input or update_output):
  577. node.id_data.do_live_update = toggle_update
  578. return
  579. if update_input or update_output and (socket_maps is not None):
  580. if update_input :
  581. if node.bl_idname == 'MantisSchemaGroup':
  582. schema_length=0
  583. if sl := node.inputs.get("Schema Length"):
  584. schema_length = sl.default_value
  585. # sometimes this isn't available yet # TODO not happy about this solution
  586. remove_me=[]
  587. # remove all found map items but the Schema Length input (reuse it)
  588. for i, socket in enumerate(node.inputs):
  589. if socket.identifier == "Schema Length" and i == 0:
  590. continue
  591. elif (socket_map_in is None) or socket.identifier in socket_map_in.keys():
  592. remove_me.append(socket)
  593. elif should_remove_socket(node, socket):
  594. remove_me.append(socket)
  595. while remove_me:
  596. node.inputs.remove(remove_me.pop())
  597. if update_output:
  598. remove_me=[]
  599. for socket in node.outputs:
  600. if (socket_map_out is None) or socket.identifier in socket_map_out.keys():
  601. remove_me.append(socket)
  602. elif should_remove_socket(node, socket):
  603. remove_me.append(socket)
  604. while remove_me:
  605. node.inputs.remove(remove_me.pop())
  606. from .utilities.utilities import relink_socket_map_add_socket
  607. reorder_me_input = []; input_index = 0
  608. reorder_me_output = []; output_index = 0
  609. def update_group_sockets(interface_item, is_input):
  610. socket_map = socket_map_in if is_input else socket_map_out
  611. socket_collection = node.inputs if is_input else node.outputs
  612. counter = input_index if is_input else output_index
  613. reorder_collection = reorder_me_input if is_input else reorder_me_output
  614. if socket_map:
  615. if item.identifier in socket_map.keys():
  616. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  617. do_relink(node, socket, socket_map, item.in_out)
  618. else:
  619. for has_socket in socket_collection:
  620. if has_socket.bl_idname == item.bl_socket_idname and \
  621. has_socket.name == item.name:
  622. reorder_collection.append((has_socket, counter))
  623. break
  624. else:
  625. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  626. else:
  627. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  628. counter += 1
  629. # TODO: de-duplicate this hideous stuff
  630. for item in node.node_tree.interface.items_tree:
  631. if item.item_type != "SOCKET": continue
  632. if (item.in_out == 'INPUT' and update_input):
  633. # check and see if it exists... should only happen in curves on startup
  634. if item.bl_socket_idname in ['EnumCurveSocket']:
  635. for exists in node.inputs: # NOTE: check if the socket was not deleted
  636. if exists.identifier == item.identifier:
  637. # this happens for curve inputs because of some shennanigans with how
  638. # blender loads IDs - I can't set the ID until the file has loaded
  639. # so I have to avoid touching the socket until then...
  640. break
  641. else:
  642. update_group_sockets(item, True)
  643. else:
  644. update_group_sockets(item, True)
  645. input_index += 1
  646. if (item.in_out == 'OUTPUT' and update_output):
  647. if item.bl_socket_idname in ['EnumCurveSocket']: # LOOK up there at the comment!
  648. for exists in node.outputs:
  649. if exists.identifier == item.identifier:
  650. break
  651. else:
  652. update_group_sockets(item, False)
  653. else:
  654. update_group_sockets(item, False)
  655. output_index += 1
  656. both_reorders = zip([reorder_me_input, reorder_me_output], [node.inputs, node.outputs])
  657. for reorder_task, collection in both_reorders:
  658. for socket, position in reorder_task:
  659. for i, s in enumerate(collection): # get the index
  660. if s.identifier == socket.identifier: break
  661. else:
  662. prRed(f"WARN: could not reorder socket {socket.name}")
  663. to_index = position
  664. if (not socket.is_output) and node.bl_idname == "MantisSchemaGroup":
  665. to_index+=1
  666. collection.move(i, to_index)
  667. # at this point there is no wildcard socket
  668. if socket_map_in and '__extend__' in socket_map_in.keys():
  669. do_relink(node, None, socket_map_in, in_out='INPUT', parent_name='Constant' )
  670. node.id_data.do_live_update = toggle_update
  671. def node_tree_prop_update(self, context):
  672. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  673. return # so we check if an update is currently running.
  674. self.is_updating = True
  675. def init_schema(self, context):
  676. if len(self.inputs) == 0:
  677. self.inputs.new("UnsignedIntSocket", "Schema Length", identifier='Schema Length')
  678. if self.inputs[-1].bl_idname != "WildcardSocket":
  679. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  680. init_schema(self, context)
  681. try:
  682. node_group_update(self, force=True)
  683. finally: # ensure this line is run even if there is an error
  684. self.is_updating = False
  685. if self.bl_idname in ['MantisSchemaGroup'] and self.node_tree is not None:
  686. init_schema(self, context)
  687. from bpy.types import NodeCustomGroup
  688. def group_draw_buttons(self, context, layout):
  689. row = layout.row(align=True)
  690. row.prop(self, "node_tree", text="")
  691. if self.node_tree is None:
  692. row.operator("mantis.new_node_tree", text="", icon='PLUS', emboss=True)
  693. else:
  694. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  695. class MantisNodeGroup(Node, MantisUINode):
  696. bl_idname = "MantisNodeGroup"
  697. bl_label = "Node Group"
  698. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree, update=node_tree_prop_update,)
  699. is_updating:BoolProperty(default=False)
  700. def draw_label(self):
  701. if self.node_tree is None:
  702. return "Node Group"
  703. else:
  704. return self.node_tree.name
  705. def draw_buttons(self, context, layout):
  706. group_draw_buttons(self, context, layout)
  707. def update(self):
  708. if self.node_tree is None:
  709. return
  710. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  711. return # so we check if an update is currently running.
  712. live_update = self.id_data.do_live_update
  713. self.is_updating = True
  714. try:
  715. node_group_update(self)
  716. finally: # we need to reset this regardless of whether or not the operation succeeds!
  717. self.is_updating = False
  718. self.id_data.do_live_update = live_update # ensure this remains the same
  719. class GraphError(Exception):
  720. pass
  721. class BlenderVersionError(Exception):
  722. pass
  723. def get_signature_from_edited_tree(node, context):
  724. sig_path=[None,]
  725. for item in context.space_data.path[:-1]:
  726. sig_path.append(item.node_tree.nodes.active.name)
  727. return tuple(sig_path+[node.name])
  728. def poll_node_tree_schema(self, object):
  729. if isinstance(object, SchemaTree):
  730. return True
  731. return False
  732. # TODO tiny UI problem - inserting new links into the tree will not place them in the right place.
  733. class SchemaGroup(Node, MantisUINode):
  734. bl_idname = "MantisSchemaGroup"
  735. bl_label = "Node Schema"
  736. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree_schema, update=node_tree_prop_update,)
  737. is_updating:BoolProperty(default=False)
  738. def draw_buttons(self, context, layout):
  739. group_draw_buttons(self, context, layout)
  740. def draw_label(self):
  741. if self.node_tree is None:
  742. return "Schema Group"
  743. else:
  744. return self.node_tree.name
  745. def update(self):
  746. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  747. return # so we check if an update is currently running.
  748. if self.node_tree is None:
  749. return
  750. live_update = self.id_data.do_live_update
  751. self.is_updating = True
  752. try:
  753. node_group_update(self)
  754. # reset things if necessary:
  755. if self.node_tree:
  756. if len(self.inputs) == 0:
  757. self.inputs.new("UnsignedIntSocket", "Schema Length", identifier='Schema Length')
  758. if self.inputs[-1].identifier != "__extend__":
  759. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  760. finally: # we need to reset this regardless of whether or not the operation succeeds!
  761. self.is_updating = False
  762. self.id_data.do_live_update = live_update # ensure this remains the same
  763. # replace names with bl_idnames for reading the tree and solving schemas.
  764. replace_types = ["NodeGroupInput", "NodeGroupOutput", "SchemaIncomingConnection",
  765. "SchemaArrayInput", "SchemaArrayInputAll", "SchemaConstInput", "SchemaConstOutput",
  766. "SchemaIndex", "SchemaOutgoingConnection", "SchemaArrayOutput","SchemaArrayInputGet",
  767. ]
  768. # anything that gets properties added in the graph... this is a clumsy approach but I need to watch for this
  769. # in schema generation and this is the easiest way to do it for now.
  770. custom_props_types = ["LinkArmature", "UtilityKeyframe", "UtilityFCurve", "UtilityDriver", "xFormBone",
  771. "xFormArmature", "xFormGeometryObject", "xFormObjectInstance", "xFormCurvePin",]
  772. # filters for determining if a link is a hierarchy link or a non-hierarchy (cyclic) link.
  773. from_name_filter = frozenset({"Driver",})
  774. to_name_filter = frozenset({
  775. "Custom Object xForm Override",
  776. "Custom Object",
  777. "Deform Bones",
  778. })
  779. # nodes that must be solved as if they were Schema because they send arrays out.
  780. array_output_types = [
  781. 'UtilityArrayGet', 'UtilityKDChoosePoint', 'UtilityKDChooseXForm',
  782. ]
  783. def can_remove_socket_for_autogen(node, socket) -> bool:
  784. """ Whether to enable socket removal optimization for the socket
  785. This should be disallowed if e.g. it is a custom property.
  786. """
  787. return False # for now! This doesn't seem to be working...
  788. # the problem is that Schema does this, and so does Readtree
  789. # and they can try and both do it. That's bad.
  790. if node.socket_templates:
  791. for s_template in node.socket_templates:
  792. if s_template.name == socket:
  793. # raise NotImplementedError
  794. return True
  795. elif node.node_type == 'UTILITY':
  796. return True # HACK because most utilities don't have socket templates yet
  797. return False
  798. # The MantisExecutionContext class is used to store the execution-specific variables
  799. # that are used when executing the tree
  800. # Importantly, it is NOT used to store variables between solutions, these belong to the
  801. # tree class.
  802. class MantisExecutionContext():
  803. def __init__(
  804. self,
  805. base_tree,
  806. ):
  807. self.base_tree = base_tree
  808. self.execution_id = base_tree.execution_id
  809. self.execution_failed=False
  810. self.interface_nodes = {}
  811. self.b_objects={} # objects created by Mantis during execution
  812. self.tagged_for_overlay = [] # nodes mutated by overlay system
  813. self.overlay_data = [] # dict of list of Overlay objects
  814. from typing import Any
  815. # using these frozen sets accelerate lookup when checking for this
  816. FILL_PARAMETERS_SKIP_ROOTS = frozenset({ 'MANTIS_AUTOGENERATED', 'SCHEMA_AUTOGENERATED', })
  817. FILL_PARAMETERS_SKIP_NAMES = frozenset({ "NodeGroupOutput", "NodeGroupInput", })
  818. FILL_PARAMETERS_SKIP_SOCKETS = frozenset({ 'RelationshipSocket', 'xFormSocket', })
  819. from .socket_definitions import no_default_value
  820. class MantisNode:
  821. """
  822. This class contains the basic interface for a Mantis Node.
  823. A MantisNode is used internally by Mantis to represent the final evaluated node graph.
  824. It gets generated with data from a MantisUINode when the graph is read.
  825. """
  826. __slots__ = (
  827. "base_tree", "signature", "ui_signature",
  828. "inputs", "outputs",
  829. "parameters", "drivers", "bObject",
  830. "hierarchy_connections", "connections",
  831. "hierarchy_dependencies", "dependencies",
  832. "unmet_hierarchy_dependency_count",
  833. "prepared", "executed", "execution_prepared",
  834. "mContext",
  835. "is_schema_prototype"
  836. )
  837. node_type = 'UNINITIALIZED'
  838. socket_templates = None
  839. property_socket_map = {}
  840. passes=frozenset({})
  841. def __init__(self, signature : tuple,
  842. base_tree : bpy.types.NodeTree,
  843. socket_templates : list[MantisSocketTemplate]=[],
  844. additional_parameters :dict = {}, ):
  845. self.base_tree=base_tree
  846. self.signature = signature
  847. self.ui_signature = signature
  848. self.inputs = MantisNodeSocketCollection(node=self, is_input=True)
  849. self.outputs = MantisNodeSocketCollection(node=self, is_input=False)
  850. self.parameters, self.drivers = {}, []; self.bObject=None
  851. self.hierarchy_connections, self.connections = [], []
  852. self.hierarchy_dependencies, self.dependencies = [], []
  853. self.unmet_hierarchy_dependency_count = float("inf") # we will set this when filling the dependencies lists
  854. self.prepared, self.executed = False, False
  855. self.execution_prepared = False
  856. # execution_prepared is for tracking prep state in execution, so that I can avoid preparing nodes
  857. # again without changing the readtree code much.
  858. self.mContext = None # for now I am gonna set this at runtime
  859. self.is_schema_prototype = False
  860. # I know it isn't "beautiful OOP" or whatever, but it is just easier
  861. # code should be simple and do things in the simplest way.
  862. # in the future I can refactor it, but it will require changes to 100+
  863. # classes, instead of adding about 5 lines of code elsewhere.
  864. if self.socket_templates:
  865. self.init_sockets( additional_parameters )
  866. @property
  867. def name(self):
  868. return self.ui_signature[-1]
  869. @property
  870. def bl_idname(self): # this and the above exist solely to maintain interface w/bpy.types.Node
  871. from .utilities.utilities import get_ui_node
  872. return get_ui_node(self.ui_signature, self.base_tree).bl_idname
  873. def reset_execution(self) -> None:
  874. """ Reset the node for additional execution without re-building the tree."""
  875. self.drivers.clear(); self.bObject=None
  876. self.executed = False
  877. self.execution_prepared = False
  878. def init_sockets(self, additional_parameters : dict = {}) -> None:
  879. # Formerly I was doing this:
  880. # self.inputs.init_sockets(self.socket_templates)
  881. # self.outputs.init_sockets(self.socket_templates)
  882. # Since doing each one causes some redundancy, we'll just reimplement it
  883. # This is a highly used and therefore expensive function so we have to make small
  884. # optimizations like this, even tho it is ugly.
  885. traverse_in, traverse_out = {}, {}
  886. for socket in self.socket_templates:
  887. if socket.traverse_target:
  888. if socket.is_input:
  889. traverse_in[socket.name] = socket.traverse_target
  890. else:
  891. traverse_out[socket.name] = socket.traverse_target
  892. if socket.ui_only == True: continue # used in UI but not in generation
  893. if socket.is_input:
  894. self.inputs[socket.name] = NodeSocket(is_input=True, name=socket.name,
  895. node=self,)
  896. else:
  897. self.outputs[socket.name] = NodeSocket(is_input=False, name=socket.name,
  898. node=self,)
  899. self.parameters[socket.name] = None
  900. for traverse_owner, traverse_target in traverse_in.items():
  901. self.inputs[traverse_owner].traverse_target = self.outputs[traverse_target]
  902. self.inputs[traverse_owner].can_traverse = True
  903. for traverse_owner, traverse_target in traverse_out.items():
  904. self.outputs[traverse_owner].traverse_target = self.inputs[traverse_target]
  905. self.outputs[traverse_owner].can_traverse = True
  906. for key, value in additional_parameters.items():
  907. self.parameters[key]=value
  908. def init_parameters(self, additional_parameters = {}) -> None:
  909. for socket in self.inputs:
  910. self.parameters[socket.name] = None
  911. for socket in self.outputs:
  912. self.parameters[socket.name] = None
  913. for key, value in additional_parameters.items():
  914. self.parameters[key]=value
  915. # We really only need to do this once at class registration
  916. # Therefore the goal is not to have any mutable data here
  917. # ======================= READ BELOW =======================
  918. # We have the following classes of Mantis Socket ==> Blender Proeprty relationships:
  919. # Scalar: 1 Mantis scalar ==> 1 Blender property. 1 Filler.
  920. # Vector: 1 Mantis Vector socket ==> Blender vector property. 1 Filler.
  921. # Scalar Combo: 1 Mantis scalar ==> many Blender scalars. 1 Filler per property.
  922. # Vector Combo: 1 Mantis vector ==> vector of Blender vector property. 1 Filler per property.
  923. # In every case, 1 filler per Blender property.
  924. @classmethod
  925. def gen_property_socket_map(cls, prop_owner_group=None) -> dict:
  926. from .mantis_dataclasses import MantisSocketFiller
  927. from dataclasses import replace
  928. from bpy.app import version as bpy_version
  929. if cls.property_socket_map: # retrieve the cache if possible
  930. return cls.property_socket_map
  931. props_sockets = {}
  932. for s_template in cls.socket_templates:
  933. if s_template.min_bpy_version:
  934. if bpy_version < s_template.min_bpy_version:
  935. prPurple(f"Skipping socket {s_template.name} because "
  936. f"it requires Blender {s_template.min_bpy_version} or higher")
  937. continue # We can't set or drive this obviously.
  938. if prop_owner_group is not None and s_template.prop_owner_group != prop_owner_group:
  939. continue # for composite objects like bones
  940. if not s_template.blender_property: # this one has to be handled by the node itself.
  941. continue # Or maybe it is UI-only, in any case we don't need to do anything here.
  942. # Default to (Scalar <==> Scalar), as tuples for compatibility with other code paths
  943. vector_property, combo = False, False # TODO: make socket templates pre-tuple-ize this
  944. defaults = ( s_template.default_value, ); properties = ( s_template.blender_property, )
  945. if isinstance( s_template.default_value, (list, tuple) ):
  946. vector_property = True # this tells us if MANTIS provides a vector
  947. # if Blender consumes a vector, then we map the vector to the vector. Easy.
  948. if isinstance(s_template.blender_property, (tuple, list)):
  949. # But maybe we provide data from one Mantis Socket to many Blender properties...
  950. combo=True; properties = s_template.blender_property
  951. if vector_property: # we have to break the default value up so we can map
  952. # mantis data element-wise to a vector of Blender properties
  953. defaults = s_template.default_value
  954. # Now iteratre through the properties and make 1 filler per.
  955. for i, property in enumerate(properties):
  956. default_index = i if vector_property and combo else 0 # only needed for Combo Vector
  957. default = defaults[default_index] # usually 1:1 except for Combo Scalar
  958. key = s_template.name + f"_{default_index}" + (f"_{property}" if combo else "")
  959. value_index = default_index if combo and vector_property else None
  960. from .utilities import socket_filler_operators as operators
  961. property_value_operator = None
  962. if s_template.property_value_operator:
  963. property_value_operator = getattr(operators, s_template.property_value_operator)
  964. props_sockets[key] = MantisSocketFiller(
  965. socket_name = s_template.name, # This is a dict because node
  966. property_name = property, # instances should be able
  967. value_index = value_index, # to edit Fillers.
  968. default_value = default, # The keys are not inherently
  969. combo_property = combo, # meaningful and are
  970. vector_property = vector_property, # NOT USED DOWNSTREAM!
  971. is_animatable = s_template.is_animatable,
  972. property_group = s_template.prop_owner_group,
  973. property_value_operator = property_value_operator)
  974. if prop_owner_group is None:
  975. cls.property_socket_map = props_sockets # We should cache this one!
  976. return props_sockets
  977. def set_traverse(self, traversal_pairs = [(str, str)]) -> None:
  978. for (a, b) in traversal_pairs:
  979. self.inputs[a].set_traverse_target(self.outputs[b])
  980. self.outputs[b].set_traverse_target(self.inputs[a])
  981. def clear_traverse(self, inputs = [str], outputs = [str]) -> None:
  982. for inp in inputs:
  983. self.inputs[inp].set_traverse(None)
  984. for out in outputs:
  985. self.inputs[out].set_traverse(None)
  986. def flush_links(self) -> None:
  987. for inp in self.inputs.values():
  988. inp.flush_links()
  989. for out in self.outputs.values():
  990. out.flush_links()
  991. def update_socket_value(self, blender_property, value) -> bool:
  992. change_handled=False
  993. if self.node_type == 'LINK':
  994. if len(self.bObject) == 0: # - there are no downstream xForms
  995. return True # so there is nothing to do here
  996. for b_ob in self.bObject:
  997. try:
  998. setattr(b_ob, blender_property, value)
  999. change_handled=True
  1000. except Exception as e:
  1001. print("Failed to update mantis socket because of %s" % e,
  1002. "Updating tree instead.")
  1003. else:
  1004. try:
  1005. b_ob = self.bObject
  1006. if self.node_type == 'XFORM': # HACK
  1007. b_ob = self.bGetObject()
  1008. setattr(b_ob, blender_property, value)
  1009. change_handled=True
  1010. except Exception as e:
  1011. print("Failed to update mantis socket because of %s" % e,
  1012. "Updating tree instead.")
  1013. return change_handled
  1014. def ui_modify_socket(self, ui_socket, socket_name=None) -> bool:
  1015. """ Handle changes in the node's UI. Updates the rig if possible."""
  1016. # Always update the node's data
  1017. change_handled=False
  1018. if socket_name is None: socket_name = ui_socket.name
  1019. value = ui_socket.default_value
  1020. # apply overlay variables here so this updates predictably
  1021. if (isinstance(value, str) and
  1022. (self.signature, ui_socket.identifier) in self.mContext.tagged_for_overlay):
  1023. from .execution.readtree import node_scan_overlays
  1024. value = node_scan_overlays(self, ui_socket.identifier)
  1025. # TODO: I need to make Node Groups apply overlays downstream, but since
  1026. # they don't update live anyway, no need just yet
  1027. if socket_name == 'Enable': value = not value
  1028. try:
  1029. self.parameters[ui_socket.name]=value
  1030. except KeyError:
  1031. prRed(f"Unhandled change occured in socket {ui_socket.name} in node"
  1032. f" {ui_socket.node.name} in tree {ui_socket.node.id_data.name}.")
  1033. for s_template in self.socket_templates:
  1034. if s_template.name==ui_socket.name:
  1035. change_handled = True
  1036. if not s_template.blender_property: return False
  1037. elif isinstance(s_template.blender_property, str):
  1038. change_handled &= self.update_socket_value(
  1039. s_template.blender_property, value)
  1040. else: # it is a tuple
  1041. for i, prop in enumerate(s_template.blender_property):
  1042. try:
  1043. change_handled &= self.update_socket_value(
  1044. prop, value[i])
  1045. except IndexError:
  1046. prRed(f"{ui_socket.name} does not have enough values to unpack"
  1047. " to update the Mantis tree. Please report this as a bug.")
  1048. change_handled=False
  1049. break # we don't have to look through any more socket templates
  1050. return change_handled
  1051. # the goal here is to tag the node as unprepared
  1052. # but some nodes are always prepared, so we have to kick it forward.
  1053. def reset_execution_recursive(self):
  1054. self.reset_execution()
  1055. if self.prepared==False: return # all good from here
  1056. for conn in self.hierarchy_connections:
  1057. conn.reset_execution_recursive()
  1058. def evaluate_input(self, input_name, index=0) -> Any:
  1059. from .utilities.node_common import trace_single_line
  1060. if not (self.inputs.get(input_name)): # get the named parameter if there is no input
  1061. return self.parameters.get(input_name) # this will return None if the parameter does not exist.
  1062. # this trace() should give a key error if there is a problem
  1063. # it is NOT handled here because it should NOT happen - so I want the error message.
  1064. trace = trace_single_line(self, input_name, index)
  1065. prop = trace[0][-1].parameters[trace[1].name] #trace[0] = the list of traced nodes; read its parameters
  1066. return prop
  1067. def fill_parameters(self, ui_node=None) -> None:
  1068. from mathutils import Matrix
  1069. from .utilities.utilities import handle_overlay_detect
  1070. if not ui_node:
  1071. if ( (self.signature[0] in FILL_PARAMETERS_SKIP_ROOTS) or
  1072. (self.signature[-1] in FILL_PARAMETERS_SKIP_NAMES) ): # I think this is harmless
  1073. return None
  1074. raise RuntimeError(wrapRed("No UI Node found for... %s" % ( [self.base_tree] + list(self.signature[1:]) ) ) )
  1075. ui_inputs = ui_node.inputs; ui_outputs = ui_node.outputs
  1076. for key in self.parameters.keys():
  1077. if self.parameters[key] is not None: # the parameters are usually initialized as None.
  1078. continue # will be filled by the node itself
  1079. if node_socket := ui_inputs.get(key):
  1080. if node_socket.bl_idname in FILL_PARAMETERS_SKIP_SOCKETS: continue
  1081. elif node_socket.is_linked and (not node_socket.is_output): continue
  1082. # we will get the value from the link, because this is a linked input port.
  1083. # very importantly, we do not pass linked outputs
  1084. # fill these because they are probably Input nodes.
  1085. if node_socket.bl_idname in no_default_value: continue
  1086. if node_socket.bl_idname == 'MatrixSocket':
  1087. v = node_socket.default_value
  1088. self.parameters[key] = Matrix(( tuple(v[0:4]),
  1089. tuple(v[4:8]),
  1090. tuple(v[8:12]),
  1091. tuple(v[12:16]) ))
  1092. elif (value := node_socket.default_value) is not None:
  1093. if isinstance(value, str) and "$" in value:
  1094. value = handle_overlay_detect(self, node_socket.identifier, value)
  1095. self.parameters[key] = value
  1096. else:
  1097. raise RuntimeError(wrapRed("No value found for " + self.__repr__() + " when filling out node parameters for " + ui_node.name + "::"+node_socket.name))
  1098. # I don't think this works! but I like the idea
  1099. def call_on_all_ancestors(self, *args, **kwargs):
  1100. """Resolve the dependencies of this node with the named method and its arguments.
  1101. First, dependencies are discovered by walking backwards through the tree. Once the root
  1102. nodes are discovered, the method is called by each node in dependency order.
  1103. The first argument MUST be the name of the method as a string.
  1104. """
  1105. if args[0] == 'call_on_all_ancestors': raise RuntimeError("Very funny!")
  1106. from .utilities.utilities import get_all_dependencies
  1107. from collections import deque
  1108. # get all dependencies by walking backward through the tree.
  1109. all_dependencies = get_all_dependencies(self)
  1110. # get just the roots
  1111. can_solve = deque(filter(lambda a : len(a.hierarchy_connections) == 0, all_dependencies))
  1112. solved = set()
  1113. while can_solve:
  1114. node = can_solve.pop()
  1115. method = getattr(node, args[0])
  1116. method(*args[0:], **kwargs)
  1117. solved.add(node)
  1118. can_solve.extendleft(filter(lambda a : a in all_dependencies, node.hierarchy_connections))
  1119. if self in solved:
  1120. break
  1121. return
  1122. # gets targets for constraints and deformers and should handle all cases
  1123. def get_target_and_subtarget(self, constraint_or_deformer, input_name = "Target", index = 0,):
  1124. from bpy.types import PoseBone, Object, SplineIKConstraint
  1125. subtarget = ''; target = self.evaluate_input(input_name, index)
  1126. if target:
  1127. if not hasattr(target, "bGetObject"):
  1128. if hasattr(constraint_or_deformer, 'name'):
  1129. name = constraint_or_deformer.name
  1130. else:
  1131. name = 'NAME NOT FOUND'
  1132. prRed(f"No {input_name} target found for {name} in {self} because there is no connected node, or node is wrong type")
  1133. return
  1134. if (isinstance(target.bGetObject(), PoseBone)):
  1135. subtarget = target.bGetObject().name
  1136. target = target.bGetParentArmature()
  1137. elif (isinstance(target.bGetObject(), Object) ):
  1138. target = target.bGetObject()
  1139. else:
  1140. raise RuntimeError("Cannot interpret constraint or deformer target!")
  1141. if (isinstance(constraint_or_deformer, SplineIKConstraint)):
  1142. if target and target.type not in ["CURVE"]:
  1143. raise GraphError(wrapRed("Error: %s requires a Curve input, not %s" %
  1144. (self, type(target))))
  1145. constraint_or_deformer.target = target# don't get a subtarget
  1146. if (input_name == 'Pole Target'):
  1147. constraint_or_deformer.pole_target, constraint_or_deformer.pole_subtarget = target, subtarget
  1148. else:
  1149. if hasattr(constraint_or_deformer, "target"):
  1150. constraint_or_deformer.target = target
  1151. if hasattr(constraint_or_deformer, "object"):
  1152. constraint_or_deformer.object = target
  1153. if hasattr(constraint_or_deformer, "subtarget"):
  1154. constraint_or_deformer.subtarget = subtarget
  1155. # This function is for registering the objects a node creates in the global dict
  1156. # The goal is to have a global map of node <==> object and object <==> node
  1157. # so that we can do e.g. selection syncing, etc.
  1158. # NOTE: I'm not registering with mContext here, that happens elsewhere
  1159. # but it is probably a good idea to refactor this together.
  1160. def bRegisterObject(self, ob_type, ob_value, sub_ob_value = None):
  1161. ui_signature = self.ui_signature
  1162. if selection_sync_node_to_object.get(ui_signature) is None:
  1163. selection_sync_node_to_object[ui_signature] = []
  1164. ob_name = ob_value.name
  1165. sub_ob_name = sub_ob_value.name if sub_ob_value else None
  1166. key = (ob_name, sub_ob_name)
  1167. if ob_type in ['OBJECT', 'BONE']:
  1168. selection_sync_object_to_node[key] = ui_signature
  1169. selection_sync_node_to_object[ui_signature].append( key )
  1170. # PASSES DEFINED HERE!
  1171. def bPrepare(self, bContext=None):
  1172. return # This one runs BEFORE anything else
  1173. def bTransformPass(self, bContext=None):
  1174. return # This one runs in EDIT MODE
  1175. def bRelationshipPass(self, bContext=None):
  1176. return # This one runs in POSE MODE
  1177. def bFinalize(self, bContext=None):
  1178. return
  1179. def bModifierApply(self, bContext=None):
  1180. return
  1181. if environ.get("DOERROR"):
  1182. def __repr__(self):
  1183. return self.signature.__repr__()
  1184. else:
  1185. def __repr__(self):
  1186. return self.ui_signature.__repr__()
  1187. # do I need this and the link class above?
  1188. class DummyLink:
  1189. __slots__ = ("from_socket", "to_socket",
  1190. "from_mantis_node", "to_mantis_node",
  1191. "multi_input_sort_id",
  1192. "original_from")
  1193. #gonna use this for faking links to keep the interface consistent
  1194. def __init__(self, from_socket, to_socket, from_mantis_node=None, to_mantis_node=None, original_from=None, multi_input_sort_id=0):
  1195. self.from_socket = from_socket
  1196. self.to_socket = to_socket
  1197. self.from_mantis_node = from_mantis_node
  1198. self.to_mantis_node = to_mantis_node
  1199. self.multi_input_sort_id = multi_input_sort_id
  1200. # self.from_node = from_socket.node
  1201. # self.to_node = to_socket.node
  1202. if (original_from):
  1203. self.original_from = original_from
  1204. else:
  1205. self.original_from = self.from_socket
  1206. def __repr__(self):
  1207. return(self.from_mantis_node.__repr__()+":"+self.from_socket.name + " -> " + self.to_mantis_node.__repr__()+":"+self.to_socket.name)
  1208. def detect_hierarchy_link(from_node, from_socket, to_node, to_socket,):
  1209. if to_node.node_type in ['DUMMY_SCHEMA', 'SCHEMA']:
  1210. return False #TODO: find out if filtering SCHEMA types is wise
  1211. if from_socket in from_name_filter and to_socket in {"Array"}:
  1212. # SPECIAL CASE: arrays essentially extend the non-hierarchy edge
  1213. # so if the connection to the array isn't hierarchy, the array node
  1214. # in the middle gets disconnected and never executes.
  1215. # SO we need to make all the edges until the end hierarchy.
  1216. # TODO: test the graph for cycles and tag the "last" edge in the cycle
  1217. # is the general solution but that is toooooo slow in Python
  1218. return True
  1219. if (from_socket in from_name_filter) or (to_socket in to_name_filter):
  1220. return False
  1221. # if from_node.__class__.__name__ in ["UtilityCombineVector", "UtilityCombineThreeBool"]:
  1222. # return False
  1223. return True
  1224. class NodeLink:
  1225. __slots__ = (
  1226. "from_node",
  1227. "from_socket",
  1228. "to_node",
  1229. "to_socket",
  1230. "multi_input_sort_id",
  1231. "sub_sort_id",
  1232. "is_hierarchy",
  1233. "is_alive",
  1234. )
  1235. def __init__(self, from_node, from_socket, to_node, to_socket, multi_input_sort_id=0, sub_sort_id=0):
  1236. if from_node.signature == to_node.signature:
  1237. raise RuntimeError("Cannot connect a node to itself.")
  1238. self.from_node = from_node
  1239. self.from_socket = from_socket
  1240. self.to_node = to_node
  1241. self.to_socket = to_socket
  1242. self.from_node.outputs[self.from_socket].links.append(self)
  1243. # it is the responsibility of the node that uses these links to sort them correctly based on the sort_id
  1244. self.multi_input_sort_id = multi_input_sort_id # this is the sort_id of the link in the UI
  1245. self.sub_sort_id = sub_sort_id # this is for sorting within a bundled link (one link in the UI)
  1246. self.to_node.inputs[self.to_socket].links.append(self)
  1247. self.is_hierarchy = detect_hierarchy_link(from_node, from_socket, to_node, to_socket,)
  1248. self.is_alive = True
  1249. def __repr__(self):
  1250. return self.from_node.outputs[self.from_socket].__repr__() + " --> " + self.to_node.inputs[self.to_socket].__repr__()
  1251. # link_string = # if I need to colorize output for debugging.
  1252. # if self.is_hierarchy:
  1253. # return wrapOrange(link_string)
  1254. # else:
  1255. # return wrapWhite(link_string)
  1256. def die(self):
  1257. self.is_alive = False
  1258. self.to_node.inputs[self.to_socket].flush_links()
  1259. self.from_node.outputs[self.from_socket].flush_links()
  1260. def insert_node(self, middle_node, middle_node_in, middle_node_out, re_init_hierarchy = True):
  1261. to_node = self.to_node
  1262. to_socket = self.to_socket
  1263. self.to_node = middle_node
  1264. self.to_socket = middle_node_in
  1265. middle_node.outputs[middle_node_out].connect(to_node, to_socket)
  1266. if re_init_hierarchy:
  1267. from .utilities.utilities import init_connections, init_dependencies
  1268. init_connections(self.from_node)
  1269. init_connections(middle_node)
  1270. init_dependencies(middle_node)
  1271. init_dependencies(to_node)
  1272. class NodeSocket:
  1273. __slots__ = (
  1274. "can_traverse",
  1275. "traverse_target",
  1276. "node",
  1277. "name",
  1278. "is_input",
  1279. "links",
  1280. "is_linked",
  1281. )
  1282. def __init__(self, is_input = False,
  1283. node = None, name = None,
  1284. traverse_target = None):
  1285. self.can_traverse = False # to/from the other side of the parent node
  1286. self.traverse_target = None
  1287. self.node = node
  1288. self.name = name
  1289. self.is_input = is_input
  1290. self.links = []
  1291. self.is_linked = False
  1292. if (traverse_target):
  1293. self.can_traverse = True
  1294. def connect(self, node, socket, sort_id=0, sub_sort_id=0):
  1295. if (self.is_input):
  1296. to_node = self.node; from_node = node
  1297. to_socket = self.name; from_socket = socket
  1298. else:
  1299. from_node = self.node; to_node = node
  1300. from_socket = self.name; to_socket = socket
  1301. from_node.outputs[from_socket].is_linked = True
  1302. to_node.inputs[to_socket].is_linked = True
  1303. # NOTE: I have removed a check for duplicate links here.
  1304. # Schemas sometimes have valid duplicate links.
  1305. # It is conceivable that this will lead to bugs, but I judge it unlikely.
  1306. new_link = NodeLink(
  1307. from_node,
  1308. from_socket,
  1309. to_node,
  1310. to_socket,
  1311. sort_id,
  1312. sub_sort_id)
  1313. return new_link
  1314. def set_traverse_target(self, traverse_target):
  1315. self.traverse_target = traverse_target
  1316. if traverse_target: self.can_traverse = True
  1317. else: self.can_traverse = False
  1318. def flush_links(self):
  1319. """ Removes dead links from this socket."""
  1320. self.links = [l for l in self.links if l.is_alive]
  1321. self.links.sort(key=links_sort_key)
  1322. self.is_linked = bool(self.links)
  1323. @property
  1324. def is_connected(self):
  1325. return len(self.links)>0
  1326. def __repr__(self):
  1327. return self.node.__repr__() + "::" + self.name
  1328. class MantisNodeSocketCollection(dict):
  1329. __slots__ = ("is_input", "node",)
  1330. def __init__(self, node, is_input=False):
  1331. self.is_input = is_input
  1332. self.node = node
  1333. def init_sockets(self, sockets):
  1334. for socket in sockets:
  1335. if socket.ui_only == True: continue # used in UI but not in generation
  1336. if socket.is_input != self.is_input: continue
  1337. self[socket.name] = NodeSocket(is_input=self.is_input, name=socket.name, node=self.node)
  1338. def __delitem__(self, key):
  1339. """Deletes a node socket by name, and all its links."""
  1340. socket = self[key]
  1341. for l in socket.links:
  1342. l.die()
  1343. super().__delitem__(key)
  1344. def __iter__(self):
  1345. """Makes the class iterable"""
  1346. return iter(self.values())