utilities.py 71 KB

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