i_o.py 39 KB

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