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