utilities.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. #fool: should be wrColor like prColor... dumb
  2. def wrapRed(skk): return "\033[91m{}\033[00m".format(skk)
  3. def wrapGreen(skk): return "\033[92m{}\033[00m".format(skk)
  4. def wrapPurple(skk): return "\033[95m{}\033[00m".format(skk)
  5. def wrapWhite(skk): return "\033[97m{}\033[00m".format(skk)
  6. def wrapOrange(skk): return "\033[0;33m{}\033[00m".format(skk)
  7. # these should reimplement the print interface..
  8. def prRed(*args): print (*[wrapRed(arg) for arg in args])
  9. def prGreen(*args): print (*[wrapGreen(arg) for arg in args])
  10. def prPurple(*args): print (*[wrapPurple(arg) for arg in args])
  11. def prWhite(*args): print (*[wrapWhite(arg) for arg in args])
  12. def prOrange(*args): print (*[wrapOrange(arg) for arg in args])
  13. # add THIS to the top of a file for easy access:
  14. # from mantis.utilities import (prRed, prGreen, prPurple, prWhite,
  15. # prOrange,
  16. # wrapRed, wrapGreen, wrapPurple, wrapWhite,
  17. # wrapOrange,)
  18. def float_lerp(a : float, b : float, factor : float) -> float:
  19. return (a * (1.0 - factor)) + (b * factor)
  20. # A fuction for getting to the end of a Reroute.
  21. # TODO: this seems really inefficient!
  22. def socket_seek(start_link, links):
  23. link = start_link
  24. while(link.from_socket):
  25. for newlink in links:
  26. if link.from_socket.node.inputs:
  27. if link.from_node.bl_idname != 'NodeReroute':
  28. return link.from_socket
  29. if newlink.to_socket == link.from_socket.node.inputs[0]:
  30. link=newlink; break
  31. else:
  32. break
  33. return link.from_socket
  34. # THIS ONE is better. I don't know what I was thinking up above.
  35. # TODO: try and refactor to use this function instead
  36. def find_reroute_start_socket(reroute, track='BACK'):
  37. # "BACK" traces back through the tree
  38. # "FORWARD" traces forward through the tree
  39. socket = None
  40. while (reroute and track == 'BACK'):
  41. if len(reroute.inputs[0].links) == 1:
  42. link = reroute.inputs[0].links[0]
  43. socket = link.from_socket
  44. if link.from_node.bl_idname == 'NodeReroute':
  45. reroute = link.from_node
  46. else:
  47. link, reroute = None, None
  48. while (reroute and track == 'FORWARD'):
  49. if len(reroute.outputs[0].links) == 1:
  50. link = reroute.outputs[0].links[0]
  51. socket = link.to_socket
  52. if link.to_node.bl_idname == 'NodeReroute':
  53. reroute = link.to_node
  54. else:
  55. link, reroute = None, None
  56. return socket
  57. # this creates fake links that have the same interface as Blender's
  58. # so that I can bypass Reroutes
  59. def clear_reroutes(links):
  60. from .base_definitions import DummyLink
  61. kept_links, rerouted_starts = [], []
  62. rerouted = []
  63. all_links = links.copy()
  64. while(all_links):
  65. link = all_links.pop()
  66. to_cls = link.to_socket.node.bl_idname
  67. from_cls = link.from_socket.node.bl_idname
  68. reroute_classes = ["NodeReroute"]
  69. if (to_cls in reroute_classes and
  70. from_cls in reroute_classes):
  71. rerouted.append(link)
  72. elif (to_cls in reroute_classes and not
  73. from_cls in reroute_classes):
  74. rerouted.append(link)
  75. elif (from_cls in reroute_classes and not
  76. to_cls in reroute_classes):
  77. rerouted_starts.append(link)
  78. else:
  79. kept_links.append(link)
  80. for start in rerouted_starts:
  81. from_socket = socket_seek(start, rerouted)
  82. new_link = DummyLink(from_socket=from_socket, to_socket=start.to_socket, nc_from=None, nc_to=None, multi_input_sort_id=start.multi_input_sort_id )
  83. kept_links.append(new_link)
  84. return kept_links
  85. def tree_from_nc(sig, base_tree):
  86. if (sig[0] == 'MANTIS_AUTOGENERATED'):
  87. sig = sig[:-2] # cut off the end part of the signature (because it uses socket.name and socket.identifier)
  88. # this will lead to totally untraceble bugs in the event of a change in how signatures are assigned
  89. tree = base_tree
  90. for i, path_item in enumerate(sig):
  91. if (i == 0) or (i == len(sig) - 1):
  92. continue
  93. tree = tree.nodes.get(path_item).node_tree
  94. return tree
  95. def get_node_prototype(sig, base_tree):
  96. return tree_from_nc(sig, base_tree).nodes.get( sig[-1] )
  97. ##################################################################################################
  98. # groups and changing sockets -- this is used extensively by Schema.
  99. ##################################################################################################
  100. # this one returns None if there is an error.
  101. def get_socket_maps(node, force=False):
  102. maps = [{}, {}]
  103. node_collection = ["inputs", "outputs"]
  104. links = ["from_socket", "to_socket"]
  105. for collection, map, linked_socket in zip(node_collection, maps, links):
  106. for sock in getattr(node, collection):
  107. if sock.is_linked:
  108. other_sockets = []
  109. # Sort the links first (in case they are mult-input), because Blender doesn't
  110. links = sorted(list(sock.links), key = lambda l : l.multi_input_sort_id)
  111. # HACK here because Blender will crash if the socket values in the NodeReroute
  112. # are mutated. Because this seems to happen in a deffered way, I can't account
  113. # for it except by checking the node later...
  114. # TODO: The fact that I need this hack means I can probably solve this problem
  115. # for all node types in a safer way, since they may also be dynamic somehow
  116. for l in links:
  117. if "from" in linked_socket and l.from_node.bl_idname == "NodeReroute":
  118. other_sockets.append(l.from_node)
  119. elif "to" in linked_socket and l.to_node.bl_idname == "NodeReroute":
  120. other_sockets.append(l.to_node)
  121. else:
  122. other_sockets.append(getattr(l, linked_socket))
  123. from bpy.types import NodeSocket
  124. keep_sockets=[]
  125. for other_socket in other_sockets.copy():
  126. if isinstance(other_socket, NodeSocket) and \
  127. other_socket.bl_idname == 'NodeSocketUndefined':
  128. continue # this one is bad
  129. keep_sockets.append(other_socket)
  130. map[sock.identifier]= keep_sockets
  131. elif hasattr(sock, "default_value"):
  132. if sock.get("default_value") is not None:
  133. val = sock['default_value']
  134. elif sock.bl_idname == "EnumCurveSocket" and sock.get("default_value") is None:
  135. # HACK I need to add this special case because during file-load,
  136. # this value is None and should not be altered until it is set once.
  137. continue
  138. elif "Enum" in sock.bl_idname and isinstance(sock.get("default_value"), int):
  139. continue # for string enum properties that have not yet initialized (at startup)
  140. elif (val := sock.default_value) is not None:
  141. pass
  142. elif not force:
  143. continue
  144. map[sock.identifier]=val
  145. else:
  146. from .socket_definitions import no_default_value
  147. if sock.bl_idname in no_default_value:
  148. map[sock.identifier]=None
  149. else:
  150. raise RuntimeError(f"ERROR: Could not get socket data for socket of type: {sock.bl_idname}")
  151. return maps
  152. # this function is completely overloaded with different purposes and code paths
  153. # TODO refactor everything that funnels into this function
  154. # make this stuff simpler.
  155. def do_relink(node, socket, map, in_out='INPUT', parent_name = ''):
  156. if not node.__class__.is_registered_node_type(): return
  157. tree = node.id_data; interface_in_out = 'OUTPUT' if in_out == 'INPUT' else 'INPUT'
  158. if hasattr(node, "node_tree"):
  159. tree = node.node_tree
  160. interface_in_out=in_out
  161. from bpy.types import NodeSocket, Node
  162. get_string = '__extend__'
  163. if socket: get_string = socket.identifier
  164. from .base_definitions import SchemaUINode
  165. if (hasattr(node, "node_tree") or isinstance(node, SchemaUINode)) and get_string not in map.keys():
  166. # this happens when we are creating a new node group and need to update it from nothing.
  167. return
  168. val = map[get_string] # this will throw an error if the socket isn't there. Good!
  169. if isinstance(val, list):
  170. for sub_val in val:
  171. # this will only happen once because it assigns socket, so it is safe to do in the for loop.
  172. if socket is None:
  173. socket = sub_val
  174. if sub_val.bl_idname == "NodeReroute":
  175. # we have to trace the reroute node...
  176. if in_out == 'INPUT':
  177. socket = find_reroute_start_socket(sub_val)
  178. else:
  179. socket = find_reroute_start_socket(sub_val, track="FORWARD")
  180. sock_type = socket.interface_type
  181. name = unique_socket_name(node, socket, tree)
  182. if parent_name:
  183. interface_socket = update_interface(tree.interface, name, interface_in_out, sock_type, parent_name)
  184. if in_out =='INPUT':
  185. socket = node.inputs.new(sock_type, name, identifier=interface_socket.identifier)
  186. else:
  187. socket = node.outputs.new(sock_type, name, identifier=interface_socket.identifier)
  188. if parent_name == 'Array': socket.display_shape='SQUARE_DOT'
  189. if parent_name == 'Constant': socket.display_shape='CIRCLE_DOT'
  190. # then move it up and delete the other link.
  191. # this also needs to modify the interface of the node tree.
  192. if isinstance(sub_val, NodeSocket):
  193. l = None
  194. if in_out =='INPUT':
  195. l = node.id_data.links.new(input=sub_val, output=socket)
  196. else:
  197. l = node.id_data.links.new(input=socket, output=sub_val)
  198. if l is None:
  199. raise RuntimeError("Could not create link")
  200. elif isinstance(sub_val, Node):
  201. l = None
  202. # this happens when it is a NodeReroute
  203. if not socket.is_output:
  204. l = node.id_data.links.new(input=sub_val.outputs[0], output=socket)
  205. else:
  206. l = node.id_data.links.new(input=socket, output=sub_val.inputs[0])
  207. if l is None:
  208. raise RuntimeError("Could not create link")
  209. else:
  210. raise RuntimeError("Unhandled case in do_relink()")
  211. elif get_string != "__extend__":
  212. if not socket.is_output:
  213. from bpy.app import version as bpy_version
  214. if bpy_version >=(4,5,0): # VERSIONING
  215. # for some reason, this is throwing an error now
  216. from bpy.types import bpy_prop_array
  217. if isinstance(val, bpy_prop_array):
  218. if in_out == "INPUT" and hasattr(socket, 'input') and socket.input == False:
  219. return # doesn't matter, this is a Matrix socket in a bone or something
  220. # raise RuntimeError(
  221. # f"Cannot set property in socket of type {socket.bl_idname} due to bug in Blender: "
  222. # f"{node.id_data.name}:{node.name}:{socket.name} ")
  223. # TODO: report this weird bug!
  224. try:
  225. if socket.bl_idname == 'BooleanThreeTupleSocket':
  226. # it is so annoying that I have to do this
  227. socket.default_value = [bool(val[0]), bool(val[1]), bool(val[2])]
  228. else:
  229. socket.default_value = val
  230. except (AttributeError, ValueError): # must be readonly or maybe it doesn't have a d.v.
  231. pass
  232. def update_interface(interface, name, in_out, sock_type, parent_name):
  233. from bpy.app import version as bpy_version
  234. if parent_name:
  235. if not (interface_parent := interface.items_tree.get(parent_name)):
  236. interface_parent = interface.new_panel(name=parent_name)
  237. if bpy_version != (4,5,0):
  238. socket = interface.new_socket(name=name,in_out=in_out, socket_type=sock_type, parent=interface_parent)
  239. else: # blender 4.5.0 LTS, have to workaround a bug!
  240. from .versioning import workaround_4_5_0_interface_update
  241. socket = workaround_4_5_0_interface_update(tree=interface.id_data, name=name, in_out=in_out,
  242. sock_type=sock_type, parent_name=parent_name, do_parent=True)
  243. if parent_name == 'Connection':
  244. in_out = 'OUTPUT' if in_out == 'INPUT' else 'INPUT' # flip this make sure connections always do both
  245. interface.new_socket(name=name,in_out=in_out, socket_type=sock_type, parent=interface_parent)
  246. return socket
  247. else:
  248. raise RuntimeError(wrapRed("Cannot add interface item to tree without specifying type."))
  249. # D.node_groups['Rigging Nodes'].interface.new_socket('beans', description='the b word', socket_type='NodeSocketGeometry')
  250. #UGLY BAD REFACTOR
  251. def relink_socket_map_add_socket(node, socket_collection, item, in_out=None,):
  252. from bpy.app import version as bpy_version
  253. if not in_out: in_out=item.in_out
  254. if hasattr(item, 'is_array'):
  255. multi = item.is_array
  256. if node.bl_idname in ['MantisSchemaGroup'] and item.parent and item.parent.name == 'Array':
  257. multi = True if in_out == 'INPUT' else False
  258. # have to work around a bug in 4.5.0 that prevents me from declaring custom socket types
  259. # I have arbitrarily chosen to use the NodeSocketGeometry type to signal that this one is affected.
  260. if bpy_version == (4, 5, 0) and item.bl_socket_idname == 'NodeSocketGeometry':
  261. from .versioning import socket_add_workaround_for_4_5_0_LTS
  262. s = socket_add_workaround_for_4_5_0_LTS(item, socket_collection, multi)
  263. else:
  264. s = socket_collection.new(type=item.bl_socket_idname, name=item.name, identifier=item.identifier, use_multi_input=multi)
  265. if hasattr(s, 'default_value'):
  266. from bpy.types import bpy_prop_array
  267. from mathutils import Vector
  268. default_value = 'REPORT BUG ON GITLAB' # default to bug string
  269. val_type = type(s.default_value) # why tf can't I match/case here?
  270. if val_type is bool: default_value = item.default_bool
  271. if val_type is int: default_value = item.default_int
  272. if val_type is float: default_value = item.default_float
  273. if val_type is Vector: default_value = item.default_float
  274. if val_type is str: default_value = item.default_string
  275. if val_type is bpy_prop_array: default_value = item.default_float
  276. s.default_value = default_value
  277. if item.parent.name == 'Array': s.display_shape = 'SQUARE_DOT'
  278. elif item.parent.name == 'Constant': s.display_shape='CIRCLE_DOT'
  279. return s
  280. # TODO REFACTOR THIS
  281. # I did this awful thing because I needed the above code
  282. # but I have provided this interface to Mantis
  283. # I did not follow the Single Responsibility Principle
  284. # I am now suffering for it, as I rightly deserve.
  285. def relink_socket_map(node, socket_collection, map, item, in_out=None,):
  286. s = relink_socket_map_add_socket(node, socket_collection, item, in_out=None,)
  287. do_relink(node, s, map)
  288. def unique_socket_name(node, other_socket, tree):
  289. name_stem = other_socket.bl_label; num=0
  290. # if hasattr(other_socket, "default_value"):
  291. # name_stem = type(other_socket.default_value).__name__
  292. for item in tree.interface.items_tree:
  293. if item.item_type == 'PANEL': continue
  294. if other_socket.is_output and item.in_out == 'INPUT': continue
  295. if not other_socket.is_output and item.in_out == 'OUTPUT': continue
  296. if name_stem in item.name: num+=1
  297. name = name_stem + '.' + str(num).zfill(3)
  298. return name
  299. ##############################
  300. # Dealing with Objects
  301. ##############################
  302. # use this to ensure the active object is set back when changing it
  303. def preserve_active_object(func):
  304. def wrapper(*args, **kwargs):
  305. import bpy
  306. original_active = bpy.context.active_object
  307. func(*args, **kwargs)
  308. bpy.context.view_layer.objects.active = original_active
  309. return wrapper
  310. def switch_mode(mode='OBJECT', objects = []):
  311. active = None
  312. if objects:
  313. from bpy import context, ops
  314. active = objects[-1]
  315. context.view_layer.objects.active = active
  316. if (active):
  317. with context.temp_override(**{'active_object':active, 'selected_objects':objects}):
  318. ops.object.mode_set(mode=mode)
  319. return active
  320. # run this in Object mode, during bFinalize
  321. @preserve_active_object
  322. def bind_modifier_operator(modifier, operator):
  323. # now we have to bind it
  324. ob = modifier.id_data
  325. ob.modifiers.active = modifier
  326. import bpy
  327. bpy.context.view_layer.objects.active = ob
  328. # Context override does not do anything here... it isn't handled in the C code
  329. # I have verified this by building Blender with print statements to debug.
  330. # let's just make sure the target object has its modifiers disabled and update the dg
  331. targ_attr = "target"
  332. if hasattr(modifier, "object"): targ_attr = "object"
  333. target = getattr(modifier, targ_attr)
  334. if target:
  335. prWhite(f"Binding Deformer {modifier.name} to target {target.name}")
  336. operator(modifier=modifier.name)
  337. def get_default_collection(collection_type='WIDGET'):
  338. from .preferences import get_bl_addon_object
  339. from bpy import data, context
  340. mantis_addon = get_bl_addon_object(raise_error=True)
  341. match collection_type:
  342. case "WIDGET":
  343. default_collection_name=mantis_addon.preferences.WidgetDefaultCollection
  344. case "CURVE":
  345. default_collection_name=mantis_addon.preferences.CurveDefaultCollection
  346. case "ARMATURE":
  347. default_collection_name=mantis_addon.preferences.MetaArmatureDefaultCollection
  348. if default_collection_name:
  349. if not (default_collection := data.collections.get(default_collection_name)):
  350. default_collection = data.collections.new(default_collection_name)
  351. context.scene.collection.children.link(default_collection)
  352. collection = default_collection
  353. else: collection = context.collection
  354. return collection
  355. def import_widget_obj(path,):
  356. from bpy.app import version as bpy_version
  357. from bpy import context, data
  358. from os import path as os_path
  359. file_name = os_path.split(path)[-1]
  360. obj_name = os_path.splitext(file_name)[0]
  361. collection = get_default_collection(collection_type='WIDGET')
  362. if bpy_version < (4,5,0):
  363. original_active = context.active_object
  364. # for blender versions prior to 4.5.0, we have to import with an operator
  365. from bpy.ops import wm as wm_ops
  366. ob_names_before = data.objects.keys()
  367. wm_ops.obj_import(
  368. filepath=path,
  369. check_existing=False,
  370. forward_axis='NEGATIVE_Z',
  371. up_axis='Y',
  372. validate_meshes=True,)
  373. # just make sure the active object doesn't change
  374. context.view_layer.objects.active = original_active
  375. # the below is a HACK... I can find the objects in the .obj file
  376. # by scanning the file for the "o" prefix and checking the name.
  377. # but that may be slow if the obj is big. which would make a bad widget!
  378. ob = None
  379. for ob in data.objects:
  380. if ob.name in ob_names_before: continue
  381. # this is easier than setting the active collection before import.
  382. for other_collection in ob.users_collection:
  383. other_collection.objects.unlink(ob)
  384. from math import pi as PI
  385. from mathutils import Matrix
  386. m = ob.data
  387. for v in m.vertices:
  388. v.co = Matrix.Rotation(PI/2, 4, 'X') @ v.co
  389. collection.objects.link(ob)
  390. return ob # return the first one, that should be the one
  391. else: # no new object was found - fail.
  392. # I don't expect this to happen unless there is an error in the operator.
  393. raise RuntimeError(f"Failed to import {file_name}. This is probably"
  394. "a bug or a corrupted file.")
  395. else:
  396. prWhite(f"INFO: using Geometry Nodes to import {file_name}")
  397. mesh = data.meshes.new(obj_name)
  398. ob = data.objects.new(name=obj_name, object_data=mesh)
  399. # we'll do a geometry nodes import
  400. collection.objects.link(ob)
  401. if (import_modifier := ob.modifiers.get("Import OBJ")) is None:
  402. import_modifier = ob.modifiers.new("Import OBJ", type='NODES')
  403. ng = data.node_groups.get("Import OBJ")
  404. if ng is None:
  405. from .geometry_node_graphgen import gen_import_obj_node_group
  406. ng = gen_import_obj_node_group()
  407. import_modifier.node_group = ng
  408. import_modifier["Socket_0"]=path
  409. return ob
  410. def import_object_from_file(path):
  411. # first let's check to see if we need it.
  412. from os import path as os_path
  413. file_name = os_path.split(path)[-1]
  414. obj_name = os_path.splitext(file_name)[0]
  415. extension = os_path.splitext(file_name)[1]
  416. if extension == '.obj':
  417. return import_widget_obj(path,)
  418. else:
  419. raise RuntimeError(f"Failed to parse filename {path}")
  420. def import_metarig_data(metarig_data : dict, ):
  421. from bpy import data, context
  422. from mathutils import Matrix
  423. from collections import deque
  424. # the metarig data is a dict with a bunch of nodes in it
  425. # start at node 'MANTIS_RESERVED'
  426. armature_data = metarig_data['MANTIS_RESERVED']
  427. children = deque(armature_data["children"].copy())
  428. if (armature := data.armatures.get(armature_data['name'])) is None:
  429. armature = data.armatures.new(armature_data['name'])
  430. # if we need to do anything here...
  431. if (armature_object := data.objects.get(armature_data['name'])) is None:
  432. armature_object = data.objects.new(armature_data['name'], object_data=armature)
  433. armature_object.matrix_world = Matrix(
  434. ( armature_data['matrix'][:4],
  435. armature_data['matrix'][4:8],
  436. armature_data['matrix'][8:12],
  437. armature_data['matrix'][12:16], )
  438. )
  439. prGreen (armature_data['name'])
  440. # have to add it to the view layer to switch modes.
  441. collection = get_default_collection(collection_type="ARMATURE")
  442. collection.objects.link(armature_object)
  443. # we'll do this to ensure it is actually in the scene for the mode switch
  444. context.scene.collection.objects.link(armature_object)
  445. switch_mode('EDIT', objects = [armature_object])
  446. while (children):
  447. child_name = children.pop()
  448. child_data = metarig_data[child_name]
  449. eb = armature.edit_bones.new(name=child_data['name'])
  450. if parent_name := child_data['parent']:
  451. eb.parent = armature.edit_bones[parent_name]
  452. eb.length = child_data['length']
  453. eb.matrix = Matrix(
  454. ( child_data['matrix'][:4],
  455. child_data['matrix'][4:8],
  456. child_data['matrix'][8:12],
  457. child_data['matrix'][12:16], )
  458. )
  459. displacement = eb.matrix.to_3x3().transposed().row[1] * child_data['length']
  460. eb.tail = eb.matrix.decompose()[0] + displacement
  461. children.extendleft (child_data['children'].copy())
  462. switch_mode('OBJECT', objects = [armature_object])
  463. # and now we can remove it from the scene collection, since it is in the Armature collection
  464. context.scene.collection.objects.unlink(armature_object)
  465. # note that this will not correct if the object exists and is wrong.
  466. return armature_object
  467. def import_curve_data_to_object(curve_name, curve_data):
  468. # the curve data will come as a single curve's data
  469. from bpy import data
  470. curve_object = data.objects.new(curve_name, data.curves.new(name=curve_name, type='CURVE'))
  471. curve_object.data.dimensions = '3D'
  472. prGreen (curve_name)
  473. for spline_data in curve_data:
  474. spline = curve_object.data.splines.new(type=spline_data['type'])
  475. points_data = spline_data['points']
  476. points_collection = spline.points
  477. if spline.type == 'BEZIER':
  478. # the points are bez_pts
  479. spline.bezier_points.add(len(points_data)-1)
  480. points_collection = spline.bezier_points
  481. else:
  482. spline.points.add(len(points_data)-1) # it starts with 1 already
  483. for i, point_data in enumerate(points_data):
  484. if spline.type == 'BEZIER':
  485. pt = spline.bezier_points[i]
  486. else:
  487. pt = spline.points[i]
  488. for prop in dir(pt):
  489. if prop == 'w':
  490. continue
  491. if prop == 'co' and spline.type != 'BEZIER':
  492. value = point_data[prop]
  493. pt.co = (value[0], value[1], value[2], point_data['w'])
  494. continue
  495. if prop in point_data.keys():
  496. setattr(pt, prop, point_data[prop])
  497. for prop in dir(spline):
  498. if prop in spline_data.keys():
  499. if prop in ['points', 'type', 'index']: continue
  500. setattr(spline, prop, spline_data[prop])
  501. collection = get_default_collection(collection_type="CURVE")
  502. collection.objects.link(curve_object)
  503. return curve_object
  504. def get_component_library_items(path='ADD_ARMATURE'):
  505. from os import path as os_path
  506. from .preferences import get_bl_addon_object
  507. bl_mantis_addon = get_bl_addon_object()
  508. return_value=[]
  509. if bl_mantis_addon:
  510. match path:
  511. case 'ADD_ARMATURE':
  512. components_path = bl_mantis_addon.preferences.ComponentsLibraryFolder
  513. case 'AUTOLOAD':
  514. components_path = bl_mantis_addon.preferences.ComponentsAutoLoadFolder
  515. component_names = {}
  516. from os import walk as os_walk
  517. for path_root, dirs, files, in os_walk(components_path):
  518. for file in files:
  519. relative_file_name = os_path.join(os_path.sep.join(dirs), file)
  520. if file.endswith('.rig'):
  521. component_names[relative_file_name[:-4]] = relative_file_name
  522. if component_names.keys():
  523. for i, (name, path) in enumerate(component_names.items()):
  524. return_value.append( (path, name, path, 'NODE_TREE', i) )
  525. return return_value
  526. ##############################
  527. # READ TREE and also Schema Solve!
  528. ##############################
  529. # TODO: refactor the following two functions, they should be one function with arguments.
  530. def init_connections(nc):
  531. c, hc = [], []
  532. for i in nc.outputs.values():
  533. for l in i.links:
  534. # if l.from_node != nc:
  535. # continue
  536. if l.is_hierarchy:
  537. hc.append(l.to_node)
  538. c.append(l.to_node)
  539. nc.hierarchy_connections = hc
  540. nc.connections = c
  541. def init_dependencies(nc):
  542. c, hc = [], []
  543. for i in nc.inputs.values():
  544. for l in i.links:
  545. # if l.to_node != nc:
  546. # continue
  547. if l.is_hierarchy:
  548. hc.append(l.from_node)
  549. c.append(l.from_node)
  550. nc.hierarchy_dependencies = hc
  551. nc.dependencies = c
  552. def schema_dependency_handle_item(schema, all_nc, item,):
  553. hierarchy = True
  554. from .base_definitions import from_name_filter, to_name_filter
  555. if item.in_out == 'INPUT':
  556. dependencies = schema.dependencies
  557. hierarchy_dependencies = schema.hierarchy_dependencies
  558. if item.parent and item.parent.name == 'Array':
  559. for schema_idname in ['SchemaArrayInput', 'SchemaArrayInputGet', 'SchemaArrayInputAll']:
  560. if (nc := all_nc.get( (*schema.signature, schema_idname) )):
  561. for to_link in nc.outputs[item.name].links:
  562. if to_link.to_socket in to_name_filter:
  563. # hierarchy_reason='a'
  564. hierarchy = False
  565. for from_link in schema.inputs[item.identifier].links:
  566. if from_link.from_socket in from_name_filter:
  567. hierarchy = False
  568. # hierarchy_reason='b'
  569. if from_link.from_node not in dependencies:
  570. if hierarchy:
  571. hierarchy_dependencies.append(from_link.from_node)
  572. dependencies.append(from_link.from_node)
  573. if item.parent and item.parent.name == 'Constant':
  574. if nc := all_nc.get((*schema.signature, 'SchemaConstInput')):
  575. for to_link in nc.outputs[item.name].links:
  576. if to_link.to_socket in to_name_filter:
  577. # hierarchy_reason='dependencies'
  578. hierarchy = False
  579. for from_link in schema.inputs[item.identifier].links:
  580. if from_link.from_socket in from_name_filter:
  581. # hierarchy_reason='d'
  582. hierarchy = False
  583. if from_link.from_node not in dependencies:
  584. if hierarchy:
  585. hierarchy_dependencies.append(from_link.from_node)
  586. dependencies.append(from_link.from_node)
  587. if item.parent and item.parent.name == 'Connection':
  588. if nc := all_nc.get((*schema.signature, 'SchemaIncomingConnection')):
  589. for to_link in nc.outputs[item.name].links:
  590. if to_link.to_socket in to_name_filter:
  591. # hierarchy_reason='e'
  592. hierarchy = False
  593. for from_link in schema.inputs[item.identifier].links:
  594. if from_link.from_socket in from_name_filter:
  595. # hierarchy_reason='f'
  596. hierarchy = False
  597. if from_link.from_node not in dependencies:
  598. if hierarchy:
  599. hierarchy_dependencies.append(from_link.from_node)
  600. dependencies.append(from_link.from_node)
  601. def init_schema_dependencies(schema, all_nc):
  602. """ Initialize the dependencies for Schema, and mark them as hierarchy or non-hierarchy dependencies
  603. Non-hierarchy dependencies are e.g. drivers and custom transforms.
  604. """
  605. tree = schema.prototype.node_tree
  606. if tree is None:
  607. raise RuntimeError(f"Cannot get dependencies for schema {schema}")
  608. schema.dependencies = []
  609. schema.hierarchy_dependencies = []
  610. for l in schema.inputs["Schema Length"].links:
  611. schema.hierarchy_dependencies.append(l.from_node)
  612. if tree.interface:
  613. for item in tree.interface.items_tree:
  614. if item.item_type == 'PANEL':
  615. continue
  616. schema_dependency_handle_item(schema, all_nc, item,)
  617. def check_and_add_root(n, roots, include_non_hierarchy=False):
  618. if (include_non_hierarchy * len(n.dependencies)) > 0:
  619. return
  620. elif len(n.hierarchy_dependencies) > 0:
  621. return
  622. roots.append(n)
  623. def get_link_in_out(link):
  624. from .base_definitions import replace_types
  625. from_name, to_name = link.from_socket.node.name, link.to_socket.node.name
  626. # catch special bl_idnames and bunch the connections up
  627. if link.from_socket.node.bl_idname in replace_types:
  628. from_name = link.from_socket.node.bl_idname
  629. if link.to_socket.node.bl_idname in replace_types:
  630. to_name = link.to_socket.node.bl_idname
  631. return from_name, to_name
  632. def link_node_containers(tree_path_names, link, local_nc, from_suffix='', to_suffix=''):
  633. dummy_types = ["DUMMY", "DUMMY_SCHEMA"]
  634. from_name, to_name = get_link_in_out(link)
  635. nc_from = local_nc.get( (*tree_path_names, from_name+from_suffix) )
  636. nc_to = local_nc.get( (*tree_path_names, to_name+to_suffix))
  637. if (nc_from and nc_to):
  638. from_s, to_s = link.from_socket.name, link.to_socket.name
  639. if nc_to.node_type in dummy_types: to_s = link.to_socket.identifier
  640. if nc_from.node_type in dummy_types: from_s = link.from_socket.identifier
  641. try:
  642. connection = nc_from.outputs[from_s].connect(node=nc_to, socket=to_s, sort_id=link.multi_input_sort_id)
  643. if connection is None:
  644. prWhite(f"Already connected: {from_name}:{from_s}->{to_name}:{to_s}")
  645. return connection
  646. except KeyError as e:
  647. prRed(f"{nc_from}:{from_s} or {nc_to}:{to_s} missing; review the connections printed below:")
  648. print (nc_from.outputs.keys())
  649. print (nc_to.inputs.keys())
  650. raise e
  651. else:
  652. prRed(nc_from, nc_to, (*tree_path_names, from_name+from_suffix), (*tree_path_names, to_name+to_suffix))
  653. raise RuntimeError(wrapRed(f"Link not connected: {nc_from} -> {nc_to} in tree" ))
  654. def get_all_dependencies(nc):
  655. from .base_definitions import GraphError
  656. """ find all dependencies for a mantis node"""
  657. nodes = []
  658. check_nodes = [nc]
  659. nodes_checked = set()
  660. while (len(check_nodes) > 0):
  661. node = check_nodes.pop()
  662. nodes_checked.add (node)
  663. connected_nodes = node.hierarchy_dependencies
  664. for new_node in connected_nodes:
  665. if new_node in nodes:
  666. continue
  667. nodes.append(new_node)
  668. if new_node not in nodes_checked:
  669. check_nodes.append(new_node)
  670. return nodes
  671. def get_all_nodes_of_type(base_tree, bl_idname):
  672. nodes = []
  673. check_nodes = list(base_tree.nodes)
  674. while (len(check_nodes) > 0):
  675. node = check_nodes.pop()
  676. if node.bl_idname in bl_idname:
  677. nodes.append(node)
  678. if hasattr(node, "node_tree"):
  679. check_nodes.extend(list(node.node_tree.nodes))
  680. return nodes
  681. def trace_all_nodes_from_root(root, nodes):
  682. from .base_definitions import GraphError
  683. """ find all dependencies for a mantis node"""
  684. nodes.add(root); check_nodes = [root]
  685. nodes_checked = set()
  686. while (len(check_nodes) > 0):
  687. node = check_nodes.pop(); nodes_checked.add (node)
  688. connected_nodes = []
  689. for output in node.outputs:
  690. for l in output.links:
  691. if l.to_node not in nodes:
  692. connected_nodes.append(l.to_node)
  693. for new_node in connected_nodes:
  694. nodes.add(new_node)
  695. if new_node not in nodes_checked:
  696. check_nodes.append(new_node)
  697. return nodes
  698. ##################################################################################################
  699. # misc
  700. ##################################################################################################
  701. # TODO: get the matrix to return a mathutils.Matrix so I don't need a function call here
  702. def to_mathutils_value(socket):
  703. if hasattr(socket, "default_value"):
  704. val = socket.default_value
  705. if socket.bl_idname in ['MatrixSocket']:
  706. return socket.TellValue()
  707. else:
  708. return val
  709. else:
  710. return None
  711. def all_trees_in_tree(base_tree, selected=False):
  712. """ Recursively finds all trees referenced in a given base-tree."""
  713. # note that this is recursive but not by tail-end recursion
  714. # a while-loop is a better way to do recursion in Python.
  715. trees = [base_tree]
  716. can_descend = True
  717. check_trees = [base_tree]
  718. while (len(check_trees) > 0): # this seems innefficient, why 2 loops?
  719. new_trees = []
  720. while (len(check_trees) > 0):
  721. tree = check_trees.pop()
  722. for node in tree.nodes:
  723. if selected == True and node.select == False:
  724. continue
  725. if new_tree := getattr(node, "node_tree", None):
  726. if new_tree in trees: continue
  727. new_trees.append(new_tree)
  728. trees.append(new_tree)
  729. check_trees = new_trees
  730. return trees
  731. # this is a destructive operation, not a pure function or whatever. That isn't good but I don't care.
  732. def SugiyamaGraph(tree, iterations):
  733. from grandalf.graphs import Vertex, Edge, Graph, graph_core
  734. class defaultview(object):
  735. w,h = 1,1
  736. xz = (0,0)
  737. graph = Graph()
  738. no_links = set()
  739. verts = {}
  740. for n in tree.nodes:
  741. if n.select == True:
  742. v = Vertex(n.name)
  743. v.view = defaultview()
  744. v.view.xy = n.location
  745. v.view.h = n.height*2.5
  746. v.view.w = n.width*2.2
  747. verts[n.name] = v
  748. no_links.add(n.name)
  749. graph.add_vertex(v)
  750. n.select=False
  751. edges = []
  752. inverted_edges=[]
  753. not_a_root = set()
  754. for link in tree.links:
  755. if (link.from_node.name not in verts.keys()) or (link.to_node.name not in verts.keys()):
  756. continue # problem??
  757. weight = 1 # maybe this is useful
  758. not_a_root.add(link.to_node.name) # if it has a edge-input it is not a root.
  759. e = Edge(verts[link.from_node.name], verts[link.to_node.name], weight)
  760. graph.add_edge(e)
  761. edges.append(e )
  762. if link.is_valid == False:
  763. inverted_edges.append(e)
  764. if link.from_node.name in no_links:
  765. no_links.remove(link.from_node.name)
  766. if link.to_node.name in no_links:
  767. no_links.remove(link.to_node.name)
  768. try:
  769. from grandalf.layouts import SugiyamaLayout
  770. # .C[0] is the first "graph core" that contains a connected graph.
  771. sug = SugiyamaLayout(graph.C[0])
  772. sug.init_all()
  773. sug.draw(iterations)
  774. # Digco is good for small graphs.
  775. # from grandalf.layouts import DigcoLayout
  776. # dco = DigcoLayout(graph.C[0])
  777. # dco.init_all()
  778. # dco.draw(iterations)
  779. except KeyboardInterrupt:
  780. pass # just use what it has calculated so far, I guess
  781. for v in graph.C[0].sV:
  782. for n in tree.nodes:
  783. if n.name == v.data:
  784. n.location.x = v.view.xy[1]
  785. n.location.y = v.view.xy[0]
  786. n.select = True
  787. # now we can take all the input nodes and try to put them in a sensible place
  788. # not sure why but this absolutely does not do anything
  789. for n_name in no_links:
  790. n = tree.nodes.get(n_name)
  791. next_node = None
  792. for output in n.outputs:
  793. if output.is_linked == True:
  794. next_node = output.links[0].to_node
  795. break
  796. # let's see if the next node
  797. if next_node:
  798. # need to find the other node in the same layer...
  799. other_node = None
  800. for s_input in next_node.inputs:
  801. if s_input.is_linked:
  802. other_node = s_input.links[0].from_node
  803. if other_node is n:
  804. continue
  805. else:
  806. break
  807. if other_node:
  808. n.location = other_node.location
  809. n.location.y -= other_node.height*2
  810. else: # we'll just position it next to the next node
  811. n.location = next_node.location
  812. n.location.x -= next_node.width*1.5
  813. def project_point_to_plane(point, origin, normal):
  814. return point - normal.dot(point- origin)*normal
  815. ##################################################################################################
  816. # stuff I should probably refactor!!
  817. ##################################################################################################
  818. # This is really, really stupid way to do this
  819. def gen_nc_input_for_data(socket):
  820. # Class List #TODO deduplicate
  821. from . import xForm_nodes, link_nodes, misc_nodes, primitives_nodes, deformer_nodes, math_nodes, schema_nodes
  822. from .internal_containers import NoOpNode
  823. classes = {}
  824. for module in [xForm_nodes, link_nodes, misc_nodes, primitives_nodes, deformer_nodes, math_nodes, schema_nodes]:
  825. for cls in module.TellClasses():
  826. classes[cls.__name__] = cls
  827. #
  828. socket_class_map = {
  829. "MatrixSocket" : classes["InputMatrix"],
  830. "xFormSocket" : None,
  831. "RelationshipSocket" : NoOpNode,
  832. "DeformerSocket" : NoOpNode,
  833. "GeometrySocket" : classes["InputExistingGeometryData"],
  834. "EnableSocket" : classes["InputBoolean"],
  835. "HideSocket" : classes["InputBoolean"],
  836. #
  837. "DriverSocket" : None,
  838. "DriverVariableSocket" : None,
  839. "FCurveSocket" : None,
  840. "KeyframeSocket" : None,
  841. "BoneCollectionSocket" : classes["InputString"],
  842. #
  843. "xFormParameterSocket" : None,
  844. "ParameterBoolSocket" : classes["InputBoolean"],
  845. "ParameterIntSocket" : classes["InputFloat"], #TODO: make an Int node for this
  846. "ParameterFloatSocket" : classes["InputFloat"],
  847. "ParameterVectorSocket" : classes["InputVector"],
  848. "ParameterStringSocket" : classes["InputString"],
  849. #
  850. "TransformSpaceSocket" : classes["InputTransformSpace"],
  851. "BooleanSocket" : classes["InputBoolean"],
  852. "BooleanThreeTupleSocket" : classes["InputBooleanThreeTuple"],
  853. "RotationOrderSocket" : classes["InputRotationOrder"],
  854. "QuaternionSocket" : None,
  855. "QuaternionSocketAA" : None,
  856. "UnsignedIntSocket" : classes["InputFloat"],
  857. "IntSocket" : classes["InputFloat"],
  858. "StringSocket" : classes["InputString"],
  859. #
  860. "BoolUpdateParentNode" : classes["InputBoolean"],
  861. "IKChainLengthSocket" : classes["InputFloat"],
  862. "EnumInheritScale" : classes["InputString"],
  863. "EnumRotationMix" : classes["InputString"],
  864. "EnumRotationMixCopyTransforms" : classes["InputString"],
  865. "EnumMaintainVolumeStretchTo" : classes["InputString"],
  866. "EnumRotationStretchTo" : classes["InputString"],
  867. "EnumTrackAxis" : classes["InputString"],
  868. "EnumUpAxis" : classes["InputString"],
  869. "EnumLockAxis" : classes["InputString"],
  870. "EnumLimitMode" : classes["InputString"],
  871. "EnumYScaleMode" : classes["InputString"],
  872. "EnumXZScaleMode" : classes["InputString"],
  873. "EnumCurveSocket" : classes["InputString"],
  874. "EnumMetaRigSocket" : classes["InputString"],
  875. # Deformers
  876. "EnumSkinning" : classes["InputString"],
  877. #
  878. "FloatSocket" : classes["InputFloat"],
  879. "FloatFactorSocket" : classes["InputFloat"],
  880. "FloatPositiveSocket" : classes["InputFloat"],
  881. "FloatAngleSocket" : classes["InputFloat"],
  882. "VectorSocket" : classes["InputVector"],
  883. "VectorEulerSocket" : classes["InputVector"],
  884. "VectorTranslationSocket" : classes["InputVector"],
  885. "VectorScaleSocket" : classes["InputVector"],
  886. # Drivers
  887. "EnumDriverVariableType" : classes["InputString"],
  888. "EnumDriverVariableEvaluationSpace" : classes["InputString"],
  889. "EnumDriverRotationMode" : classes["InputString"],
  890. "EnumDriverType" : classes["InputString"],
  891. "EnumKeyframeInterpTypeSocket" : classes["InputString"],
  892. "EnumKeyframeBezierHandleTypeSocket" : classes["InputString"],
  893. # Math
  894. "MathFloatOperation" : classes["InputString"],
  895. "MathVectorOperation" : classes["InputString"],
  896. "MatrixTransformOperation" : classes["InputString"],
  897. # Schema
  898. "WildcardSocket" : None,
  899. }
  900. return socket_class_map.get(socket.bl_idname, None)
  901. ####################################
  902. # CURVE STUFF
  903. ####################################
  904. def make_perpendicular(v1, v2):
  905. from .base_definitions import FLOAT_EPSILON
  906. if (v1.length_squared < FLOAT_EPSILON) or (v2.length_squared < FLOAT_EPSILON):
  907. raise RuntimeError("Cannot generate perpendicular vetor for zero-length vector")
  908. projected = (v2.dot(v1) / v1.dot(v1)) * v1
  909. perpendicular = v2 - projected
  910. return perpendicular
  911. # this stuff could be branchless but I don't use it much TODO
  912. def cap(val, maxValue):
  913. if (val > maxValue):
  914. return maxValue
  915. return val
  916. def capMin(val, minValue):
  917. if (val < minValue):
  918. return minValue
  919. return val
  920. def wrap(min : float, max : float, value: float) -> float:
  921. range = max-min; remainder = value % range
  922. if remainder > max: return min + remainder-max
  923. else: return remainder
  924. def lerpVal(a, b, fac = 0.5):
  925. return a + ( (b-a) * fac)
  926. #wtf this doesn't do anything even remotely similar to wrap
  927. # HACK BAD FIXME UNBREAK ME BAD
  928. # I don't understand what this function does but I am using it in multiple places?
  929. def old_bad_wrap_that_should_be_refactored(val, maxValue, minValue = None):
  930. if (val > maxValue):
  931. return (-1 * ((maxValue - val) + 1))
  932. if ((minValue) and (val < minValue)):
  933. return (val + maxValue)
  934. return val
  935. #TODO clean this up
  936. def extract_spline_suffix(spline_index):
  937. return ".spline."+str(spline_index).zfill(3)+".extracted"
  938. def do_extract_spline(data, spline):
  939. remove_me = []
  940. for other_spline in data.splines:
  941. if other_spline != spline: remove_me.append(other_spline)
  942. while remove_me: data.splines.remove(remove_me.pop())
  943. def extract_spline(curve, spline_index):
  944. """ Given a curve object and spline index, returns a new object
  945. containing only the selcted spline. The new object is bound to
  946. the original curve.
  947. """
  948. if len(curve.data.splines) == 1:
  949. return curve # nothing to do here.
  950. spline_suffix = extract_spline_suffix(spline_index)
  951. from bpy import data
  952. if (new_ob := data.objects.get(curve.name+spline_suffix)) is None:
  953. new_ob=curve.copy(); new_ob.name=curve.name+spline_suffix
  954. # if the data exists, it is probably stale, so delete it and start over.
  955. if (old_data := data.objects.get(curve.data.name+spline_suffix)) is not None:
  956. data.curves.remove(old_data)
  957. new_data=curve.data.copy(); new_data.name=curve.data.name+spline_suffix
  958. new_ob.data = new_data
  959. # do not check for index error here, it is the calling function's responsibility
  960. do_extract_spline(new_data, new_data.splines[spline_index])
  961. return new_ob
  962. def bind_extracted_spline_to_curve(new_ob, curve):
  963. # Set up a relationship between the new object and the old object
  964. # now, weirdly enough - we can't use parenting very easily because Blender
  965. # defines the parent on a curve relative to the evaluated path animation
  966. # Setting the inverse matrix is too much work. Use Copy Transforms instead.
  967. from .xForm_nodes import reset_object_data
  968. reset_object_data(new_ob)
  969. c = new_ob.constraints.new("COPY_TRANSFORMS"); c.target=curve
  970. new_ob.parent=curve
  971. return new_ob
  972. def get_extracted_spline_object(proto_curve, spline_index, mContext):
  973. # we're storing it separately like this to ensure all nodes use the same
  974. # object if they extract the same spline for use by Mantis.
  975. # this should be transparent to the user since it is working around a
  976. # a limitation in Blender.
  977. extracted_spline_name = proto_curve.name+extract_spline_suffix(spline_index)
  978. if curve := mContext.b_objects.get(extracted_spline_name):
  979. return curve
  980. else:
  981. curve = extract_spline(proto_curve, spline_index)
  982. if curve.name != proto_curve.name: # if there is only one spline, no
  983. bind_extracted_spline_to_curve(curve, proto_curve)# dupe is created.
  984. mContext.b_objects[extracted_spline_name] = curve
  985. return curve
  986. def nurbs_copy_bez_spline(curve, bez_spline, do_setup=True):
  987. other_spline= curve.data.splines.new('NURBS')
  988. other_spline.use_endpoint_u=True
  989. other_spline.use_bezier_u=True
  990. bez_pts = bez_spline.bezier_points
  991. bez_data=[]
  992. for i, bez_pt in enumerate(bez_pts):
  993. if i > 0:
  994. bez_data.append(bez_pt.handle_left.copy())
  995. bez_data.append(bez_pt.co.copy())
  996. if i != len(bez_pts)-1:
  997. bez_data.append(bez_pt.handle_right.copy())
  998. other_spline.points.add(len(bez_data)-1)
  999. for i, pt in enumerate(bez_data):
  1000. other_spline.points[i].co=(*pt,1.0) # add the W value here
  1001. if do_setup: # do the stuff that makes it behave the same as a bez spline
  1002. other_spline.use_endpoint_u = True; other_spline.use_bezier_u = True
  1003. other_spline.order_u=4 # set to 1 for poly
  1004. return other_spline
  1005. def RibbonMeshEdgeLengths(m, ribbon):
  1006. tE = ribbon[0]; bE = ribbon[1]; c = ribbon[2]
  1007. lengths = []
  1008. for i in range( len( tE ) ): #tE and bE are same length
  1009. if (c == True):
  1010. v1NextInd = tE[old_bad_wrap_that_should_be_refactored((i+1), len(tE) - 1)]
  1011. else:
  1012. v1NextInd = tE[cap((i+1) , len(tE) - 1 )]
  1013. v1 = m.vertices[tE[i]]; v1Next = m.vertices[v1NextInd]
  1014. if (c == True):
  1015. v2NextInd = bE[old_bad_wrap_that_should_be_refactored((i+1), len(bE) - 1)]
  1016. else:
  1017. v2NextInd = bE[cap((i+1) , len(bE) - 1 )]
  1018. v2 = m.vertices[bE[i]]; v2Next = m.vertices[v2NextInd]
  1019. v = v1.co.lerp(v2.co, 0.5); vNext = v1Next.co.lerp(v2Next.co, 0.5)
  1020. # get the center, edges may not be straight so total length
  1021. # of one edge may be more than the ribbon center's length
  1022. lengths.append(( v - vNext ).length)
  1023. return lengths
  1024. def EnsureCurveIsRibbon(crv, defaultRadius = 0.1):
  1025. from .base_definitions import FLOAT_EPSILON
  1026. crvRadius = 0
  1027. crv.data.offset = 0
  1028. if (crv.data.bevel_depth < FLOAT_EPSILON):
  1029. crvRadius = crv.data.extrude
  1030. else: #Set ribbon from bevel depth
  1031. crvRadius = crv.data.bevel_depth
  1032. crv.data.bevel_depth = 0
  1033. crv.data.extrude = crvRadius
  1034. if (crvRadius < FLOAT_EPSILON):
  1035. crv.data.extrude = defaultRadius
  1036. def SetRibbonData(m, ribbon):
  1037. #maybe this could be incorporated into the DetectWireEdges function?
  1038. #maybe I can check for closed poly curves here? under what other circumstance
  1039. # will I find the ends of the wire have identical coordinates?
  1040. ribbonData = []
  1041. tE = ribbon[0].copy(); bE = ribbon[1].copy()# circle = ribbon[2]
  1042. #
  1043. lengths = RibbonMeshEdgeLengths(m, ribbon)
  1044. lengths.append(0)
  1045. totalLength = sum(lengths)
  1046. # m.calc_normals() #calculate normals
  1047. # it appears this has been removed.
  1048. for i, (t, b) in enumerate(zip(tE, bE)):
  1049. ind = old_bad_wrap_that_should_be_refactored( (i + 1), len(tE) - 1 )
  1050. tNext = tE[ind]; bNext = bE[ind]
  1051. ribbonData.append( ( (t,b), (tNext, bNext), lengths[i] ) )
  1052. #if this is a circle, the last v in vertData has a length, otherwise 0
  1053. return ribbonData, totalLength
  1054. def WireMeshEdgeLengths(m, wire):
  1055. circle = False
  1056. vIndex = wire.copy()
  1057. for e in m.edges:
  1058. if ((e.vertices[0] == vIndex[-1]) and (e.vertices[1] == vIndex[0])):
  1059. #this checks for an edge between the first and last vertex in the wire
  1060. circle = True
  1061. break
  1062. lengths = []
  1063. for i in range(len(vIndex)):
  1064. v = m.vertices[vIndex[i]]
  1065. if (circle == True):
  1066. vNextInd = vIndex[old_bad_wrap_that_should_be_refactored((i+1), len(vIndex) - 1)]
  1067. else:
  1068. vNextInd = vIndex[cap((i+1), len(vIndex) - 1 )]
  1069. vNext = m.vertices[vNextInd]
  1070. lengths.append(( v.co - vNext.co ).length)
  1071. #if this is a circular wire mesh, this should wrap instead of cap
  1072. return lengths
  1073. def GetDataFromWire(m, wire):
  1074. vertData = []
  1075. vIndex = wire.copy()
  1076. lengths = WireMeshEdgeLengths(m, wire)
  1077. lengths.append(0)
  1078. totalLength = sum(lengths)
  1079. for i, vInd in enumerate(vIndex):
  1080. #-1 to avoid IndexError
  1081. vNext = vIndex[ (old_bad_wrap_that_should_be_refactored(i+1, len(vIndex) - 1)) ]
  1082. vertData.append((vInd, vNext, lengths[i]))
  1083. #if this is a circle, the last v in vertData has a length, otherwise 0
  1084. return vertData, totalLength
  1085. def DetectWireEdges(mesh):
  1086. # Returns a list of vertex indices belonging to wire meshes
  1087. # NOTE: this assumes a mesh object with only wire meshes
  1088. ret = []
  1089. import bmesh
  1090. bm = bmesh.new()
  1091. try:
  1092. bm.from_mesh(mesh)
  1093. ends = []
  1094. for v in bm.verts:
  1095. if (len(v.link_edges) == 1):
  1096. ends.append(v.index)
  1097. for e in bm.edges:
  1098. assert (e.is_wire == True),"This function can only run on wire meshes"
  1099. if (e.verts[1].index - e.verts[0].index != 1):
  1100. ends.append(e.verts[1].index)
  1101. ends.append(e.verts[0].index)
  1102. for i in range(len(ends)//2): # // is floor division
  1103. beg = ends[i*2]
  1104. end = ends[(i*2)+1]
  1105. indices = [(j + beg) for j in range ((end - beg) + 1)]
  1106. ret.append(indices)
  1107. finally:
  1108. bm.free()
  1109. return ret
  1110. def FindNearestPointOnWireMesh(m, pointsList):
  1111. from mathutils import Vector
  1112. from mathutils.geometry import intersect_point_line
  1113. from math import sqrt
  1114. wires = DetectWireEdges(m)
  1115. ret = []
  1116. # prevFactor = None
  1117. for wire, points in zip(wires, pointsList):
  1118. vertData, total_length = GetDataFromWire(m, wire)
  1119. factorsOut = []
  1120. for p in points:
  1121. prevDist = float('inf')
  1122. curDist = float('inf')
  1123. v1 = None
  1124. v2 = None
  1125. for i in range(len(vertData) - 1):
  1126. #but it shouldn't check the last one
  1127. if (p == m.vertices[i].co):
  1128. v1 = vertData[i]
  1129. v2 = vertData[i+1]
  1130. offset = 0
  1131. break
  1132. else:
  1133. curDist = ( ((m.vertices[vertData[i][0]].co - p).length) +
  1134. ((m.vertices[vertData[i][1]].co - p).length) )/2
  1135. if (curDist < prevDist):
  1136. v1 = vertData[i]
  1137. v2 = vertData[i+1]
  1138. prevDist = curDist
  1139. offset = intersect_point_line(p, m.vertices[v1[0]].co,
  1140. m.vertices[v2[0]].co)[1]
  1141. if (offset < 0):
  1142. offset = 0
  1143. elif (offset > 1):
  1144. offset = 1
  1145. # Assume the vertices are in order
  1146. v1Length = 0
  1147. v2Length = v2[2]
  1148. for i in range(v1[0]):
  1149. v1Length += vertData[i][2]
  1150. factor = ((offset * (v2Length)) + v1Length )/total_length
  1151. factor = wrap(0, 1, factor) # doesn't hurt to wrap it if it's over 1 or less than 0
  1152. factorsOut.append(factor)
  1153. ret.append( factorsOut )
  1154. return ret
  1155. def mesh_from_curve(crv, context, ribbon=True):
  1156. """Utility function for converting a mesh to a curve
  1157. which will return the correct mesh even with modifiers"""
  1158. import bpy
  1159. m = None
  1160. bevel = crv.data.bevel_depth
  1161. extrude = crv.data.extrude
  1162. offset = crv.data.offset
  1163. try:
  1164. if (len(crv.modifiers) > 0):
  1165. do_unlink = False
  1166. if (not context.scene.collection.all_objects.get(crv.name)):
  1167. context.collection.objects.link(crv) # i guess this forces the dg to update it?
  1168. do_unlink = True
  1169. dg = context.view_layer.depsgraph
  1170. # just gonna modify it for now lol
  1171. if ribbon:
  1172. EnsureCurveIsRibbon(crv)
  1173. else:
  1174. crv.data.bevel_depth=0
  1175. crv.data.extrude=0
  1176. crv.data.offset=0
  1177. # try:
  1178. dg.update()
  1179. mOb = crv.evaluated_get(dg)
  1180. m = bpy.data.meshes.new_from_object(mOb)
  1181. m.name=crv.data.name+'_mesh'
  1182. if (do_unlink):
  1183. context.collection.objects.unlink(crv)
  1184. else: # (ಥ﹏ಥ) why can't I just use this !
  1185. # for now I will just do it like this
  1186. if ribbon:
  1187. EnsureCurveIsRibbon(crv)
  1188. else:
  1189. crv.data.bevel_depth=0
  1190. crv.data.extrude=0
  1191. crv.data.offset=0
  1192. m = bpy.data.meshes.new_from_object(crv)
  1193. finally:
  1194. crv.data.bevel_depth = bevel
  1195. crv.data.extrude = extrude
  1196. crv.data.offset = offset
  1197. return m
  1198. def DetectRibbon(f, bm, skipMe):
  1199. fFirst = f.index
  1200. cont = True
  1201. circle = False
  1202. tEdge, bEdge = [],[]
  1203. while (cont == True):
  1204. skipMe.add(f.index)
  1205. tEdge.append (f.loops[0].vert.index) # top-left
  1206. bEdge.append (f.loops[3].vert.index) # bottom-left
  1207. nEdge = bm.edges.get([f.loops[1].vert, f.loops[2].vert])
  1208. nFaces = nEdge.link_faces
  1209. if (len(nFaces) == 1):
  1210. cont = False
  1211. else:
  1212. for nFace in nFaces:
  1213. if (nFace != f):
  1214. f = nFace
  1215. break
  1216. if (f.index == fFirst):
  1217. cont = False
  1218. circle = True
  1219. if (cont == False): # we've reached the end, get the last two:
  1220. tEdge.append (f.loops[1].vert.index) # top-right
  1221. bEdge.append (f.loops[2].vert.index) # bottom-right
  1222. # this will create a loop for rings --
  1223. # "the first shall be the last and the last shall be first"
  1224. return (tEdge,bEdge,circle)
  1225. def DetectRibbons(m, fReport = None):
  1226. # Returns list of vertex indices belonging to ribbon mesh edges
  1227. # NOTE: this assumes a mesh object with only ribbon meshes
  1228. # ---DO NOT call this script with a mesh that isn't a ribbon!--- #
  1229. import bmesh
  1230. bm = bmesh.new()
  1231. bm.from_mesh(m)
  1232. mIslands, mIsland = [], []
  1233. skipMe = set()
  1234. bm.faces.ensure_lookup_table()
  1235. #first, get a list of mesh islands
  1236. for f in bm.faces:
  1237. if (f.index in skipMe):
  1238. continue #already done here
  1239. checkMe = [f]
  1240. while (len(checkMe) > 0):
  1241. facesFound = 0
  1242. for f in checkMe:
  1243. if (f.index in skipMe):
  1244. continue #already done here
  1245. mIsland.append(f)
  1246. skipMe.add(f.index)
  1247. for e in f.edges:
  1248. checkMe += e.link_faces
  1249. if (facesFound == 0):
  1250. #this is the last iteration
  1251. mIslands.append(mIsland)
  1252. checkMe, mIsland = [], []
  1253. ribbons = []
  1254. skipMe = set() # to store ends already checked
  1255. for mIsl in mIslands:
  1256. ribbon = None
  1257. first = float('inf')
  1258. for f in mIsl:
  1259. if (f.index in skipMe):
  1260. continue #already done here
  1261. if (f.index < first):
  1262. first = f.index
  1263. adjF = 0
  1264. for e in f.edges:
  1265. adjF+= (len(e.link_faces) - 1)
  1266. # every face other than this one is added to the list
  1267. if (adjF == 1):
  1268. ribbon = (DetectRibbon(f, bm, skipMe) )
  1269. break
  1270. if (ribbon == None):
  1271. ribbon = (DetectRibbon(bm.faces[first], bm, skipMe) )
  1272. ribbons.append(ribbon)
  1273. # print (ribbons)
  1274. return ribbons
  1275. def data_from_ribbon_mesh(m, factorsList, mat, ribbons = None, fReport = None):
  1276. #Note, factors list should be equal in length the the number of wires
  1277. #Now working for multiple wires, ugly tho
  1278. if (ribbons == None):
  1279. ribbons = DetectRibbons(m, fReport=fReport)
  1280. if (ribbons is None):
  1281. if (fReport):
  1282. fReport(type = {'ERROR'}, message="No ribbon to get data from.")
  1283. else:
  1284. print ("No ribbon to get data from.")
  1285. return None
  1286. ret = []
  1287. for factors, ribbon in zip(factorsList, ribbons):
  1288. points = []
  1289. widths = []
  1290. normals = []
  1291. ribbonData, totalLength = SetRibbonData(m, ribbon)
  1292. for fac in factors:
  1293. if (fac == 0):
  1294. data = ribbonData[0]
  1295. curFac = 0
  1296. elif (fac == 1):
  1297. data = ribbonData[-1]
  1298. curFac = 0
  1299. else:
  1300. targetLength = totalLength * fac
  1301. data = ribbonData[0]
  1302. curLength = 0
  1303. for ( (t, b), (tNext, bNext), length,) in ribbonData:
  1304. if (curLength >= targetLength):
  1305. break
  1306. curLength += length
  1307. data = ( (t, b), (tNext, bNext), length,)
  1308. targetLengthAtEdge = (curLength - targetLength)
  1309. if (targetLength == 0):
  1310. curFac = 0
  1311. elif (targetLength == totalLength):
  1312. curFac = 1
  1313. else:
  1314. # NOTE: This can be Zero. Find out why!
  1315. if data[2] == 0:
  1316. curFac=0
  1317. else:
  1318. curFac = 1 - (targetLengthAtEdge/ data[2]) #length
  1319. t1 = m.vertices[data[0][0]]; b1 = m.vertices[data[0][1]]
  1320. t2 = m.vertices[data[1][0]]; b2 = m.vertices[data[1][1]]
  1321. #location
  1322. loc1 = (t1.co).lerp(b1.co, 0.5)
  1323. loc2 = (t2.co).lerp(b2.co, 0.5)
  1324. #width
  1325. w1 = (t1.co - b1.co).length/2
  1326. w2 = (t2.co - b2.co).length/2 #radius, not diameter
  1327. #normal
  1328. n1 = (t1.normal).slerp(b1.normal, 0.5)
  1329. n2 = (t1.normal).slerp(b2.normal, 0.5)
  1330. if ((data[0][0] > data[1][0]) and (ribbon[2] == False)):
  1331. curFac = 0
  1332. #don't interpolate if at the end of a ribbon that isn't circular
  1333. if ( 0 < curFac < 1):
  1334. outPoint = loc1.lerp(loc2, curFac)
  1335. outNorm = n1.lerp(n2, curFac)
  1336. outWidth = w1 + ( (w2-w1) * curFac)
  1337. elif (curFac <= 0):
  1338. outPoint = loc1.copy()
  1339. outNorm = n1
  1340. outWidth = w1
  1341. elif (curFac >= 1):
  1342. outPoint = loc2.copy()
  1343. outNorm = n2
  1344. outWidth = w2
  1345. outPoint = mat @ outPoint
  1346. outNorm.normalize()
  1347. points.append ( outPoint.copy() ) #copy because this is an actual vertex location
  1348. widths.append ( outWidth )
  1349. normals.append( outNorm )
  1350. ret.append( (points, widths, normals) )
  1351. return ret # this is a list of tuples containing three lists
  1352. #This bisection search is generic, and it searches based on the
  1353. # magnitude of the error, rather than the sign.
  1354. # If the sign of the error is meaningful, a simpler function
  1355. # can be used.
  1356. def do_bisect_search_by_magnitude(
  1357. owner,
  1358. attribute,
  1359. index = None,
  1360. test_function = None,
  1361. modify = None,
  1362. max_iterations = 10000,
  1363. threshold = 0.0001,
  1364. thresh2 = 0.0005,
  1365. context = None,
  1366. update_dg = None,
  1367. ):
  1368. from math import floor
  1369. i = 0; best_so_far = 0; best = float('inf')
  1370. min = 0; center = max_iterations//2; max = max_iterations
  1371. # enforce getting the absolute value, in case the function has sign information
  1372. # The sign may be useful in a sign-aware bisect search, but this one is more robust!
  1373. test = lambda : abs(test_function(owner, attribute, index, context = context,))
  1374. while (i <= max_iterations):
  1375. upper = (max - ((max-center))//2)
  1376. modify(owner, attribute, index, upper, context = context); error1 = test()
  1377. lower = (center - ((center-min))//2)
  1378. modify(owner, attribute, index, lower, context = context); error2 = test()
  1379. if (error1 < error2):
  1380. min = center
  1381. center, check = upper, upper
  1382. error = error1
  1383. else:
  1384. max = center
  1385. center, check = lower, lower
  1386. error = error2
  1387. if (error <= threshold) or (min == max-1):
  1388. break
  1389. if (error < thresh2):
  1390. j = min
  1391. while (j < max):
  1392. modify(owner, attribute, index, j * 1/max_iterations, context = context)
  1393. error = test()
  1394. if (error < best):
  1395. best_so_far = j; best = error
  1396. if (error <= threshold):
  1397. break
  1398. j+=1
  1399. else: # loop has completed without finding a solution
  1400. i = best_so_far; error = test()
  1401. modify(owner, attribute, index, best_so_far, context = context)
  1402. break
  1403. if (error < best):
  1404. best_so_far = check; best = error
  1405. i+=1
  1406. if update_dg:
  1407. update_dg.update()
  1408. else: # Loop has completed without finding a solution
  1409. i = best_so_far
  1410. modify(owner, attribute, best_so_far, context = context); i+=1