__init__.py 17 KB

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