i_o.py 40 KB

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