i_o.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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, Matrix
  7. NODES_REMOVED=["xFormRootNode"]
  8. # Node bl_idname, # Socket Name
  9. SOCKETS_REMOVED=[("UtilityDriverVariable", "Transform Channel"),
  10. ("xFormRootNode","World Out"),
  11. ("UtilitySwitch","xForm"),
  12. ("LinkDrivenParameter", "Enable")]
  13. # Node Class #Prior bl_idname # prior name # new bl_idname # new name, # Multi
  14. # Debugging values.
  15. print_read_only_warning = False
  16. print_link_failure = False
  17. # ignore these because they are either unrelated python stuff or useless or borked
  18. prop_ignore = [ "__dict__", "__doc__", "__module__", "__weakref__",# "name",
  19. "bl_height_default", "bl_height_max", "bl_height_min",
  20. "bl_icon", "bl_rna", "bl_static_type", "bl_description",
  21. "bl_width_default", "bl_width_max", "bl_width_min",
  22. "__annotations__", "original", "rna_type", "view_center",
  23. "links", "nodes", "internal_links", "inputs", "outputs",
  24. "__slots__", "dimensions", "type", "interface",
  25. "library_weak_reference", "parsed_tree", "node_tree_updater",
  26. "asset_data", "preview", # blender asset stuff
  27. "object_reference", # this one is here to hold on to widgets when appending
  28. "color_tag" , # added in blender 4.4, not used by Mantis, readonly.
  29. # more blender properties...
  30. "bl_use_group_interface", "default_group_node_width", "id_type",
  31. # blender runtime stuff
  32. "animation_data", "description", "grease_pencil", "is_editable",
  33. "is_embedded_data", "is_evaluated", "is_library_indirect", "is_missing",
  34. "is_runtime_data", "library", "name_full", "override_library",
  35. "session_uid", "tag", "use_extra_user", "use_fake_user", "users",
  36. # some Mantis stuff I don't need to save
  37. "do_live_update", "is_executing", "is_exporting", "hash", "filepath",
  38. "prevent_next_exec", "execution_id", "num_links", "tree_valid",
  39. "interface_helper",
  40. # node stuff
  41. "mantis_node_class_name", "color", "height", "initialized", "select",
  42. "show_options", "show_preview", "show_texture", "use_custom_color",
  43. "warning_propagation",
  44. # these are in Bone
  45. "socket_count", "display_bb_settings", "display_def_settings",
  46. "display_ik_settings", "display_vp_settings",
  47. ]
  48. # don't ignore: "bl_idname", "bl_label",
  49. # ignore the name, it's the dict - key for the node props
  50. # no that's stupid don't ignore the name good grief
  51. # I am doing this because these are interactions with other addons that cause problems and probably don't exist for any given user
  52. prop_ignore.extend(['keymesh'])
  53. # trees
  54. prop_ignore_tree = prop_ignore.copy()
  55. prop_ignore_tree.extend(["bl_label", "name"])
  56. prop_ignore_interface = prop_ignore.copy()
  57. # Geometry Nodes stuff that Mantis doesn't use
  58. prop_ignore_interface.extend( [ "attribute_domain",
  59. "default_attribute_name",
  60. "default_input",
  61. "force_non_field",
  62. "hide_in_modifier",
  63. "hide_value",
  64. # no idea what this is, also don't care
  65. "is_inspect_output",
  66. "is_panel_toggle",
  67. "layer_selection_field",
  68. "structure_type", ] )
  69. from bpy.app import version
  70. if version >= (4,5,0):
  71. SOCKETS_REMOVED.append( ("LinkSplineIK", "Use Original Scale"))
  72. add_inputs_bl_idnames = [
  73. "UtilityDriver", "UtilityFCurve", "DeformerMorphTargetDeform",
  74. "LinkArmature",
  75. "xFormBoneNode"
  76. # for custom properties, right?
  77. # For a long time this wasn't in here and I guess there weren't problems
  78. # I really don't know if adding it here is right...
  79. ]
  80. # this works but it is really ugly and probably quite inneficient
  81. # TODO: make hotkeys for export and import and reload from file
  82. # we need to give the tree a filepath attribute and update it on saving
  83. # then we need to use the filepath attribute to load from
  84. # finally we need to use a few operators to choose whether to open a menu or not
  85. # and we need a message to display on save/load so that the user knows it is happening
  86. # TODO:
  87. # Additionally export MetaRig and Curve and other referenced data
  88. # Meshes can be exported as .obj and imported via GN
  89. def TellClasses():
  90. return [ MantisExportNodeTreeSaveAs, MantisExportNodeTreeSave, MantisExportNodeTree, MantisImportNodeTree, MantisReloadNodeTree]
  91. # https://stackoverflow.com/questions/42033142/is-there-an-easy-way-to-check-if-an-object-is-json-serializable-in-python - thanks!
  92. def is_jsonable(x):
  93. import json
  94. try:
  95. json.dumps(x)
  96. return True
  97. except (TypeError, OverflowError):
  98. return False
  99. # https://stackoverflow.com/questions/295135/turn-a-stritree-into-a-valid-filename - thank you user "Sophie Gage"
  100. def remove_special_characters(name):
  101. import re; return re.sub('[^\w_.)( -]', '', name)# re = regular expressions
  102. def fix_custom_parameter(n, property_definition, ):
  103. if n.bl_idname in ['xFormNullNode', 'xFormBoneNode', 'xFormArmatureNode', 'xFormGeometryObjectNode',]:
  104. prop_name = property_definition["name"]
  105. prop_type = property_definition["bl_idname"]
  106. if prop_type in ['ParameterBoolSocket', 'ParameterIntSocket', 'ParameterFloatSocket', 'ParameterVectorSocket' ]:
  107. # is it good to make both of them?
  108. input = n.inputs.new( prop_type, prop_name)
  109. output = n.outputs.new( prop_type, prop_name)
  110. if property_definition["is_output"] == True:
  111. return output
  112. return input
  113. elif n.bl_idname in ['LinkArmature']:
  114. prop_name = property_definition["name"]
  115. prop_type = property_definition["bl_idname"]
  116. input = n.inputs.new( prop_type, prop_name)
  117. return input
  118. return None
  119. # def scan_tree_for_objects(base_tree, current_tree):
  120. # # goal: find all referenced armature and curve objects
  121. # # return [set(armatures), set(curves)]
  122. # armatures = set()
  123. # curves = set()
  124. # for node in base_tree.parsed_tree.values():
  125. # from .utilities import get_node_prototype
  126. # if node.ui_signature is None:
  127. # continue
  128. # ui_node = get_node_prototype(node.ui_signature, node.base_tree)
  129. # if ui_node is None or ui_node.id_data != current_tree:
  130. # continue
  131. # if hasattr(node, "bGetObject"):
  132. # ob = node.bGetObject()
  133. # print(node, ob)
  134. # if ob is None:
  135. # continue
  136. # if not hasattr(node, "type"):
  137. # continue
  138. # if ob.type == 'ARMATURE':
  139. # armatures.add(ob)
  140. # if ob.type == 'CURVE':
  141. # curves.add(ob)
  142. # return (armatures, curves)
  143. # Currently this isn't very robust and doesn't seek backwards
  144. # to see if a dependency is created by node connections.
  145. # TODO it remains to be seen if that is even a desirable behaviour.
  146. def scan_tree_for_objects(base_tree, current_tree):
  147. from bpy import data
  148. armatures, curves = set(), set()
  149. for node in current_tree.nodes:
  150. match node.bl_idname:
  151. case "UtilityMetaRig":
  152. if node.inputs[0].is_linked:
  153. continue
  154. if (armature := node.inputs[0].search_prop) is not None:
  155. armatures.add(armature)
  156. case "InputExistingGeometryObjectNode":
  157. if node.inputs["Name"].is_linked:
  158. continue
  159. ob_name = node.inputs["Name"].default_value
  160. if ob := data.objects.get(ob_name):
  161. if ob.type == "ARMATURE":
  162. armatures.add(ob)
  163. elif ob.type == "CURVE":
  164. curves.add(ob)
  165. case "xFormArmatureNode":
  166. if node.inputs["Name"].is_linked:
  167. continue
  168. armature_name = node.inputs["Name"].default_value
  169. armature = data.objects.get(armature_name)
  170. if armature:
  171. armatures.add(armature)
  172. case "xFormGeometryObjectNode":
  173. if node.inputs["Name"].is_linked:
  174. continue
  175. ob_name = node.inputs["Name"].default_value
  176. if ob := data.objects.get(ob_name):
  177. if ob.type == "ARMATURE":
  178. armatures.add(ob)
  179. elif ob.type == "CURVE":
  180. curves.add(ob)
  181. for input in node.inputs:
  182. if input.bl_idname in ["EnumCurveSocket"]:
  183. if input.search_prop is not None:
  184. curves.add(input.search_prop)
  185. # NOW check the parsed_tree and see if it is possible to find any other
  186. # objects referred to/provided by the tree
  187. return (curves, armatures )
  188. from dataclasses import dataclass, field, asdict
  189. # some basic classes to define curve point types
  190. @dataclass
  191. class crv_pnt_data():
  192. co : tuple[float, float, float] = field(default=(0,0,0,))
  193. handle_left : tuple[float, float, float] = field(default=(0,0,0,))
  194. handle_right : tuple[float, float, float] = field(default=(0,0,0,))
  195. handle_left_type : str = field(default="ALIGNED")
  196. handle_right_type : str = field(default="ALIGNED")
  197. radius : float = field(default=0.0)
  198. tilt : float = field(default=0.0)
  199. w : float = field(default=0.0)
  200. @dataclass
  201. class spline_data():
  202. type : str = field(default='POLY')
  203. points : list[dict] = field(default_factory=[])
  204. order_u : int = field(default=4)
  205. radius_interpolation : str = field(default="LINEAR")
  206. tilt_interpolation : str = field(default="LINEAR")
  207. resolution_u : int = field(default=12)
  208. use_bezier_u : bool = field(default=False)
  209. use_cyclic_u : bool = field(default=False)
  210. use_endpoint_u : bool = field(default=False)
  211. index : int = field(default=0)
  212. object_name : str = field(default='Curve')
  213. def get_curve_for_pack(object):
  214. splines = []
  215. for i, spline in enumerate(object.data.splines):
  216. points = []
  217. if spline.type == 'BEZIER':
  218. for point in spline.bezier_points:
  219. export_pnt = crv_pnt_data(
  220. co = tuple(point.co),
  221. radius = point.radius,
  222. tilt = point.tilt,
  223. handle_left = tuple(point.handle_left),
  224. handle_right = tuple(point.handle_right),
  225. handle_left_type = point.handle_left_type,
  226. handle_right_type = point.handle_right_type,
  227. )
  228. points.append(asdict(export_pnt))
  229. else:
  230. for point in spline.points:
  231. export_pnt = crv_pnt_data(
  232. co = point.co[:3], # exclude the w value
  233. radius = point.radius,
  234. tilt = point.tilt,
  235. w = point.co[3],
  236. )
  237. points.append(export_pnt)
  238. export_spl = spline_data(
  239. type = spline.type,
  240. points = points,
  241. order_u = spline.order_u,
  242. radius_interpolation = spline.radius_interpolation,
  243. tilt_interpolation = spline.tilt_interpolation,
  244. resolution_u = spline.resolution_u,
  245. use_bezier_u = spline.use_bezier_u,
  246. use_cyclic_u = spline.use_cyclic_u,
  247. use_endpoint_u = spline.use_endpoint_u,
  248. index = i,
  249. object_name = object.name,)
  250. splines.append(asdict(export_spl))
  251. return splines
  252. def matrix_as_tuple(matrix):
  253. return ( matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
  254. matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
  255. matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3],
  256. matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3], )
  257. @dataclass
  258. class metabone_data:
  259. object_name : str = field(default='')
  260. name : str = field(default=''),
  261. type : str = field(default='BONE'),
  262. matrix : tuple[float] = field(default=()),
  263. parent : str = field(default=''),
  264. length : float = field(default=-1.0),
  265. children : list[str] = field(default_factory=[]),
  266. # keep it really simple for now. I'll add BBone and envelope later on
  267. # when I make them accessible from the meta-rig
  268. def get_armature_for_pack(object):
  269. metarig_data = {}
  270. armature_data = metabone_data( object_name = object.name,
  271. name=object.name, type='ARMATURE',
  272. matrix=matrix_as_tuple(object.matrix_world),
  273. parent="", # NOTE that this is not always a fair assumption!
  274. length = -1.0, children =[],)
  275. metarig_data[object.name] = asdict(armature_data)
  276. metarig_data["MANTIS_RESERVED"] = asdict(armature_data) # just in case a bone is named the same as the armature
  277. for bone in object.data.bones:
  278. parent_name = ''
  279. if bone.parent is None:
  280. armature_data.children.append(bone.name)
  281. else:
  282. parent_name=bone.parent.name
  283. children=[]
  284. for c in bone.children:
  285. children.append(c.name)
  286. bone_data = metabone_data( object_name = object.name,
  287. name=bone.name, type='BONE',
  288. matrix=matrix_as_tuple(bone.matrix_local),
  289. parent=parent_name, length = bone.length, children = children,
  290. )
  291. metarig_data[bone.name]=asdict(bone_data)
  292. return metarig_data
  293. def get_socket_data(socket, ignore_if_default=False):
  294. # TODO: don't get stuff in the socket templates
  295. # PROBLEM: I don't have easy access to this from the ui class (or mantis class)
  296. socket_data = {}
  297. socket_data["name"] = socket.name
  298. socket_data["bl_idname"] = socket.bl_idname
  299. socket_data["is_output"] = socket.is_output
  300. socket_data["is_multi_input"] = socket.is_multi_input
  301. # here is where we'll handle a socket_data'socket special data
  302. if socket.bl_idname == "EnumMetaBoneSocket":
  303. socket_data["bone"] = socket.bone
  304. if socket.bl_idname in ["EnumMetaBoneSocket", "EnumMetaRigSocket", "EnumCurveSocket"]:
  305. if sp := socket.get("search_prop"): # may be None
  306. socket_data["search_prop"] = sp.name # this is an object.
  307. #
  308. if hasattr(socket, "default_value"):
  309. value = socket.default_value
  310. else:
  311. value = None
  312. return socket_data # we don't need to store any more.
  313. if not is_jsonable(value): # FIRST try and make a tuple out of it because JSON doesn't like mutables
  314. value = tuple(value)
  315. if not is_jsonable(value): # now see if it worked and crash out if it didn't
  316. raise RuntimeError(f"Error serializing data in {socket.node.name}::{socket.name} for value of type {type(value)}")
  317. socket_data["default_value"] = value
  318. # TODO TODO implement "ignore if default" feature here
  319. # at this point we can get the custom parameter ui hints if we want
  320. if not socket.is_output:
  321. # try and get this data
  322. if value := getattr(socket,'min', None):
  323. socket_data["min"] = value
  324. if value := getattr(socket,'max', None):
  325. socket_data["max"] = value
  326. if value := getattr(socket,'soft_min', None):
  327. socket_data["soft_min"] = value
  328. if value := getattr(socket,'soft_max', None):
  329. socket_data["soft_max"] = value
  330. if value := getattr(socket,'description', None):
  331. socket_data["description"] = value
  332. return socket_data
  333. #
  334. def get_node_data(ui_node):
  335. # if this is a node-group, force it to update its interface, because it may be messed up.
  336. # can remove this HACK when I have stronger guarentees about node-group's keeping the interface
  337. from .base_definitions import node_group_update
  338. if hasattr(ui_node, "node_tree"):
  339. ui_node.is_updating = True
  340. try: # HERE BE DANGER
  341. node_group_update(ui_node, force=True)
  342. finally: # ensure this line is run even if there is an error
  343. ui_node.is_updating = False
  344. node_props, inputs, outputs = {}, {}, {}
  345. for propname in dir(ui_node):
  346. value = getattr(ui_node, propname)
  347. if propname in ['fake_fcurve_ob']:
  348. value=value.name
  349. if (propname in prop_ignore) or ( callable(value) ):
  350. continue
  351. if value.__class__.__name__ in ["Vector", "Color"]:
  352. value = tuple(value)
  353. if isinstance(value, bpy.types.NodeTree):
  354. value = value.name
  355. if isinstance(value, bpy.types.bpy_prop_array):
  356. value = tuple(value)
  357. if propname == "parent" and value:
  358. value = value.name
  359. if not is_jsonable(value):
  360. raise RuntimeError(f"Could not export... {ui_node.name}, {propname}, {type(value)}")
  361. if value is None:
  362. continue
  363. node_props[propname] = value
  364. # so we have to accumulate the parent location because the location is not absolute
  365. if propname == "location" and ui_node.parent is not None:
  366. location_acc = Vector((0,0))
  367. parent = ui_node.parent
  368. while (parent):
  369. location_acc += parent.location
  370. parent = parent.parent
  371. location_acc += getattr(ui_node, propname)
  372. node_props[propname] = tuple(location_acc)
  373. # this works!
  374. if ui_node.bl_idname in ['RerouteNode']:
  375. return node_props # we don't need to get the socket information.
  376. for i, ui_socket in enumerate(ui_node.inputs):
  377. socket = get_socket_data(ui_socket)
  378. socket["index"]=i
  379. inputs[ui_socket.identifier] = socket
  380. for i, ui_socket in enumerate(ui_node.outputs):
  381. socket = get_socket_data(ui_socket)
  382. socket["index"]=i
  383. outputs[ui_socket.identifier] = socket
  384. node_props["inputs"] = inputs
  385. node_props["outputs"] = outputs
  386. return node_props
  387. def get_tree_data(tree):
  388. tree_info = {}
  389. for propname in dir(tree):
  390. # if getattr(tree, propname):
  391. # pass
  392. if (propname in prop_ignore_tree) or ( callable(getattr(tree, propname)) ):
  393. continue
  394. v = getattr(tree, propname)
  395. if isinstance(getattr(tree, propname), bpy.types.bpy_prop_array):
  396. v = tuple(getattr(tree, propname))
  397. if not is_jsonable( v ):
  398. raise RuntimeError(f"Not JSON-able: {propname}, type: {type(v)}")
  399. tree_info[propname] = v
  400. tree_info["name"]=tree.name
  401. return tree_info
  402. def get_interface_data(tree, tree_in_out):
  403. for sock in tree.interface.items_tree:
  404. sock_data={}
  405. if sock.item_type == 'PANEL':
  406. sock_data["name"] = sock.name
  407. sock_data["item_type"] = sock.item_type
  408. sock_data["description"] = sock.description
  409. sock_data["default_closed"] = sock.default_closed
  410. tree_in_out[sock.name] = sock_data
  411. # if it is a socket....
  412. else:
  413. # we need to get the socket class from the bl_idname
  414. bl_socket_idname = sock.bl_socket_idname
  415. # try and import it
  416. from . import socket_definitions
  417. # WANT an attribute error if this fails.
  418. socket_class = getattr(socket_definitions, bl_socket_idname)
  419. sock_parent = None
  420. if sock.parent:
  421. sock_parent = sock.parent.name
  422. for propname in dir(sock):
  423. if propname in prop_ignore_interface:
  424. continue
  425. if (propname == "parent"):
  426. sock_data[propname] = sock_parent
  427. continue
  428. v = getattr(sock, propname)
  429. if (propname in prop_ignore) or ( callable(v) ):
  430. continue
  431. if isinstance(getattr(sock, propname), bpy.types.bpy_prop_array):
  432. v = tuple(getattr(sock, propname))
  433. if not is_jsonable( v ):
  434. raise RuntimeError(f"{propname}, {type(v)}")
  435. sock_data[propname] = v
  436. # this is a property. pain.
  437. sock_data["socket_type"] = socket_class.interface_type.fget(socket_class)
  438. tree_in_out[sock.identifier] = sock_data
  439. def export_to_json(trees, base_tree=None, path="", write_file=True, only_selected=False, ):
  440. export_data = {}
  441. for tree in trees:
  442. current_tree_is_base_tree = False
  443. if tree is trees[-1]:
  444. current_tree_is_base_tree = True
  445. tree_info, tree_in_out = {}, {}
  446. tree_info = get_tree_data(tree)
  447. curves, metarig_data = {}, {}
  448. embed_metarigs=True
  449. if base_tree and embed_metarigs:
  450. curves_in_tree, metarigs_in_tree = scan_tree_for_objects(base_tree, tree)
  451. for crv in curves_in_tree:
  452. curves[crv.name] = get_curve_for_pack(crv)
  453. for mr in metarigs_in_tree:
  454. metarig_data[mr.name] = get_armature_for_pack(mr)
  455. # if only_selected:
  456. # # all in/out links, relative to the selection, should be marked and used to initialize tree properties
  457. if not only_selected: # we'll handle this later with the links
  458. for sock in tree.interface.items_tree:
  459. get_interface_data(tree, tree_in_out) # it concerns me that this one modifies
  460. # the collection instead of getting the data and returning it. TODO refactor this
  461. nodes = {}
  462. for node in tree.nodes:
  463. if only_selected and node.select == False:
  464. continue
  465. nodes[node.name] = get_node_data(node)
  466. links = []
  467. in_sockets, out_sockets = {}, {}
  468. unique_sockets_from, unique_sockets_to = {}, {}
  469. in_node = {"name":"MANTIS_AUTOGEN_GROUP_INPUT", "bl_idname":"NodeGroupInput", "inputs":in_sockets}
  470. out_node = {"name":"MANTIS_AUTOGEN_GROUP_OUTPUT", "bl_idname":"NodeGroupOutput", "outputs":out_sockets}
  471. add_input_node, add_output_node = False, False
  472. for link in tree.links:
  473. from_node_name, from_socket_id = link.from_node.name, link.from_socket.identifier
  474. to_node_name, to_socket_id = link.to_node.name, link.to_socket.identifier
  475. from_socket_name, to_socket_name = link.from_socket.name, link.to_socket.name
  476. # get the indices of the sockets to be absolutely sure
  477. for from_outoput_index, outp in enumerate(link.from_node.outputs):
  478. # for some reason, 'is' does not return True no matter what...
  479. # so we are gonn compare the memory address directly, this is stupid
  480. if (outp.as_pointer() == link.from_socket.as_pointer()): break
  481. else:
  482. problem=link.from_node.name + "::" + link.from_socket.name
  483. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  484. for to_input_index, inp in enumerate(link.to_node.inputs):
  485. if (inp.as_pointer() == link.to_socket.as_pointer()): break
  486. else:
  487. problem = link.to_node.name + "::" + link.to_socket.name
  488. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  489. if current_tree_is_base_tree:
  490. if (only_selected and link.from_node.select) and (not link.to_node.select):
  491. # handle an output in the tree
  492. add_output_node=True
  493. if not (sock_name := unique_sockets_to.get(link.from_socket.node.name+link.from_socket.identifier)):
  494. sock_name = link.to_socket.name; name_stub = sock_name
  495. used_names = list(tree_in_out.keys()); i=0
  496. while sock_name in used_names:
  497. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  498. unique_sockets_to[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  499. out_sock = out_sockets.get(sock_name)
  500. if not out_sock:
  501. out_sock = {}; out_sockets[sock_name] = out_sock
  502. out_sock["index"]=len(out_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  503. # what in the bad word is happening here?
  504. # why?
  505. # why no de-duplication?
  506. # what was I thinking?
  507. # TODO REFACTOR THIS SOON
  508. out_sock["name"] = sock_name
  509. out_sock["identifier"] = sock_name
  510. out_sock["bl_idname"] = link.to_socket.bl_idname
  511. out_sock["is_output"] = False
  512. out_sock["source"]=[link.to_socket.node.name,link.to_socket.identifier]
  513. 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
  514. sock_data={}
  515. sock_data["name"] = sock_name
  516. sock_data["item_type"] = "SOCKET"
  517. sock_data["default_closed"] = False
  518. # record the actual bl_idname and the proper interface type.
  519. sock_data["socket_type"] = link.from_socket.interface_type
  520. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  521. sock_data["identifier"] = sock_name
  522. sock_data["in_out"]="OUTPUT"
  523. sock_data["index"]=out_sock["index"]
  524. tree_in_out[sock_name] = sock_data
  525. to_node_name=out_node["name"]
  526. to_socket_id=out_sock["identifier"]
  527. to_input_index=out_sock["index"]
  528. to_socket_name=out_sock["name"]
  529. elif (only_selected and (not link.from_node.select)) and link.to_node.select:
  530. add_input_node=True
  531. # we need to get a unique name for this
  532. # use the Tree IN/Out because we are dealing with Group in/out
  533. if not (sock_name := unique_sockets_from.get(link.from_socket.node.name+link.from_socket.identifier)):
  534. sock_name = link.from_socket.name; name_stub = sock_name
  535. used_names = list(tree_in_out.keys()); i=0
  536. while sock_name in used_names:
  537. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  538. unique_sockets_from[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  539. in_sock = in_sockets.get(sock_name)
  540. if not in_sock:
  541. in_sock = {}; in_sockets[sock_name] = in_sock
  542. in_sock["index"]=len(in_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  543. #
  544. in_sock["name"] = sock_name
  545. in_sock["identifier"] = sock_name
  546. in_sock["bl_idname"] = link.from_socket.bl_idname
  547. in_sock["is_output"] = True
  548. 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
  549. in_sock["source"] = [link.from_socket.node.name,link.from_socket.identifier]
  550. sock_data={}
  551. sock_data["name"] = sock_name
  552. sock_data["item_type"] = "SOCKET"
  553. sock_data["default_closed"] = False
  554. # record the actual bl_idname and the proper interface type.
  555. sock_data["socket_type"] = link.from_socket.interface_type
  556. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  557. sock_data["identifier"] = sock_name
  558. sock_data["in_out"]="INPUT"
  559. sock_data["index"]=in_sock["index"]
  560. tree_in_out[sock_name] = sock_data
  561. from_node_name=in_node.get("name")
  562. from_socket_id=in_sock["identifier"]
  563. from_outoput_index=in_sock["index"]
  564. from_socket_name=in_node.get("name")
  565. # parentheses matter here...
  566. elif (only_selected and not (link.from_node.select and link.to_node.select)):
  567. continue
  568. elif only_selected and not (link.from_node.select and link.to_node.select):
  569. continue # pass if both links are not selected
  570. links.append( (from_node_name,
  571. from_socket_id,
  572. to_node_name,
  573. to_socket_id,
  574. from_outoput_index,
  575. to_input_index,
  576. from_socket_name,
  577. to_socket_name) ) # it's a tuple
  578. if add_input_node or add_output_node:
  579. all_nodes_bounding_box=[Vector((float("inf"),float("inf"))), Vector((-float("inf"),-float("inf")))]
  580. for n in nodes.values():
  581. if n["location"][0] < all_nodes_bounding_box[0].x:
  582. all_nodes_bounding_box[0].x = n["location"][0]
  583. if n["location"][1] < all_nodes_bounding_box[0].y:
  584. all_nodes_bounding_box[0].y = n["location"][1]
  585. #
  586. if n["location"][0] > all_nodes_bounding_box[1].x:
  587. all_nodes_bounding_box[1].x = n["location"][0]
  588. if n["location"][1] > all_nodes_bounding_box[1].y:
  589. all_nodes_bounding_box[1].y = n["location"][1]
  590. if add_input_node:
  591. 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))
  592. nodes["MANTIS_AUTOGEN_GROUP_INPUT"]=in_node
  593. if add_output_node:
  594. 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))
  595. nodes["MANTIS_AUTOGEN_GROUP_OUTPUT"]=out_node
  596. export_data[tree.name] = (tree_info, tree_in_out, nodes, links, curves, metarig_data,) # f_curves)
  597. return export_data
  598. def write_json_data(data, path):
  599. import json
  600. with open(path, "w") as file:
  601. print(wrapWhite("Writing mantis tree data to: "), wrapGreen(file.name))
  602. file.write( json.dumps(data, indent = 4) )
  603. def get_link_sockets(link, tree, tree_socket_id_map):
  604. from_node_name = link[0]
  605. from_socket_id = link[1]
  606. to_node_name = link[2]
  607. to_socket_id = link[3]
  608. from_output_index = link[4]
  609. to_input_index = link[5]
  610. from_socket_name = link[6]
  611. to_socket_name = link[7]
  612. # TODO: make this a loop and swap out the in/out stuff
  613. # this is OK but I want to avoid code-duplication, which this almost is.
  614. from_node = tree.nodes.get(from_node_name)
  615. # first try and get by name. we'll use this if the ID and the name do not match.
  616. # from_sock = from_node.outputs.get(from_socket_name)
  617. id1 = from_socket_id
  618. if hasattr(from_node, "node_tree") or \
  619. from_node.bl_idname in ["SchemaArrayInput",
  620. "SchemaArrayInputGet",
  621. "SchemaArrayInputAll",
  622. "SchemaConstInput",
  623. "SchemaIncomingConnection", ]: # now we have to map by something else
  624. try:
  625. id1 = from_node.outputs[from_socket_name].identifier
  626. except KeyError: # we'll try index if nothing else works
  627. try:
  628. id1 = from_node.outputs[from_output_index].identifier
  629. except IndexError as e:
  630. prRed("failed to create link: "
  631. f"{from_node_name}:{from_socket_id} --> {to_node_name}:{to_socket_id}")
  632. return (None, None)
  633. elif from_node.bl_idname in ["NodeGroupInput"]:
  634. id1 = tree_socket_id_map.get(from_socket_id)
  635. for from_sock in from_node.outputs:
  636. if from_sock.identifier == id1: break
  637. else:
  638. from_sock = None
  639. id2 = to_socket_id
  640. to_node = tree.nodes[to_node_name]
  641. if hasattr(to_node, "node_tree") or \
  642. to_node.bl_idname in ["SchemaArrayOutput",
  643. "SchemaConstOutput",
  644. "SchemaOutgoingConnection", ]: # now we have to map by something else
  645. try:
  646. id2 = to_node.inputs[to_socket_name].identifier
  647. except KeyError: # we'll try index if nothing else works
  648. try: # nesting try/except is ugly but it is right...
  649. id2 = to_node.inputs[to_input_index].identifier
  650. except IndexError as e:
  651. prRed("failed to create link: "
  652. f"{from_node_name}:{from_socket_id} --> {to_node_name}:{to_socket_id}")
  653. return (None, None)
  654. elif to_node.bl_idname in ["NodeGroupOutput"]:
  655. id2 = tree_socket_id_map.get(to_socket_id)
  656. for to_sock in to_node.inputs:
  657. if to_sock.identifier == id2: break
  658. else:
  659. to_sock = None
  660. return from_sock, to_sock
  661. def setup_sockets(node, propslist, in_out="inputs"):
  662. sockets_removed = []
  663. for i, (s_id, s_val) in enumerate(propslist[in_out].items()):
  664. if node.bl_idname in ['NodeReroute']:
  665. break # Reroute Nodes do not have anything I can set or modify.
  666. for socket_removed in SOCKETS_REMOVED:
  667. if node.bl_idname == socket_removed[0] and s_id == socket_removed[1]:
  668. prWhite(f"INFO: Ignoring import of socket {s_id}; it has been removed.")
  669. sockets_removed.append(s_val["index"])
  670. sockets_removed.sort()
  671. continue
  672. if s_val["is_output"]:
  673. if node.bl_idname in "MantisSchemaGroup":
  674. node.is_updating = True
  675. try:
  676. socket = node.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id)
  677. finally:
  678. node.is_updating=False
  679. elif s_val["index"] >= len(node.outputs):
  680. if node.bl_idname in add_inputs_bl_idnames:
  681. socket = node.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, )
  682. else: # first try to get by ID AND name. ID's switch around a bit so we need both to match.
  683. for socket in node.outputs:
  684. if socket.identifier == s_id and socket.name == s_val['name']:
  685. break
  686. # this often fails for group outputs and such
  687. # because the socket ID may not be the same when it is re-generated
  688. else: # otherwise try to get the index
  689. # IT IS NOT CLEAR but this is what throws the index error below BAD
  690. # try to get by name
  691. socket = node.outputs.get(s_val['name'])
  692. if not socket:
  693. try:
  694. socket = node.outputs[int(s_val["index"])]
  695. except IndexError as e:
  696. print (node.id_data.name)
  697. print (propslist['name'])
  698. print (s_id, s_val['name'], s_val['index'])
  699. raise e
  700. if socket.name != s_val["name"]:
  701. right_name = s_val['name']
  702. prRed( "There has been an error getting a socket while importing data."
  703. f"found name: {socket.name}; should have found: {right_name}.")
  704. else:
  705. for removed_index in sockets_removed:
  706. if s_val["index"] > removed_index:
  707. s_val["index"]-=1
  708. if s_val["index"] >= len(node.inputs):
  709. if node.bl_idname in add_inputs_bl_idnames:
  710. socket = node.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  711. elif node.bl_idname in ["MantisSchemaGroup"]:
  712. node.is_updating = True
  713. try:
  714. socket = node.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  715. finally:
  716. node.is_updating=False
  717. elif node.bl_idname in ["NodeGroupOutput"]:
  718. pass # this is dealt with separately
  719. else:
  720. prWhite("Not found: ", propslist['name'], s_val["name"], s_id)
  721. prRed("Index: ", s_val["index"], "Number of inputs", len(node.inputs))
  722. for thing1, thing2 in zip(propslist[in_out].keys(), getattr(node, in_out).keys()):
  723. print (thing1, thing2)
  724. raise NotImplementedError(wrapRed(f"{node.bl_idname} in {node.id_data.name} needs to be handled in JSON load."))
  725. else: # first try to get by ID AND name. ID's switch around a bit so we need both to match.
  726. for socket in node.inputs:
  727. if socket.identifier == s_id and socket.name == s_val['name']:
  728. break
  729. # failing to find the socket by ID is less common for inputs than outputs.
  730. # it usually isn't a problem.
  731. else: # otherwise try to get the index
  732. # IT IS NOT CLEAR but this is what throws the index error below BAD
  733. socket = node.inputs.get(s_val["name"])
  734. if not socket:
  735. socket = node.inputs[int(s_val["index"])]
  736. # finally we need to check that the name matches.
  737. if socket.name != s_val["name"]:
  738. right_name = s_val['name']
  739. prRed( "There has been an error getting a socket while importing data."
  740. f"found name: {socket.name}; should have found: {right_name}.")
  741. # set the value
  742. for s_p, s_v in s_val.items():
  743. if s_p not in ["default_value"]:
  744. if s_p == "search_prop" and node.bl_idname == 'UtilityMetaRig':
  745. socket.node.armature= s_v
  746. socket.search_prop=bpy.data.objects.get(s_v)
  747. if s_p == "search_prop" and node.bl_idname in ['UtilityMatrixFromCurve', 'UtilityMatricesFromCurve']:
  748. socket.search_prop=bpy.data.objects.get(s_v)
  749. elif s_p == "bone" and socket.bl_idname == 'EnumMetaBoneSocket':
  750. socket.bone = s_v
  751. socket.node.pose_bone = s_v
  752. continue # not editable and NOT SAFE
  753. #
  754. if socket.bl_idname in ["BooleanThreeTupleSocket"]:
  755. value = bool(s_v[0]), bool(s_v[1]), bool(s_v[2]),
  756. s_v = value
  757. try:
  758. setattr(socket, s_p , s_v)
  759. except TypeError as e:
  760. prRed("Can't set socket due to type mismatch: ", node.name, socket.name, s_p, s_v)
  761. # raise e
  762. except ValueError as e:
  763. prRed("Can't set socket due to type mismatch: ", node.name, socket.name, s_p, s_v)
  764. # raise e
  765. except AttributeError as e:
  766. if print_read_only_warning == True:
  767. prWhite("Tried to write a read-only property, ignoring...")
  768. prWhite(f"{socket.node.name}[{socket.name}].{s_p} is read only, cannot set value to {s_v}")
  769. def do_import_from_file(filepath, context):
  770. import json
  771. all_trees = [n_tree for n_tree in bpy.data.node_groups if n_tree.bl_idname in ["MantisTree", "SchemaTree"]]
  772. for tree in all_trees:
  773. tree.is_exporting = True
  774. tree.do_live_update = False
  775. def do_cleanup(tree):
  776. tree.is_exporting = False
  777. tree.do_live_update = True
  778. tree.prevent_next_exec = True
  779. with open(filepath, 'r', encoding='utf-8') as f:
  780. data = json.load(f)
  781. do_import(data,context, search_multi_files=True, filepath=filepath)
  782. for tree in all_trees:
  783. do_cleanup(tree)
  784. tree = bpy.data.node_groups[list(data.keys())[-1]]
  785. try:
  786. context.space_data.node_tree = tree
  787. except AttributeError: # not hovering over the Node Editor
  788. pass
  789. return {'FINISHED'}
  790. # otherwise:
  791. # repeat this because we left the with, this is bad and ugly but I don't care
  792. for tree in all_trees:
  793. do_cleanup(tree)
  794. return {'CANCELLED'}
  795. # TODO figure out the right way to dedupe this stuff (see above)
  796. # I need this function for recursing through multi-file components
  797. # but I am using the with statement in the above function...
  798. # it should be easy to refactor but I don't know 100% for sure
  799. # the behaviour will be identical or if that matters.
  800. def get_graph_data_from_json(filepath) -> dict:
  801. import json
  802. with open(filepath, 'r', encoding='utf-8') as f:
  803. data = json.load(f)
  804. return data
  805. def do_import(data, context, search_multi_files=False, filepath=''):
  806. trees = []
  807. tree_sock_id_maps = {}
  808. # First: init the interface of the node graph
  809. for tree_name, tree_data in data.items():
  810. tree_info = tree_data[0]
  811. tree_in_out = tree_data[1]
  812. # need to make a new tree; first, try to get it:
  813. tree = bpy.data.node_groups.get(tree_info["name"])
  814. if tree is None:
  815. tree = bpy.data.node_groups.new(tree_info["name"], tree_info["bl_idname"])
  816. tree.nodes.clear(); tree.links.clear(); tree.interface.clear()
  817. # this may be a bad bad thing to do without some kind of warning TODO TODO
  818. tree.is_executing = True
  819. tree.do_live_update = False
  820. trees.append(tree)
  821. tree_sock_id_map = {}
  822. tree_sock_id_maps[tree.name] = tree_sock_id_map
  823. interface_parent_me = {}
  824. # I need to guarantee that the interface items are in the right order.
  825. interface_sockets = [] # I'll just sort them afterwards so I hold them here.
  826. default_position=0 # We'll use this if the position attribute is not set when e.g. making groups.
  827. for s_name, s_props in tree_in_out.items():
  828. if s_props["item_type"] == 'SOCKET':
  829. if s_props["socket_type"] == "LayerMaskSocket":
  830. continue
  831. if (socket_type := s_props["socket_type"]) == "NodeSocketColor":
  832. socket_type = "VectorSocket"
  833. if bpy.app.version != (4,5,0):
  834. sock = tree.interface.new_socket(s_props["name"], in_out=s_props["in_out"], socket_type=socket_type)
  835. else: # blender 4.5.0 LTS, have to workaround a bug!
  836. from .versioning import workaround_4_5_0_interface_update
  837. sock = workaround_4_5_0_interface_update(tree=tree, name=s_props["name"], in_out=s_props["in_out"],
  838. sock_type=socket_type, parent_name=s_props.get("parent", ''))
  839. tree_sock_id_map[s_name] = sock.identifier
  840. if not (socket_position := s_props.get('position')):
  841. socket_position=default_position; default_position+=1
  842. interface_sockets.append( (sock, socket_position) )
  843. # TODO: set whatever properties are needed (default, etc)
  844. if panel := s_props.get("parent"): # this get is just to maintain compatibility with an older form of this script... and it is harmless
  845. interface_parent_me[sock] = (panel, s_props["position"])
  846. else: # it's a panel
  847. panel = tree.interface.new_panel(s_props["name"], description=s_props.get("description"), default_closed=s_props.get("default_closed"))
  848. for socket, (panel, index) in interface_parent_me.items():
  849. tree.interface.move_to_parent(
  850. socket,
  851. tree.interface.items_tree.get(panel),
  852. index,
  853. )
  854. # BUG this was screwing up the order of things
  855. # so I want to fix it and re-enable it
  856. if True:
  857. # Go BACK through and set the index/position now that all items exist.
  858. interface_sockets.sort(key=lambda a : a[1])
  859. for (socket, position) in interface_sockets:
  860. tree.interface.move(socket, position)
  861. # Now go and do nodes and links
  862. for tree_name, tree_data in data.items():
  863. print ("Importing sub-graph: %s with %s nodes" % (wrapGreen(tree_name), wrapPurple(len(tree_data[2]))) )
  864. tree_info = tree_data[0]
  865. nodes = tree_data[2]
  866. links = tree_data[3]
  867. parent_me = []
  868. tree = bpy.data.node_groups.get(tree_info["name"])
  869. tree.is_executing = True
  870. tree.do_live_update = False
  871. trees.append(tree)
  872. tree_sock_id_map=tree_sock_id_maps[tree.name]
  873. interface_parent_me = {}
  874. # from mantis.utilities import prRed, prWhite, prOrange, prGreen
  875. for name, propslist in nodes.items():
  876. bl_idname = propslist["bl_idname"]
  877. if bl_idname in NODES_REMOVED:
  878. prWhite(f"INFO: Ignoring import of node {name} of type {bl_idname}; it has been removed.")
  879. continue
  880. n = tree.nodes.new(bl_idname)
  881. if bl_idname in ["DeformerMorphTargetDeform"]:
  882. n.inputs.remove(n.inputs[-1]) # get rid of the wildcard
  883. if n.bl_idname in [ "SchemaArrayInput",
  884. "SchemaArrayInputGet",
  885. "SchemaArrayInputAll",
  886. "SchemaArrayOutput",
  887. "SchemaConstInput",
  888. "SchemaConstOutput",
  889. "SchemaOutgoingConnection",
  890. "SchemaIncomingConnection",]:
  891. n.update()
  892. if sub_tree := propslist.get("node_tree"):
  893. # now that I am doing multi-file exports, this is tricky
  894. # we need to see if the tree exists and if not, recurse
  895. # and import that tree before continuing.
  896. grp_tree = bpy.data.node_groups.get(sub_tree)
  897. if grp_tree is None: # for multi-file component this is intentional
  898. if search_multi_files: # we'll get the filename and recurse
  899. from bpy.path import native_pathsep, clean_name
  900. from os import path as os_path
  901. native_filepath = native_pathsep(filepath)
  902. directory = os_path.split(native_filepath)[0]
  903. subtree_filepath = os_path.join(directory, clean_name(sub_tree)+'.rig')
  904. subtree_data = get_graph_data_from_json(subtree_filepath)
  905. do_import(subtree_data, context,
  906. search_multi_files=True,
  907. filepath=subtree_filepath)
  908. #now get the grp_tree lol
  909. grp_tree = bpy.data.node_groups[sub_tree]
  910. else: # otherwise it is an error
  911. raise RuntimeError(f"Tree {sub_tree} not available to import.")
  912. n.node_tree = grp_tree
  913. from .base_definitions import node_group_update
  914. n.is_updating = True
  915. try:
  916. node_group_update(n, force = True)
  917. finally:
  918. n.is_updating=False
  919. # set up sockets
  920. setup_sockets(n, propslist, in_out="inputs")
  921. setup_sockets(n, propslist, in_out="outputs")
  922. for p, v in propslist.items():
  923. if p in ["node_tree",
  924. "sockets",
  925. "inputs",
  926. "outputs",
  927. "warning_propagation",
  928. "socket_idname"]:
  929. continue
  930. # will throw AttributeError if read-only
  931. # will throw TypeError if wrong type...
  932. if n.bl_idname == "NodeFrame" and p in ["width, height, location"]:
  933. continue
  934. if version < (4,4,0) and p == 'location_absolute':
  935. continue
  936. if p == "parent" and v is not None:
  937. parent_me.append( (n.name, v) )
  938. v = None # for now) #TODO
  939. try:
  940. setattr(n, p, v)
  941. except Exception as e:
  942. prRed (p)
  943. raise e
  944. for l in links:
  945. from_socket_name = l[6]
  946. to_socket_name = l[7]
  947. name1=l[0]
  948. name2=l[2]
  949. from_sock, to_sock = get_link_sockets(l, tree, tree_sock_id_map)
  950. try:
  951. link = tree.links.new(from_sock, to_sock)
  952. except TypeError:
  953. prPurple (from_sock)
  954. prOrange (to_sock)
  955. if print_link_failure:
  956. from_node_name = link[0]; from_socket_id = link[1]
  957. to_node_name = link[2]; to_socket_id = link[3]
  958. prWhite(f"looking for... {from_node_name}:{from_socket_id}, {to_node_name}:{to_socket_id}")
  959. prRed (f"Failed: {l[0]}:{l[1]} --> {l[2]}:{l[3]}")
  960. prRed (f" got node: {from_node_name}, {to_node_name}")
  961. prRed (f" got socket: {from_sock}, {to_sock}")
  962. raise RuntimeError
  963. else:
  964. prRed(f"Failed to add link in {tree.name}: {name1}:{from_socket_name}, {name2}:{to_socket_name}")
  965. # if at this point it doesn't work... we need to fix
  966. for name, p in parent_me:
  967. if (n := tree.nodes.get(name)) and (p := tree.nodes.get(p)):
  968. n.parent = p
  969. # otherwise the frame node is missing because it was not included in the data e.g. when grouping nodes.
  970. # TODO: IMPORT THIS DATA HERE!!!
  971. # try:
  972. # curves = tree_data[4]
  973. # armatures = tree_data[5]
  974. # except KeyError: # shouldn't happen but maybe someone has an old file
  975. # curves = {}
  976. # armatures = {}
  977. # for curve_name, curve_data in curves.items():
  978. # from .utilities import import_curve_data_to_object
  979. # import_curve_data_to_object(curve_name, curve_data)
  980. tree.is_executing = False
  981. tree.do_live_update = True
  982. def export_multi_file(trees : list, filepath : str, base_name :str) -> None:
  983. for t in trees:
  984. # this should name them the name of the tree...
  985. from bpy.path import native_pathsep, clean_name
  986. from os import path as os_path
  987. from os import mkdir
  988. native_filepath = native_pathsep(filepath)
  989. directory = os_path.split(native_filepath)[0]
  990. export_data = export_to_json([t], os_path.join(directory,
  991. clean_name(t.name)+'.rig'))
  992. write_json_data(export_data, os_path.join(directory,
  993. clean_name(t.name)+'.rig'))
  994. import bpy
  995. from bpy_extras.io_utils import ImportHelper, ExportHelper
  996. from bpy.props import StringProperty, BoolProperty, EnumProperty
  997. from bpy.types import Operator
  998. # Save As
  999. class MantisExportNodeTreeSaveAs(Operator, ExportHelper):
  1000. """Export a Mantis Node Tree by filename."""
  1001. bl_idname = "mantis.export_save_as"
  1002. bl_label = "Export Mantis Tree as ...(JSON)"
  1003. # ExportHelper mix-in class uses this.
  1004. filename_ext = ".rig"
  1005. filter_glob: StringProperty(
  1006. default="*.rig",
  1007. options={'HIDDEN'},
  1008. maxlen=255, # Max internal buffer length, longer would be clamped.
  1009. )
  1010. export_trees_together : BoolProperty(
  1011. default=False,
  1012. name="Pack All Sub-Trees",
  1013. description="Pack all Sub-trees into one file?")
  1014. @classmethod
  1015. def poll(cls, context):
  1016. return hasattr(context.space_data, 'path')
  1017. def execute(self, context):
  1018. # we need to get the dependent trees from self.tree...
  1019. # there is no self.tree
  1020. # how do I choose a tree?
  1021. base_tree=context.space_data.path[-1].node_tree
  1022. from .utilities import all_trees_in_tree
  1023. trees = all_trees_in_tree(base_tree)[::-1]
  1024. prGreen("Exporting node graph with dependencies...")
  1025. for t in trees:
  1026. prGreen ("Node graph: \"%s\"" % (t.name))
  1027. base_tree.is_exporting = True
  1028. if self.export_trees_together:
  1029. export_data = export_to_json(trees, base_tree, self.filepath)
  1030. write_json_data(export_data, self.filepath)
  1031. else:
  1032. export_multi_file(trees, self.filepath, base_tree.name)
  1033. base_tree.is_exporting = False
  1034. base_tree.prevent_next_exec = True
  1035. # set the properties on the base tree for re-exporting with alt-s
  1036. base_tree.filepath = self.filepath
  1037. base_tree.export_all_subtrees_together = self.export_trees_together
  1038. return {'FINISHED'}
  1039. # Save
  1040. class MantisExportNodeTreeSave(Operator):
  1041. """Save a Mantis Node Tree to disk."""
  1042. bl_idname = "mantis.export_save"
  1043. bl_label = "Export Mantis Tree (JSON)"
  1044. @classmethod
  1045. def poll(cls, context):
  1046. return hasattr(context.space_data, 'path')
  1047. def execute(self, context):
  1048. base_tree=context.space_data.path[-1].node_tree
  1049. filepath = base_tree.filepath
  1050. from .utilities import all_trees_in_tree
  1051. trees = all_trees_in_tree(base_tree)[::-1]
  1052. prGreen("Exporting node graph with dependencies...")
  1053. for t in trees:
  1054. prGreen ("Node graph: \"%s\"" % (t.name))
  1055. base_tree.is_exporting = True
  1056. if base_tree.export_all_subtrees_together:
  1057. export_data = export_to_json(trees, filepath)
  1058. write_json_data(export_data, filepath)
  1059. else:
  1060. export_multi_file(trees, filepath, base_tree.name)
  1061. base_tree.is_exporting = False
  1062. base_tree.prevent_next_exec = True
  1063. return {'FINISHED'}
  1064. # Save Choose:
  1065. class MantisExportNodeTree(Operator):
  1066. """Save a Mantis Node Tree to disk."""
  1067. bl_idname = "mantis.export_save_choose"
  1068. bl_label = "Export Mantis Tree (JSON)"
  1069. @classmethod
  1070. def poll(cls, context):
  1071. return hasattr(context.space_data, 'path')
  1072. def execute(self, context):
  1073. base_tree=context.space_data.path[-1].node_tree
  1074. if base_tree.filepath:
  1075. prRed(base_tree.filepath)
  1076. return bpy.ops.mantis.export_save()
  1077. else:
  1078. return bpy.ops.mantis.export_save_as('INVOKE_DEFAULT')
  1079. # here is what needs to be done...
  1080. # - modify this to work with a sort of parsed-tree instead (sort of)
  1081. # - this needs to treat each sub-graph on its own
  1082. # - is this a problem? do I need to reconsider how I treat the graph data in mantis?
  1083. # - I should learn functional programming / currying
  1084. # - then the parsed-tree this builds must be executed as Blender nodes
  1085. # - I think... this is not important right now. not yet.
  1086. # - KEEP IT SIMPLE, STUPID
  1087. class MantisImportNodeTree(Operator, ImportHelper):
  1088. """Import a Mantis Node Tree."""
  1089. bl_idname = "mantis.import_tree"
  1090. bl_label = "Import Mantis Tree (JSON)"
  1091. # ImportHelper mixin class uses this
  1092. filename_ext = ".rig"
  1093. filter_glob : StringProperty(
  1094. default="*.rig",
  1095. options={'HIDDEN'},
  1096. maxlen=255, # Max internal buffer length, longer would be clamped.
  1097. )
  1098. def execute(self, context):
  1099. return do_import_from_file(self.filepath, context)
  1100. # this is useful:
  1101. # https://blender.stackexchange.com/questions/73286/how-to-call-a-confirmation-dialog-box
  1102. # class MantisReloadConfirmMenu(bpy.types.Panel):
  1103. # bl_label = "Confirm?"
  1104. # bl_idname = "OBJECT_MT_mantis_reload_confirm"
  1105. # def draw(self, context):
  1106. # layout = self.layout
  1107. # layout.operator("mantis.reload_tree")
  1108. class MantisReloadNodeTree(Operator):
  1109. # """Import a Mantis Node Tree."""
  1110. # bl_idname = "mantis.reload_tree"
  1111. # bl_label = "Import Mantis Tree"
  1112. """Reload Mantis Tree"""
  1113. bl_idname = "mantis.reload_tree"
  1114. bl_label = "Confirm reload tree?"
  1115. bl_options = {'REGISTER', 'INTERNAL'}
  1116. @classmethod
  1117. def poll(cls, context):
  1118. if hasattr(context.space_data, 'path'):
  1119. return True
  1120. return False
  1121. def invoke(self, context, event):
  1122. return context.window_manager.invoke_confirm(self, event)
  1123. def execute(self, context):
  1124. base_tree=context.space_data.path[-1].node_tree
  1125. if not base_tree.filepath:
  1126. self.report({'ERROR'}, "Tree has not been saved - so it cannot be reloaded.")
  1127. return {'CANCELLED'}
  1128. self.report({'INFO'}, "reloading tree")
  1129. return do_import_from_file(base_tree.filepath, context)
  1130. # todo:
  1131. # - export metarig and option to import it
  1132. # - same with controls
  1133. # - it would be nice to have a library of these that can be imported alongside the mantis graph