i_o.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  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.parsed_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. # some mistakes in versioning makes it possible for older trees to have
  449. # standard Blender types instead of Mantis types
  450. if bl_socket_idname == 'NodeSocketFloat':
  451. bl_socket_idname = 'FloatSocket'
  452. elif bl_socket_idname == 'NodeSocketVector':
  453. bl_socket_idname = 'VectorSocket'
  454. elif bl_socket_idname == 'NodeSocketInt':
  455. bl_socket_idname = 'IntSocket'
  456. try:
  457. socket_class = getattr(socket_definitions, bl_socket_idname)
  458. except AttributeError: # sometimes the class doesn't work.
  459. # I think this happens because of an oversight in versioning. Sorry.
  460. socket_class = getattr(socket_definitions, "FloatSocket")
  461. prRed(f"Cannot export interface socket of type {bl_socket_idname}.\n"
  462. f"See interface socket: {sock.name} in tree {tree.name}.\n"
  463. f"Try to change the socket type to a Mantis type.\n"
  464. f"Exporting a FloatSocket instead. This will not alter Mantis' "
  465. f"usability or behavior.")
  466. sock_parent = None
  467. if sock.parent:
  468. sock_parent = sock.parent.name
  469. for propname in dir(sock):
  470. if propname in prop_ignore_interface:
  471. continue
  472. if (propname == "parent"):
  473. sock_data[propname] = sock_parent
  474. continue
  475. v = getattr(sock, propname)
  476. if (propname in prop_ignore) or ( callable(v) ):
  477. continue
  478. if isinstance(getattr(sock, propname), bpy.types.bpy_prop_array):
  479. v = tuple(getattr(sock, propname))
  480. if not is_jsonable( v ):
  481. raise RuntimeError(f"{propname}, {type(v)}")
  482. sock_data[propname] = v
  483. # this is a property. pain.
  484. sock_data["socket_type"] = socket_class.interface_type.fget(socket_class)
  485. tree_in_out[sock.identifier] = sock_data
  486. def export_to_json(trees, base_tree=None, path="", write_file=True, only_selected=False, ):
  487. export_data = {}
  488. for tree in trees:
  489. current_tree_is_base_tree = False
  490. if tree is trees[-1]:
  491. current_tree_is_base_tree = True
  492. tree_info, tree_in_out = {}, {}
  493. tree_info = get_tree_data(tree)
  494. curves, metarig_data = {}, {}
  495. embed_metarigs=True
  496. if base_tree and embed_metarigs:
  497. curves_in_tree, metarigs_in_tree = scan_tree_for_objects(base_tree, tree)
  498. for crv in curves_in_tree:
  499. curves[crv.name] = get_curve_for_pack(crv)
  500. for mr in metarigs_in_tree:
  501. metarig_data[mr.name] = get_armature_for_pack(mr)
  502. # if only_selected:
  503. # # all in/out links, relative to the selection, should be marked and used to initialize tree properties
  504. if not only_selected: # we'll handle this later with the links
  505. for sock in tree.interface.items_tree:
  506. get_interface_data(tree, tree_in_out) # it concerns me that this one modifies
  507. # the collection instead of getting the data and returning it. TODO refactor this
  508. nodes = {}
  509. for node in tree.nodes:
  510. if only_selected and node.select == False:
  511. continue
  512. nodes[node.name] = get_node_data(node)
  513. links = []
  514. in_sockets, out_sockets = {}, {}
  515. unique_sockets_from, unique_sockets_to = {}, {}
  516. in_node = {"name":"MANTIS_AUTOGEN_GROUP_INPUT", "bl_idname":"NodeGroupInput", "inputs":in_sockets}
  517. out_node = {"name":"MANTIS_AUTOGEN_GROUP_OUTPUT", "bl_idname":"NodeGroupOutput", "outputs":out_sockets}
  518. add_input_node, add_output_node = False, False
  519. for link in tree.links:
  520. from_node_name, from_socket_id = link.from_node.name, link.from_socket.identifier
  521. to_node_name, to_socket_id = link.to_node.name, link.to_socket.identifier
  522. from_socket_name, to_socket_name = link.from_socket.name, link.to_socket.name
  523. # get the indices of the sockets to be absolutely sure
  524. for from_outoput_index, outp in enumerate(link.from_node.outputs):
  525. # for some reason, 'is' does not return True no matter what...
  526. # so we are gonn compare the memory address directly, this is stupid
  527. if (outp.as_pointer() == link.from_socket.as_pointer()): break
  528. else:
  529. problem=link.from_node.name + "::" + link.from_socket.name
  530. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  531. for to_input_index, inp in enumerate(link.to_node.inputs):
  532. if (inp.as_pointer() == link.to_socket.as_pointer()): break
  533. else:
  534. problem = link.to_node.name + "::" + link.to_socket.name
  535. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  536. if current_tree_is_base_tree:
  537. if (only_selected and link.from_node.select) and (not link.to_node.select):
  538. # handle an output in the tree
  539. add_output_node=True
  540. if not (sock_name := unique_sockets_to.get(link.from_socket.node.name+link.from_socket.identifier)):
  541. sock_name = link.to_socket.name; name_stub = sock_name
  542. used_names = list(tree_in_out.keys()); i=0
  543. while sock_name in used_names:
  544. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  545. unique_sockets_to[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  546. out_sock = out_sockets.get(sock_name)
  547. if not out_sock:
  548. out_sock = {}; out_sockets[sock_name] = out_sock
  549. out_sock["index"]=len(out_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  550. # what in the bad word is happening here?
  551. # why?
  552. # why no de-duplication?
  553. # what was I thinking?
  554. # TODO REFACTOR THIS SOON
  555. out_sock["name"] = sock_name
  556. out_sock["identifier"] = sock_name
  557. out_sock["bl_idname"] = link.to_socket.bl_idname
  558. out_sock["is_output"] = False
  559. out_sock["source"]=[link.to_socket.node.name,link.to_socket.identifier]
  560. 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
  561. sock_data={}
  562. sock_data["name"] = sock_name
  563. sock_data["item_type"] = "SOCKET"
  564. sock_data["default_closed"] = False
  565. # record the actual bl_idname and the proper interface type.
  566. sock_data["socket_type"] = link.from_socket.interface_type
  567. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  568. sock_data["identifier"] = sock_name
  569. sock_data["in_out"]="OUTPUT"
  570. sock_data["index"]=out_sock["index"]
  571. tree_in_out[sock_name] = sock_data
  572. to_node_name=out_node["name"]
  573. to_socket_id=out_sock["identifier"]
  574. to_input_index=out_sock["index"]
  575. to_socket_name=out_sock["name"]
  576. elif (only_selected and (not link.from_node.select)) and link.to_node.select:
  577. add_input_node=True
  578. # we need to get a unique name for this
  579. # use the Tree IN/Out because we are dealing with Group in/out
  580. if not (sock_name := unique_sockets_from.get(link.from_socket.node.name+link.from_socket.identifier)):
  581. sock_name = link.from_socket.name; name_stub = sock_name
  582. used_names = list(tree_in_out.keys()); i=0
  583. while sock_name in used_names:
  584. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  585. unique_sockets_from[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  586. in_sock = in_sockets.get(sock_name)
  587. if not in_sock:
  588. in_sock = {}; in_sockets[sock_name] = in_sock
  589. in_sock["index"]=len(in_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  590. #
  591. in_sock["name"] = sock_name
  592. in_sock["identifier"] = sock_name
  593. in_sock["bl_idname"] = link.from_socket.bl_idname
  594. in_sock["is_output"] = True
  595. 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
  596. in_sock["source"] = [link.from_socket.node.name,link.from_socket.identifier]
  597. sock_data={}
  598. sock_data["name"] = sock_name
  599. sock_data["item_type"] = "SOCKET"
  600. sock_data["default_closed"] = False
  601. # record the actual bl_idname and the proper interface type.
  602. sock_data["socket_type"] = link.from_socket.interface_type
  603. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  604. sock_data["identifier"] = sock_name
  605. sock_data["in_out"]="INPUT"
  606. sock_data["index"]=in_sock["index"]
  607. tree_in_out[sock_name] = sock_data
  608. from_node_name=in_node.get("name")
  609. from_socket_id=in_sock["identifier"]
  610. from_outoput_index=in_sock["index"]
  611. from_socket_name=in_node.get("name")
  612. # parentheses matter here...
  613. elif (only_selected and not (link.from_node.select and link.to_node.select)):
  614. continue
  615. elif only_selected and not (link.from_node.select and link.to_node.select):
  616. continue # pass if both links are not selected
  617. links.append( (from_node_name,
  618. from_socket_id,
  619. to_node_name,
  620. to_socket_id,
  621. from_outoput_index,
  622. to_input_index,
  623. from_socket_name,
  624. to_socket_name) ) # it's a tuple
  625. if add_input_node or add_output_node:
  626. all_nodes_bounding_box=[Vector((float("inf"),float("inf"))), Vector((-float("inf"),-float("inf")))]
  627. for n in nodes.values():
  628. if n["location"][0] < all_nodes_bounding_box[0].x:
  629. all_nodes_bounding_box[0].x = n["location"][0]
  630. if n["location"][1] < all_nodes_bounding_box[0].y:
  631. all_nodes_bounding_box[0].y = n["location"][1]
  632. #
  633. if n["location"][0] > all_nodes_bounding_box[1].x:
  634. all_nodes_bounding_box[1].x = n["location"][0]
  635. if n["location"][1] > all_nodes_bounding_box[1].y:
  636. all_nodes_bounding_box[1].y = n["location"][1]
  637. if add_input_node:
  638. 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))
  639. nodes["MANTIS_AUTOGEN_GROUP_INPUT"]=in_node
  640. if add_output_node:
  641. 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))
  642. nodes["MANTIS_AUTOGEN_GROUP_OUTPUT"]=out_node
  643. export_data[tree.name] = (tree_info, tree_in_out, nodes, links, curves, metarig_data,) # f_curves)
  644. return export_data
  645. def write_json_data(data, path):
  646. import json
  647. with open(path, "w") as file:
  648. print(wrapWhite("Writing mantis tree data to: "), wrapGreen(file.name))
  649. file.write( json.dumps(data, indent = 4) )
  650. def get_link_sockets(link, tree, tree_socket_id_map):
  651. from_node_name = link[0]
  652. from_socket_id = link[1]
  653. to_node_name = link[2]
  654. to_socket_id = link[3]
  655. from_output_index = link[4]
  656. to_input_index = link[5]
  657. from_socket_name = link[6]
  658. to_socket_name = link[7]
  659. # TODO: make this a loop and swap out the in/out stuff
  660. # this is OK but I want to avoid code-duplication, which this almost is.
  661. from_node = tree.nodes.get(from_node_name)
  662. # first try and get by name. we'll use this if the ID and the name do not match.
  663. # from_sock = from_node.outputs.get(from_socket_name)
  664. id1 = from_socket_id
  665. if hasattr(from_node, "node_tree") or \
  666. from_node.bl_idname in ["SchemaArrayInput",
  667. "SchemaArrayInputGet",
  668. "SchemaArrayInputAll",
  669. "SchemaConstInput",
  670. "SchemaIncomingConnection", ]: # now we have to map by something else
  671. try:
  672. id1 = from_node.outputs[from_socket_name].identifier
  673. except KeyError: # we'll try index if nothing else works
  674. try:
  675. id1 = from_node.outputs[from_output_index].identifier
  676. except IndexError as e:
  677. prRed("failed to create link: "
  678. f"{from_node_name}:{from_socket_id} --> {to_node_name}:{to_socket_id}")
  679. return (None, None)
  680. elif from_node.bl_idname in ["NodeGroupInput"]:
  681. id1 = tree_socket_id_map.get(from_socket_id)
  682. for from_sock in from_node.outputs:
  683. if from_sock.identifier == id1: break
  684. else:
  685. from_sock = None
  686. id2 = to_socket_id
  687. to_node = tree.nodes[to_node_name]
  688. if hasattr(to_node, "node_tree") or \
  689. to_node.bl_idname in ["SchemaArrayOutput",
  690. "SchemaConstOutput",
  691. "SchemaOutgoingConnection", ]: # now we have to map by something else
  692. try:
  693. id2 = to_node.inputs[to_socket_name].identifier
  694. except KeyError: # we'll try index if nothing else works
  695. try: # nesting try/except is ugly but it is right...
  696. id2 = to_node.inputs[to_input_index].identifier
  697. except IndexError as e:
  698. prRed("failed to create link: "
  699. f"{from_node_name}:{from_socket_id} --> {to_node_name}:{to_socket_id}")
  700. return (from_sock, None)
  701. elif to_node.bl_idname in ["NodeGroupOutput"]:
  702. id2 = tree_socket_id_map.get(to_socket_id)
  703. for to_sock in to_node.inputs:
  704. if to_sock.identifier == id2: break
  705. else:
  706. to_sock = None
  707. return from_sock, to_sock
  708. def setup_sockets(node, propslist, in_out="inputs"):
  709. sockets_removed = []
  710. socket = None
  711. for i, (s_id, s_val) in enumerate(propslist[in_out].items()):
  712. if node.bl_idname in ['NodeReroute']:
  713. break # Reroute Nodes do not have anything I can set or modify.
  714. for socket_removed in SOCKETS_REMOVED:
  715. if node.bl_idname == socket_removed[0] and s_id == socket_removed[1]:
  716. prWhite(f"INFO: Ignoring import of socket {s_id}; it has been removed.")
  717. sockets_removed.append(s_val["index"])
  718. sockets_removed.sort()
  719. continue
  720. if s_val["is_output"]:
  721. if node.bl_idname in "MantisSchemaGroup":
  722. node.is_updating = True
  723. try:
  724. socket = node.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id)
  725. finally:
  726. node.is_updating=False
  727. elif s_val["index"] >= len(node.outputs):
  728. if node.bl_idname in add_inputs_bl_idnames:
  729. socket = node.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, )
  730. else: # first try to get by ID AND name. ID's switch around a bit so we need both to match.
  731. for socket in node.outputs:
  732. if socket.identifier == s_id and socket.name == s_val['name']:
  733. break
  734. # this often fails for group outputs and such
  735. # because the socket ID may not be the same when it is re-generated
  736. else: # otherwise try to get the index
  737. # IT IS NOT CLEAR but this is what throws the index error below BAD
  738. # try to get by name
  739. socket = node.outputs.get(s_val['name'])
  740. if not socket:
  741. try:
  742. socket = node.outputs[int(s_val["index"])]
  743. except IndexError as e:
  744. print (node.id_data.name)
  745. print (propslist['name'])
  746. print (s_id, s_val['name'], s_val['index'])
  747. raise e
  748. if socket.name != s_val["name"]:
  749. right_name = s_val['name']
  750. prRed( "There has been an error getting a socket while importing data."
  751. f"found name: {socket.name}; should have found: {right_name}.")
  752. else:
  753. for removed_index in sockets_removed:
  754. if s_val["index"] > removed_index:
  755. s_val["index"]-=1
  756. if s_val["index"] >= len(node.inputs):
  757. if node.bl_idname in add_inputs_bl_idnames:
  758. socket = node.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  759. elif node.bl_idname in ["MantisSchemaGroup"]:
  760. node.is_updating = True
  761. try:
  762. socket = node.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  763. finally:
  764. node.is_updating=False
  765. elif node.bl_idname in ["NodeGroupOutput"]:
  766. pass # this is dealt with separately
  767. else:
  768. prWhite("Not found: ", propslist['name'], s_val["name"], s_id)
  769. prRed("Index: ", s_val["index"], "Number of inputs", len(node.inputs))
  770. for thing1, thing2 in zip(propslist[in_out].keys(), getattr(node, in_out).keys()):
  771. print (thing1, thing2)
  772. raise NotImplementedError(wrapRed(f"{node.bl_idname} in {node.id_data.name} needs to be handled in JSON load."))
  773. else: # first try to get by ID AND name. ID's switch around a bit so we need both to match.
  774. for socket in node.inputs:
  775. if socket.identifier == s_id and socket.name == s_val['name']:
  776. break
  777. # failing to find the socket by ID is less common for inputs than outputs.
  778. # it usually isn't a problem.
  779. else: # otherwise try to get the index
  780. # IT IS NOT CLEAR but this is what throws the index error below BAD
  781. socket = node.inputs.get(s_val["name"])
  782. if not socket:
  783. socket = node.inputs[int(s_val["index"])]
  784. # finally we need to check that the name matches.
  785. if socket.name != s_val["name"]:
  786. right_name = s_val['name']
  787. prRed( "There has been an error getting a socket while importing data."
  788. f"found name: {socket.name}; should have found: {right_name}.")
  789. if socket is None:
  790. # Error?
  791. return
  792. # set the value
  793. for s_p, s_v in s_val.items():
  794. if s_p not in ["default_value"]:
  795. if s_p == "search_prop" and node.bl_idname == 'UtilityMetaRig':
  796. socket.node.armature= s_v
  797. socket.search_prop=bpy.data.objects.get(s_v)
  798. if s_p == "search_prop" and node.bl_idname in ['UtilityMatrixFromCurve', 'UtilityMatricesFromCurve']:
  799. socket.search_prop=bpy.data.objects.get(s_v)
  800. elif s_p == "bone" and socket.bl_idname == 'EnumMetaBoneSocket':
  801. socket.bone = s_v
  802. socket.node.pose_bone = s_v
  803. continue # not editable and NOT SAFE
  804. #
  805. if socket.bl_idname in ["BooleanThreeTupleSocket"]:
  806. value = bool(s_v[0]), bool(s_v[1]), bool(s_v[2]),
  807. s_v = value
  808. try:
  809. setattr(socket, s_p , s_v)
  810. except TypeError as e:
  811. prRed("Can't set socket due to type mismatch: ", node.name, socket.name, s_p, s_v)
  812. # raise e
  813. except ValueError as e:
  814. prRed("Can't set socket due to type mismatch: ", node.name, socket.name, s_p, s_v)
  815. # raise e
  816. except AttributeError as e:
  817. if print_read_only_warning == True:
  818. prWhite("Tried to write a read-only property, ignoring...")
  819. prWhite(f"{socket.node.name}[{socket.name}].{s_p} is read only, cannot set value to {s_v}")
  820. def do_import_from_file(filepath, context):
  821. import json
  822. all_trees = [n_tree for n_tree in bpy.data.node_groups if n_tree.bl_idname in ["MantisTree", "SchemaTree"]]
  823. for tree in all_trees:
  824. tree.is_exporting = True
  825. tree.do_live_update = False
  826. def do_cleanup(tree):
  827. tree.is_exporting = False
  828. tree.do_live_update = True
  829. tree.prevent_next_exec = True
  830. with open(filepath, 'r', encoding='utf-8') as f:
  831. data = json.load(f)
  832. do_import(data,context, search_multi_files=True, filepath=filepath)
  833. for tree in all_trees:
  834. do_cleanup(tree)
  835. tree = bpy.data.node_groups[list(data.keys())[-1]]
  836. try:
  837. context.space_data.node_tree = tree
  838. except AttributeError: # not hovering over the Node Editor
  839. pass
  840. return {'FINISHED'}
  841. # otherwise:
  842. # repeat this because we left the with, this is bad and ugly but I don't care
  843. for tree in all_trees:
  844. do_cleanup(tree)
  845. return {'CANCELLED'}
  846. # TODO figure out the right way to dedupe this stuff (see above)
  847. # I need this function for recursing through multi-file components
  848. # but I am using the with statement in the above function...
  849. # it should be easy to refactor but I don't know 100% for sure
  850. # the behaviour will be identical or if that matters.
  851. def get_graph_data_from_json(filepath) -> dict:
  852. import json
  853. with open(filepath, 'r', encoding='utf-8') as f:
  854. data = json.load(f)
  855. return data
  856. def do_import(data, context, search_multi_files=False, filepath='', skip_existing=False):
  857. trees = []
  858. tree_sock_id_maps = {}
  859. skip_trees = set()
  860. # First: init the interface of the node graph
  861. for tree_name, tree_data in data.items():
  862. tree_info = tree_data[0]
  863. tree_in_out = tree_data[1]
  864. # TODO: IMPORT THIS DATA HERE!!!
  865. try:
  866. curves = tree_data[4]
  867. armatures = tree_data[5]
  868. except IndexError: # shouldn't happen but maybe someone has an old file
  869. curves = {}
  870. armatures = {}
  871. for curve_name, curve_data in curves.items():
  872. from .utilities import import_curve_data_to_object, import_metarig_data
  873. import_curve_data_to_object(curve_name, curve_data)
  874. for armature_name, armature_data in armatures.items():
  875. import_metarig_data(armature_data)
  876. # need to make a new tree; first, try to get it:
  877. tree = bpy.data.node_groups.get(tree_info["name"])
  878. if tree and skip_existing:
  879. skip_trees.add(tree.name)
  880. continue # already done here because the tree already exists.
  881. if tree is None:
  882. tree = bpy.data.node_groups.new(tree_info["name"], tree_info["bl_idname"])
  883. tree.nodes.clear(); tree.links.clear(); tree.interface.clear()
  884. # this may be a bad bad thing to do without some kind of warning TODO TODO
  885. tree.is_executing = True
  886. tree.do_live_update = False
  887. trees.append(tree)
  888. tree_sock_id_map = {}
  889. tree_sock_id_maps[tree.name] = tree_sock_id_map
  890. interface_parent_me = {}
  891. # I need to guarantee that the interface items are in the right order.
  892. interface_sockets = [] # I'll just sort them afterwards so I hold them here.
  893. default_position=0 # We'll use this if the position attribute is not set when e.g. making groups.
  894. for s_name, s_props in tree_in_out.items():
  895. if s_props["item_type"] == 'SOCKET':
  896. if s_props["socket_type"] == "LayerMaskSocket":
  897. continue
  898. if (socket_type := s_props["socket_type"]) == "NodeSocketColor":
  899. socket_type = "VectorSocket"
  900. if bpy.app.version != (4,5,0):
  901. sock = tree.interface.new_socket(s_props["name"], in_out=s_props["in_out"], socket_type=socket_type)
  902. else: # blender 4.5.0 LTS, have to workaround a bug!
  903. from .versioning import workaround_4_5_0_interface_update
  904. sock = workaround_4_5_0_interface_update(tree=tree, name=s_props["name"], in_out=s_props["in_out"],
  905. sock_type=socket_type, parent_name=s_props.get("parent", ''))
  906. tree_sock_id_map[s_name] = sock.identifier
  907. if not (socket_position := s_props.get('position')):
  908. socket_position=default_position; default_position+=1
  909. interface_sockets.append( (sock, socket_position) )
  910. # TODO: set whatever properties are needed (default, etc)
  911. if panel := s_props.get("parent"): # this get is just to maintain compatibility with an older form of this script... and it is harmless
  912. interface_parent_me[sock] = (panel, s_props["position"])
  913. else: # it's a panel
  914. panel = tree.interface.new_panel(s_props["name"], description=s_props.get("description"), default_closed=s_props.get("default_closed"))
  915. for socket, (panel, index) in interface_parent_me.items():
  916. tree.interface.move_to_parent(
  917. socket,
  918. tree.interface.items_tree.get(panel),
  919. index,
  920. )
  921. # BUG this was screwing up the order of things
  922. # so I want to fix it and re-enable it
  923. if True:
  924. # Go BACK through and set the index/position now that all items exist.
  925. interface_sockets.sort(key=lambda a : a[1])
  926. for (socket, position) in interface_sockets:
  927. tree.interface.move(socket, position)
  928. # Now go and do nodes and links
  929. for tree_name, tree_data in data.items():
  930. if tree_name in skip_trees:
  931. continue
  932. print ("Importing sub-graph: %s with %s nodes" % (wrapGreen(tree_name), wrapPurple(len(tree_data[2]))) )
  933. tree_info = tree_data[0]
  934. nodes = tree_data[2]
  935. links = tree_data[3]
  936. parent_me = []
  937. tree = bpy.data.node_groups.get(tree_info["name"])
  938. tree.is_executing = True
  939. tree.do_live_update = False
  940. trees.append(tree)
  941. tree_sock_id_map=tree_sock_id_maps[tree.name]
  942. interface_parent_me = {}
  943. # from mantis.utilities import prRed, prWhite, prOrange, prGreen
  944. for name, propslist in nodes.items():
  945. bl_idname = propslist["bl_idname"]
  946. if bl_idname in NODES_REMOVED:
  947. prWhite(f"INFO: Ignoring import of node {name} of type {bl_idname}; it has been removed.")
  948. continue
  949. n = tree.nodes.new(bl_idname)
  950. if bl_idname in ["DeformerMorphTargetDeform"]:
  951. n.inputs.remove(n.inputs[-1]) # get rid of the wildcard
  952. if bl_idname in ['UtilityDeclareCollections']:
  953. n.collection_declarations = propslist['collection_declarations']
  954. n.update_interface()
  955. continue
  956. if n.bl_idname in [ "SchemaArrayInput",
  957. "SchemaArrayInputGet",
  958. "SchemaArrayInputAll",
  959. "SchemaArrayOutput",
  960. "SchemaConstInput",
  961. "SchemaConstOutput",
  962. "SchemaOutgoingConnection",
  963. "SchemaIncomingConnection",]:
  964. n.update()
  965. if sub_tree := propslist.get("node_tree"):
  966. # now that I am doing multi-file exports, this is tricky
  967. # we need to see if the tree exists and if not, recurse
  968. # and import that tree before continuing.
  969. grp_tree = bpy.data.node_groups.get(sub_tree)
  970. if grp_tree is None: # for multi-file component this is intentional
  971. if search_multi_files: # we'll get the filename and recurse
  972. from bpy.path import native_pathsep, clean_name
  973. from os import path as os_path
  974. native_filepath = native_pathsep(filepath)
  975. directory = os_path.split(native_filepath)[0]
  976. subtree_filepath = os_path.join(directory, clean_name(sub_tree)+'.rig')
  977. subtree_data = get_graph_data_from_json(subtree_filepath)
  978. do_import(subtree_data, context,
  979. search_multi_files=True,
  980. filepath=subtree_filepath)
  981. #now get the grp_tree lol
  982. grp_tree = bpy.data.node_groups[sub_tree]
  983. else: # otherwise it is an error
  984. raise RuntimeError(f"Tree {sub_tree} not available to import.")
  985. n.node_tree = grp_tree
  986. from .base_definitions import node_group_update
  987. n.is_updating = True
  988. try:
  989. node_group_update(n, force = True)
  990. finally:
  991. n.is_updating=False
  992. # set up sockets
  993. setup_sockets(n, propslist, in_out="inputs")
  994. setup_sockets(n, propslist, in_out="outputs")
  995. for p, v in propslist.items():
  996. if p in ["node_tree",
  997. "sockets",
  998. "inputs",
  999. "outputs",
  1000. "warning_propagation",
  1001. "socket_idname"]:
  1002. continue
  1003. # will throw AttributeError if read-only
  1004. # will throw TypeError if wrong type...
  1005. if n.bl_idname == "NodeFrame" and p in ["width, height, location"]:
  1006. continue
  1007. if version < (4,4,0) and p == 'location_absolute':
  1008. continue
  1009. if p == "parent" and v is not None:
  1010. parent_me.append( (n.name, v) )
  1011. v = None # for now) #TODO
  1012. try:
  1013. setattr(n, p, v)
  1014. except Exception as e:
  1015. prRed (p)
  1016. raise e
  1017. for l in links:
  1018. from_socket_name = l[6]
  1019. to_socket_name = l[7]
  1020. name1=l[0]
  1021. name2=l[2]
  1022. from_sock, to_sock = get_link_sockets(l, tree, tree_sock_id_map)
  1023. try:
  1024. link = tree.links.new(from_sock, to_sock)
  1025. except TypeError:
  1026. prPurple (from_sock)
  1027. prOrange (to_sock)
  1028. if print_link_failure:
  1029. from_node_name = l[0]; from_socket_id = l[1]
  1030. to_node_name = l[2]; to_socket_id = l[3]
  1031. prWhite(f"looking for... {from_node_name}:{from_socket_id}, {to_node_name}:{to_socket_id}")
  1032. prRed (f"Failed: {l[0]}:{l[1]} --> {l[2]}:{l[3]}")
  1033. prRed (f" got node: {from_node_name}, {to_node_name}")
  1034. prRed (f" got socket: {from_sock}, {to_sock}")
  1035. prWhite(f"Failed to add link in {tree.name}: {name1}:{from_socket_name}, {name2}:{to_socket_name}")
  1036. raise RuntimeError
  1037. else:
  1038. prRed(f"Failed to add link in {tree.name}: {name1}:{from_socket_name}, {name2}:{to_socket_name}")
  1039. # if at this point it doesn't work... we need to fix
  1040. for name, p in parent_me:
  1041. if (n := tree.nodes.get(name)) and (p := tree.nodes.get(p)):
  1042. n.parent = p
  1043. # otherwise the frame node is missing because it was not included in the data e.g. when grouping nodes.
  1044. tree.is_executing = False
  1045. tree.do_live_update = True
  1046. def export_multi_file(trees : list, base_tree, filepath : str, base_name :str) -> None:
  1047. for t in trees:
  1048. # this should name them the name of the tree...
  1049. from bpy.path import native_pathsep, clean_name
  1050. from os import path as os_path
  1051. from os import mkdir
  1052. native_filepath = native_pathsep(filepath)
  1053. directory = os_path.split(native_filepath)[0]
  1054. export_data = export_to_json([t], base_tree, os_path.join(directory,
  1055. clean_name(t.name)+'.rig'))
  1056. write_json_data(export_data, os_path.join(directory,
  1057. clean_name(t.name)+'.rig'))
  1058. import bpy
  1059. from bpy_extras.io_utils import ImportHelper, ExportHelper
  1060. from bpy.props import StringProperty, BoolProperty, EnumProperty
  1061. from bpy.types import Operator
  1062. # Save As
  1063. class MantisExportNodeTreeSaveAs(Operator, ExportHelper):
  1064. """Export a Mantis Node Tree by filename."""
  1065. bl_idname = "mantis.export_save_as"
  1066. bl_label = "Export Mantis Tree as ...(.rig)"
  1067. # ExportHelper mix-in class uses this.
  1068. filename_ext = ".rig"
  1069. filter_glob: StringProperty(
  1070. default="*.rig",
  1071. options={'HIDDEN'},
  1072. maxlen=255, # Max internal buffer length, longer would be clamped.
  1073. )
  1074. export_trees_together : BoolProperty(
  1075. default=False,
  1076. name="Pack All Sub-Trees",
  1077. description="Pack all Sub-trees into one file?")
  1078. @classmethod
  1079. def poll(cls, context):
  1080. return hasattr(context.space_data, 'path')
  1081. def execute(self, context):
  1082. # we need to get the dependent trees from self.tree...
  1083. # there is no self.tree
  1084. # how do I choose a tree?
  1085. base_tree=context.space_data.path[-1].node_tree
  1086. from .utilities import all_trees_in_tree
  1087. trees = all_trees_in_tree(base_tree)[::-1]
  1088. prGreen("Exporting node graph with dependencies...")
  1089. for t in trees:
  1090. prGreen ("Node graph: \"%s\"" % (t.name))
  1091. base_tree.is_exporting = True
  1092. if self.export_trees_together:
  1093. export_data = export_to_json(trees, base_tree, self.filepath)
  1094. write_json_data(export_data, self.filepath)
  1095. else:
  1096. export_multi_file(trees, base_tree, self.filepath, base_tree.name)
  1097. base_tree.is_exporting = False
  1098. base_tree.prevent_next_exec = True
  1099. # set the properties on the base tree for re-exporting with alt-s
  1100. base_tree.filepath = self.filepath
  1101. base_tree.export_all_subtrees_together = self.export_trees_together
  1102. return {'FINISHED'}
  1103. # Save
  1104. class MantisExportNodeTreeSave(Operator):
  1105. """Save a Mantis Node Tree to disk."""
  1106. bl_idname = "mantis.export_save"
  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. filepath = base_tree.filepath
  1114. from .utilities import all_trees_in_tree
  1115. trees = all_trees_in_tree(base_tree)[::-1]
  1116. prGreen("Exporting node graph with dependencies...")
  1117. for t in trees:
  1118. prGreen ("Node graph: \"%s\"" % (t.name))
  1119. base_tree.is_exporting = True
  1120. if base_tree.export_all_subtrees_together:
  1121. export_data = export_to_json(trees, base_tree, filepath)
  1122. write_json_data(export_data, filepath)
  1123. else:
  1124. export_multi_file(trees, base_tree, filepath, base_tree.name)
  1125. base_tree.is_exporting = False
  1126. base_tree.prevent_next_exec = True
  1127. return {'FINISHED'}
  1128. # Save Choose:
  1129. class MantisExportNodeTree(Operator):
  1130. """Save a Mantis Node Tree to disk."""
  1131. bl_idname = "mantis.export_save_choose"
  1132. bl_label = "Export Mantis Tree (.rig)"
  1133. @classmethod
  1134. def poll(cls, context):
  1135. return hasattr(context.space_data, 'path')
  1136. def execute(self, context):
  1137. base_tree=context.space_data.path[-1].node_tree
  1138. if base_tree.filepath:
  1139. prRed(base_tree.filepath)
  1140. return bpy.ops.mantis.export_save()
  1141. else:
  1142. return bpy.ops.mantis.export_save_as('INVOKE_DEFAULT')
  1143. # here is what needs to be done...
  1144. # - modify this to work with a sort of parsed-tree instead (sort of)
  1145. # - this needs to treat each sub-graph on its own
  1146. # - is this a problem? do I need to reconsider how I treat the graph data in mantis?
  1147. # - I should learn functional programming / currying
  1148. # - then the parsed-tree this builds must be executed as Blender nodes
  1149. # - I think... this is not important right now. not yet.
  1150. # - KEEP IT SIMPLE, STUPID
  1151. class MantisImportNodeTree(Operator, ImportHelper):
  1152. """Import a Mantis Node Tree."""
  1153. bl_idname = "mantis.import_tree"
  1154. bl_label = "Import Mantis Tree (.rig)"
  1155. # ImportHelper mixin class uses this
  1156. filename_ext = ".rig"
  1157. filter_glob : StringProperty(
  1158. default="*.rig",
  1159. options={'HIDDEN'},
  1160. maxlen=255, # Max internal buffer length, longer would be clamped.
  1161. )
  1162. def execute(self, context):
  1163. import cProfile
  1164. from os import environ
  1165. do_profile=False
  1166. if environ.get("DOPROFILE"):
  1167. do_profile=True
  1168. pass_error = True
  1169. if do_profile:
  1170. import pstats, io
  1171. from pstats import SortKey
  1172. with cProfile.Profile() as pr:
  1173. return_value = do_import_from_file(self.filepath, context)
  1174. s = io.StringIO()
  1175. sortby = SortKey.TIME
  1176. # sortby = SortKey.CUMULATIVE
  1177. ps = pstats.Stats(pr, stream=s).strip_dirs().sort_stats(sortby)
  1178. ps.print_stats(20) # print the top 20
  1179. print(s.getvalue())
  1180. return return_value
  1181. else:
  1182. return do_import_from_file(self.filepath, context)
  1183. class MantisImportNodeTreeNoMenu(Operator):
  1184. """Import a Mantis Node Tree."""
  1185. bl_idname = "mantis.import_tree_no_menu"
  1186. bl_label = "Import Mantis Tree (.rig)"
  1187. filepath : StringProperty()
  1188. def execute(self, context):
  1189. return do_import_from_file(self.filepath, context)
  1190. # this is useful:
  1191. # https://blender.stackexchange.com/questions/73286/how-to-call-a-confirmation-dialog-box
  1192. # class MantisReloadConfirmMenu(bpy.types.Panel):
  1193. # bl_label = "Confirm?"
  1194. # bl_idname = "OBJECT_MT_mantis_reload_confirm"
  1195. # def draw(self, context):
  1196. # layout = self.layout
  1197. # layout.operator("mantis.reload_tree")
  1198. class MantisReloadNodeTree(Operator):
  1199. # """Import a Mantis Node Tree."""
  1200. # bl_idname = "mantis.reload_tree"
  1201. # bl_label = "Import Mantis Tree"
  1202. """Reload Mantis Tree"""
  1203. bl_idname = "mantis.reload_tree"
  1204. bl_label = "Confirm reload tree?"
  1205. bl_options = {'REGISTER', 'INTERNAL'}
  1206. @classmethod
  1207. def poll(cls, context):
  1208. if hasattr(context.space_data, 'path'):
  1209. return True
  1210. return False
  1211. def invoke(self, context, event):
  1212. return context.window_manager.invoke_confirm(self, event)
  1213. def execute(self, context):
  1214. base_tree=context.space_data.path[-1].node_tree
  1215. if not base_tree.filepath:
  1216. self.report({'ERROR'}, "Tree has not been saved - so it cannot be reloaded.")
  1217. return {'CANCELLED'}
  1218. self.report({'INFO'}, "reloading tree")
  1219. return do_import_from_file(base_tree.filepath, context)
  1220. # todo:
  1221. # - export metarig and option to import it
  1222. # - same with controls
  1223. # - it would be nice to have a library of these that can be imported alongside the mantis graph