utilities.py 58 KB

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