utilities.py 50 KB

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