utilities.py 52 KB

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