utilities.py 39 KB

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