utilities.py 68 KB

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