utilities.py 53 KB

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