utilities.py 66 KB

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