__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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=12
  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. # I'll need to do some fiddling here when it comes time to try
  300. # and make rig definitions animatable.
  301. @persistent
  302. def on_animation_playback_pre_handler(scene,depsgraph):
  303. for t in bpy.data.node_groups:
  304. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  305. t.is_executing = True
  306. @persistent
  307. def on_animation_playback_post_handler(scene,depsgraph):
  308. for t in bpy.data.node_groups:
  309. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  310. t.is_executing = False
  311. @persistent
  312. def on_undo_post_handler(scene): # the undo will trigger a depsgraph update
  313. for t in bpy.data.node_groups: # so we enable prevent_next_exec.
  314. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  315. t.prevent_next_exec = True
  316. t.hash=""
  317. # set the tree to invalid to trigger a tree update
  318. # since the context data is wiped by an undo.
  319. from .menu_classes import node_context_menu_draw
  320. def register():
  321. from bpy.utils import register_class
  322. for cls in classes:
  323. try:
  324. register_class(cls)
  325. except RuntimeError as e:
  326. prRed(f"Registration error for class: {cls.__name__}")
  327. raise e
  328. nodeitems_utils.register_node_categories('MantisNodeCategories', node_categories)
  329. nodeitems_utils.register_node_categories('SchemaNodeCategories', schema_categories)
  330. bpy.types.NODE_MT_context_menu.append(node_context_menu_draw)
  331. km, kmi = init_keymaps()
  332. for k in kmi:
  333. k.active = True
  334. addon_keymaps.append((km, k))
  335. # add the handlers
  336. bpy.app.handlers.depsgraph_update_pre.insert(0, update_handler)
  337. bpy.app.handlers.depsgraph_update_post.insert(0, execute_handler)
  338. bpy.app.handlers.load_post.insert(0, version_update_handler)
  339. bpy.app.handlers.animation_playback_pre.insert(0, on_animation_playback_pre_handler)
  340. bpy.app.handlers.animation_playback_post.insert(0, on_animation_playback_post_handler)
  341. bpy.app.handlers.undo_post.insert(0, on_undo_post_handler)
  342. # I'm adding mine in first to ensure other addons don't mess up mine
  343. # but I am a good citizen! so my addon won't mess up yours! probably...
  344. def unregister():
  345. bpy.types.NODE_MT_context_menu.remove(node_context_menu_draw)
  346. for tree in bpy.data.node_groups: # ensure it doesn't try to update while quitting.
  347. if tree.bl_idname in ['MantisTree, SchemaTree']:
  348. tree.is_exporting=True; tree.is_executing=True
  349. nodeitems_utils.unregister_node_categories('MantisNodeCategories')
  350. nodeitems_utils.unregister_node_categories('SchemaNodeCategories')
  351. from bpy.utils import unregister_class
  352. for cls in reversed(classes):
  353. unregister_class(cls)
  354. for km, kmi in addon_keymaps:
  355. km.keymap_items.remove(kmi)
  356. addon_keymaps.clear()