utilities.py 65 KB

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