base_definitions.py 47 KB

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