utilities.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. #fool: should be wrColor like prColor... dumb
  2. def wrapRed(skk): return "\033[91m{}\033[00m".format(skk)
  3. def wrapGreen(skk): return "\033[92m{}\033[00m".format(skk)
  4. def wrapPurple(skk): return "\033[95m{}\033[00m".format(skk)
  5. def wrapWhite(skk): return "\033[97m{}\033[00m".format(skk)
  6. def wrapOrange(skk): return "\033[0;33m{}\033[00m".format(skk)
  7. # these should reimplement the print interface..
  8. def prRed(*args): print (*[wrapRed(arg) for arg in args])
  9. def prGreen(*args): print (*[wrapGreen(arg) for arg in args])
  10. def prPurple(*args): print (*[wrapPurple(arg) for arg in args])
  11. def prWhite(*args): print (*[wrapWhite(arg) for arg in args])
  12. def prOrange(*args): print (*[wrapOrange(arg) for arg in args])
  13. # add THIS to the top of a file for easy access:
  14. # from mantis.utilities import (prRed, prGreen, prPurple, prWhite,
  15. # prOrange,
  16. # wrapRed, wrapGreen, wrapPurple, wrapWhite,
  17. # wrapOrange,)
  18. def float_lerp(a : float, b : float, factor : float) -> float:
  19. return (a * (1.0 - factor)) + (b * factor)
  20. def find_reroute_start_socket(reroute, track='BACK'):
  21. # "BACK" traces back through the tree and returns one socket
  22. # "FORWARD" traces forward through the tree and returns a list of sockets
  23. from ..base_definitions import reroute_cache
  24. from .node_common import GraphError
  25. # We assume the cache is good, the tree is responsible for this
  26. tree = reroute.id_data
  27. tree_cache = reroute_cache.get(tree.name)
  28. if track == 'FORWARD':
  29. cache_item = tree_cache.get(reroute.name); sockets = []
  30. if not cache_item: # I think this is OK, they don't always go somewhere
  31. return # And this FORWARD trace is always a background task
  32. for node_name, socket_index in cache_item.destinations:
  33. sockets.append(tree.nodes.get(node_name).inputs[socket_index])
  34. return sockets
  35. if track == 'BACK':
  36. cache_item = tree_cache.get(reroute.name)
  37. if not cache_item or not cache_item.source:
  38. raise GraphError(f"There is a missing link in the tree at reroute node: {reroute.name}")
  39. return tree.nodes.get(cache_item.source[0]).outputs[cache_item.source[1]]
  40. # this creates fake links that have the same interface as Blender's
  41. # so that I can bypass Reroutes
  42. def clear_reroutes(links):
  43. from ..base_definitions import DummyLink
  44. kept_links, rerouted_starts = [], []
  45. rerouted = []
  46. all_links = links.copy()
  47. while(all_links):
  48. link = all_links.pop()
  49. to_cls = link.to_socket.node.bl_idname
  50. from_cls = link.from_socket.node.bl_idname
  51. reroute_classes = ["NodeReroute"]
  52. if (to_cls in reroute_classes and
  53. from_cls in reroute_classes):
  54. rerouted.append(link)
  55. elif (to_cls in reroute_classes and not
  56. from_cls in reroute_classes):
  57. rerouted.append(link)
  58. elif (from_cls in reroute_classes and not
  59. to_cls in reroute_classes):
  60. rerouted_starts.append(link)
  61. else:
  62. kept_links.append(link)
  63. for start in rerouted_starts:
  64. from_socket = find_reroute_start_socket(start.from_node)
  65. new_link = DummyLink(from_socket=from_socket,
  66. to_socket=start.to_socket,
  67. from_mantis_node=None,
  68. to_mantis_node=None,
  69. multi_input_sort_id=start.multi_input_sort_id )
  70. kept_links.append(new_link)
  71. return kept_links
  72. def tree_from_mantis_node(sig, base_tree):
  73. if (sig[0] == 'MANTIS_AUTOGENERATED'):
  74. sig = sig[:-2] # cut off the end part of the signature (because it uses socket.name and socket.identifier)
  75. # this will lead to totally untraceble bugs in the event of a change in how signatures are assigned
  76. tree = base_tree
  77. for i, path_item in enumerate(sig):
  78. if (i == 0) or (i == len(sig) - 1):
  79. continue
  80. tree = tree.nodes.get(path_item).node_tree
  81. return tree
  82. def get_ui_node(sig, base_tree):
  83. return tree_from_mantis_node(sig, base_tree).nodes.get( sig[-1] )
  84. # Function for splitting up
  85. def split_quoted_substrings_to_strings(text):
  86. import re
  87. pattern = r'''(?:"([^"]*)"|'([^']*)'|([^"']+))'''
  88. substrings = [
  89. next(group for group in match.groups() if group is not None)
  90. for match in re.finditer(pattern, text)
  91. ]
  92. return substrings
  93. ##################################################################################################
  94. # groups and changing sockets -- this is used extensively by Schema.
  95. ##################################################################################################
  96. # this one returns None if there is an error.
  97. def get_socket_maps(node, force=False):
  98. maps = [{}, {}]
  99. node_collection = ["inputs", "outputs"]
  100. links = ["from_socket", "to_socket"]
  101. for collection, map, linked_socket in zip(node_collection, maps, links):
  102. for sock in getattr(node, collection):
  103. if sock.is_linked:
  104. other_sockets = []
  105. # Sort the links first (in case they are mult-input), because Blender doesn't
  106. links = sorted(list(sock.links), key = lambda l : l.multi_input_sort_id)
  107. # HACK here because Blender will crash if the socket values in the NodeReroute
  108. # are mutated. Because this seems to happen in a deffered way, I can't account
  109. # for it except by checking the node later...
  110. # TODO: The fact that I need this hack means I can probably solve this problem
  111. # for all node types in a safer way, since they may also be dynamic somehow
  112. for l in links:
  113. if "from" in linked_socket and l.from_node.bl_idname == "NodeReroute":
  114. other_sockets.append(l.from_node)
  115. elif "to" in linked_socket and l.to_node.bl_idname == "NodeReroute":
  116. other_sockets.append(l.to_node)
  117. else:
  118. other_sockets.append(getattr(l, linked_socket))
  119. from bpy.types import NodeSocket
  120. keep_sockets=[]
  121. for other_socket in other_sockets.copy():
  122. if isinstance(other_socket, NodeSocket) and \
  123. other_socket.bl_idname == 'NodeSocketUndefined':
  124. continue # this one is bad
  125. keep_sockets.append(other_socket)
  126. map[sock.identifier]= keep_sockets
  127. elif hasattr(sock, "default_value"):
  128. # in blender 5.0 we have to use sock.default_value insted of sock.get("default_value") :/
  129. if sock.bl_idname == "EnumCurveSocket" and sock.default_value is None:
  130. # HACK I need to add this special case because during file-load,
  131. # this value is None and should not be altered until it is set once.
  132. continue
  133. if sock.default_value is not None:
  134. val = getattr(sock, "default_value")
  135. elif "Enum" in sock.bl_idname and isinstance(sock.get("default_value"), int):
  136. continue # for string enum properties that have not yet initialized (at startup)
  137. elif (val := sock.default_value) is not None:
  138. pass
  139. elif not force:
  140. continue
  141. map[sock.identifier]=val
  142. else:
  143. from ..socket_definitions import no_default_value
  144. if sock.bl_idname in no_default_value:
  145. map[sock.identifier]=None
  146. else:
  147. raise RuntimeError(f"ERROR: Could not get socket data for socket of type: {sock.bl_idname}")
  148. return maps
  149. def generate_intervening_reroute(socket, other_socket,):
  150. from bpy.app import version as bpy_version
  151. print ("i have to make a reroute node here lol")
  152. node = socket.node
  153. reroute = node.id_data.nodes.new('NodeReroute')
  154. # NOTE that this doesn't really do a good job of placing it. Whatever.
  155. l = node.id_data.links.new(input=other_socket, output=reroute.inputs[0])
  156. l = node.id_data.links.new(input=reroute.outputs[0], output=socket)
  157. reroute.location = node.location.lerp(other_socket.node.location, 0.25)
  158. if (bpy_version >= (4,4,0)): # correct the reroute color if possible
  159. reroute.socket_idname = other_socket.bl_idname
  160. return l
  161. # this function is completely overloaded with different purposes and code paths
  162. # TODO refactor everything that funnels into this function
  163. # make this stuff simpler.
  164. def do_relink(node, socket, map, in_out='INPUT', parent_name = ''):
  165. if not node.__class__.is_registered_node_type(): return
  166. tree = node.id_data; interface_in_out = 'OUTPUT' if in_out == 'INPUT' else 'INPUT'
  167. if hasattr(node, "node_tree"):
  168. tree = node.node_tree
  169. interface_in_out=in_out
  170. from bpy.types import NodeSocket, Node
  171. get_string = '__extend__'
  172. if socket: get_string = socket.identifier
  173. from ..base_definitions import SchemaUINode
  174. if (hasattr(node, "node_tree") or isinstance(node, SchemaUINode)) and get_string not in map.keys():
  175. # this happens when we are creating a new node group and need to update it from nothing.
  176. return
  177. val = map[get_string] # this will throw an error if the socket isn't there. Good!
  178. # IF there are multiple links going from one node-socket to this socket, then we have to relink
  179. # every socket but the first one before it can go in
  180. # Counter for every socket starts at 0 and if it is greater than 0, add a reroute intervening
  181. # then decrement the counter while relinking,
  182. socket_counters = {}
  183. if isinstance(val, list):
  184. for sub_val in val:
  185. # this will only happen once because it assigns socket, so it is safe to do in the for loop.
  186. if socket is None:
  187. socket = sub_val; sockets = [socket]
  188. if sub_val.bl_idname == "NodeReroute":
  189. # we have to trace the reroute node...
  190. if in_out == 'INPUT':
  191. socket = find_reroute_start_socket(sub_val); sockets = [socket]
  192. else:
  193. sockets = find_reroute_start_socket(sub_val, track="FORWARD")
  194. for socket in sockets:
  195. sock_type = socket.interface_type
  196. name = unique_socket_name(node, socket, tree)
  197. if parent_name:
  198. interface_socket = update_interface(tree.interface, name, interface_in_out, sock_type, parent_name)
  199. if in_out =='INPUT':
  200. socket = node.inputs.new(sock_type, name, identifier=interface_socket.identifier)
  201. else:
  202. socket = node.outputs.new(sock_type, name, identifier=interface_socket.identifier)
  203. if parent_name == 'Array': socket.display_shape='SQUARE_DOT'
  204. if parent_name == 'Constant': socket.display_shape='CIRCLE_DOT'
  205. # then move it up and delete the other link.
  206. # this also needs to modify the interface of the node tree.
  207. if isinstance(sub_val, NodeSocket):
  208. counter_id=sub_val.node.name+"::"+sub_val.identifier
  209. l = None
  210. if in_out =='INPUT':
  211. if socket_counters.get(counter_id) is None:
  212. socket_counters[counter_id] = 0
  213. if socket_counters[counter_id] == 0:
  214. l = node.id_data.links.new(input=sub_val, output=socket)
  215. else:
  216. l = generate_intervening_reroute(socket, sub_val)
  217. socket_counters[counter_id] += 1
  218. else:
  219. l = node.id_data.links.new(input=socket, output=sub_val)
  220. if l is None:
  221. raise RuntimeError("Could not create link")
  222. elif isinstance(sub_val, Node):
  223. counter_id=sub_val.name+"::Output"
  224. l = None
  225. # this happens when it is a NodeReroute
  226. if not socket.is_output:
  227. if socket_counters.get(counter_id) is None:
  228. socket_counters[counter_id] = 0
  229. if socket_counters[counter_id] == 0:
  230. l = node.id_data.links.new(input=sub_val.outputs[0], output=socket)
  231. else:
  232. # NOTE maybe this should make another reroute from the source to here instead
  233. l = generate_intervening_reroute(socket, sub_val.outputs[0])
  234. socket_counters[counter_id] += 1
  235. else:
  236. l = node.id_data.links.new(input=socket, output=sub_val.inputs[0])
  237. if l is None:
  238. raise RuntimeError("Could not create link")
  239. else:
  240. raise RuntimeError("Unhandled case in do_relink()")
  241. elif get_string != "__extend__":
  242. if not socket.is_output:
  243. from bpy.app import version as bpy_version
  244. if bpy_version >=(4,5,0): # VERSIONING
  245. # for some reason, this is throwing an error now
  246. from bpy.types import bpy_prop_array
  247. if isinstance(val, bpy_prop_array):
  248. if in_out == "INPUT" and hasattr(socket, 'input') and socket.input == False:
  249. return # doesn't matter, this is a Matrix socket in a bone or something
  250. # raise RuntimeError(
  251. # f"Cannot set property in socket of type {socket.bl_idname} due to bug in Blender: "
  252. # f"{node.id_data.name}:{node.name}:{socket.name} ")
  253. # TODO: report this weird bug!
  254. try:
  255. if socket.bl_idname == 'BooleanThreeTupleSocket':
  256. # it is so annoying that I have to do this
  257. socket.default_value = [bool(val[0]), bool(val[1]), bool(val[2])]
  258. else:
  259. socket.default_value = val
  260. except (AttributeError, ValueError): # must be readonly or maybe it doesn't have a d.v.
  261. pass
  262. def read_schema_type(interface_item):
  263. # VERSIONING CODE
  264. tree=interface_item.id_data
  265. version = tree.mantis_version
  266. old_version = False
  267. if version[0] == 0:
  268. if version[1] < 13: old_version = True
  269. # unfortunately we need to check this stuff for the versioning code to run correctly the first time.
  270. # UNLESS I can find a way to prevent this code from running before versioning
  271. if old_version or (not hasattr(interface_item, 'is_array')):
  272. # it is not a custom interface class and/or the file is old.
  273. if interface_item.parent:
  274. return interface_item.parent.name
  275. else:
  276. if interface_item.is_array:
  277. return 'Array'
  278. if interface_item.is_connection:
  279. return 'Connection'
  280. return 'Constant'
  281. def update_interface(interface, name, in_out, sock_type, parent_name):
  282. from bpy.app import version as bpy_version
  283. if parent_name:
  284. if not (interface_parent := interface.items_tree.get(parent_name)):
  285. interface_parent = interface.new_panel(name=parent_name)
  286. if bpy_version != (4,5,0):
  287. socket = interface.new_socket(name=name,in_out=in_out, socket_type=sock_type, parent=interface_parent)
  288. else: # blender 4.5.0 LTS, have to workaround a bug!
  289. from ..versioning import workaround_4_5_0_interface_update
  290. socket = workaround_4_5_0_interface_update(tree=interface.id_data, name=name, in_out=in_out,
  291. sock_type=sock_type, parent_name=parent_name, do_parent=True)
  292. match parent_name:
  293. case "Connection":
  294. socket.is_connection=True
  295. case "Array":
  296. socket.is_array=True
  297. if parent_name == 'Connection':
  298. in_out = 'OUTPUT' if in_out == 'INPUT' else 'INPUT' # flip this make sure connections always do both
  299. other_socket = interface.new_socket(name=name,in_out=in_out, socket_type=sock_type, parent=interface_parent)
  300. other_socket.is_connection = True
  301. return socket
  302. else:
  303. raise RuntimeError(wrapRed("Cannot add interface item to tree without specifying type."))
  304. #UGLY BAD REFACTOR
  305. def relink_socket_map_add_socket(node, socket_collection, item, in_out=None,):
  306. from bpy.app import version as bpy_version
  307. # if not in_out: in_out=item.in_out
  308. multi=False
  309. if in_out == 'INPUT' and read_schema_type(item) == 'Array':
  310. multi = True
  311. # have to work around a bug in 4.5.0 that prevents me from declaring custom socket types
  312. # I have arbitrarily chosen to use the NodeSocketGeometry type to signal that this one is affected.
  313. if bpy_version == (4, 5, 0) and item.bl_socket_idname == 'NodeSocketGeometry':
  314. from ..versioning import socket_add_workaround_for_4_5_0_LTS
  315. s = socket_add_workaround_for_4_5_0_LTS(item, socket_collection, multi)
  316. else:
  317. s = socket_collection.new(type=item.bl_socket_idname, name=item.name, identifier=item.identifier, use_multi_input=multi)
  318. if hasattr(s, 'default_value') and hasattr(s, 'is_valid_interface_type') and \
  319. s.is_valid_interface_type == True:
  320. if s.bl_idname not in ['MatrixSocket']: # no default value implemented
  321. from bpy.types import bpy_prop_array
  322. from mathutils import Vector
  323. default_value = 'REPORT BUG ON GITLAB' # default to bug string
  324. val_type = type(s.default_value) # why tf can't I match/case here?
  325. if val_type is bool: default_value = item.default_bool
  326. if val_type is int: default_value = item.default_int
  327. if val_type is float: default_value = item.default_float
  328. if val_type is Vector: default_value = item.default_vector
  329. if val_type is str: default_value = item.default_string
  330. if val_type is bpy_prop_array: default_value = item.default_bool_vector
  331. if not s.is_property_readonly("default_value"):
  332. s.default_value = default_value
  333. else: # TODO: make this work with color sets.
  334. raise Warning("WARN: Not yet implemented: default values for color sets.")
  335. if read_schema_type(item) == 'Array': s.display_shape = 'SQUARE_DOT'
  336. elif node.bl_idname in ['MantisSchemaGroup'] and read_schema_type(item) == 'Constant':
  337. 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. links = clear_reroutes([link])
  694. if links:
  695. link = links[0]
  696. else:
  697. return
  698. dummy_types = ["DUMMY", "DUMMY_SCHEMA"]
  699. from_name, to_name = get_link_in_out(link)
  700. from_mantis_node = local_mantis_nodes.get( (*tree_path_names, from_name+from_suffix) )
  701. to_mantis_node = local_mantis_nodes.get( (*tree_path_names, to_name+to_suffix))
  702. if (from_mantis_node and to_mantis_node):
  703. from_s, to_s = link.from_socket.name, link.to_socket.name
  704. if to_mantis_node.node_type in dummy_types: to_s = link.to_socket.identifier
  705. if from_mantis_node.node_type in dummy_types: from_s = link.from_socket.identifier
  706. try:
  707. connection = from_mantis_node.outputs[from_s].connect(node=to_mantis_node, socket=to_s, sort_id=link.multi_input_sort_id)
  708. if connection is None:
  709. prWhite(f"Already connected: {from_name}:{from_s}->{to_name}:{to_s}")
  710. return connection
  711. except KeyError as e:
  712. prRed(f"{from_mantis_node}:{from_s} or {to_mantis_node}:{to_s} missing; review the connections printed below:")
  713. print (from_mantis_node.outputs.keys())
  714. print (to_mantis_node.inputs.keys())
  715. raise e
  716. else:
  717. prRed(from_mantis_node, to_mantis_node, (*tree_path_names, from_name+from_suffix), (*tree_path_names, to_name+to_suffix))
  718. if to_mantis_node is None:
  719. prRed( "Error: mantis node with signature "
  720. f"{(*tree_path_names, to_name+to_suffix)} "
  721. "does not exist.")
  722. if from_mantis_node is None:
  723. prRed("Error: mantis node with signature "
  724. f"{(*tree_path_names, from_name+from_suffix)} "
  725. "does not exist.")
  726. raise RuntimeError(wrapRed(f"Link not connected: {from_mantis_node} -> {to_mantis_node} in tree" ))
  727. def get_all_dependencies(mantis_node):
  728. from ..base_definitions import GraphError
  729. """ find all dependencies for a mantis node"""
  730. nodes = []
  731. check_nodes = [mantis_node]
  732. nodes_checked = set()
  733. while (len(check_nodes) > 0):
  734. node = check_nodes.pop()
  735. nodes_checked.add (node)
  736. connected_nodes = node.hierarchy_dependencies
  737. for new_node in connected_nodes:
  738. if new_node in nodes:
  739. continue
  740. nodes.append(new_node)
  741. if new_node not in nodes_checked:
  742. check_nodes.append(new_node)
  743. return nodes
  744. def get_all_nodes_of_type(base_tree, bl_idname):
  745. nodes = []
  746. check_nodes = list(base_tree.nodes)
  747. while (len(check_nodes) > 0):
  748. node = check_nodes.pop()
  749. if node.bl_idname in bl_idname:
  750. nodes.append(node)
  751. if hasattr(node, "node_tree"):
  752. check_nodes.extend(list(node.node_tree.nodes))
  753. return nodes
  754. def trace_all_nodes_from_root(root, nodes):
  755. from ..base_definitions import GraphError
  756. """ find all dependencies for a mantis node"""
  757. nodes.add(root); check_nodes = [root]
  758. nodes_checked = set()
  759. while (len(check_nodes) > 0):
  760. node = check_nodes.pop(); nodes_checked.add (node)
  761. connected_nodes = []
  762. for output in node.outputs:
  763. for l in output.links:
  764. if l.to_node not in nodes:
  765. connected_nodes.append(l.to_node)
  766. for new_node in connected_nodes:
  767. nodes.add(new_node)
  768. if new_node not in nodes_checked:
  769. check_nodes.append(new_node)
  770. return nodes
  771. ##################################################################################################
  772. # misc
  773. ##################################################################################################
  774. # TODO: get the matrix to return a mathutils.Matrix so I don't need a function call here
  775. def to_mathutils_value(socket):
  776. if hasattr(socket, "default_value"):
  777. val = socket.default_value
  778. if socket.bl_idname in ['MatrixSocket']:
  779. return socket.TellValue()
  780. else:
  781. return val
  782. else:
  783. return None
  784. def all_trees_in_tree(base_tree, selected=False):
  785. """ Recursively finds all trees referenced in a given base-tree."""
  786. # note that this is recursive but not by tail-end recursion
  787. # a while-loop is a better way to do recursion in Python.
  788. trees = [base_tree]
  789. can_descend = True
  790. check_trees = [base_tree]
  791. while (len(check_trees) > 0): # this seems innefficient, why 2 loops?
  792. new_trees = []
  793. while (len(check_trees) > 0):
  794. tree = check_trees.pop()
  795. for node in tree.nodes:
  796. if selected == True and node.select == False:
  797. continue
  798. if new_tree := getattr(node, "node_tree", None):
  799. if new_tree in trees: continue
  800. new_trees.append(new_tree)
  801. trees.append(new_tree)
  802. check_trees = new_trees
  803. return trees
  804. # this is a destructive operation, not a pure function or whatever. That isn't good but I don't care.
  805. def SugiyamaGraph(tree, iterations):
  806. from grandalf.graphs import Vertex, Edge, Graph, graph_core
  807. class defaultview(object):
  808. w,h = 1,1
  809. xz = (0,0)
  810. graph = Graph()
  811. no_links = set()
  812. verts = {}
  813. for n in tree.nodes:
  814. if n.select == True:
  815. v = Vertex(n.name)
  816. v.view = defaultview()
  817. v.view.xy = n.location
  818. v.view.h = n.height*2.5
  819. v.view.w = n.width*2.2
  820. verts[n.name] = v
  821. no_links.add(n.name)
  822. graph.add_vertex(v)
  823. n.select=False
  824. edges = []
  825. inverted_edges=[]
  826. not_a_root = set()
  827. for link in tree.links:
  828. if (link.from_node.name not in verts.keys()) or (link.to_node.name not in verts.keys()):
  829. continue # problem??
  830. weight = 1 # maybe this is useful
  831. not_a_root.add(link.to_node.name) # if it has a edge-input it is not a root.
  832. e = Edge(verts[link.from_node.name], verts[link.to_node.name], weight)
  833. graph.add_edge(e)
  834. edges.append(e )
  835. if link.is_valid == False:
  836. inverted_edges.append(e)
  837. if link.from_node.name in no_links:
  838. no_links.remove(link.from_node.name)
  839. if link.to_node.name in no_links:
  840. no_links.remove(link.to_node.name)
  841. try:
  842. from grandalf.layouts import SugiyamaLayout
  843. # .C[0] is the first "graph core" that contains a connected graph.
  844. sug = SugiyamaLayout(graph.C[0])
  845. sug.init_all()
  846. sug.draw(iterations)
  847. # Digco is good for small graphs.
  848. # from grandalf.layouts import DigcoLayout
  849. # dco = DigcoLayout(graph.C[0])
  850. # dco.init_all()
  851. # dco.draw(iterations)
  852. except KeyboardInterrupt:
  853. pass # just use what it has calculated so far, I guess
  854. for v in graph.C[0].sV:
  855. for n in tree.nodes:
  856. if n.name == v.data:
  857. n.location.x = v.view.xy[1]
  858. n.location.y = v.view.xy[0]
  859. n.select = True
  860. # now we can take all the input nodes and try to put them in a sensible place
  861. # not sure why but this absolutely does not do anything
  862. for n_name in no_links:
  863. n = tree.nodes.get(n_name)
  864. next_node = None
  865. for output in n.outputs:
  866. if output.is_linked == True:
  867. next_node = output.links[0].to_node
  868. break
  869. # let's see if the next node
  870. if next_node:
  871. # need to find the other node in the same layer...
  872. other_node = None
  873. for s_input in next_node.inputs:
  874. if s_input.is_linked:
  875. other_node = s_input.links[0].from_node
  876. if other_node is n:
  877. continue
  878. else:
  879. break
  880. if other_node:
  881. n.location = other_node.location
  882. n.location.y -= other_node.height*2
  883. else: # we'll just position it next to the next node
  884. n.location = next_node.location
  885. n.location.x -= next_node.width*1.5
  886. def project_point_to_plane(point, origin, normal):
  887. return point - normal.dot(point- origin)*normal
  888. # If a $ character is in a value, it is an overlay request
  889. # in the root tree, supply it immediately, otherwise tag this node
  890. # once we finish pulling data from the tree we handle the overlay.
  891. def handle_overlay_detect(node, socket_id, value) -> str:
  892. mContext = node.mContext
  893. root_tree = mContext.base_tree
  894. root_items_tree = root_tree.interface.items_tree
  895. # detect if it is in the root tree, if so, handle immediately
  896. out_value = value
  897. if node.signature[0] is None and len(node.signature) ==2:
  898. for key, interface_item in root_items_tree.items():
  899. if interface_item.item_type != "SOCKET": continue
  900. if interface_item.in_out != "INPUT": continue
  901. # NOTE this will need to change if overlays extend to other data types
  902. if not hasattr(interface_item, "default_string"): continue
  903. out_value = out_value.replace("$"+key, interface_item.default_string)
  904. else: # since it is not root, we have to tag it.
  905. mContext.tagged_for_overlay.append((node.signature, socket_id))
  906. return out_value
  907. ####################################
  908. # CURVE STUFF
  909. ####################################
  910. def make_perpendicular(v1, v2):
  911. from ..base_definitions import FLOAT_EPSILON
  912. if (v1.length_squared < FLOAT_EPSILON) or (v2.length_squared < FLOAT_EPSILON):
  913. raise RuntimeError("Cannot generate perpendicular vetor for zero-length vector")
  914. projected = (v2.dot(v1) / v1.dot(v1)) * v1
  915. perpendicular = v2 - projected
  916. return perpendicular
  917. # this stuff could be branchless but I don't use it much TODO
  918. def cap(val, maxValue):
  919. if (val > maxValue):
  920. return maxValue
  921. return val
  922. def capMin(val, minValue):
  923. if (val < minValue):
  924. return minValue
  925. return val
  926. def wrap(min : float, max : float, value: float) -> float:
  927. range = max-min; remainder = value % range
  928. if remainder > max: return min + remainder-max
  929. else: return remainder
  930. def lerpVal(a, b, fac = 0.5):
  931. return a + ( (b-a) * fac)
  932. #wtf this doesn't do anything even remotely similar to wrap
  933. # HACK BAD FIXME UNBREAK ME BAD
  934. # I don't understand what this function does but I am using it in multiple places?
  935. def old_bad_wrap_that_should_be_refactored(val, maxValue, minValue = None):
  936. if (val > maxValue):
  937. return (-1 * ((maxValue - val) + 1))
  938. if ((minValue) and (val < minValue)):
  939. return (val + maxValue)
  940. return val
  941. #TODO clean this up
  942. def extract_spline_suffix(spline_index):
  943. return ".spline."+str(spline_index).zfill(3)+".extracted"
  944. def do_extract_spline(data, spline):
  945. remove_me = []
  946. for other_spline in data.splines:
  947. if other_spline != spline: remove_me.append(other_spline)
  948. while remove_me: data.splines.remove(remove_me.pop())
  949. def extract_spline(curve, spline_index):
  950. """ Given a curve object and spline index, returns a new object
  951. containing only the selcted spline. The new object is bound to
  952. the original curve.
  953. """
  954. if len(curve.data.splines) == 1:
  955. return curve # nothing to do here.
  956. spline_suffix = extract_spline_suffix(spline_index)
  957. from bpy import data
  958. if (new_ob := data.objects.get(curve.name+spline_suffix)) is None:
  959. new_ob=curve.copy(); new_ob.name=curve.name+spline_suffix
  960. # if the data exists, it is probably stale, so delete it and start over.
  961. if (old_data := data.objects.get(curve.data.name+spline_suffix)) is not None:
  962. data.curves.remove(old_data)
  963. new_data=curve.data.copy(); new_data.name=curve.data.name+spline_suffix
  964. new_ob.data = new_data
  965. # do not check for index error here, it is the calling function's responsibility
  966. do_extract_spline(new_data, new_data.splines[spline_index])
  967. return new_ob
  968. def bind_extracted_spline_to_curve(new_ob, curve):
  969. # Set up a relationship between the new object and the old object
  970. # now, weirdly enough - we can't use parenting very easily because Blender
  971. # defines the parent on a curve relative to the evaluated path animation
  972. # Setting the inverse matrix is too much work. Use Copy Transforms instead.
  973. from ..xForm_nodes import reset_object_data
  974. reset_object_data(new_ob)
  975. c = new_ob.constraints.new("COPY_TRANSFORMS"); c.target=curve
  976. new_ob.parent=curve
  977. return new_ob
  978. def get_extracted_spline_object(proto_curve, spline_index, mContext):
  979. # we're storing it separately like this to ensure all nodes use the same
  980. # object if they extract the same spline for use by Mantis.
  981. # this should be transparent to the user since it is working around a
  982. # a limitation in Blender.
  983. extracted_spline_name = proto_curve.name+extract_spline_suffix(spline_index)
  984. if curve := mContext.b_objects.get(extracted_spline_name):
  985. return curve
  986. else:
  987. curve = extract_spline(proto_curve, spline_index)
  988. if curve.name != proto_curve.name: # if there is only one spline, no
  989. bind_extracted_spline_to_curve(curve, proto_curve)# dupe is created.
  990. mContext.b_objects[extracted_spline_name] = curve
  991. return curve
  992. def nurbs_copy_bez_spline(curve, bez_spline, do_setup=True):
  993. other_spline= curve.data.splines.new('NURBS')
  994. other_spline.use_endpoint_u=True
  995. other_spline.use_bezier_u=True
  996. bez_pts = bez_spline.bezier_points
  997. bez_data=[]
  998. for i, bez_pt in enumerate(bez_pts):
  999. if i > 0:
  1000. bez_data.append(bez_pt.handle_left.copy())
  1001. bez_data.append(bez_pt.co.copy())
  1002. if i != len(bez_pts)-1:
  1003. bez_data.append(bez_pt.handle_right.copy())
  1004. other_spline.points.add(len(bez_data)-1)
  1005. for i, pt in enumerate(bez_data):
  1006. other_spline.points[i].co=(*pt,1.0) # add the W value here
  1007. if do_setup: # do the stuff that makes it behave the same as a bez spline
  1008. other_spline.use_endpoint_u = True; other_spline.use_bezier_u = True
  1009. other_spline.order_u=4 # set to 1 for poly
  1010. return other_spline
  1011. def RibbonMeshEdgeLengths(m, ribbon):
  1012. tE = ribbon[0]; bE = ribbon[1]; c = ribbon[2]
  1013. lengths = []
  1014. for i in range( len( tE ) ): #tE and bE are same length
  1015. if (c == True):
  1016. v1NextInd = tE[old_bad_wrap_that_should_be_refactored((i+1), len(tE) - 1)]
  1017. else:
  1018. v1NextInd = tE[cap((i+1) , len(tE) - 1 )]
  1019. v1 = m.vertices[tE[i]]; v1Next = m.vertices[v1NextInd]
  1020. if (c == True):
  1021. v2NextInd = bE[old_bad_wrap_that_should_be_refactored((i+1), len(bE) - 1)]
  1022. else:
  1023. v2NextInd = bE[cap((i+1) , len(bE) - 1 )]
  1024. v2 = m.vertices[bE[i]]; v2Next = m.vertices[v2NextInd]
  1025. v = v1.co.lerp(v2.co, 0.5); vNext = v1Next.co.lerp(v2Next.co, 0.5)
  1026. # get the center, edges may not be straight so total length
  1027. # of one edge may be more than the ribbon center's length
  1028. lengths.append(( v - vNext ).length)
  1029. return lengths
  1030. def EnsureCurveIsRibbon(crv, defaultRadius = 0.1):
  1031. from ..base_definitions import FLOAT_EPSILON
  1032. crvRadius = 0
  1033. crv.data.offset = 0
  1034. if (crv.data.bevel_depth < FLOAT_EPSILON):
  1035. crvRadius = crv.data.extrude
  1036. else: #Set ribbon from bevel depth
  1037. crvRadius = crv.data.bevel_depth
  1038. crv.data.bevel_depth = 0
  1039. crv.data.extrude = crvRadius
  1040. if (crvRadius < FLOAT_EPSILON):
  1041. crv.data.extrude = defaultRadius
  1042. def SetRibbonData(m, ribbon):
  1043. #maybe this could be incorporated into the DetectWireEdges function?
  1044. #maybe I can check for closed poly curves here? under what other circumstance
  1045. # will I find the ends of the wire have identical coordinates?
  1046. ribbonData = []
  1047. tE = ribbon[0].copy(); bE = ribbon[1].copy()# circle = ribbon[2]
  1048. #
  1049. lengths = RibbonMeshEdgeLengths(m, ribbon)
  1050. lengths.append(0)
  1051. totalLength = sum(lengths)
  1052. # m.calc_normals() #calculate normals
  1053. # it appears this has been removed.
  1054. for i, (t, b) in enumerate(zip(tE, bE)):
  1055. ind = old_bad_wrap_that_should_be_refactored( (i + 1), len(tE) - 1 )
  1056. tNext = tE[ind]; bNext = bE[ind]
  1057. ribbonData.append( ( (t,b), (tNext, bNext), lengths[i] ) )
  1058. #if this is a circle, the last v in vertData has a length, otherwise 0
  1059. return ribbonData, totalLength
  1060. def WireMeshEdgeLengths(m, wire):
  1061. circle = False
  1062. vIndex = wire.copy()
  1063. for e in m.edges:
  1064. if ((e.vertices[0] == vIndex[-1]) and (e.vertices[1] == vIndex[0])):
  1065. #this checks for an edge between the first and last vertex in the wire
  1066. circle = True
  1067. break
  1068. lengths = []
  1069. for i in range(len(vIndex)):
  1070. v = m.vertices[vIndex[i]]
  1071. if (circle == True):
  1072. vNextInd = vIndex[old_bad_wrap_that_should_be_refactored((i+1), len(vIndex) - 1)]
  1073. else:
  1074. vNextInd = vIndex[cap((i+1), len(vIndex) - 1 )]
  1075. vNext = m.vertices[vNextInd]
  1076. lengths.append(( v.co - vNext.co ).length)
  1077. #if this is a circular wire mesh, this should wrap instead of cap
  1078. return lengths
  1079. def GetDataFromWire(m, wire):
  1080. vertData = []
  1081. vIndex = wire.copy()
  1082. lengths = WireMeshEdgeLengths(m, wire)
  1083. lengths.append(0)
  1084. totalLength = sum(lengths)
  1085. for i, vInd in enumerate(vIndex):
  1086. #-1 to avoid IndexError
  1087. vNext = vIndex[ (old_bad_wrap_that_should_be_refactored(i+1, len(vIndex) - 1)) ]
  1088. vertData.append((vInd, vNext, lengths[i]))
  1089. #if this is a circle, the last v in vertData has a length, otherwise 0
  1090. return vertData, totalLength
  1091. def DetectWireEdges(mesh):
  1092. # Returns a list of vertex indices belonging to wire meshes
  1093. # NOTE: this assumes a mesh object with only wire meshes
  1094. ret = []
  1095. import bmesh
  1096. bm = bmesh.new()
  1097. try:
  1098. bm.from_mesh(mesh)
  1099. ends = []
  1100. for v in bm.verts:
  1101. if (len(v.link_edges) == 1):
  1102. ends.append(v.index)
  1103. for e in bm.edges:
  1104. assert (e.is_wire == True),"This function can only run on wire meshes"
  1105. if (e.verts[1].index - e.verts[0].index != 1):
  1106. ends.append(e.verts[1].index)
  1107. ends.append(e.verts[0].index)
  1108. for i in range(len(ends)//2): # // is floor division
  1109. beg = ends[i*2]
  1110. end = ends[(i*2)+1]
  1111. indices = [(j + beg) for j in range ((end - beg) + 1)]
  1112. ret.append(indices)
  1113. finally:
  1114. bm.free()
  1115. return ret
  1116. def FindNearestPointOnWireMesh(m, pointsList):
  1117. from mathutils import Vector
  1118. from mathutils.geometry import intersect_point_line
  1119. from math import sqrt
  1120. wires = DetectWireEdges(m)
  1121. ret = []
  1122. # prevFactor = None
  1123. for wire, points in zip(wires, pointsList):
  1124. vertData, total_length = GetDataFromWire(m, wire)
  1125. factorsOut = []
  1126. for p in points:
  1127. prevDist = float('inf')
  1128. curDist = float('inf')
  1129. v1 = None
  1130. v2 = None
  1131. for i in range(len(vertData) - 1):
  1132. #but it shouldn't check the last one
  1133. if (p == m.vertices[i].co):
  1134. v1 = vertData[i]
  1135. v2 = vertData[i+1]
  1136. offset = 0
  1137. break
  1138. else:
  1139. curDist = ( ((m.vertices[vertData[i][0]].co - p).length) +
  1140. ((m.vertices[vertData[i][1]].co - p).length) )/2
  1141. if (curDist < prevDist):
  1142. v1 = vertData[i]
  1143. v2 = vertData[i+1]
  1144. prevDist = curDist
  1145. offset = intersect_point_line(p, m.vertices[v1[0]].co,
  1146. m.vertices[v2[0]].co)[1]
  1147. if (offset < 0):
  1148. offset = 0
  1149. elif (offset > 1):
  1150. offset = 1
  1151. # Assume the vertices are in order
  1152. v1Length = 0
  1153. v2Length = v2[2]
  1154. for i in range(v1[0]):
  1155. v1Length += vertData[i][2]
  1156. factor = ((offset * (v2Length)) + v1Length )/total_length
  1157. factor = wrap(0, 1, factor) # doesn't hurt to wrap it if it's over 1 or less than 0
  1158. factorsOut.append(factor)
  1159. ret.append( factorsOut )
  1160. return ret
  1161. def mesh_from_curve(crv, context, ribbon=True):
  1162. """Utility function for converting a mesh to a curve
  1163. which will return the correct mesh even with modifiers"""
  1164. import bpy
  1165. m = None
  1166. bevel = crv.data.bevel_depth
  1167. extrude = crv.data.extrude
  1168. offset = crv.data.offset
  1169. try:
  1170. if (len(crv.modifiers) > 0):
  1171. do_unlink = False
  1172. if (not context.scene.collection.all_objects.get(crv.name)):
  1173. context.collection.objects.link(crv) # i guess this forces the dg to update it?
  1174. do_unlink = True
  1175. dg = context.view_layer.depsgraph
  1176. # just gonna modify it for now lol
  1177. if ribbon:
  1178. EnsureCurveIsRibbon(crv)
  1179. else:
  1180. crv.data.bevel_depth=0
  1181. crv.data.extrude=0
  1182. crv.data.offset=0
  1183. # try:
  1184. dg.update()
  1185. mOb = crv.evaluated_get(dg)
  1186. m = bpy.data.meshes.new_from_object(mOb)
  1187. m.name=crv.data.name+'_mesh'
  1188. if (do_unlink):
  1189. context.collection.objects.unlink(crv)
  1190. else: # (ಥ﹏ಥ) why can't I just use this !
  1191. # for now I will just do it like this
  1192. if ribbon:
  1193. EnsureCurveIsRibbon(crv)
  1194. else:
  1195. crv.data.bevel_depth=0
  1196. crv.data.extrude=0
  1197. crv.data.offset=0
  1198. m = bpy.data.meshes.new_from_object(crv)
  1199. finally:
  1200. crv.data.bevel_depth = bevel
  1201. crv.data.extrude = extrude
  1202. crv.data.offset = offset
  1203. return m
  1204. def DetectRibbon(f, bm, skipMe):
  1205. fFirst = f.index
  1206. cont = True
  1207. circle = False
  1208. tEdge, bEdge = [],[]
  1209. while (cont == True):
  1210. skipMe.add(f.index)
  1211. tEdge.append (f.loops[0].vert.index) # top-left
  1212. bEdge.append (f.loops[3].vert.index) # bottom-left
  1213. nEdge = bm.edges.get([f.loops[1].vert, f.loops[2].vert])
  1214. nFaces = nEdge.link_faces
  1215. if (len(nFaces) == 1):
  1216. cont = False
  1217. else:
  1218. for nFace in nFaces:
  1219. if (nFace != f):
  1220. f = nFace
  1221. break
  1222. if (f.index == fFirst):
  1223. cont = False
  1224. circle = True
  1225. if (cont == False): # we've reached the end, get the last two:
  1226. tEdge.append (f.loops[1].vert.index) # top-right
  1227. bEdge.append (f.loops[2].vert.index) # bottom-right
  1228. # this will create a loop for rings --
  1229. # "the first shall be the last and the last shall be first"
  1230. return (tEdge,bEdge,circle)
  1231. def DetectRibbons(m, fReport = None):
  1232. # Returns list of vertex indices belonging to ribbon mesh edges
  1233. # NOTE: this assumes a mesh object with only ribbon meshes
  1234. # ---DO NOT call this script with a mesh that isn't a ribbon!--- #
  1235. import bmesh
  1236. bm = bmesh.new()
  1237. bm.from_mesh(m)
  1238. mIslands, mIsland = [], []
  1239. skipMe = set()
  1240. bm.faces.ensure_lookup_table()
  1241. #first, get a list of mesh islands
  1242. for f in bm.faces:
  1243. if (f.index in skipMe):
  1244. continue #already done here
  1245. checkMe = [f]
  1246. while (len(checkMe) > 0):
  1247. facesFound = 0
  1248. for f in checkMe:
  1249. if (f.index in skipMe):
  1250. continue #already done here
  1251. mIsland.append(f)
  1252. skipMe.add(f.index)
  1253. for e in f.edges:
  1254. checkMe += e.link_faces
  1255. if (facesFound == 0):
  1256. #this is the last iteration
  1257. mIslands.append(mIsland)
  1258. checkMe, mIsland = [], []
  1259. ribbons = []
  1260. skipMe = set() # to store ends already checked
  1261. for mIsl in mIslands:
  1262. ribbon = None
  1263. first = float('inf')
  1264. for f in mIsl:
  1265. if (f.index in skipMe):
  1266. continue #already done here
  1267. if (f.index < first):
  1268. first = f.index
  1269. adjF = 0
  1270. for e in f.edges:
  1271. adjF+= (len(e.link_faces) - 1)
  1272. # every face other than this one is added to the list
  1273. if (adjF == 1):
  1274. ribbon = (DetectRibbon(f, bm, skipMe) )
  1275. break
  1276. if (ribbon == None):
  1277. ribbon = (DetectRibbon(bm.faces[first], bm, skipMe) )
  1278. ribbons.append(ribbon)
  1279. # print (ribbons)
  1280. return ribbons
  1281. def data_from_ribbon_mesh(m, factorsList, mat, ribbons = None, fReport = None):
  1282. #Note, factors list should be equal in length the the number of wires
  1283. #Now working for multiple wires, ugly tho
  1284. if (ribbons == None):
  1285. ribbons = DetectRibbons(m, fReport=fReport)
  1286. if (ribbons is None):
  1287. if (fReport):
  1288. fReport(type = {'ERROR'}, message="No ribbon to get data from.")
  1289. else:
  1290. print ("No ribbon to get data from.")
  1291. return None
  1292. ret = []
  1293. for factors, ribbon in zip(factorsList, ribbons):
  1294. points = []
  1295. widths = []
  1296. normals = []
  1297. ribbonData, totalLength = SetRibbonData(m, ribbon)
  1298. for fac in factors:
  1299. if (fac == 0):
  1300. data = ribbonData[0]
  1301. curFac = 0
  1302. elif (fac == 1):
  1303. data = ribbonData[-1]
  1304. curFac = 0
  1305. else:
  1306. targetLength = totalLength * fac
  1307. data = ribbonData[0]
  1308. curLength = 0
  1309. for ( (t, b), (tNext, bNext), length,) in ribbonData:
  1310. if (curLength >= targetLength):
  1311. break
  1312. curLength += length
  1313. data = ( (t, b), (tNext, bNext), length,)
  1314. targetLengthAtEdge = (curLength - targetLength)
  1315. if (targetLength == 0):
  1316. curFac = 0
  1317. elif (targetLength == totalLength):
  1318. curFac = 1
  1319. else:
  1320. # NOTE: This can be Zero. Find out why!
  1321. if data[2] == 0:
  1322. curFac=0
  1323. else:
  1324. curFac = 1 - (targetLengthAtEdge/ data[2]) #length
  1325. t1 = m.vertices[data[0][0]]; b1 = m.vertices[data[0][1]]
  1326. t2 = m.vertices[data[1][0]]; b2 = m.vertices[data[1][1]]
  1327. #location
  1328. loc1 = (t1.co).lerp(b1.co, 0.5)
  1329. loc2 = (t2.co).lerp(b2.co, 0.5)
  1330. #width
  1331. w1 = (t1.co - b1.co).length/2
  1332. w2 = (t2.co - b2.co).length/2 #radius, not diameter
  1333. #normal
  1334. n1 = (t1.normal).slerp(b1.normal, 0.5)
  1335. n2 = (t1.normal).slerp(b2.normal, 0.5)
  1336. if ((data[0][0] > data[1][0]) and (ribbon[2] == False)):
  1337. curFac = 0
  1338. #don't interpolate if at the end of a ribbon that isn't circular
  1339. if ( 0 < curFac < 1):
  1340. outPoint = loc1.lerp(loc2, curFac)
  1341. outNorm = n1.lerp(n2, curFac)
  1342. outWidth = w1 + ( (w2-w1) * curFac)
  1343. elif (curFac <= 0):
  1344. outPoint = loc1.copy()
  1345. outNorm = n1
  1346. outWidth = w1
  1347. elif (curFac >= 1):
  1348. outPoint = loc2.copy()
  1349. outNorm = n2
  1350. outWidth = w2
  1351. outPoint = mat @ outPoint
  1352. outNorm.normalize()
  1353. points.append ( outPoint.copy() ) #copy because this is an actual vertex location
  1354. widths.append ( outWidth )
  1355. normals.append( outNorm )
  1356. ret.append( (points, widths, normals) )
  1357. return ret # this is a list of tuples containing three lists
  1358. #This bisection search is generic, and it searches based on the
  1359. # magnitude of the error, rather than the sign.
  1360. # If the sign of the error is meaningful, a simpler function
  1361. # can be used.
  1362. def do_bisect_search_by_magnitude(
  1363. owner,
  1364. attribute,
  1365. index = None,
  1366. test_function = None,
  1367. modify = None,
  1368. max_iterations = 10000,
  1369. threshold = 0.0001,
  1370. thresh2 = 0.0005,
  1371. context = None,
  1372. update_dg = None,
  1373. ):
  1374. from math import floor
  1375. i = 0; best_so_far = 0; best = float('inf')
  1376. min = 0; center = max_iterations//2; max = max_iterations
  1377. # enforce getting the absolute value, in case the function has sign information
  1378. # The sign may be useful in a sign-aware bisect search, but this one is more robust!
  1379. test = lambda : abs(test_function(owner, attribute, index, context = context,))
  1380. while (i <= max_iterations):
  1381. upper = (max - ((max-center))//2)
  1382. modify(owner, attribute, index, upper, context = context); error1 = test()
  1383. lower = (center - ((center-min))//2)
  1384. modify(owner, attribute, index, lower, context = context); error2 = test()
  1385. if (error1 < error2):
  1386. min = center
  1387. center, check = upper, upper
  1388. error = error1
  1389. else:
  1390. max = center
  1391. center, check = lower, lower
  1392. error = error2
  1393. if (error <= threshold) or (min == max-1):
  1394. break
  1395. if (error < thresh2):
  1396. j = min
  1397. while (j < max):
  1398. modify(owner, attribute, index, j * 1/max_iterations, context = context)
  1399. error = test()
  1400. if (error < best):
  1401. best_so_far = j; best = error
  1402. if (error <= threshold):
  1403. break
  1404. j+=1
  1405. else: # loop has completed without finding a solution
  1406. i = best_so_far; error = test()
  1407. modify(owner, attribute, index, best_so_far, context = context)
  1408. break
  1409. if (error < best):
  1410. best_so_far = check; best = error
  1411. i+=1
  1412. if update_dg:
  1413. update_dg.update()
  1414. else: # Loop has completed without finding a solution
  1415. i = best_so_far
  1416. modify(owner, attribute, best_so_far, context = context); i+=1