__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. from . import ( ops_nodegroup,
  2. ops_ui,
  3. base_definitions,
  4. socket_definitions,
  5. link_definitions,
  6. xForm_definitions,
  7. misc_nodes_ui,
  8. primitives_definitions,
  9. deformer_definitions,
  10. math_definitions,
  11. i_o,
  12. schema_definitions,
  13. menu_classes,
  14. )
  15. from .ops_generate_tree import GenerateMantisTree
  16. from .utilities import prRed
  17. MANTIS_VERSION_MAJOR=0
  18. MANTIS_VERSION_MINOR=11
  19. MANTIS_VERSION_SUB=20
  20. classLists = [module.TellClasses() for module in [
  21. link_definitions,
  22. xForm_definitions,
  23. misc_nodes_ui,
  24. socket_definitions,
  25. ops_nodegroup,
  26. ops_ui,
  27. primitives_definitions,
  28. deformer_definitions,
  29. math_definitions,
  30. i_o,
  31. schema_definitions,
  32. base_definitions,
  33. menu_classes,
  34. ]]
  35. classLists.append( [GenerateMantisTree] )
  36. #
  37. classes = []
  38. while (classLists):
  39. classes.extend(classLists.pop())
  40. interface_classes = []
  41. from os import environ
  42. if environ.get("ENABLEVIS"):
  43. from .visualize import MantisVisualizeNode, MantisVisualizeOutput, MantisVisualizeTree
  44. classes.extend([MantisVisualizeTree, MantisVisualizeNode, MantisVisualizeOutput, ])
  45. import nodeitems_utils
  46. from nodeitems_utils import NodeCategory, NodeItem
  47. class MantisNodeCategory(NodeCategory):
  48. @classmethod
  49. def poll(cls, context):
  50. return (context.space_data.tree_type in ['MantisTree', 'SchemaTree'])
  51. class SchemaNodeCategory(NodeCategory):
  52. @classmethod
  53. def poll(cls, context):
  54. return (context.space_data.path[len(context.space_data.path)-1].node_tree.bl_idname == 'SchemaTree')
  55. class MantisGroupCategory(NodeCategory):
  56. @classmethod
  57. def poll(cls, context):
  58. return (context.space_data.path[len(context.space_data.path)-1].node_tree.bl_idname in ['MantisTree'] and len(context.space_data.path)>1)
  59. input_category=[
  60. NodeItem("InputFloatNode"),
  61. NodeItem("InputVectorNode"),
  62. NodeItem("InputBooleanNode"),
  63. NodeItem("InputStringNode"),
  64. NodeItem("InputIntNode"),
  65. NodeItem("InputMatrixNode"),
  66. NodeItem("InputExistingGeometryObject"),
  67. NodeItem("InputExistingGeometryData"),
  68. NodeItem("UtilityDeclareCollections"),
  69. NodeItem("InputThemeBoneColorSets"),
  70. NodeItem("InputColorSetPallete"),
  71. ]
  72. link_transform_category = [
  73. NodeItem("LinkCopyLocation"),
  74. NodeItem("LinkCopyRotation"),
  75. NodeItem("LinkCopyScale"),
  76. NodeItem("LinkCopyTransforms"),
  77. NodeItem("LinkLimitLocation"),
  78. NodeItem("LinkLimitScale"),
  79. NodeItem("LinkLimitRotation"),
  80. NodeItem("LinkLimitDistance"),
  81. NodeItem("LinkTransformation"),
  82. NodeItem("LinkFloor"),
  83. ]
  84. link_tracking_category = [
  85. NodeItem("LinkInverseKinematics"),
  86. NodeItem("LinkSplineIK"),
  87. NodeItem("LinkStretchTo"),
  88. NodeItem("LinkDampedTrack"),
  89. NodeItem("LinkLockedTrack"),
  90. NodeItem("LinkTrackTo"),
  91. ]
  92. link_relationship_category = [
  93. NodeItem("linkInherit"),
  94. NodeItem("LinkInheritConstraint"),
  95. NodeItem("LinkArmature"),
  96. ]
  97. deformer_category=[NodeItem(cls.bl_idname) for cls in deformer_definitions.TellClasses()]
  98. xForm_category = [
  99. NodeItem("xFormGeometryObject"),
  100. NodeItem("xFormBoneNode"),
  101. NodeItem("xFormArmatureNode"),
  102. NodeItem("xFormObjectInstance"),
  103. NodeItem("xFormCurvePin"),
  104. ]
  105. driver_category = [
  106. NodeItem("LinkDrivenParameter"),
  107. NodeItem("UtilityFCurve"),
  108. NodeItem("UtilityBoneProperties"),
  109. NodeItem("UtilityDriverVariable"),
  110. NodeItem("UtilitySwitch"),
  111. NodeItem("UtilityDriver"),
  112. NodeItem("UtilityKeyframe"),
  113. ]
  114. geometry_category = [
  115. NodeItem("GeometryCirclePrimitive"),
  116. NodeItem("GeometryLattice"),
  117. ]
  118. utility_category = [
  119. NodeItem("MathStaticInt"),
  120. NodeItem("MathStaticFloat"),
  121. NodeItem("MathStaticVector"),
  122. NodeItem("UtilityCatStrings"),
  123. NodeItem("UtilityCollectionJoin"),
  124. NodeItem("UtilityCollectionHierarchy"),
  125. NodeItem("UtilityGeometryOfXForm"),
  126. NodeItem("UtilityNameOfXForm"),
  127. NodeItem("UtilityCombineThreeBool"),
  128. NodeItem("UtilityCombineVector"),
  129. NodeItem("UtilityIntToString"),
  130. NodeItem("UtilityArrayGet"),
  131. NodeItem("UtilityArrayLength"),
  132. NodeItem("UtilityChoose"),
  133. NodeItem("UtilityCompare"),
  134. NodeItem("UtilityPrint"),
  135. NodeItem("UtilitySeparateVector"),
  136. NodeItem("UtilityGetNearestFactorOnCurve"),
  137. NodeItem("UtilityKDChoosePoint"),
  138. NodeItem("UtilityKDChooseXForm"),
  139. ]
  140. matrix_category = [
  141. NodeItem("UtilityMetaRig"),
  142. NodeItem("UtilityMatrixFromCurve"),
  143. NodeItem("UtilityMatricesFromCurve"),
  144. NodeItem("UtilityNumberOfCurveSegments"),
  145. NodeItem("UtilityMatrixFromCurveSegment"),
  146. NodeItem("UtilityPointFromCurve"),
  147. NodeItem("UtilityGetCurvePoint"),
  148. NodeItem("UtilityNumberOfSplines"),
  149. NodeItem("UtilityPointFromBoneMatrix"),
  150. NodeItem("UtilitySetBoneLength"),
  151. NodeItem("UtilityGetBoneLength"),
  152. NodeItem("UtilityBoneMatrixHeadTailFlip"),
  153. NodeItem("UtilityMatrixSetLocation"),
  154. NodeItem("UtilityMatrixFromXForm"),
  155. NodeItem("UtilityAxesFromMatrix"),
  156. NodeItem("UtilityMatrixTransform"),
  157. NodeItem("UtilityMatrixInvert"),
  158. NodeItem("UtilityMatrixCompose"),
  159. NodeItem("UtilityMatrixAlignRoll"),
  160. NodeItem("UtilityTransformationMatrix"),
  161. NodeItem("UtilitySetBoneMatrixTail"),
  162. ]
  163. groups_category = [
  164. NodeItem("MantisNodeGroup"),
  165. NodeItem("MantisSchemaGroup"),
  166. ]
  167. group_interface_category = [
  168. NodeItem("NodeGroupInput"),
  169. NodeItem("NodeGroupOutput"),
  170. ]
  171. node_categories = [
  172. # identifier, label, items list
  173. MantisNodeCategory('INPUT', "Input", items=input_category),
  174. MantisNodeCategory('LINK_TRANSFORM', "Link (Transform)", items=link_transform_category),
  175. MantisNodeCategory('LINK_TRACKING', "Link (Tracking)", items=link_tracking_category),
  176. MantisNodeCategory('LINK_RELATIONSHIP', "Link (Inheritance)", items=link_relationship_category),
  177. MantisNodeCategory('DEFORMER', "Deformer", items=deformer_category),
  178. MantisNodeCategory('XFORM', "Transform", items=xForm_category),
  179. MantisNodeCategory('DRIVER', "Driver", items=driver_category),
  180. MantisNodeCategory('GEOMETRY', "Geometry", items =geometry_category),
  181. MantisNodeCategory('UTILITIES', "Utility", items=utility_category),
  182. MantisNodeCategory('MATRIX', "Matrix", items=matrix_category),
  183. MantisNodeCategory('GROUPS', "Groups", items=groups_category),
  184. MantisGroupCategory('GROUP_INTERFACE', "Group In/Out", items=group_interface_category),
  185. ]
  186. schema_category=[NodeItem(cls.bl_idname) for cls in schema_definitions.TellClasses()]
  187. schema_categories = [
  188. SchemaNodeCategory('SCHEMA_SCHEMA', "Schema", items=schema_category),
  189. ]
  190. import bpy
  191. def init_keymaps():
  192. kc = bpy.context.window_manager.keyconfigs.addon
  193. km = kc.keymaps.new(name="Node Generic", space_type='NODE_EDITOR')
  194. kmi = [
  195. # Normal operation
  196. km.keymap_items.new("mantis.group_nodes", 'G', 'PRESS', ctrl=True),
  197. km.keymap_items.new("mantis.edit_group", 'TAB', 'PRESS'),
  198. km.keymap_items.new("mantis.execute_node_tree", 'E', 'PRESS'),
  199. km.keymap_items.new("mantis.mute_node", 'M', 'PRESS'),
  200. km.keymap_items.new("mantis.nodes_cleanup", "C", 'PRESS', shift=True,),
  201. # Testing
  202. km.keymap_items.new("mantis.query_sockets", 'Q', 'PRESS'),
  203. km.keymap_items.new("mantis.test_operator", 'T', 'PRESS'),
  204. km.keymap_items.new("mantis.visualize_output", 'V', 'PRESS'),
  205. # Saving, Loading, Reloading, etc.
  206. km.keymap_items.new("mantis.export_save_choose", "S", 'PRESS', alt=True,),
  207. km.keymap_items.new("mantis.export_save_as", "S", 'PRESS', alt=True, shift=True),
  208. km.keymap_items.new("mantis.reload_tree", "R", 'PRESS', alt=True,),
  209. km.keymap_items.new("mantis.import_tree", "O", 'PRESS', ctrl=True,),
  210. ]
  211. return km, kmi
  212. addon_keymaps = []
  213. # handlers! these have to be persistent
  214. from bpy.app.handlers import persistent
  215. from .base_definitions import hash_tree
  216. @persistent
  217. def update_handler(scene):
  218. # return
  219. context=bpy.context
  220. if context.space_data:
  221. if not hasattr(context.space_data, "path"):
  222. return
  223. trees = [p.node_tree for p in context.space_data.path]
  224. if not trees: return
  225. if (node_tree := trees[0]).bl_idname in ['MantisTree']:
  226. if node_tree.is_exporting:
  227. return
  228. if node_tree.prevent_next_exec : pass
  229. elif node_tree.do_live_update and not (node_tree.is_executing):
  230. node_tree.update_tree(context)
  231. @persistent
  232. def execute_handler(scene):
  233. context = bpy.context
  234. if context.space_data:
  235. if not hasattr(context.space_data, "path"):
  236. return
  237. trees = [p.node_tree for p in context.space_data.path]
  238. if not trees: return
  239. if (node_tree := trees[0]).bl_idname in ['MantisTree']:
  240. # check here instead of in execute_tree because these values can be
  241. # modified at weird times and checking from the handler is more consistent
  242. if ( node_tree.tree_valid) and ( node_tree.do_live_update ):
  243. node_tree.execute_tree(context)
  244. node_tree.tree_valid=False
  245. versioning_node_tasks = [
  246. #relevant bl_idnames # task
  247. #(['LinkTransformation'], transformation_constraint_radians_to_degrees)
  248. ]
  249. def node_version_update(node_tree, node):
  250. from .base_definitions import NODES_REMOVED, SOCKETS_REMOVED, SOCKETS_RENAMED, SOCKETS_ADDED
  251. rename_jobs = []
  252. if node.bl_idname in NODES_REMOVED:
  253. print(f"INFO: removing node {node.name} of type {node.bl_idname} because it has been deprecated.")
  254. node.inputs.remove(socket)
  255. return
  256. for i, socket in enumerate(node.inputs.values()):
  257. if (node.bl_idname, socket.identifier) in SOCKETS_REMOVED:
  258. print(f"INFO: removing socket {socket.identifier} of node {node.name} of type {node.bl_idname} because it has been deprecated.")
  259. node.inputs.remove(socket)
  260. for old_class, old_bl_idname, old_name, new_bl_idname, new_name, multi in SOCKETS_RENAMED:
  261. if (node.bl_idname == old_class and socket.bl_idname == old_bl_idname and socket.name == old_name):
  262. rename_jobs.append((socket, i, new_bl_idname, new_name, multi))
  263. for i, socket in enumerate(node.outputs.values()):
  264. if (node.bl_idname, socket.identifier) in SOCKETS_REMOVED:
  265. print(f"INFO: removing socket {socket.identifier} of node {node.name} of type {node.bl_idname} because it has been deprecated.")
  266. node.outputs.remove(socket)
  267. for old_class, old_bl_idname, old_name, new_bl_idname, new_name, multi in SOCKETS_RENAMED:
  268. if (node.bl_idname == old_class and socket.bl_idname == old_bl_idname and socket.name == old_name):
  269. rename_jobs.append((socket, i, new_bl_idname, new_name, multi))
  270. for bl_idname, in_out, socket_type, socket_name, index, use_multi_input, default_val in SOCKETS_ADDED:
  271. if node.bl_idname != bl_idname:
  272. continue
  273. if in_out == 'INPUT' and node.inputs.get(socket_name) is None:
  274. print(f"INFO: adding socket \"{socket_name}\" of type {socket_type} to node {node.name} of type {node.bl_idname}.")
  275. s = node.inputs.new(socket_type, socket_name, use_multi_input=use_multi_input)
  276. try:
  277. s.default_value = default_val
  278. except AttributeError:
  279. pass # the socket is read-only
  280. node.inputs.move(len(node.inputs)-1, index)
  281. socket_map = None
  282. if rename_jobs:
  283. from .utilities import get_socket_maps
  284. socket_maps = get_socket_maps(node)
  285. for socket, socket_index, new_bl_idname, new_name, multi in rename_jobs:
  286. old_id = socket.identifier
  287. print (f"Renaming socket {socket.identifier} to {new_name} in node {node.name}")
  288. from .utilities import do_relink
  289. if socket.is_output:
  290. index = 1
  291. in_out = "OUTPUT"
  292. node.outputs.remove(socket)
  293. s = node.outputs.new(new_bl_idname, new_name, identifier=new_name, use_multi_input=multi)
  294. node.outputs.move(len(node.outputs)-1, socket_index)
  295. socket_map = socket_maps[1]
  296. else:
  297. index = 0
  298. in_out = "INPUT"
  299. node.inputs.remove(socket)
  300. s = node.inputs.new(new_bl_idname, new_name, identifier=new_name, use_multi_input=multi)
  301. node.inputs.move(len(node.inputs)-1, socket_index)
  302. socket_map = socket_maps[0]
  303. socket_map[new_name] = socket_map[old_id]
  304. if new_name != old_id: del socket_map[old_id] # sometimes rename just changes the socket type or multi
  305. do_relink(node, s, socket_map)
  306. for bl_idname, task in versioning_node_tasks:
  307. if node.bl_idname in bl_idname: task(node)
  308. def do_version_update(node_tree):
  309. for node in node_tree.nodes:
  310. try:
  311. node_version_update(node_tree, node)
  312. except Exception as e:
  313. prRed(f"Error updating version in node: {node_tree.name}::{node.name}; see error:")
  314. print(e)
  315. pass
  316. # increment the version at the end
  317. node_tree.mantis_version[0] = MANTIS_VERSION_MAJOR
  318. node_tree.mantis_version[1] = MANTIS_VERSION_MINOR
  319. node_tree.mantis_version[2] = MANTIS_VERSION_SUB
  320. @persistent
  321. def version_update_handler(filename):
  322. for node_tree in bpy.data.node_groups: # ensure it can update again after file load.
  323. if node_tree.bl_idname in ["MantisTree", "SchemaTree"]:
  324. node_tree.is_exporting=False; node_tree.is_executing=False
  325. for node_tree in bpy.data.node_groups:
  326. if node_tree.bl_idname in ["MantisTree", "SchemaTree"]:
  327. if (node_tree.mantis_version[0] < MANTIS_VERSION_MAJOR) or \
  328. (node_tree.mantis_version[1] < MANTIS_VERSION_MINOR) or \
  329. (node_tree.mantis_version[2] < MANTIS_VERSION_SUB):
  330. print (f"Updating tree {node_tree.name} to {MANTIS_VERSION_MAJOR}.{MANTIS_VERSION_MINOR}.{MANTIS_VERSION_SUB}")
  331. do_version_update(node_tree)
  332. # I'll need to do some fiddling here when it comes time to try
  333. # and make rig definitions animatable.
  334. @persistent
  335. def on_animation_playback_pre_handler(scene,depsgraph):
  336. for t in bpy.data.node_groups:
  337. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  338. t.is_executing = True
  339. @persistent
  340. def on_animation_playback_post_handler(scene,depsgraph):
  341. for t in bpy.data.node_groups:
  342. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  343. t.is_executing = False
  344. @persistent
  345. def on_undo_post_handler(scene): # the undo will trigger a depsgraph update
  346. for t in bpy.data.node_groups: # so we enable prevent_next_exec.
  347. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  348. t.prevent_next_exec = True
  349. t.hash=""
  350. # set the tree to invalid to trigger a tree update
  351. # since the context data is wiped by an undo.
  352. def register():
  353. from bpy.utils import register_class
  354. for cls in classes:
  355. try:
  356. register_class(cls)
  357. except RuntimeError as e:
  358. prRed(f"Registration error for class: {cls.__name__}")
  359. raise e
  360. nodeitems_utils.register_node_categories('MantisNodeCategories', node_categories)
  361. nodeitems_utils.register_node_categories('SchemaNodeCategories', schema_categories)
  362. km, kmi = init_keymaps()
  363. for k in kmi:
  364. k.active = True
  365. addon_keymaps.append((km, k))
  366. # add the handlers
  367. bpy.app.handlers.depsgraph_update_pre.insert(0, update_handler)
  368. bpy.app.handlers.depsgraph_update_post.insert(0, execute_handler)
  369. bpy.app.handlers.load_post.insert(0, version_update_handler)
  370. bpy.app.handlers.animation_playback_pre.insert(0, on_animation_playback_pre_handler)
  371. bpy.app.handlers.animation_playback_post.insert(0, on_animation_playback_post_handler)
  372. bpy.app.handlers.undo_post.insert(0, on_undo_post_handler)
  373. # I'm adding mine in first to ensure other addons don't mess up mine
  374. # but I am a good citizen! so my addon won't mess up yours! probably...
  375. def unregister():
  376. for tree in bpy.data.node_groups: # ensure it doesn't try to update while quitting.
  377. if tree.bl_idname in ['MantisTree, SchemaTree']:
  378. tree.is_exporting=True; tree.is_executing=True
  379. nodeitems_utils.unregister_node_categories('MantisNodeCategories')
  380. nodeitems_utils.unregister_node_categories('SchemaNodeCategories')
  381. from bpy.utils import unregister_class
  382. for cls in reversed(classes):
  383. unregister_class(cls)
  384. for km, kmi in addon_keymaps:
  385. km.keymap_items.remove(kmi)
  386. addon_keymaps.clear()