i_o.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. # this is the I/O part of mantis. I eventually intend to make this a markup language. not right now tho lol
  2. from .utilities import (prRed, prGreen, prPurple, prWhite,
  3. prOrange,
  4. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  5. wrapOrange,)
  6. from mathutils import Vector
  7. NODES_REMOVED=["xFormRootNode"]
  8. # Node bl_idname, # Socket Name
  9. SOCKETS_REMOVED=[("UtilityDriverVariable", "Transform Channel"),
  10. ("xFormRootNode","World Out"),
  11. ("UtilitySwitch","xForm"),
  12. ("LinkDrivenParameter", "Enable")]
  13. # Node Class #Prior bl_idname # prior name # new bl_idname # new name, # Multi
  14. # ignore these because they are either unrelated python stuff or useless or borked
  15. prop_ignore = [ "__dict__", "__doc__", "__module__", "__weakref__",# "name",
  16. "bl_height_default", "bl_height_max", "bl_height_min",
  17. "bl_icon", "bl_rna", "bl_static_type", "bl_description",
  18. "bl_width_default", "bl_width_max", "bl_width_min",
  19. "__annotations__", "original", "rna_type", "view_center",
  20. "links", "nodes", "internal_links", "inputs", "outputs",
  21. "__slots__", "dimensions", "type", "interface",
  22. "library_weak_reference", "parsed_tree", "node_tree_updater",
  23. "asset_data", "preview", # blender asset stuff
  24. "object_reference", # this one is here to hold on to widgets when appending
  25. "color_tag" , # added in blender 4.4, not used by Mantis, readonly.
  26. # more blender properties...
  27. "bl_use_group_interface", "default_group_node_width", "id_type",
  28. # blender runtime stuff
  29. "animation_data", "description", "grease_pencil", "is_editable",
  30. "is_embedded_data", "is_evaluated", "is_library_indirect", "is_missing",
  31. "is_runtime_data", "library", "name_full", "override_library",
  32. "session_uid", "tag", "use_extra_user", "use_fake_user", "users",
  33. # some Mantis stuff I don't need to save
  34. "do_live_update", "is_executing", "is_exporting", "hash", "filepath",
  35. "prevent_next_exec", "execution_id", "num_links", "tree_valid",
  36. "interface_helper",
  37. # node stuff
  38. "mantis_node_class_name", "color", "height", "initialized", "select",
  39. "show_options", "show_preview", "show_texture", "use_custom_color",
  40. "warning_propagation",
  41. # these are in Bone
  42. "socket_count", "display_bb_settings", "display_def_settings",
  43. "display_ik_settings", "display_vp_settings",
  44. ]
  45. # don't ignore: "bl_idname", "bl_label",
  46. # ignore the name, it's the dict - key for the node props
  47. # no that's stupid don't ignore the name good grief
  48. # I am doing this because these are interactions with other addons that cause problems and probably don't exist for any given user
  49. prop_ignore.extend(['keymesh'])
  50. # trees
  51. prop_ignore_tree = prop_ignore.copy()
  52. prop_ignore_tree.extend(["bl_label", "name"])
  53. from bpy.app import version
  54. if version >= (4,5,0):
  55. SOCKETS_REMOVED.append( ("LinkSplineIK", "Use Original Scale"))
  56. add_inputs_bl_idnames = [
  57. "UtilityDriver", "UtilityFCurve", "DeformerMorphTargetDeform",
  58. "LinkArmature",
  59. ]
  60. # this works but it is really ugly and probably quite inneficient
  61. # TODO: make hotkeys for export and import and reload from file
  62. # we need to give the tree a filepath attribute and update it on saving
  63. # then we need to use the filepath attribute to load from
  64. # finally we need to use a few operators to choose whether to open a menu or not
  65. # and we need a message to display on save/load so that the user knows it is happening
  66. # TODO:
  67. # Additionally export MetaRig and Curve and other referenced data
  68. # Meshes can be exported as .obj and imported via GN
  69. def TellClasses():
  70. return [ MantisExportNodeTreeSaveAs, MantisExportNodeTreeSave, MantisExportNodeTree, MantisImportNodeTree, MantisReloadNodeTree]
  71. # https://stackoverflow.com/questions/42033142/is-there-an-easy-way-to-check-if-an-object-is-json-serializable-in-python - thanks!
  72. def is_jsonable(x):
  73. import json
  74. try:
  75. json.dumps(x)
  76. return True
  77. except (TypeError, OverflowError):
  78. return False
  79. # https://stackoverflow.com/questions/295135/turn-a-stritree-into-a-valid-filename - thank you user "Sophie Gage"
  80. def remove_special_characters(name):
  81. import re; return re.sub('[^\w_.)( -]', '', name)# re = regular expressions
  82. def fix_custom_parameter(n, property_definition, ):
  83. if n.bl_idname in ['xFormNullNode', 'xFormBoneNode', 'xFormArmatureNode', 'xFormGeometryObjectNode',]:
  84. prop_name = property_definition["name"]
  85. prop_type = property_definition["bl_idname"]
  86. if prop_type in ['ParameterBoolSocket', 'ParameterIntSocket', 'ParameterFloatSocket', 'ParameterVectorSocket' ]:
  87. # is it good to make both of them?
  88. input = n.inputs.new( prop_type, prop_name)
  89. output = n.outputs.new( prop_type, prop_name)
  90. if property_definition["is_output"] == True:
  91. return output
  92. return input
  93. elif n.bl_idname in ['LinkArmature']:
  94. prop_name = property_definition["name"]
  95. prop_type = property_definition["bl_idname"]
  96. input = n.inputs.new( prop_type, prop_name)
  97. return input
  98. return None
  99. def get_socket_data(socket, ignore_if_default=False):
  100. # TODO: don't get stuff in the socket templates
  101. # PROBLEM: I don't have easy access to this from the ui class (or mantis class)
  102. socket_data = {}
  103. socket_data["name"] = socket.name
  104. socket_data["bl_idname"] = socket.bl_idname
  105. socket_data["is_output"] = socket.is_output
  106. socket_data["is_multi_input"] = socket.is_multi_input
  107. # here is where we'll handle a socket_data'socket special data
  108. if socket.bl_idname == "EnumMetaBoneSocket":
  109. socket_data["bone"] = socket.bone
  110. if socket.bl_idname in ["EnumMetaBoneSocket", "EnumMetaRigSocket", "EnumCurveSocket"]:
  111. if sp := socket.get("search_prop"): # may be None
  112. socket_data["search_prop"] = sp.name # this is an object.
  113. #
  114. if hasattr(socket, "default_value"):
  115. value = socket.default_value
  116. else:
  117. value = None
  118. return socket_data # we don't need to store any more.
  119. if not is_jsonable(value): # FIRST try and make a tuple out of it because JSON doesn't like mutables
  120. value = tuple(value)
  121. if not is_jsonable(value): # now see if it worked and crash out if it didn't
  122. raise RuntimeError(f"Error serializing data in {socket.node.name}::{socket.name} for value of type {type(value)}")
  123. socket_data["default_value"] = value
  124. # TODO TODO implement "ignore if default" feature here
  125. # at this point we can get the custom parameter ui hints if we want
  126. if not socket.is_output:
  127. # try and get this data
  128. if value := getattr(socket,'min', None):
  129. socket_data["min"] = value
  130. if value := getattr(socket,'max', None):
  131. socket_data["max"] = value
  132. if value := getattr(socket,'soft_min', None):
  133. socket_data["soft_min"] = value
  134. if value := getattr(socket,'soft_max', None):
  135. socket_data["soft_max"] = value
  136. if value := getattr(socket,'description', None):
  137. socket_data["description"] = value
  138. return socket_data
  139. #
  140. def get_node_data(ui_node):
  141. # if this is a node-group, force it to update its interface, because it may be messed up.
  142. # can remove this HACK when I have stronger guarentees about node-group's keeping the interface
  143. from .base_definitions import node_group_update
  144. if hasattr(ui_node, "node_tree"):
  145. ui_node.is_updating = True
  146. try: # HERE BE DANGER
  147. node_group_update(ui_node, force=True)
  148. finally: # ensure this line is run even if there is an error
  149. ui_node.is_updating = False
  150. node_props, sockets = {}, {}
  151. for propname in dir(ui_node):
  152. value = getattr(ui_node, propname)
  153. if propname in ['fake_fcurve_ob']:
  154. value=value.name
  155. if (propname in prop_ignore) or ( callable(value) ):
  156. continue
  157. if value.__class__.__name__ in ["Vector", "Color"]:
  158. value = tuple(value)
  159. if isinstance(value, bpy.types.NodeTree):
  160. value = value.name
  161. if isinstance(value, bpy.types.bpy_prop_array):
  162. value = tuple(value)
  163. if propname == "parent" and value:
  164. value = value.name
  165. if not is_jsonable(value):
  166. raise RuntimeError(f"Could not export... {ui_node.name}, {propname}, {type(value)}")
  167. if value is None:
  168. continue
  169. node_props[propname] = value
  170. # so we have to accumulate the parent location because the location is not absolute
  171. if propname == "location" and ui_node.parent is not None:
  172. location_acc = Vector((0,0))
  173. parent = ui_node.parent
  174. while (parent):
  175. location_acc += parent.location
  176. parent = parent.parent
  177. location_acc += getattr(ui_node, propname)
  178. node_props[propname] = tuple(location_acc)
  179. # this works!
  180. for i, ui_socket in enumerate(ui_node.inputs):
  181. if ui_socket.is_linked: continue # not necessary to save it since it doesn't affect the tree
  182. socket = get_socket_data(ui_socket)
  183. socket["index"]=i
  184. sockets[ui_socket.identifier] = socket
  185. for i, ui_socket in enumerate(ui_node.outputs):
  186. if ui_socket.is_linked: continue # see above
  187. socket = get_socket_data(ui_socket)
  188. socket["index"]=i
  189. sockets[ui_socket.identifier] = socket
  190. node_props["sockets"] = sockets
  191. return node_props
  192. def get_tree_data(tree):
  193. tree_info = {}
  194. for propname in dir(tree):
  195. # if getattr(tree, propname):
  196. # pass
  197. if (propname in prop_ignore_tree) or ( callable(getattr(tree, propname)) ):
  198. continue
  199. v = getattr(tree, propname)
  200. if isinstance(getattr(tree, propname), bpy.types.bpy_prop_array):
  201. v = tuple(getattr(tree, propname))
  202. if not is_jsonable( v ):
  203. raise RuntimeError(f"Not JSON-able: {propname}, type: {type(v)}")
  204. tree_info[propname] = v
  205. tree_info["name"]=tree.name
  206. return tree_info
  207. def get_interface_data(tree, tree_in_out):
  208. for sock in tree.interface.items_tree:
  209. sock_data={}
  210. if sock.item_type == 'PANEL':
  211. sock_data["name"] = sock.name
  212. sock_data["item_type"] = sock.item_type
  213. sock_data["description"] = sock.description
  214. sock_data["default_closed"] = sock.default_closed
  215. tree_in_out[sock.name] = sock_data
  216. # if it is a socket....
  217. else:
  218. sock_parent = None
  219. if sock.parent:
  220. sock_parent = sock.parent.name
  221. for propname in dir(sock):
  222. v = getattr(sock, propname)
  223. if (propname in prop_ignore) or ( callable(v) ):
  224. continue
  225. if (propname == "parent"):
  226. sock_data[propname] = sock_parent
  227. continue
  228. if isinstance(getattr(sock, propname), bpy.types.bpy_prop_array):
  229. v = tuple(getattr(sock, propname))
  230. if not is_jsonable( v ):
  231. raise RuntimeError(f"{propname}, {type(v)}")
  232. sock_data[propname] = v
  233. tree_in_out[sock.identifier] = sock_data
  234. def export_to_json(trees, path="", write_file=True, only_selected=False):
  235. export_data = {}
  236. for tree in trees:
  237. current_tree_is_base_tree = False
  238. if tree is trees[-1]:
  239. current_tree_is_base_tree = True
  240. tree_info, tree_in_out = {}, {}
  241. tree_info = get_tree_data(tree)
  242. # if only_selected:
  243. # # all in/out links, relative to the selection, should be marked and used to initialize tree properties
  244. if not only_selected: # we'll handle this later with the links
  245. for sock in tree.interface.items_tree:
  246. get_interface_data(tree, tree_in_out) # it concerns me that this one modifies
  247. # the collection instead of getting the data and returning it. TODO refactor this
  248. nodes = {}
  249. for node in tree.nodes:
  250. if only_selected and node.select == False:
  251. continue
  252. nodes[node.name] = get_node_data(node)
  253. links = []
  254. in_sockets, out_sockets = {}, {}
  255. unique_sockets_from, unique_sockets_to = {}, {}
  256. in_node = {"name":"MANTIS_AUTOGEN_GROUP_INPUT", "bl_idname":"NodeGroupInput", "sockets":in_sockets}
  257. out_node = {"name":"MANTIS_AUTOGEN_GROUP_OUTPUT", "bl_idname":"NodeGroupOutput", "sockets":out_sockets}
  258. add_input_node, add_output_node = False, False
  259. for link in tree.links:
  260. from_node_name, from_socket_id = link.from_node.name, link.from_socket.identifier
  261. to_node_name, to_socket_id = link.to_node.name, link.to_socket.identifier
  262. from_socket_name, to_socket_name = link.from_socket.name, link.to_socket.name
  263. # get the indices of the sockets to be absolutely sure
  264. for from_outoput_index, outp in enumerate(link.from_node.outputs):
  265. # for some reason, 'is' does not return True no matter what...
  266. # so we are gonn compare the memory address directly, this is stupid
  267. if (outp.as_pointer() == link.from_socket.as_pointer()): break
  268. else:
  269. problem=link.from_node.name + "::" + link.from_socket.name
  270. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  271. for to_input_index, inp in enumerate(link.to_node.inputs):
  272. if (inp.as_pointer() == link.to_socket.as_pointer()): break
  273. else:
  274. problem = link.to_node.name + "::" + link.to_socket.name
  275. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  276. if current_tree_is_base_tree:
  277. if (only_selected and link.from_node.select) and (not link.to_node.select):
  278. # handle an output in the tree
  279. add_output_node=True
  280. if not (sock_name := unique_sockets_to.get(link.from_socket.node.name+link.from_socket.identifier)):
  281. sock_name = link.to_socket.name; name_stub = sock_name
  282. used_names = list(tree_in_out.keys()); i=0
  283. while sock_name in used_names:
  284. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  285. unique_sockets_to[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  286. out_sock = out_sockets.get(sock_name)
  287. if not out_sock:
  288. out_sock = {}; out_sockets[sock_name] = out_sock
  289. out_sock["index"]=len(out_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  290. # what in the bad word is happening here?
  291. # why?
  292. # why no de-duplication?
  293. # what was I thinking?
  294. # TODO REFACTOR THIS SOON
  295. out_sock["name"] = sock_name
  296. out_sock["identifier"] = sock_name
  297. out_sock["bl_idname"] = link.to_socket.bl_idname
  298. out_sock["is_output"] = False
  299. out_sock["source"]=[link.to_socket.node.name,link.to_socket.identifier]
  300. out_sock["is_multi_input"] = False # this is not something I can even set on tree interface items, and this code is not intended for making Schema
  301. sock_data={}
  302. sock_data["name"] = sock_name
  303. sock_data["item_type"] = "SOCKET"
  304. sock_data["default_closed"] = False
  305. # these two are the same thing, but I need both?
  306. sock_data["socket_type"] = link.from_socket.bl_idname
  307. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  308. sock_data["identifier"] = sock_name
  309. sock_data["in_out"]="OUTPUT"
  310. sock_data["index"]=out_sock["index"]
  311. tree_in_out[sock_name] = sock_data
  312. to_node_name=out_node["name"]
  313. to_socket_id=out_sock["identifier"]
  314. to_input_index=out_sock["index"]
  315. to_socket_name=out_sock["name"]
  316. elif (only_selected and (not link.from_node.select)) and link.to_node.select:
  317. add_input_node=True
  318. # we need to get a unique name for this
  319. # use the Tree IN/Out because we are dealing with Group in/out
  320. if not (sock_name := unique_sockets_from.get(link.from_socket.node.name+link.from_socket.identifier)):
  321. sock_name = link.from_socket.name; name_stub = sock_name
  322. used_names = list(tree_in_out.keys()); i=0
  323. while sock_name in used_names:
  324. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  325. unique_sockets_from[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  326. in_sock = in_sockets.get(sock_name)
  327. if not in_sock:
  328. in_sock = {}; in_sockets[sock_name] = in_sock
  329. in_sock["index"]=len(in_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  330. #
  331. in_sock["name"] = sock_name
  332. in_sock["identifier"] = sock_name
  333. in_sock["bl_idname"] = link.from_socket.bl_idname
  334. in_sock["is_output"] = True
  335. in_sock["is_multi_input"] = False # this is not something I can even set on tree interface items, and this code is not intended for making Schema
  336. in_sock["source"] = [link.from_socket.node.name,link.from_socket.identifier]
  337. sock_data={}
  338. sock_data["name"] = sock_name
  339. sock_data["item_type"] = "SOCKET"
  340. sock_data["default_closed"] = False
  341. # these two are the same thing, but I need both?
  342. sock_data["socket_type"] = link.from_socket.bl_idname
  343. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  344. sock_data["identifier"] = sock_name
  345. sock_data["in_out"]="INPUT"
  346. sock_data["index"]=in_sock["index"]
  347. tree_in_out[sock_name] = sock_data
  348. from_node_name=in_node.get("name")
  349. from_socket_id=in_sock["identifier"]
  350. from_outoput_index=in_sock["index"]
  351. from_socket_name=in_node.get("name")
  352. # parentheses matter here...
  353. elif (only_selected and not (link.from_node.select and link.to_node.select)):
  354. continue
  355. elif only_selected and not (link.from_node.select and link.to_node.select):
  356. continue # pass if both links are not selected
  357. links.append( (from_node_name,
  358. from_socket_id,
  359. to_node_name,
  360. to_socket_id,
  361. from_outoput_index,
  362. to_input_index,
  363. from_socket_name,
  364. to_socket_name) ) # it's a tuple
  365. if add_input_node or add_output_node:
  366. all_nodes_bounding_box=[Vector((float("inf"),float("inf"))), Vector((-float("inf"),-float("inf")))]
  367. for n in nodes.values():
  368. if n["location"][0] < all_nodes_bounding_box[0].x:
  369. all_nodes_bounding_box[0].x = n["location"][0]
  370. if n["location"][1] < all_nodes_bounding_box[0].y:
  371. all_nodes_bounding_box[0].y = n["location"][1]
  372. #
  373. if n["location"][0] > all_nodes_bounding_box[1].x:
  374. all_nodes_bounding_box[1].x = n["location"][0]
  375. if n["location"][1] > all_nodes_bounding_box[1].y:
  376. all_nodes_bounding_box[1].y = n["location"][1]
  377. if add_input_node:
  378. in_node["location"] = Vector((all_nodes_bounding_box[0].x-400, all_nodes_bounding_box[0].lerp(all_nodes_bounding_box[1], 0.5).y))
  379. nodes["MANTIS_AUTOGEN_GROUP_INPUT"]=in_node
  380. if add_output_node:
  381. out_node["location"] = Vector((all_nodes_bounding_box[1].x+400, all_nodes_bounding_box[0].lerp(all_nodes_bounding_box[1], 0.5).y))
  382. nodes["MANTIS_AUTOGEN_GROUP_OUTPUT"]=out_node
  383. export_data[tree.name] = (tree_info, tree_in_out, nodes, links,) # f_curves)
  384. import json
  385. if not write_file:
  386. return export_data # gross to have a different type of return value... but I don't care
  387. with open(path, "w") as file:
  388. print(wrapWhite("Writing mantis tree data to: "), wrapGreen(file.name))
  389. file.write( json.dumps(export_data, indent = 4) )
  390. # I'm gonna do this in a totally naive way, because this should already be sorted properly
  391. # for the sake of dependency satisfaction. So the current "tree" should be the "main" tree
  392. tree.filepath = path
  393. def do_import_from_file(filepath, context):
  394. import json
  395. all_trees = [n_tree for n_tree in bpy.data.node_groups if n_tree.bl_idname in ["MantisTree", "SchemaTree"]]
  396. for tree in all_trees:
  397. tree.is_exporting = True
  398. tree.do_live_update = False
  399. def do_cleanup(tree):
  400. tree.is_exporting = False
  401. tree.do_live_update = True
  402. tree.prevent_next_exec = True
  403. with open(filepath, 'r', encoding='utf-8') as f:
  404. data = json.load(f)
  405. do_import(data,context)
  406. for tree in all_trees:
  407. do_cleanup(tree)
  408. tree = bpy.data.node_groups[list(data.keys())[-1]]
  409. try:
  410. context.space_data.node_tree = tree
  411. except AttributeError: # not hovering over the Node Editor
  412. pass
  413. return {'FINISHED'}
  414. # otherwise:
  415. # repeat this because we left the with, this is bad and ugly but I don't care
  416. for tree in all_trees:
  417. do_cleanup(tree)
  418. return {'CANCELLED'}
  419. def do_import(data, context):
  420. trees = []
  421. tree_sock_id_maps = {}
  422. # First: init the interface of the node graph
  423. for tree_name, tree_data in data.items():
  424. tree_info = tree_data[0]
  425. tree_in_out = tree_data[1]
  426. # need to make a new tree; first, try to get it:
  427. tree = bpy.data.node_groups.get(tree_info["name"])
  428. if tree is None:
  429. tree = bpy.data.node_groups.new(tree_info["name"], tree_info["bl_idname"])
  430. tree.nodes.clear(); tree.links.clear(); tree.interface.clear()
  431. # this may be a bad bad thing to do without some kind of warning TODO TODO
  432. tree.is_executing = True
  433. tree.do_live_update = False
  434. trees.append(tree)
  435. tree_sock_id_map = {}
  436. tree_sock_id_maps[tree.name] = tree_sock_id_map
  437. interface_parent_me = {}
  438. # I need to guarantee that the interface items are in the right order.
  439. interface_sockets = [] # I'll just sort them afterwards so I hold them here.
  440. default_position=0 # We'll use this if the position attribute is not set when e.g. making groups.
  441. for s_name, s_props in tree_in_out.items():
  442. if s_props["item_type"] == 'SOCKET':
  443. if s_props["bl_socket_idname"] == "LayerMaskSocket":
  444. continue
  445. if (socket_type := s_props["bl_socket_idname"]) == "NodeSocketColor":
  446. socket_type = "VectorSocket"
  447. if bpy.app.version != (4,5,0):
  448. sock = tree.interface.new_socket(s_props["name"], in_out=s_props["in_out"], socket_type=socket_type)
  449. else: # blender 4.5.0 LTS, have to workaround a bug!
  450. from .versioning import workaround_4_5_0_interface_update
  451. sock = workaround_4_5_0_interface_update(tree=tree, name=s_props["name"], in_out=s_props["in_out"],
  452. sock_type=socket_type, parent_name=s_props.get("parent", ''))
  453. tree_sock_id_map[s_name] = sock.identifier
  454. if not (socket_position := s_props.get('position')):
  455. socket_position=default_position; default_position+=1
  456. interface_sockets.append( (sock, socket_position) )
  457. # TODO: set whatever properties are needed (default, etc)
  458. if panel := s_props.get("parent"): # this get is just to maintain compatibility with an older form of this script... and it is harmless
  459. interface_parent_me[sock] = (panel, s_props["position"])
  460. else: # it's a panel
  461. panel = tree.interface.new_panel(s_props["name"], description=s_props.get("description"), default_closed=s_props.get("default_closed"))
  462. for socket, (panel, index) in interface_parent_me.items():
  463. tree.interface.move_to_parent(
  464. socket,
  465. tree.interface.items_tree.get(panel),
  466. index,
  467. )
  468. # BUG this was screwing up the order of things
  469. # so I wan tot fix it and re-enable it
  470. if False:
  471. # Go BACK through and set the index/position now that all items exist.
  472. interface_sockets.sort(key=lambda a : a[1])
  473. for (socket, position) in interface_sockets:
  474. tree.interface.move(socket, position)
  475. # Now go and do nodes and links
  476. for tree_name, tree_data in data.items():
  477. print ("Importing sub-graph: %s with %s nodes" % (wrapGreen(tree_name), wrapPurple(len(tree_data[2]))) )
  478. tree_info = tree_data[0]
  479. nodes = tree_data[2]
  480. links = tree_data[3]
  481. parent_me = []
  482. tree = bpy.data.node_groups.get(tree_info["name"])
  483. tree.is_executing = True
  484. tree.do_live_update = False
  485. trees.append(tree)
  486. tree_sock_id_map=tree_sock_id_maps[tree.name]
  487. interface_parent_me = {}
  488. # from mantis.utilities import prRed, prWhite, prOrange, prGreen
  489. for name, propslist in nodes.items():
  490. bl_idname = propslist["bl_idname"]
  491. if bl_idname in NODES_REMOVED:
  492. prWhite(f"INFO: Ignoring import of node {name} of type {bl_idname}; it has been removed.")
  493. continue
  494. n = tree.nodes.new(bl_idname)
  495. if bl_idname in ["DeformerMorphTargetDeform"]:
  496. n.inputs.remove(n.inputs[-1]) # get rid of the wildcard
  497. if n.bl_idname in [ "SchemaArrayInput",
  498. "SchemaArrayInputGet",
  499. "SchemaArrayOutput",
  500. "SchemaConstInput",
  501. "SchemaConstOutput",
  502. "SchemaOutgoingConnection",
  503. "SchemaIncomingConnection",]:
  504. n.update()
  505. if sub_tree := propslist.get("node_tree"):
  506. n.node_tree = bpy.data.node_groups.get(sub_tree)
  507. from .base_definitions import node_group_update
  508. n.is_updating = True
  509. try:
  510. node_group_update(n, force = True)
  511. finally:
  512. n.is_updating=False
  513. sockets_removed = []
  514. for i, (s_id, s_val) in enumerate(propslist["sockets"].items()):
  515. for socket_removed in SOCKETS_REMOVED:
  516. if n.bl_idname == socket_removed[0] and s_id == socket_removed[1]:
  517. prWhite(f"INFO: Ignoring import of socket {s_id}; it has been removed.")
  518. sockets_removed.append(s_val["index"])
  519. sockets_removed.sort()
  520. continue
  521. try:
  522. if s_val["is_output"]: # for some reason it thinks the index is a string?
  523. if n.bl_idname in "MantisSchemaGroup":
  524. n.is_updating = True
  525. try:
  526. socket = n.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id)
  527. finally:
  528. n.is_updating=False
  529. else:
  530. socket = n.outputs[int(s_val["index"])]
  531. else:
  532. for removed_index in sockets_removed:
  533. if s_val["index"] > removed_index:
  534. s_val["index"]-=1
  535. if s_val["index"] >= len(n.inputs):
  536. if n.bl_idname in add_inputs_bl_idnames:
  537. socket = n.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  538. elif n.bl_idname in ["MantisSchemaGroup"]:
  539. n.is_updating = True
  540. try:
  541. socket = n.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  542. finally:
  543. n.is_updating=False
  544. elif n.bl_idname in ["NodeGroupOutput"]:
  545. pass # this is dealt with separately
  546. else:
  547. prWhite("Not found: ", n.name, s_val["name"], s_id)
  548. prRed("Index: ", s_val["index"], "Number of inputs", len(n.inputs))
  549. raise NotImplementedError(wrapRed(f"{n.bl_idname} needs to be handled in JSON load."))
  550. else: # most of the time
  551. socket = n.inputs[int(s_val["index"])]
  552. except IndexError:
  553. socket = fix_custom_parameter(n, propslist["sockets"][s_id])
  554. if socket is None:
  555. is_output = "output" if {s_val["is_output"]} else "input"
  556. prRed(s_val, type(s_val))
  557. raise RuntimeError(is_output, n.name, s_val["name"], s_id, len(n.inputs))
  558. for s_p, s_v in s_val.items():
  559. if s_p not in ["default_value"]:
  560. if s_p == "search_prop" and n.bl_idname == 'UtilityMetaRig':
  561. socket.node.armature= s_v
  562. socket.search_prop=bpy.data.objects.get(s_v)
  563. if s_p == "search_prop" and n.bl_idname in ['UtilityMatrixFromCurve', 'UtilityMatricesFromCurve']:
  564. socket.search_prop=bpy.data.objects.get(s_v)
  565. elif s_p == "bone" and socket.bl_idname == 'EnumMetaBoneSocket':
  566. socket.bone = s_v
  567. socket.node.pose_bone = s_v
  568. continue # not editable and NOT SAFE
  569. #
  570. if socket.bl_idname in ["BooleanThreeTupleSocket"]:
  571. value = bool(s_v[0]), bool(s_v[1]), bool(s_v[2]),
  572. s_v = value
  573. try:
  574. setattr(socket, s_p , s_v)
  575. except TypeError as e:
  576. prRed("Can't set socket due to type mismatch: ", n.name, socket.name, s_p, s_v)
  577. # raise e
  578. except ValueError as e:
  579. prRed("Can't set socket due to type mismatch: ", n.name, socket.name, s_p, s_v)
  580. # raise e
  581. except AttributeError as e:
  582. prWhite("Tried to write a read-only property, ignoring...")
  583. prWhite(f"{socket.node.name}[{socket.name}].{s_p} is read only, cannot set value to {s_v}")
  584. for p, v in propslist.items():
  585. if p in ["node_tree", "sockets", "warning_propagation", "socket_idname"]:
  586. continue
  587. # will throw AttributeError if read-only
  588. # will throw TypeError if wrong type...
  589. if n.bl_idname == "NodeFrame" and p in ["width, height, location"]:
  590. continue
  591. if version < (4,4,0) and p == 'location_absolute':
  592. continue
  593. if p == "parent" and v is not None:
  594. parent_me.append( (n.name, v) )
  595. v = None # for now) #TODO
  596. try:
  597. setattr(n, p, v)
  598. except Exception as e:
  599. print (p)
  600. raise e
  601. for l in links:
  602. id1 = l[1]
  603. id2 = l[3]
  604. #
  605. name1=l[6]
  606. name2=l[7]
  607. # if the from/to socket or node has been removed, continue
  608. from_node = tree.nodes.get(l[0])
  609. if not from_node:
  610. prWhite(f"INFO: cannot create link {l[0]}:{l[1]} --> {l[2]}:{l[3]}")
  611. continue
  612. if hasattr(from_node, "node_tree"): # now we have to map by name actually
  613. try:
  614. id1 = from_node.outputs[l[4]].identifier
  615. except IndexError:
  616. prRed ("Index incorrect")
  617. id1 = None
  618. elif from_node.bl_idname in ["NodeGroupInput"]:
  619. id1 = tree_sock_id_map.get(l[1])
  620. if id1 is None:
  621. prRed(l[1])
  622. # prOrange (l[1], id1)
  623. elif from_node.bl_idname in ["SchemaArrayInput", "SchemaConstInput", "SchemaIncomingConnection"]:
  624. # try the index instead
  625. id1 = from_node.outputs[l[4]].identifier
  626. for from_sock in from_node.outputs:
  627. if from_sock.identifier == id1: break
  628. else: # we can raise a runtime error here actually
  629. from_sock = None
  630. to_node = tree.nodes[l[2]]
  631. if hasattr(to_node, "node_tree"):
  632. try:
  633. id2 = to_node.inputs[l[5]].identifier
  634. except IndexError:
  635. prRed ("Index incorrect")
  636. id2 = None
  637. elif to_node.bl_idname in ["NodeGroupOutput"]:
  638. id2 = tree_sock_id_map.get(l[3])
  639. elif to_node.bl_idname in ["SchemaArrayOutput", "SchemaConstOutput", "SchemaOutgoingConnection"]:
  640. # try the index instead
  641. id2 = to_node.inputs[l[5]].identifier
  642. for to_sock in to_node.inputs:
  643. if to_sock.identifier == id2: break
  644. else:
  645. to_sock = None
  646. try:
  647. link = tree.links.new(from_sock, to_sock)
  648. except TypeError:
  649. if ((id1 is not None) and ("Layer Mask" in id1)) or ((id2 is not None) and ("Layer Mask" in id2)):
  650. pass
  651. else:
  652. prWhite(f"looking for... {name1}:{id1}, {name2}:{id2}")
  653. prRed (f"Failed: {l[0]}:{l[1]} --> {l[2]}:{l[3]}")
  654. prRed (f" got node: {from_node.name}, {to_node.name}")
  655. prRed (f" got socket: {from_sock}, {to_sock}")
  656. prOrange(to_node.inputs.keys())
  657. if from_sock is None:
  658. prOrange ("Candidates...")
  659. for out in from_node.outputs:
  660. prOrange(" %s, id=%s" % (out.name, out.identifier))
  661. for k, v in tree_sock_id_map.items():
  662. print (wrapOrange(k), wrapPurple(v))
  663. if to_sock is None:
  664. prOrange ("Candidates...")
  665. for inp in to_node.inputs:
  666. prOrange(" %s, id=%s" % (inp.name, inp.identifier))
  667. for k, v in tree_sock_id_map.items():
  668. print (wrapOrange(k), wrapPurple(v))
  669. raise RuntimeError
  670. # if at this point it doesn't work... we need to fix
  671. for name, p in parent_me:
  672. if (n := tree.nodes.get(name)) and (p := tree.nodes.get(p)):
  673. n.parent = p
  674. # otherwise the frame node is missing because it was not included in the data e.g. when grouping nodes.
  675. tree.is_executing = False
  676. tree.do_live_update = True
  677. import bpy
  678. from bpy_extras.io_utils import ImportHelper, ExportHelper
  679. from bpy.props import StringProperty, BoolProperty, EnumProperty
  680. from bpy.types import Operator
  681. # Save As
  682. class MantisExportNodeTreeSaveAs(Operator, ExportHelper):
  683. """Export a Mantis Node Tree by filename."""
  684. bl_idname = "mantis.export_save_as"
  685. bl_label = "Export Mantis Tree as ...(JSON)"
  686. # ExportHelper mix-in class uses this.
  687. filename_ext = ".rig"
  688. filter_glob: StringProperty(
  689. default="*.rig",
  690. options={'HIDDEN'},
  691. maxlen=255, # Max internal buffer length, longer would be clamped.
  692. )
  693. @classmethod
  694. def poll(cls, context):
  695. return hasattr(context.space_data, 'path')
  696. def execute(self, context):
  697. # we need to get the dependent trees from self.tree...
  698. # there is no self.tree
  699. # how do I choose a tree?
  700. base_tree=context.space_data.path[-1].node_tree
  701. from .utilities import all_trees_in_tree
  702. trees = all_trees_in_tree(base_tree)[::-1]
  703. prGreen("Exporting node graph with dependencies...")
  704. for t in trees:
  705. prGreen ("Node graph: \"%s\"" % (t.name))
  706. base_tree.is_exporting = True
  707. export_to_json(trees, self.filepath)
  708. base_tree.is_exporting = False
  709. base_tree.prevent_next_exec = True
  710. return {'FINISHED'}
  711. # Save
  712. class MantisExportNodeTreeSave(Operator):
  713. """Save a Mantis Node Tree to disk."""
  714. bl_idname = "mantis.export_save"
  715. bl_label = "Export Mantis Tree (JSON)"
  716. @classmethod
  717. def poll(cls, context):
  718. return hasattr(context.space_data, 'path')
  719. def execute(self, context):
  720. base_tree=context.space_data.path[-1].node_tree
  721. from .utilities import all_trees_in_tree
  722. trees = all_trees_in_tree(base_tree)[::-1]
  723. prGreen("Exporting node graph with dependencies...")
  724. for t in trees:
  725. prGreen ("Node graph: \"%s\"" % (t.name))
  726. base_tree.is_exporting = True
  727. export_to_json(trees, self.filepath)
  728. base_tree.is_exporting = False
  729. base_tree.prevent_next_exec = True
  730. return {'FINISHED'}
  731. # Save Choose:
  732. class MantisExportNodeTree(Operator):
  733. """Save a Mantis Node Tree to disk."""
  734. bl_idname = "mantis.export_save_choose"
  735. bl_label = "Export Mantis Tree (JSON)"
  736. @classmethod
  737. def poll(cls, context):
  738. return hasattr(context.space_data, 'path')
  739. def execute(self, context):
  740. base_tree=context.space_data.path[-1].node_tree
  741. if base_tree.filepath:
  742. prRed(base_tree.filepath)
  743. return bpy.ops.mantis.export_save()
  744. else:
  745. return bpy.ops.mantis.export_save_as('INVOKE_DEFAULT')
  746. # here is what needs to be done...
  747. # - modify this to work with a sort of parsed-tree instead (sort of)
  748. # - this needs to treat each sub-graph on its own
  749. # - is this a problem? do I need to reconsider how I treat the graph data in mantis?
  750. # - I should learn functional programming / currying
  751. # - then the parsed-tree this builds must be executed as Blender nodes
  752. # - I think... this is not important right now. not yet.
  753. # - KEEP IT SIMPLE, STUPID
  754. class MantisImportNodeTree(Operator, ImportHelper):
  755. """Import a Mantis Node Tree."""
  756. bl_idname = "mantis.import_tree"
  757. bl_label = "Import Mantis Tree (JSON)"
  758. # ImportHelper mixin class uses this
  759. filename_ext = ".rig"
  760. filter_glob : StringProperty(
  761. default="*.rig",
  762. options={'HIDDEN'},
  763. maxlen=255, # Max internal buffer length, longer would be clamped.
  764. )
  765. def execute(self, context):
  766. return do_import_from_file(self.filepath, context)
  767. # this is useful:
  768. # https://blender.stackexchange.com/questions/73286/how-to-call-a-confirmation-dialog-box
  769. # class MantisReloadConfirmMenu(bpy.types.Panel):
  770. # bl_label = "Confirm?"
  771. # bl_idname = "OBJECT_MT_mantis_reload_confirm"
  772. # def draw(self, context):
  773. # layout = self.layout
  774. # layout.operator("mantis.reload_tree")
  775. class MantisReloadNodeTree(Operator):
  776. # """Import a Mantis Node Tree."""
  777. # bl_idname = "mantis.reload_tree"
  778. # bl_label = "Import Mantis Tree"
  779. """Reload Mantis Tree"""
  780. bl_idname = "mantis.reload_tree"
  781. bl_label = "Confirm reload tree?"
  782. bl_options = {'REGISTER', 'INTERNAL'}
  783. @classmethod
  784. def poll(cls, context):
  785. if hasattr(context.space_data, 'path'):
  786. return True
  787. return False
  788. def invoke(self, context, event):
  789. return context.window_manager.invoke_confirm(self, event)
  790. def execute(self, context):
  791. base_tree=context.space_data.path[-1].node_tree
  792. if not base_tree.filepath:
  793. self.report({'ERROR'}, "Tree has not been saved - so it cannot be reloaded.")
  794. return {'CANCELLED'}
  795. self.report({'INFO'}, "reloading tree")
  796. return do_import_from_file(base_tree.filepath, context)
  797. # todo:
  798. # - export metarig and option to import it
  799. # - same with controls
  800. # - it would be nice to have a library of these that can be imported alongside the mantis graph