i_o.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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(asdict(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_children = []
  271. for bone in object.data.bones:
  272. parent_name = ''
  273. if bone.parent is None:
  274. armature_children.append(bone.name)
  275. else:
  276. parent_name=bone.parent.name
  277. children=[]
  278. for c in bone.children:
  279. children.append(c.name)
  280. bone_data = metabone_data( object_name = object.name,
  281. name=bone.name, type='BONE',
  282. matrix=matrix_as_tuple(bone.matrix_local),
  283. parent=parent_name, length = bone.length, children = children,
  284. )
  285. metarig_data[bone.name]=asdict(bone_data)
  286. armature_data = metabone_data( object_name = object.name,
  287. name=object.name, type='ARMATURE',
  288. matrix=matrix_as_tuple(object.matrix_world),
  289. parent="", # NOTE that this is not always a fair assumption!
  290. length = -1.0, children = armature_children,)
  291. metarig_data[object.name] = asdict(armature_data)
  292. metarig_data["MANTIS_RESERVED"] = asdict(armature_data) # just in case a bone is named the same as the armature
  293. return metarig_data
  294. def get_socket_data(socket, ignore_if_default=False):
  295. # TODO: don't get stuff in the socket templates
  296. # PROBLEM: I don't have easy access to this from the ui class (or mantis class)
  297. socket_data = {}
  298. socket_data["name"] = socket.name
  299. socket_data["bl_idname"] = socket.bl_idname
  300. socket_data["is_output"] = socket.is_output
  301. socket_data["is_multi_input"] = socket.is_multi_input
  302. # here is where we'll handle a socket_data'socket special data
  303. if socket.bl_idname == "EnumMetaBoneSocket":
  304. socket_data["bone"] = socket.bone
  305. if socket.bl_idname in ["EnumMetaBoneSocket", "EnumMetaRigSocket", "EnumCurveSocket"]:
  306. if sp := socket.get("search_prop"): # may be None
  307. socket_data["search_prop"] = sp.name # this is an object.
  308. #
  309. if hasattr(socket, "default_value"):
  310. value = socket.default_value
  311. else:
  312. value = None
  313. return socket_data # we don't need to store any more.
  314. if not is_jsonable(value): # FIRST try and make a tuple out of it because JSON doesn't like mutables
  315. value = tuple(value)
  316. if not is_jsonable(value): # now see if it worked and crash out if it didn't
  317. raise RuntimeError(f"Error serializing data in {socket.node.name}::{socket.name} for value of type {type(value)}")
  318. socket_data["default_value"] = value
  319. # TODO TODO implement "ignore if default" feature here
  320. # at this point we can get the custom parameter ui hints if we want
  321. if not socket.is_output:
  322. # try and get this data
  323. if value := getattr(socket,'min', None):
  324. socket_data["min"] = value
  325. if value := getattr(socket,'max', None):
  326. socket_data["max"] = value
  327. if value := getattr(socket,'soft_min', None):
  328. socket_data["soft_min"] = value
  329. if value := getattr(socket,'soft_max', None):
  330. socket_data["soft_max"] = value
  331. if value := getattr(socket,'description', None):
  332. socket_data["description"] = value
  333. return socket_data
  334. #
  335. def get_node_data(ui_node):
  336. # if this is a node-group, force it to update its interface, because it may be messed up.
  337. # can remove this HACK when I have stronger guarentees about node-group's keeping the interface
  338. from .base_definitions import node_group_update
  339. if hasattr(ui_node, "node_tree"):
  340. ui_node.is_updating = True
  341. try: # HERE BE DANGER
  342. node_group_update(ui_node, force=True)
  343. finally: # ensure this line is run even if there is an error
  344. ui_node.is_updating = False
  345. node_props, inputs, outputs = {}, {}, {}
  346. for propname in dir(ui_node):
  347. value = getattr(ui_node, propname)
  348. if propname in ['fake_fcurve_ob']:
  349. value=value.name
  350. if (propname in prop_ignore) or ( callable(value) ):
  351. continue
  352. if value.__class__.__name__ in ["Vector", "Color"]:
  353. value = tuple(value)
  354. if isinstance(value, bpy.types.NodeTree):
  355. value = value.name
  356. if isinstance(value, bpy.types.bpy_prop_array):
  357. value = tuple(value)
  358. if propname == "parent" and value:
  359. value = value.name
  360. if not is_jsonable(value):
  361. raise RuntimeError(f"Could not export... {ui_node.name}, {propname}, {type(value)}")
  362. if value is None:
  363. continue
  364. node_props[propname] = value
  365. # so we have to accumulate the parent location because the location is not absolute
  366. if propname == "location" and ui_node.parent is not None:
  367. location_acc = Vector((0,0))
  368. parent = ui_node.parent
  369. while (parent):
  370. location_acc += parent.location
  371. parent = parent.parent
  372. location_acc += getattr(ui_node, propname)
  373. node_props[propname] = tuple(location_acc)
  374. # this works!
  375. if ui_node.bl_idname in ['RerouteNode']:
  376. return node_props # we don't need to get the socket information.
  377. for i, ui_socket in enumerate(ui_node.inputs):
  378. socket = get_socket_data(ui_socket)
  379. socket["index"]=i
  380. inputs[ui_socket.identifier] = socket
  381. for i, ui_socket in enumerate(ui_node.outputs):
  382. socket = get_socket_data(ui_socket)
  383. socket["index"]=i
  384. outputs[ui_socket.identifier] = socket
  385. node_props["inputs"] = inputs
  386. node_props["outputs"] = outputs
  387. return node_props
  388. def get_tree_data(tree):
  389. tree_info = {}
  390. for propname in dir(tree):
  391. # if getattr(tree, propname):
  392. # pass
  393. if (propname in prop_ignore_tree) or ( callable(getattr(tree, propname)) ):
  394. continue
  395. v = getattr(tree, propname)
  396. if isinstance(getattr(tree, propname), bpy.types.bpy_prop_array):
  397. v = tuple(getattr(tree, propname))
  398. if not is_jsonable( v ):
  399. raise RuntimeError(f"Not JSON-able: {propname}, type: {type(v)}")
  400. tree_info[propname] = v
  401. tree_info["name"]=tree.name
  402. return tree_info
  403. def get_interface_data(tree, tree_in_out):
  404. for sock in tree.interface.items_tree:
  405. sock_data={}
  406. if sock.item_type == 'PANEL':
  407. sock_data["name"] = sock.name
  408. sock_data["item_type"] = sock.item_type
  409. sock_data["description"] = sock.description
  410. sock_data["default_closed"] = sock.default_closed
  411. tree_in_out[sock.name] = sock_data
  412. # if it is a socket....
  413. else:
  414. # we need to get the socket class from the bl_idname
  415. bl_socket_idname = sock.bl_socket_idname
  416. # try and import it
  417. from . import socket_definitions
  418. # WANT an attribute error if this fails.
  419. socket_class = getattr(socket_definitions, bl_socket_idname)
  420. sock_parent = None
  421. if sock.parent:
  422. sock_parent = sock.parent.name
  423. for propname in dir(sock):
  424. if propname in prop_ignore_interface:
  425. continue
  426. if (propname == "parent"):
  427. sock_data[propname] = sock_parent
  428. continue
  429. v = getattr(sock, propname)
  430. if (propname in prop_ignore) or ( callable(v) ):
  431. continue
  432. if isinstance(getattr(sock, propname), bpy.types.bpy_prop_array):
  433. v = tuple(getattr(sock, propname))
  434. if not is_jsonable( v ):
  435. raise RuntimeError(f"{propname}, {type(v)}")
  436. sock_data[propname] = v
  437. # this is a property. pain.
  438. sock_data["socket_type"] = socket_class.interface_type.fget(socket_class)
  439. tree_in_out[sock.identifier] = sock_data
  440. def export_to_json(trees, base_tree=None, path="", write_file=True, only_selected=False, ):
  441. export_data = {}
  442. for tree in trees:
  443. current_tree_is_base_tree = False
  444. if tree is trees[-1]:
  445. current_tree_is_base_tree = True
  446. tree_info, tree_in_out = {}, {}
  447. tree_info = get_tree_data(tree)
  448. curves, metarig_data = {}, {}
  449. embed_metarigs=True
  450. if base_tree and embed_metarigs:
  451. curves_in_tree, metarigs_in_tree = scan_tree_for_objects(base_tree, tree)
  452. for crv in curves_in_tree:
  453. curves[crv.name] = get_curve_for_pack(crv)
  454. for mr in metarigs_in_tree:
  455. metarig_data[mr.name] = get_armature_for_pack(mr)
  456. # if only_selected:
  457. # # all in/out links, relative to the selection, should be marked and used to initialize tree properties
  458. if not only_selected: # we'll handle this later with the links
  459. for sock in tree.interface.items_tree:
  460. get_interface_data(tree, tree_in_out) # it concerns me that this one modifies
  461. # the collection instead of getting the data and returning it. TODO refactor this
  462. nodes = {}
  463. for node in tree.nodes:
  464. if only_selected and node.select == False:
  465. continue
  466. nodes[node.name] = get_node_data(node)
  467. links = []
  468. in_sockets, out_sockets = {}, {}
  469. unique_sockets_from, unique_sockets_to = {}, {}
  470. in_node = {"name":"MANTIS_AUTOGEN_GROUP_INPUT", "bl_idname":"NodeGroupInput", "inputs":in_sockets}
  471. out_node = {"name":"MANTIS_AUTOGEN_GROUP_OUTPUT", "bl_idname":"NodeGroupOutput", "outputs":out_sockets}
  472. add_input_node, add_output_node = False, False
  473. for link in tree.links:
  474. from_node_name, from_socket_id = link.from_node.name, link.from_socket.identifier
  475. to_node_name, to_socket_id = link.to_node.name, link.to_socket.identifier
  476. from_socket_name, to_socket_name = link.from_socket.name, link.to_socket.name
  477. # get the indices of the sockets to be absolutely sure
  478. for from_outoput_index, outp in enumerate(link.from_node.outputs):
  479. # for some reason, 'is' does not return True no matter what...
  480. # so we are gonn compare the memory address directly, this is stupid
  481. if (outp.as_pointer() == link.from_socket.as_pointer()): break
  482. else:
  483. problem=link.from_node.name + "::" + link.from_socket.name
  484. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  485. for to_input_index, inp in enumerate(link.to_node.inputs):
  486. if (inp.as_pointer() == link.to_socket.as_pointer()): break
  487. else:
  488. problem = link.to_node.name + "::" + link.to_socket.name
  489. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  490. if current_tree_is_base_tree:
  491. if (only_selected and link.from_node.select) and (not link.to_node.select):
  492. # handle an output in the tree
  493. add_output_node=True
  494. if not (sock_name := unique_sockets_to.get(link.from_socket.node.name+link.from_socket.identifier)):
  495. sock_name = link.to_socket.name; name_stub = sock_name
  496. used_names = list(tree_in_out.keys()); i=0
  497. while sock_name in used_names:
  498. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  499. unique_sockets_to[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  500. out_sock = out_sockets.get(sock_name)
  501. if not out_sock:
  502. out_sock = {}; out_sockets[sock_name] = out_sock
  503. out_sock["index"]=len(out_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  504. # what in the bad word is happening here?
  505. # why?
  506. # why no de-duplication?
  507. # what was I thinking?
  508. # TODO REFACTOR THIS SOON
  509. out_sock["name"] = sock_name
  510. out_sock["identifier"] = sock_name
  511. out_sock["bl_idname"] = link.to_socket.bl_idname
  512. out_sock["is_output"] = False
  513. out_sock["source"]=[link.to_socket.node.name,link.to_socket.identifier]
  514. 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
  515. sock_data={}
  516. sock_data["name"] = sock_name
  517. sock_data["item_type"] = "SOCKET"
  518. sock_data["default_closed"] = False
  519. # record the actual bl_idname and the proper interface type.
  520. sock_data["socket_type"] = link.from_socket.interface_type
  521. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  522. sock_data["identifier"] = sock_name
  523. sock_data["in_out"]="OUTPUT"
  524. sock_data["index"]=out_sock["index"]
  525. tree_in_out[sock_name] = sock_data
  526. to_node_name=out_node["name"]
  527. to_socket_id=out_sock["identifier"]
  528. to_input_index=out_sock["index"]
  529. to_socket_name=out_sock["name"]
  530. elif (only_selected and (not link.from_node.select)) and link.to_node.select:
  531. add_input_node=True
  532. # we need to get a unique name for this
  533. # use the Tree IN/Out because we are dealing with Group in/out
  534. if not (sock_name := unique_sockets_from.get(link.from_socket.node.name+link.from_socket.identifier)):
  535. sock_name = link.from_socket.name; name_stub = sock_name
  536. used_names = list(tree_in_out.keys()); i=0
  537. while sock_name in used_names:
  538. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  539. unique_sockets_from[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  540. in_sock = in_sockets.get(sock_name)
  541. if not in_sock:
  542. in_sock = {}; in_sockets[sock_name] = in_sock
  543. in_sock["index"]=len(in_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  544. #
  545. in_sock["name"] = sock_name
  546. in_sock["identifier"] = sock_name
  547. in_sock["bl_idname"] = link.from_socket.bl_idname
  548. in_sock["is_output"] = True
  549. 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
  550. in_sock["source"] = [link.from_socket.node.name,link.from_socket.identifier]
  551. sock_data={}
  552. sock_data["name"] = sock_name
  553. sock_data["item_type"] = "SOCKET"
  554. sock_data["default_closed"] = False
  555. # record the actual bl_idname and the proper interface type.
  556. sock_data["socket_type"] = link.from_socket.interface_type
  557. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  558. sock_data["identifier"] = sock_name
  559. sock_data["in_out"]="INPUT"
  560. sock_data["index"]=in_sock["index"]
  561. tree_in_out[sock_name] = sock_data
  562. from_node_name=in_node.get("name")
  563. from_socket_id=in_sock["identifier"]
  564. from_outoput_index=in_sock["index"]
  565. from_socket_name=in_node.get("name")
  566. # parentheses matter here...
  567. elif (only_selected and not (link.from_node.select and link.to_node.select)):
  568. continue
  569. elif only_selected and not (link.from_node.select and link.to_node.select):
  570. continue # pass if both links are not selected
  571. links.append( (from_node_name,
  572. from_socket_id,
  573. to_node_name,
  574. to_socket_id,
  575. from_outoput_index,
  576. to_input_index,
  577. from_socket_name,
  578. to_socket_name) ) # it's a tuple
  579. if add_input_node or add_output_node:
  580. all_nodes_bounding_box=[Vector((float("inf"),float("inf"))), Vector((-float("inf"),-float("inf")))]
  581. for n in nodes.values():
  582. if n["location"][0] < all_nodes_bounding_box[0].x:
  583. all_nodes_bounding_box[0].x = n["location"][0]
  584. if n["location"][1] < all_nodes_bounding_box[0].y:
  585. all_nodes_bounding_box[0].y = n["location"][1]
  586. #
  587. if n["location"][0] > all_nodes_bounding_box[1].x:
  588. all_nodes_bounding_box[1].x = n["location"][0]
  589. if n["location"][1] > all_nodes_bounding_box[1].y:
  590. all_nodes_bounding_box[1].y = n["location"][1]
  591. if add_input_node:
  592. 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))
  593. nodes["MANTIS_AUTOGEN_GROUP_INPUT"]=in_node
  594. if add_output_node:
  595. 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))
  596. nodes["MANTIS_AUTOGEN_GROUP_OUTPUT"]=out_node
  597. export_data[tree.name] = (tree_info, tree_in_out, nodes, links, curves, metarig_data,) # f_curves)
  598. return export_data
  599. def write_json_data(data, path):
  600. import json
  601. with open(path, "w") as file:
  602. print(wrapWhite("Writing mantis tree data to: "), wrapGreen(file.name))
  603. file.write( json.dumps(data, indent = 4) )
  604. def get_link_sockets(link, tree, tree_socket_id_map):
  605. from_node_name = link[0]
  606. from_socket_id = link[1]
  607. to_node_name = link[2]
  608. to_socket_id = link[3]
  609. from_output_index = link[4]
  610. to_input_index = link[5]
  611. from_socket_name = link[6]
  612. to_socket_name = link[7]
  613. # TODO: make this a loop and swap out the in/out stuff
  614. # this is OK but I want to avoid code-duplication, which this almost is.
  615. from_node = tree.nodes.get(from_node_name)
  616. # first try and get by name. we'll use this if the ID and the name do not match.
  617. # from_sock = from_node.outputs.get(from_socket_name)
  618. id1 = from_socket_id
  619. if hasattr(from_node, "node_tree") or \
  620. from_node.bl_idname in ["SchemaArrayInput",
  621. "SchemaArrayInputGet",
  622. "SchemaArrayInputAll",
  623. "SchemaConstInput",
  624. "SchemaIncomingConnection", ]: # now we have to map by something else
  625. try:
  626. id1 = from_node.outputs[from_socket_name].identifier
  627. except KeyError: # we'll try index if nothing else works
  628. try:
  629. id1 = from_node.outputs[from_output_index].identifier
  630. except IndexError as e:
  631. prRed("failed to create link: "
  632. f"{from_node_name}:{from_socket_id} --> {to_node_name}:{to_socket_id}")
  633. return (None, None)
  634. elif from_node.bl_idname in ["NodeGroupInput"]:
  635. id1 = tree_socket_id_map.get(from_socket_id)
  636. for from_sock in from_node.outputs:
  637. if from_sock.identifier == id1: break
  638. else:
  639. from_sock = None
  640. id2 = to_socket_id
  641. to_node = tree.nodes[to_node_name]
  642. if hasattr(to_node, "node_tree") or \
  643. to_node.bl_idname in ["SchemaArrayOutput",
  644. "SchemaConstOutput",
  645. "SchemaOutgoingConnection", ]: # now we have to map by something else
  646. try:
  647. id2 = to_node.inputs[to_socket_name].identifier
  648. except KeyError: # we'll try index if nothing else works
  649. try: # nesting try/except is ugly but it is right...
  650. id2 = to_node.inputs[to_input_index].identifier
  651. except IndexError as e:
  652. prRed("failed to create link: "
  653. f"{from_node_name}:{from_socket_id} --> {to_node_name}:{to_socket_id}")
  654. return (None, None)
  655. elif to_node.bl_idname in ["NodeGroupOutput"]:
  656. id2 = tree_socket_id_map.get(to_socket_id)
  657. for to_sock in to_node.inputs:
  658. if to_sock.identifier == id2: break
  659. else:
  660. to_sock = None
  661. return from_sock, to_sock
  662. def setup_sockets(node, propslist, in_out="inputs"):
  663. sockets_removed = []
  664. for i, (s_id, s_val) in enumerate(propslist[in_out].items()):
  665. if node.bl_idname in ['NodeReroute']:
  666. break # Reroute Nodes do not have anything I can set or modify.
  667. for socket_removed in SOCKETS_REMOVED:
  668. if node.bl_idname == socket_removed[0] and s_id == socket_removed[1]:
  669. prWhite(f"INFO: Ignoring import of socket {s_id}; it has been removed.")
  670. sockets_removed.append(s_val["index"])
  671. sockets_removed.sort()
  672. continue
  673. if s_val["is_output"]:
  674. if node.bl_idname in "MantisSchemaGroup":
  675. node.is_updating = True
  676. try:
  677. socket = node.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id)
  678. finally:
  679. node.is_updating=False
  680. elif s_val["index"] >= len(node.outputs):
  681. if node.bl_idname in add_inputs_bl_idnames:
  682. socket = node.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, )
  683. else: # first try to get by ID AND name. ID's switch around a bit so we need both to match.
  684. for socket in node.outputs:
  685. if socket.identifier == s_id and socket.name == s_val['name']:
  686. break
  687. # this often fails for group outputs and such
  688. # because the socket ID may not be the same when it is re-generated
  689. else: # otherwise try to get the index
  690. # IT IS NOT CLEAR but this is what throws the index error below BAD
  691. # try to get by name
  692. socket = node.outputs.get(s_val['name'])
  693. if not socket:
  694. try:
  695. socket = node.outputs[int(s_val["index"])]
  696. except IndexError as e:
  697. print (node.id_data.name)
  698. print (propslist['name'])
  699. print (s_id, s_val['name'], s_val['index'])
  700. raise e
  701. if socket.name != s_val["name"]:
  702. right_name = s_val['name']
  703. prRed( "There has been an error getting a socket while importing data."
  704. f"found name: {socket.name}; should have found: {right_name}.")
  705. else:
  706. for removed_index in sockets_removed:
  707. if s_val["index"] > removed_index:
  708. s_val["index"]-=1
  709. if s_val["index"] >= len(node.inputs):
  710. if node.bl_idname in add_inputs_bl_idnames:
  711. socket = node.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  712. elif node.bl_idname in ["MantisSchemaGroup"]:
  713. node.is_updating = True
  714. try:
  715. socket = node.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  716. finally:
  717. node.is_updating=False
  718. elif node.bl_idname in ["NodeGroupOutput"]:
  719. pass # this is dealt with separately
  720. else:
  721. prWhite("Not found: ", propslist['name'], s_val["name"], s_id)
  722. prRed("Index: ", s_val["index"], "Number of inputs", len(node.inputs))
  723. for thing1, thing2 in zip(propslist[in_out].keys(), getattr(node, in_out).keys()):
  724. print (thing1, thing2)
  725. raise NotImplementedError(wrapRed(f"{node.bl_idname} in {node.id_data.name} needs to be handled in JSON load."))
  726. else: # first try to get by ID AND name. ID's switch around a bit so we need both to match.
  727. for socket in node.inputs:
  728. if socket.identifier == s_id and socket.name == s_val['name']:
  729. break
  730. # failing to find the socket by ID is less common for inputs than outputs.
  731. # it usually isn't a problem.
  732. else: # otherwise try to get the index
  733. # IT IS NOT CLEAR but this is what throws the index error below BAD
  734. socket = node.inputs.get(s_val["name"])
  735. if not socket:
  736. socket = node.inputs[int(s_val["index"])]
  737. # finally we need to check that the name matches.
  738. if socket.name != s_val["name"]:
  739. right_name = s_val['name']
  740. prRed( "There has been an error getting a socket while importing data."
  741. f"found name: {socket.name}; should have found: {right_name}.")
  742. # set the value
  743. for s_p, s_v in s_val.items():
  744. if s_p not in ["default_value"]:
  745. if s_p == "search_prop" and node.bl_idname == 'UtilityMetaRig':
  746. socket.node.armature= s_v
  747. socket.search_prop=bpy.data.objects.get(s_v)
  748. if s_p == "search_prop" and node.bl_idname in ['UtilityMatrixFromCurve', 'UtilityMatricesFromCurve']:
  749. socket.search_prop=bpy.data.objects.get(s_v)
  750. elif s_p == "bone" and socket.bl_idname == 'EnumMetaBoneSocket':
  751. socket.bone = s_v
  752. socket.node.pose_bone = s_v
  753. continue # not editable and NOT SAFE
  754. #
  755. if socket.bl_idname in ["BooleanThreeTupleSocket"]:
  756. value = bool(s_v[0]), bool(s_v[1]), bool(s_v[2]),
  757. s_v = value
  758. try:
  759. setattr(socket, s_p , s_v)
  760. except TypeError as e:
  761. prRed("Can't set socket due to type mismatch: ", node.name, socket.name, s_p, s_v)
  762. # raise e
  763. except ValueError as e:
  764. prRed("Can't set socket due to type mismatch: ", node.name, socket.name, s_p, s_v)
  765. # raise e
  766. except AttributeError as e:
  767. if print_read_only_warning == True:
  768. prWhite("Tried to write a read-only property, ignoring...")
  769. prWhite(f"{socket.node.name}[{socket.name}].{s_p} is read only, cannot set value to {s_v}")
  770. def do_import_from_file(filepath, context):
  771. import json
  772. all_trees = [n_tree for n_tree in bpy.data.node_groups if n_tree.bl_idname in ["MantisTree", "SchemaTree"]]
  773. for tree in all_trees:
  774. tree.is_exporting = True
  775. tree.do_live_update = False
  776. def do_cleanup(tree):
  777. tree.is_exporting = False
  778. tree.do_live_update = True
  779. tree.prevent_next_exec = True
  780. with open(filepath, 'r', encoding='utf-8') as f:
  781. data = json.load(f)
  782. do_import(data,context, search_multi_files=True, filepath=filepath)
  783. for tree in all_trees:
  784. do_cleanup(tree)
  785. tree = bpy.data.node_groups[list(data.keys())[-1]]
  786. try:
  787. context.space_data.node_tree = tree
  788. except AttributeError: # not hovering over the Node Editor
  789. pass
  790. return {'FINISHED'}
  791. # otherwise:
  792. # repeat this because we left the with, this is bad and ugly but I don't care
  793. for tree in all_trees:
  794. do_cleanup(tree)
  795. return {'CANCELLED'}
  796. # TODO figure out the right way to dedupe this stuff (see above)
  797. # I need this function for recursing through multi-file components
  798. # but I am using the with statement in the above function...
  799. # it should be easy to refactor but I don't know 100% for sure
  800. # the behaviour will be identical or if that matters.
  801. def get_graph_data_from_json(filepath) -> dict:
  802. import json
  803. with open(filepath, 'r', encoding='utf-8') as f:
  804. data = json.load(f)
  805. return data
  806. def do_import(data, context, search_multi_files=False, filepath=''):
  807. trees = []
  808. tree_sock_id_maps = {}
  809. # First: init the interface of the node graph
  810. for tree_name, tree_data in data.items():
  811. tree_info = tree_data[0]
  812. tree_in_out = tree_data[1]
  813. # TODO: IMPORT THIS DATA HERE!!!
  814. try:
  815. curves = tree_data[4]
  816. armatures = tree_data[5]
  817. except IndexError: # shouldn't happen but maybe someone has an old file
  818. curves = {}
  819. armatures = {}
  820. for curve_name, curve_data in curves.items():
  821. from .utilities import import_curve_data_to_object, import_metarig_data
  822. import_curve_data_to_object(curve_name, curve_data)
  823. for armature_name, armature_data in armatures.items():
  824. import_metarig_data(armature_data)
  825. # need to make a new tree; first, try to get it:
  826. tree = bpy.data.node_groups.get(tree_info["name"])
  827. if tree is None:
  828. tree = bpy.data.node_groups.new(tree_info["name"], tree_info["bl_idname"])
  829. tree.nodes.clear(); tree.links.clear(); tree.interface.clear()
  830. # this may be a bad bad thing to do without some kind of warning TODO TODO
  831. tree.is_executing = True
  832. tree.do_live_update = False
  833. trees.append(tree)
  834. tree_sock_id_map = {}
  835. tree_sock_id_maps[tree.name] = tree_sock_id_map
  836. interface_parent_me = {}
  837. # I need to guarantee that the interface items are in the right order.
  838. interface_sockets = [] # I'll just sort them afterwards so I hold them here.
  839. default_position=0 # We'll use this if the position attribute is not set when e.g. making groups.
  840. for s_name, s_props in tree_in_out.items():
  841. if s_props["item_type"] == 'SOCKET':
  842. if s_props["socket_type"] == "LayerMaskSocket":
  843. continue
  844. if (socket_type := s_props["socket_type"]) == "NodeSocketColor":
  845. socket_type = "VectorSocket"
  846. if bpy.app.version != (4,5,0):
  847. sock = tree.interface.new_socket(s_props["name"], in_out=s_props["in_out"], socket_type=socket_type)
  848. else: # blender 4.5.0 LTS, have to workaround a bug!
  849. from .versioning import workaround_4_5_0_interface_update
  850. sock = workaround_4_5_0_interface_update(tree=tree, name=s_props["name"], in_out=s_props["in_out"],
  851. sock_type=socket_type, parent_name=s_props.get("parent", ''))
  852. tree_sock_id_map[s_name] = sock.identifier
  853. if not (socket_position := s_props.get('position')):
  854. socket_position=default_position; default_position+=1
  855. interface_sockets.append( (sock, socket_position) )
  856. # TODO: set whatever properties are needed (default, etc)
  857. if panel := s_props.get("parent"): # this get is just to maintain compatibility with an older form of this script... and it is harmless
  858. interface_parent_me[sock] = (panel, s_props["position"])
  859. else: # it's a panel
  860. panel = tree.interface.new_panel(s_props["name"], description=s_props.get("description"), default_closed=s_props.get("default_closed"))
  861. for socket, (panel, index) in interface_parent_me.items():
  862. tree.interface.move_to_parent(
  863. socket,
  864. tree.interface.items_tree.get(panel),
  865. index,
  866. )
  867. # BUG this was screwing up the order of things
  868. # so I want to fix it and re-enable it
  869. if True:
  870. # Go BACK through and set the index/position now that all items exist.
  871. interface_sockets.sort(key=lambda a : a[1])
  872. for (socket, position) in interface_sockets:
  873. tree.interface.move(socket, position)
  874. # Now go and do nodes and links
  875. for tree_name, tree_data in data.items():
  876. print ("Importing sub-graph: %s with %s nodes" % (wrapGreen(tree_name), wrapPurple(len(tree_data[2]))) )
  877. tree_info = tree_data[0]
  878. nodes = tree_data[2]
  879. links = tree_data[3]
  880. parent_me = []
  881. tree = bpy.data.node_groups.get(tree_info["name"])
  882. tree.is_executing = True
  883. tree.do_live_update = False
  884. trees.append(tree)
  885. tree_sock_id_map=tree_sock_id_maps[tree.name]
  886. interface_parent_me = {}
  887. # from mantis.utilities import prRed, prWhite, prOrange, prGreen
  888. for name, propslist in nodes.items():
  889. bl_idname = propslist["bl_idname"]
  890. if bl_idname in NODES_REMOVED:
  891. prWhite(f"INFO: Ignoring import of node {name} of type {bl_idname}; it has been removed.")
  892. continue
  893. n = tree.nodes.new(bl_idname)
  894. if bl_idname in ["DeformerMorphTargetDeform"]:
  895. n.inputs.remove(n.inputs[-1]) # get rid of the wildcard
  896. if n.bl_idname in [ "SchemaArrayInput",
  897. "SchemaArrayInputGet",
  898. "SchemaArrayInputAll",
  899. "SchemaArrayOutput",
  900. "SchemaConstInput",
  901. "SchemaConstOutput",
  902. "SchemaOutgoingConnection",
  903. "SchemaIncomingConnection",]:
  904. n.update()
  905. if sub_tree := propslist.get("node_tree"):
  906. # now that I am doing multi-file exports, this is tricky
  907. # we need to see if the tree exists and if not, recurse
  908. # and import that tree before continuing.
  909. grp_tree = bpy.data.node_groups.get(sub_tree)
  910. if grp_tree is None: # for multi-file component this is intentional
  911. if search_multi_files: # we'll get the filename and recurse
  912. from bpy.path import native_pathsep, clean_name
  913. from os import path as os_path
  914. native_filepath = native_pathsep(filepath)
  915. directory = os_path.split(native_filepath)[0]
  916. subtree_filepath = os_path.join(directory, clean_name(sub_tree)+'.rig')
  917. subtree_data = get_graph_data_from_json(subtree_filepath)
  918. do_import(subtree_data, context,
  919. search_multi_files=True,
  920. filepath=subtree_filepath)
  921. #now get the grp_tree lol
  922. grp_tree = bpy.data.node_groups[sub_tree]
  923. else: # otherwise it is an error
  924. raise RuntimeError(f"Tree {sub_tree} not available to import.")
  925. n.node_tree = grp_tree
  926. from .base_definitions import node_group_update
  927. n.is_updating = True
  928. try:
  929. node_group_update(n, force = True)
  930. finally:
  931. n.is_updating=False
  932. # set up sockets
  933. setup_sockets(n, propslist, in_out="inputs")
  934. setup_sockets(n, propslist, in_out="outputs")
  935. for p, v in propslist.items():
  936. if p in ["node_tree",
  937. "sockets",
  938. "inputs",
  939. "outputs",
  940. "warning_propagation",
  941. "socket_idname"]:
  942. continue
  943. # will throw AttributeError if read-only
  944. # will throw TypeError if wrong type...
  945. if n.bl_idname == "NodeFrame" and p in ["width, height, location"]:
  946. continue
  947. if version < (4,4,0) and p == 'location_absolute':
  948. continue
  949. if p == "parent" and v is not None:
  950. parent_me.append( (n.name, v) )
  951. v = None # for now) #TODO
  952. try:
  953. setattr(n, p, v)
  954. except Exception as e:
  955. prRed (p)
  956. raise e
  957. for l in links:
  958. from_socket_name = l[6]
  959. to_socket_name = l[7]
  960. name1=l[0]
  961. name2=l[2]
  962. from_sock, to_sock = get_link_sockets(l, tree, tree_sock_id_map)
  963. try:
  964. link = tree.links.new(from_sock, to_sock)
  965. except TypeError:
  966. prPurple (from_sock)
  967. prOrange (to_sock)
  968. if print_link_failure:
  969. from_node_name = link[0]; from_socket_id = link[1]
  970. to_node_name = link[2]; to_socket_id = link[3]
  971. prWhite(f"looking for... {from_node_name}:{from_socket_id}, {to_node_name}:{to_socket_id}")
  972. prRed (f"Failed: {l[0]}:{l[1]} --> {l[2]}:{l[3]}")
  973. prRed (f" got node: {from_node_name}, {to_node_name}")
  974. prRed (f" got socket: {from_sock}, {to_sock}")
  975. raise RuntimeError
  976. else:
  977. prRed(f"Failed to add link in {tree.name}: {name1}:{from_socket_name}, {name2}:{to_socket_name}")
  978. # if at this point it doesn't work... we need to fix
  979. for name, p in parent_me:
  980. if (n := tree.nodes.get(name)) and (p := tree.nodes.get(p)):
  981. n.parent = p
  982. # otherwise the frame node is missing because it was not included in the data e.g. when grouping nodes.
  983. tree.is_executing = False
  984. tree.do_live_update = True
  985. def export_multi_file(trees : list, filepath : str, base_name :str) -> None:
  986. for t in trees:
  987. # this should name them the name of the tree...
  988. from bpy.path import native_pathsep, clean_name
  989. from os import path as os_path
  990. from os import mkdir
  991. native_filepath = native_pathsep(filepath)
  992. directory = os_path.split(native_filepath)[0]
  993. export_data = export_to_json([t], os_path.join(directory,
  994. clean_name(t.name)+'.rig'))
  995. write_json_data(export_data, os_path.join(directory,
  996. clean_name(t.name)+'.rig'))
  997. import bpy
  998. from bpy_extras.io_utils import ImportHelper, ExportHelper
  999. from bpy.props import StringProperty, BoolProperty, EnumProperty
  1000. from bpy.types import Operator
  1001. # Save As
  1002. class MantisExportNodeTreeSaveAs(Operator, ExportHelper):
  1003. """Export a Mantis Node Tree by filename."""
  1004. bl_idname = "mantis.export_save_as"
  1005. bl_label = "Export Mantis Tree as ...(JSON)"
  1006. # ExportHelper mix-in class uses this.
  1007. filename_ext = ".rig"
  1008. filter_glob: StringProperty(
  1009. default="*.rig",
  1010. options={'HIDDEN'},
  1011. maxlen=255, # Max internal buffer length, longer would be clamped.
  1012. )
  1013. export_trees_together : BoolProperty(
  1014. default=False,
  1015. name="Pack All Sub-Trees",
  1016. description="Pack all Sub-trees into one file?")
  1017. @classmethod
  1018. def poll(cls, context):
  1019. return hasattr(context.space_data, 'path')
  1020. def execute(self, context):
  1021. # we need to get the dependent trees from self.tree...
  1022. # there is no self.tree
  1023. # how do I choose a tree?
  1024. base_tree=context.space_data.path[-1].node_tree
  1025. from .utilities import all_trees_in_tree
  1026. trees = all_trees_in_tree(base_tree)[::-1]
  1027. prGreen("Exporting node graph with dependencies...")
  1028. for t in trees:
  1029. prGreen ("Node graph: \"%s\"" % (t.name))
  1030. base_tree.is_exporting = True
  1031. if self.export_trees_together:
  1032. export_data = export_to_json(trees, base_tree, self.filepath)
  1033. write_json_data(export_data, self.filepath)
  1034. else:
  1035. export_multi_file(trees, self.filepath, base_tree.name)
  1036. base_tree.is_exporting = False
  1037. base_tree.prevent_next_exec = True
  1038. # set the properties on the base tree for re-exporting with alt-s
  1039. base_tree.filepath = self.filepath
  1040. base_tree.export_all_subtrees_together = self.export_trees_together
  1041. return {'FINISHED'}
  1042. # Save
  1043. class MantisExportNodeTreeSave(Operator):
  1044. """Save a Mantis Node Tree to disk."""
  1045. bl_idname = "mantis.export_save"
  1046. bl_label = "Export Mantis Tree (JSON)"
  1047. @classmethod
  1048. def poll(cls, context):
  1049. return hasattr(context.space_data, 'path')
  1050. def execute(self, context):
  1051. base_tree=context.space_data.path[-1].node_tree
  1052. filepath = base_tree.filepath
  1053. from .utilities import all_trees_in_tree
  1054. trees = all_trees_in_tree(base_tree)[::-1]
  1055. prGreen("Exporting node graph with dependencies...")
  1056. for t in trees:
  1057. prGreen ("Node graph: \"%s\"" % (t.name))
  1058. base_tree.is_exporting = True
  1059. if base_tree.export_all_subtrees_together:
  1060. export_data = export_to_json(trees, filepath)
  1061. write_json_data(export_data, filepath)
  1062. else:
  1063. export_multi_file(trees, filepath, base_tree.name)
  1064. base_tree.is_exporting = False
  1065. base_tree.prevent_next_exec = True
  1066. return {'FINISHED'}
  1067. # Save Choose:
  1068. class MantisExportNodeTree(Operator):
  1069. """Save a Mantis Node Tree to disk."""
  1070. bl_idname = "mantis.export_save_choose"
  1071. bl_label = "Export Mantis Tree (JSON)"
  1072. @classmethod
  1073. def poll(cls, context):
  1074. return hasattr(context.space_data, 'path')
  1075. def execute(self, context):
  1076. base_tree=context.space_data.path[-1].node_tree
  1077. if base_tree.filepath:
  1078. prRed(base_tree.filepath)
  1079. return bpy.ops.mantis.export_save()
  1080. else:
  1081. return bpy.ops.mantis.export_save_as('INVOKE_DEFAULT')
  1082. # here is what needs to be done...
  1083. # - modify this to work with a sort of parsed-tree instead (sort of)
  1084. # - this needs to treat each sub-graph on its own
  1085. # - is this a problem? do I need to reconsider how I treat the graph data in mantis?
  1086. # - I should learn functional programming / currying
  1087. # - then the parsed-tree this builds must be executed as Blender nodes
  1088. # - I think... this is not important right now. not yet.
  1089. # - KEEP IT SIMPLE, STUPID
  1090. class MantisImportNodeTree(Operator, ImportHelper):
  1091. """Import a Mantis Node Tree."""
  1092. bl_idname = "mantis.import_tree"
  1093. bl_label = "Import Mantis Tree (JSON)"
  1094. # ImportHelper mixin class uses this
  1095. filename_ext = ".rig"
  1096. filter_glob : StringProperty(
  1097. default="*.rig",
  1098. options={'HIDDEN'},
  1099. maxlen=255, # Max internal buffer length, longer would be clamped.
  1100. )
  1101. def execute(self, context):
  1102. return do_import_from_file(self.filepath, context)
  1103. # this is useful:
  1104. # https://blender.stackexchange.com/questions/73286/how-to-call-a-confirmation-dialog-box
  1105. # class MantisReloadConfirmMenu(bpy.types.Panel):
  1106. # bl_label = "Confirm?"
  1107. # bl_idname = "OBJECT_MT_mantis_reload_confirm"
  1108. # def draw(self, context):
  1109. # layout = self.layout
  1110. # layout.operator("mantis.reload_tree")
  1111. class MantisReloadNodeTree(Operator):
  1112. # """Import a Mantis Node Tree."""
  1113. # bl_idname = "mantis.reload_tree"
  1114. # bl_label = "Import Mantis Tree"
  1115. """Reload Mantis Tree"""
  1116. bl_idname = "mantis.reload_tree"
  1117. bl_label = "Confirm reload tree?"
  1118. bl_options = {'REGISTER', 'INTERNAL'}
  1119. @classmethod
  1120. def poll(cls, context):
  1121. if hasattr(context.space_data, 'path'):
  1122. return True
  1123. return False
  1124. def invoke(self, context, event):
  1125. return context.window_manager.invoke_confirm(self, event)
  1126. def execute(self, context):
  1127. base_tree=context.space_data.path[-1].node_tree
  1128. if not base_tree.filepath:
  1129. self.report({'ERROR'}, "Tree has not been saved - so it cannot be reloaded.")
  1130. return {'CANCELLED'}
  1131. self.report({'INFO'}, "reloading tree")
  1132. return do_import_from_file(base_tree.filepath, context)
  1133. # todo:
  1134. # - export metarig and option to import it
  1135. # - same with controls
  1136. # - it would be nice to have a library of these that can be imported alongside the mantis graph