utilities.py 51 KB

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