__init__.py 17 KB

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