utilities.py 40 KB

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