utilities.py 49 KB

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