utilities.py 52 KB

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