__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. from . import ( ops_nodegroup,
  2. ops_ui,
  3. base_definitions,
  4. socket_definitions,
  5. link_nodes_ui,
  6. xForm_nodes_ui,
  7. misc_nodes_ui,
  8. primitives_nodes_ui,
  9. deformer_nodes_ui,
  10. math_nodes_ui,
  11. i_o,
  12. schema_nodes_ui,
  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=12
  19. MANTIS_VERSION_SUB=17
  20. classLists = [module.TellClasses() for module in [
  21. link_nodes_ui,
  22. xForm_nodes_ui,
  23. misc_nodes_ui,
  24. socket_definitions,
  25. ops_nodegroup,
  26. ops_ui,
  27. primitives_nodes_ui,
  28. deformer_nodes_ui,
  29. math_nodes_ui,
  30. i_o,
  31. schema_nodes_ui,
  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 .preferences import MantisPreferences
  42. classes.append(MantisPreferences)
  43. from os import environ
  44. if environ.get("ENABLEVIS"):
  45. from .visualize import MantisVisualizeNode, MantisVisualizeOutput, MantisVisualizeTree
  46. classes.extend([MantisVisualizeTree, MantisVisualizeNode, MantisVisualizeOutput, ])
  47. import nodeitems_utils
  48. from nodeitems_utils import NodeCategory, NodeItem
  49. class MantisNodeCategory(NodeCategory):
  50. @classmethod
  51. def poll(cls, context):
  52. return (context.space_data.tree_type in ['MantisTree', 'SchemaTree'])
  53. class SchemaNodeCategory(NodeCategory):
  54. @classmethod
  55. def poll(cls, context):
  56. return (context.space_data.path[len(context.space_data.path)-1].node_tree.bl_idname == 'SchemaTree')
  57. class MantisGroupCategory(NodeCategory):
  58. @classmethod
  59. def poll(cls, context):
  60. return (context.space_data.path[len(context.space_data.path)-1].node_tree.bl_idname in ['MantisTree'] and len(context.space_data.path)>1)
  61. input_category=[
  62. NodeItem("InputFloatNode"),
  63. NodeItem("InputVectorNode"),
  64. NodeItem("InputBooleanNode"),
  65. NodeItem("InputBooleanThreeTupleNode"),
  66. NodeItem("InputStringNode"),
  67. NodeItem("InputIntNode"),
  68. NodeItem("InputMatrixNode"),
  69. NodeItem("InputWidget"),
  70. NodeItem("InputExistingGeometryObject"),
  71. NodeItem("InputExistingGeometryData"),
  72. NodeItem("UtilityDeclareCollections"),
  73. NodeItem("InputThemeBoneColorSets"),
  74. NodeItem("InputColorSetPallete"),
  75. ]
  76. link_transform_category = [
  77. NodeItem("LinkCopyLocation"),
  78. NodeItem("LinkCopyRotation"),
  79. NodeItem("LinkCopyScale"),
  80. NodeItem("LinkCopyTransforms"),
  81. NodeItem("LinkLimitLocation"),
  82. NodeItem("LinkLimitScale"),
  83. NodeItem("LinkLimitRotation"),
  84. NodeItem("LinkLimitDistance"),
  85. NodeItem("LinkTransformation"),
  86. NodeItem("LinkFloor"),
  87. ]
  88. link_tracking_category = [
  89. NodeItem("LinkInverseKinematics"),
  90. NodeItem("LinkSplineIK"),
  91. NodeItem("LinkStretchTo"),
  92. NodeItem("LinkDampedTrack"),
  93. NodeItem("LinkLockedTrack"),
  94. NodeItem("LinkTrackTo"),
  95. ]
  96. link_relationship_category = [
  97. NodeItem("linkInherit"),
  98. NodeItem("LinkInheritConstraint"),
  99. NodeItem("LinkArmature"),
  100. ]
  101. deformer_category=[NodeItem(cls.bl_idname) for cls in deformer_nodes_ui.TellClasses()]
  102. xForm_category = [
  103. NodeItem("xFormGeometryObject"),
  104. NodeItem("xFormBoneNode"),
  105. NodeItem("xFormArmatureNode"),
  106. NodeItem("xFormObjectInstance"),
  107. NodeItem("xFormCurvePin"),
  108. ]
  109. driver_category = [
  110. NodeItem("LinkDrivenParameter"),
  111. NodeItem("UtilityFCurve"),
  112. NodeItem("UtilityBoneProperties"),
  113. NodeItem("UtilityDriverVariable"),
  114. NodeItem("UtilitySwitch"),
  115. NodeItem("UtilityDriver"),
  116. NodeItem("UtilityKeyframe"),
  117. ]
  118. geometry_category = [
  119. NodeItem("GeometryCirclePrimitive"),
  120. NodeItem("GeometryLattice"),
  121. ]
  122. utility_category = [
  123. NodeItem("MathStaticInt"),
  124. NodeItem("MathStaticFloat"),
  125. NodeItem("MathStaticVector"),
  126. NodeItem("UtilityCatStrings"),
  127. NodeItem("UtilityCollectionJoin"),
  128. NodeItem("UtilityCollectionHierarchy"),
  129. NodeItem("UtilityGeometryOfXForm"),
  130. NodeItem("UtilityNameOfXForm"),
  131. NodeItem("UtilityCombineThreeBool"),
  132. NodeItem("UtilityCombineVector"),
  133. NodeItem("UtilityIntToString"),
  134. NodeItem("UtilityArrayGet"),
  135. NodeItem("UtilityArrayLength"),
  136. NodeItem("UtilityChoose"),
  137. NodeItem("UtilityCompare"),
  138. NodeItem("UtilityPrint"),
  139. NodeItem("UtilitySeparateVector"),
  140. NodeItem("UtilityGetNearestFactorOnCurve"),
  141. NodeItem("UtilityKDChoosePoint"),
  142. NodeItem("UtilityKDChooseXForm"),
  143. ]
  144. matrix_category = [
  145. NodeItem("UtilityMetaRig"),
  146. NodeItem("UtilityMatrixFromCurve"),
  147. NodeItem("UtilityMatricesFromCurve"),
  148. NodeItem("UtilityNumberOfCurveSegments"),
  149. NodeItem("UtilityMatrixFromCurveSegment"),
  150. NodeItem("UtilityPointFromCurve"),
  151. NodeItem("UtilityGetCurvePoint"),
  152. NodeItem("UtilityNumberOfSplines"),
  153. NodeItem("UtilityPointFromBoneMatrix"),
  154. NodeItem("UtilitySetBoneLength"),
  155. NodeItem("UtilityGetBoneLength"),
  156. NodeItem("UtilityBoneMatrixHeadTailFlip"),
  157. NodeItem("UtilityMatrixSetLocation"),
  158. NodeItem("UtilityMatrixFromXForm"),
  159. NodeItem("UtilityAxesFromMatrix"),
  160. NodeItem("UtilityMatrixTransform"),
  161. NodeItem("UtilityMatrixInvert"),
  162. NodeItem("UtilityMatrixCompose"),
  163. NodeItem("UtilityMatrixAlignRoll"),
  164. NodeItem("UtilityTransformationMatrix"),
  165. NodeItem("UtilitySetBoneMatrixTail"),
  166. ]
  167. groups_category = [
  168. NodeItem("MantisNodeGroup"),
  169. NodeItem("MantisSchemaGroup"),
  170. ]
  171. group_interface_category = [
  172. NodeItem("NodeGroupInput"),
  173. NodeItem("NodeGroupOutput"),
  174. ]
  175. node_categories = [
  176. # identifier, label, items list
  177. MantisNodeCategory('INPUT', "Input", items=input_category),
  178. MantisNodeCategory('LINK_TRANSFORM', "Link (Transform)", items=link_transform_category),
  179. MantisNodeCategory('LINK_TRACKING', "Link (Tracking)", items=link_tracking_category),
  180. MantisNodeCategory('LINK_RELATIONSHIP', "Link (Inheritance)", items=link_relationship_category),
  181. MantisNodeCategory('DEFORMER', "Deformer", items=deformer_category),
  182. MantisNodeCategory('XFORM', "Transform", items=xForm_category),
  183. MantisNodeCategory('DRIVER', "Driver", items=driver_category),
  184. MantisNodeCategory('GEOMETRY', "Geometry", items =geometry_category),
  185. MantisNodeCategory('UTILITIES', "Utility", items=utility_category),
  186. MantisNodeCategory('MATRIX', "Matrix", items=matrix_category),
  187. MantisNodeCategory('GROUPS', "Groups", items=groups_category),
  188. MantisGroupCategory('GROUP_INTERFACE', "Group In/Out", items=group_interface_category),
  189. ]
  190. schema_category=[NodeItem(cls.bl_idname) for cls in schema_nodes_ui.TellClasses()]
  191. schema_categories = [
  192. SchemaNodeCategory('SCHEMA_SCHEMA', "Schema", items=schema_category),
  193. ]
  194. import bpy
  195. def init_keymaps():
  196. kc = bpy.context.window_manager.keyconfigs.addon
  197. km = kc.keymaps.new(name="Node Generic", space_type='NODE_EDITOR')
  198. kmi = [
  199. # Normal operation
  200. km.keymap_items.new("mantis.group_nodes", 'G', 'PRESS', ctrl=True),
  201. km.keymap_items.new("mantis.edit_group", 'TAB', 'PRESS'),
  202. km.keymap_items.new("mantis.execute_node_tree", 'E', 'PRESS'),
  203. km.keymap_items.new("mantis.mute_node", 'M', 'PRESS'),
  204. km.keymap_items.new("mantis.nodes_cleanup", "C", 'PRESS', shift=True,),
  205. # Testing
  206. km.keymap_items.new("mantis.query_sockets", 'Q', 'PRESS'),
  207. km.keymap_items.new("mantis.test_operator", 'T', 'PRESS'),
  208. km.keymap_items.new("mantis.visualize_output", 'V', 'PRESS'),
  209. # Saving, Loading, Reloading, etc.
  210. km.keymap_items.new("mantis.export_save_choose", "S", 'PRESS', alt=True,),
  211. km.keymap_items.new("mantis.export_save_as", "S", 'PRESS', alt=True, shift=True),
  212. km.keymap_items.new("mantis.reload_tree", "R", 'PRESS', alt=True,),
  213. km.keymap_items.new("mantis.import_tree", "O", 'PRESS', ctrl=True,),
  214. ]
  215. return km, kmi
  216. addon_keymaps = []
  217. # handlers! these have to be persistent
  218. from bpy.app.handlers import persistent
  219. from .base_definitions import hash_tree
  220. @persistent
  221. def update_handler(scene):
  222. # return
  223. context=bpy.context
  224. if context.space_data:
  225. if not hasattr(context.space_data, "path"):
  226. return
  227. trees = [p.node_tree for p in context.space_data.path]
  228. if not trees: return
  229. if (node_tree := trees[0]).bl_idname in ['MantisTree']:
  230. if node_tree.is_exporting:
  231. return
  232. if node_tree.prevent_next_exec : pass
  233. elif node_tree.do_live_update and not (node_tree.is_executing):
  234. node_tree.update_tree(context)
  235. @persistent
  236. def execute_handler(scene):
  237. context = bpy.context
  238. if context.space_data:
  239. if not hasattr(context.space_data, "path"):
  240. return
  241. trees = [p.node_tree for p in context.space_data.path]
  242. if not trees: return
  243. if (node_tree := trees[0]).bl_idname in ['MantisTree']:
  244. # check here instead of in execute_tree because these values can be
  245. # modified at weird times and checking from the handler is more consistent
  246. if ( node_tree.tree_valid) and ( node_tree.do_live_update ):
  247. node_tree.execute_tree(context)
  248. node_tree.tree_valid=False
  249. from .versioning import versioning_tasks
  250. def node_version_update(node):
  251. do_once = True
  252. for bl_idname, task, required_kwargs in versioning_tasks:
  253. arg_map = {}
  254. if 'node' in required_kwargs:
  255. arg_map['node']=node
  256. if 'node_tree' in required_kwargs:
  257. arg_map['node_tree']=node.id_data
  258. if ('ALL' in bl_idname) or node.bl_idname in bl_idname:
  259. if do_once:
  260. print (f"Updating tree {node.id_data.name} to "
  261. f"{MANTIS_VERSION_MAJOR}.{MANTIS_VERSION_MINOR}.{MANTIS_VERSION_SUB}")
  262. do_once=False
  263. task(**arg_map)
  264. def do_version_update(node_tree):
  265. # set updating status for dynamic nodes to prevent bugs in socket remapping
  266. for node in node_tree.nodes:
  267. if hasattr(node, 'is_updating'):
  268. node.is_updating = True
  269. # start by doing tree versioning tasks
  270. for affected_bl_idnames, task, arguments_needed in versioning_tasks:
  271. if node_tree.bl_idname not in affected_bl_idnames: continue # this is a node task.
  272. arguments = {}
  273. if 'tree' in arguments_needed:
  274. arguments['tree']=node_tree
  275. task(**arguments)
  276. # run the updates that have no prerequisites
  277. for node in node_tree.nodes:
  278. node_version_update(node)
  279. # NOTE: if future versoning tasks have prerequisites, resolve them here and update again
  280. # reset the updating status for dynamic nodes
  281. for node in node_tree.nodes:
  282. if hasattr(node, 'is_updating'):
  283. node.is_updating = False
  284. # increment the version at the end
  285. node_tree.mantis_version[0] = MANTIS_VERSION_MAJOR
  286. node_tree.mantis_version[1] = MANTIS_VERSION_MINOR
  287. node_tree.mantis_version[2] = MANTIS_VERSION_SUB
  288. @persistent
  289. def version_update_handler(filename):
  290. for node_tree in bpy.data.node_groups: # ensure it can update again after file load.
  291. if node_tree.bl_idname in ["MantisTree", "SchemaTree"]:
  292. node_tree.is_exporting=False; node_tree.is_executing=False
  293. for node_tree in bpy.data.node_groups:
  294. if node_tree.bl_idname in ["MantisTree", "SchemaTree"]:
  295. if (node_tree.mantis_version[0] < MANTIS_VERSION_MAJOR) or \
  296. (node_tree.mantis_version[1] < MANTIS_VERSION_MINOR) or \
  297. (node_tree.mantis_version[2] < MANTIS_VERSION_SUB):
  298. do_version_update(node_tree)
  299. @persistent
  300. def autoload_components(filename):
  301. # this should not be blocking or slow!
  302. print("Auto-loading components")
  303. from os import path as os_path
  304. from .utilities import get_component_library_items, get_default_collection
  305. from .i_o import do_import
  306. from .preferences import get_bl_addon_object
  307. import json
  308. from bpy import context, data
  309. bl_addon_object = get_bl_addon_object()
  310. unlink_curves = True
  311. unlink_armatures = True
  312. if data.collections.get(bl_addon_object.preferences.CurveDefaultCollection):
  313. unlink_curves=False
  314. if data.collections.get(bl_addon_object.preferences.MetaArmatureDefaultCollection):
  315. unlink_armatures=False
  316. base_path = bl_addon_object.preferences.ComponentsAutoLoadFolder
  317. components = get_component_library_items(path='AUTOLOAD')
  318. for autoload_component in components:
  319. path = os_path.join(base_path, autoload_component[0])
  320. with open(path, 'r', encoding='utf-8') as f:
  321. json_data = json.load(f)
  322. do_import(json_data, context,
  323. search_multi_files=True, filepath=path,
  324. skip_existing=True)
  325. # let's get the node trees and assign a fake user
  326. for tree_name in json_data.keys():
  327. tree = data.node_groups.get(tree_name)
  328. tree.fake_user = True
  329. # now we need to unlink the collections, and add fake users to them
  330. curves_collection = get_default_collection(collection_type="CURVE")
  331. armature_collection = get_default_collection(collection_type="ARMATURE")
  332. if unlink_curves and (curves_collection := data.collections.get(
  333. bl_addon_object.preferences.CurveDefaultCollection)):
  334. context.scene.collection.children.unlink(curves_collection)
  335. if unlink_armatures and (armature_collection := data.collections.get(
  336. bl_addon_object.preferences.MetaArmatureDefaultCollection)):
  337. context.scene.collection.children.unlink(armature_collection)
  338. # I'll need to do some fiddling here when it comes time to try
  339. # and make rig definitions animatable.
  340. @persistent
  341. def on_animation_playback_pre_handler(scene,depsgraph):
  342. for t in bpy.data.node_groups:
  343. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  344. t.is_executing = True
  345. @persistent
  346. def on_animation_playback_post_handler(scene,depsgraph):
  347. for t in bpy.data.node_groups:
  348. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  349. t.is_executing = False
  350. @persistent
  351. def on_undo_post_handler(scene): # the undo will trigger a depsgraph update
  352. for t in bpy.data.node_groups: # so we enable prevent_next_exec.
  353. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  354. t.prevent_next_exec = True
  355. t.hash=""
  356. # set the tree to invalid to trigger a tree update
  357. # since the context data is wiped by an undo.
  358. from .menu_classes import (node_context_menu_draw, node_add_menu_draw,
  359. armature_add_menu_draw, import_menu_draw)
  360. def register():
  361. from bpy.utils import register_class
  362. for cls in classes:
  363. try:
  364. register_class(cls)
  365. except RuntimeError as e:
  366. prRed(f"Registration error for class: {cls.__name__}")
  367. raise e
  368. nodeitems_utils.register_node_categories('MantisNodeCategories', node_categories)
  369. nodeitems_utils.register_node_categories('SchemaNodeCategories', schema_categories)
  370. bpy.types.NODE_MT_context_menu.append(node_context_menu_draw)
  371. bpy.types.NODE_MT_add.append(node_add_menu_draw)
  372. bpy.types.VIEW3D_MT_armature_add.append(armature_add_menu_draw)
  373. bpy.types.TOPBAR_MT_file_import.append(import_menu_draw)
  374. km, kmi = init_keymaps()
  375. for k in kmi:
  376. k.active = True
  377. addon_keymaps.append((km, k))
  378. # add the handlers
  379. bpy.app.handlers.depsgraph_update_pre.insert(0, update_handler)
  380. bpy.app.handlers.depsgraph_update_post.insert(0, execute_handler)
  381. bpy.app.handlers.load_post.insert(0, autoload_components)
  382. bpy.app.handlers.load_post.insert(0, version_update_handler)
  383. bpy.app.handlers.animation_playback_pre.insert(0, on_animation_playback_pre_handler)
  384. bpy.app.handlers.animation_playback_post.insert(0, on_animation_playback_post_handler)
  385. bpy.app.handlers.undo_post.insert(0, on_undo_post_handler)
  386. # I'm adding mine in first to ensure other addons don't mess up mine
  387. # but I am a good citizen! so my addon won't mess up yours! probably...
  388. def unregister():
  389. bpy.types.NODE_MT_context_menu.remove(node_context_menu_draw)
  390. for tree in bpy.data.node_groups: # ensure it doesn't try to update while quitting.
  391. if tree.bl_idname in ['MantisTree, SchemaTree']:
  392. tree.is_exporting=True; tree.is_executing=True
  393. nodeitems_utils.unregister_node_categories('MantisNodeCategories')
  394. nodeitems_utils.unregister_node_categories('SchemaNodeCategories')
  395. from bpy.utils import unregister_class
  396. for cls in reversed(classes):
  397. unregister_class(cls)
  398. for km, kmi in addon_keymaps:
  399. km.keymap_items.remove(kmi)
  400. addon_keymaps.clear()