utilities.py 40 KB

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