__init__.py 16 KB

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