base_definitions.py 48 KB

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