i_o.py 38 KB

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