utilities.py 55 KB

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