__init__.py 16 KB

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