utilities.py 59 KB

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