utilities.py 51 KB

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