utilities.py 65 KB

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