__init__.py 15 KB

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