base_definitions.py 47 KB

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