i_o.py 61 KB

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