i_o.py 61 KB

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