utilities.py 50 KB

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