utilities.py 65 KB

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