misc_nodes.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  1. from .node_container_common import *
  2. from .base_definitions import MantisNode, NodeSocket, FLOAT_EPSILON
  3. from .xForm_containers import xFormArmature, xFormBone
  4. from .misc_nodes_socket_templates import *
  5. from math import pi, tau
  6. def TellClasses():
  7. return [
  8. # utility
  9. InputFloat,
  10. InputIntNode,
  11. InputVector,
  12. InputBoolean,
  13. InputBooleanThreeTuple,
  14. InputRotationOrder,
  15. InputTransformSpace,
  16. InputString,
  17. InputMatrix,
  18. InputExistingGeometryObject,
  19. InputExistingGeometryData,
  20. UtilityGeometryOfXForm,
  21. UtilityNameOfXForm,
  22. UtilityPointFromCurve,
  23. UtilityMatrixFromCurve,
  24. UtilityMatricesFromCurve,
  25. UtilityNumberOfCurveSegments,
  26. UtilityMatrixFromCurveSegment,
  27. UtilityGetCurvePoint,
  28. UtilityGetNearestFactorOnCurve,
  29. UtilityKDChoosePoint,
  30. UtilityKDChooseXForm,
  31. UtilityMetaRig,
  32. UtilityBoneProperties,
  33. UtilityDriverVariable,
  34. UtilityDriver,
  35. UtilityFCurve,
  36. UtilityKeyframe,
  37. UtilitySwitch,
  38. UtilityCombineThreeBool,
  39. UtilityCombineVector,
  40. UtilitySeparateVector,
  41. UtilityCatStrings,
  42. UtilityGetBoneLength,
  43. UtilityPointFromBoneMatrix,
  44. UtilitySetBoneLength,
  45. UtilityMatrixSetLocation,
  46. UtilityMatrixGetLocation,
  47. UtilityMatrixFromXForm,
  48. UtilityAxesFromMatrix,
  49. UtilityBoneMatrixHeadTailFlip,
  50. UtilityMatrixTransform,
  51. UtilityMatrixInvert,
  52. UtilityMatrixCompose,
  53. UtilityMatrixAlignRoll,
  54. UtilityTransformationMatrix,
  55. UtilityIntToString,
  56. UtilityArrayGet,
  57. UtilityArrayLength,
  58. UtilitySetBoneMatrixTail,
  59. # Control flow switches
  60. UtilityCompare,
  61. UtilityChoose,
  62. # useful NoOp:
  63. UtilityPrint,
  64. ]
  65. def matrix_from_head_tail(head, tail, normal=None):
  66. from mathutils import Vector, Matrix
  67. if normal is None:
  68. rotation = Vector((0,1,0)).rotation_difference((tail-head).normalized()).to_matrix()
  69. m= Matrix.LocRotScale(head, rotation, None)
  70. else: # construct a basis matrix
  71. m = Matrix.Identity(3)
  72. axis = (tail-head).normalized()
  73. conormal = axis.cross(normal)
  74. m[0]=conormal
  75. m[1]=axis
  76. m[2]=normal
  77. m = m.transposed().to_4x4()
  78. m.translation=head.copy()
  79. m[3][3]=(tail-head).length
  80. return m
  81. def get_mesh_from_curve(curve_name : str, execution_id : str, bContext, ribbon=True):
  82. from bpy import data
  83. curve = data.objects.get(curve_name)
  84. assert curve.type == 'CURVE', f"ERROR: object is not a curve: {curve_name}"
  85. from .utilities import mesh_from_curve
  86. curve_type='ribbon' if ribbon else 'wire'
  87. m_name = curve_name+'.'+str(hash(curve_name+'.'+curve_type+'.'+execution_id))
  88. if not (m := data.meshes.get(m_name)):
  89. m = mesh_from_curve(curve, bContext, ribbon)
  90. m.name = m_name
  91. return m
  92. def cleanup_curve(curve_name : str, execution_id : str) -> None:
  93. import bpy
  94. curve = bpy.data.objects.get(curve_name)
  95. m_name = curve_name+'.'+str(hash(curve.name+'.'+ execution_id))
  96. if (mesh := bpy.data.meshes.get(m_name)):
  97. bpy.data.meshes.remove(mesh)
  98. def kd_find(node, points, ref_pt, num_points):
  99. if num_points == 0:
  100. raise RuntimeError(f"Cannot find 0 points for {node}")
  101. from mathutils import kdtree
  102. kd = kdtree.KDTree(len(points))
  103. for i, pt in enumerate(points):
  104. try:
  105. kd.insert(pt, i)
  106. except (TypeError, ValueError) as e:
  107. prRed(f"Cannot get point from for {node}")
  108. raise e
  109. kd.balance()
  110. try:
  111. if num_points == 1: # make it a list to keep it consistent with
  112. result = [kd.find(ref_pt)] # find_n which returns a list
  113. else:
  114. result = kd.find_n(ref_pt, num_points)
  115. # the result of kd.find has some other stuff we don't care about
  116. except (TypeError, ValueError) as e:
  117. prRed(f"Reference Point {ref_pt} invalid for {node}")
  118. raise e
  119. return result
  120. def array_link_init_hierarchy(new_link):
  121. " Sets up hierarchy connection/dependencies for links created by Arrays."
  122. if new_link.is_hierarchy:
  123. connections = new_link.from_node.hierarchy_connections
  124. dependencies = new_link.to_node.hierarchy_dependencies
  125. else:
  126. connections = new_link.from_node.connections
  127. dependencies = new_link.to_node.dependencies
  128. connections.append(new_link.to_node)
  129. dependencies.append(new_link.from_node)
  130. def array_choose_relink(node, indices, array_input, output, ):
  131. """
  132. Used to choose the correct link to send out of an array-choose node.
  133. """
  134. keep_links = []
  135. for index in indices:
  136. l = node.inputs[array_input].links[index]
  137. keep_links.append(l)
  138. for link in node.outputs[output].links:
  139. to_node = link.to_node
  140. for l in keep_links:
  141. new_link = l.from_node.outputs[l.from_socket].connect(to_node, link.to_socket)
  142. array_link_init_hierarchy(new_link)
  143. link.die()
  144. def array_choose_data(node, data, output):
  145. """
  146. Used to choose the correct data to send out of an array-choose node.
  147. """
  148. # We need to make new outputs and link from each one based on the data in the array...
  149. node.outputs.init_sockets([output+"."+str(i).zfill(4) for i in range(len(data)) ])
  150. for i, data_item in enumerate(data):
  151. node.parameters[output+"."+str(i).zfill(4)] = data_item
  152. for link in node.outputs[output].links:
  153. to_node = link.to_node
  154. for i in range(len(data)):
  155. # Make a link from the new output.
  156. new_link = node.outputs[output+"."+str(i).zfill(4)].connect(to_node, link.to_socket)
  157. array_link_init_hierarchy(new_link)
  158. link.die()
  159. def zero_radius_error_message(node, curve):
  160. return f"ERROR: cannot get matrix from zero-radius curve point "\
  161. "in curve object: {curve.name} for node: {node}. "\
  162. "This is a limitation of Mantis (For now). Please inspect the curve and ensure "\
  163. "that each curve point has a radius greater than 0. Sometimes, this error is " \
  164. "caused by drivers. "
  165. #*#-------------------------------#++#-------------------------------#*#
  166. # B A S E C L A S S E S
  167. #*#-------------------------------#++#-------------------------------#*#
  168. class SimpleInputNode(MantisNode):
  169. def __init__(self, signature, base_tree, socket_templates=[]):
  170. super().__init__(signature, base_tree, socket_templates)
  171. self.node_type = 'UTILITY'
  172. self.prepared, self.executed = True, True
  173. #*#-------------------------------#++#-------------------------------#*#
  174. # U T I L I T Y N O D E S
  175. #*#-------------------------------#++#-------------------------------#*#
  176. class InputFloat(SimpleInputNode):
  177. '''A node representing float input'''
  178. def __init__(self, signature, base_tree):
  179. super().__init__(signature, base_tree)
  180. outputs = ["Float Input"]
  181. self.outputs.init_sockets(outputs)
  182. self.init_parameters()
  183. class InputIntNode(SimpleInputNode):
  184. '''A node representing integer input'''
  185. def __init__(self, signature, base_tree):
  186. super().__init__(signature, base_tree)
  187. outputs = ["Integer"]
  188. self.outputs.init_sockets(outputs)
  189. self.init_parameters()
  190. class InputVector(SimpleInputNode):
  191. '''A node representing vector input'''
  192. def __init__(self, signature, base_tree):
  193. super().__init__(signature, base_tree)
  194. outputs = [""]
  195. self.outputs.init_sockets(outputs)
  196. self.init_parameters()
  197. class InputBoolean(SimpleInputNode):
  198. '''A node representing boolean input'''
  199. def __init__(self, signature, base_tree):
  200. super().__init__(signature, base_tree)
  201. outputs = [""]
  202. self.outputs.init_sockets(outputs)
  203. self.init_parameters()
  204. class InputBooleanThreeTuple(SimpleInputNode):
  205. '''A node representing a tuple of three booleans'''
  206. def __init__(self, signature, base_tree):
  207. super().__init__(signature, base_tree)
  208. outputs = [""]
  209. self.outputs.init_sockets(outputs)
  210. self.init_parameters()
  211. class InputRotationOrder(SimpleInputNode):
  212. '''A node representing string input for rotation order'''
  213. def __init__(self, signature, base_tree):
  214. super().__init__(signature, base_tree)
  215. outputs = [""]
  216. self.outputs.init_sockets(outputs)
  217. self.init_parameters()
  218. class InputTransformSpace(SimpleInputNode):
  219. '''A node representing string input for transform space'''
  220. def __init__(self, signature, base_tree):
  221. super().__init__(signature, base_tree)
  222. outputs = [""]
  223. self.outputs.init_sockets(outputs)
  224. self.init_parameters()
  225. def evaluate_input(self, input_name):
  226. return self.parameters[""]
  227. class InputString(SimpleInputNode):
  228. '''A node representing string input'''
  229. def __init__(self, signature, base_tree):
  230. super().__init__(signature, base_tree)
  231. outputs = [""]
  232. self.outputs.init_sockets(outputs)
  233. self.init_parameters()
  234. class InputMatrix(SimpleInputNode):
  235. '''A node representing axis-angle quaternion input'''
  236. def __init__(self, signature, base_tree):
  237. super().__init__(signature, base_tree)
  238. outputs = ["Matrix",]
  239. self.outputs.init_sockets(outputs)
  240. self.init_parameters()
  241. class UtilityMatrixFromCurve(MantisNode):
  242. '''Get a matrix from a curve'''
  243. def __init__(self, signature, base_tree):
  244. super().__init__(signature, base_tree, MatrixFromCurveSockets)
  245. self.init_parameters()
  246. self.node_type = "UTILITY"
  247. def bPrepare(self, bContext = None,):
  248. from mathutils import Matrix
  249. import bpy
  250. mat = Matrix.Identity(4)
  251. curve_name = self.evaluate_input("Curve")
  252. curve = bpy.data.objects.get(curve_name)
  253. if not curve:
  254. prRed(f"WARN: No curve found for {self}. Using an identity matrix instead.")
  255. mat[3][3] = 1.0
  256. elif curve.type != "CURVE":
  257. prRed(f"WARN: Object {curve.name} is not a curve. Using an identity matrix instead.")
  258. mat[3][3] = 1.0
  259. else:
  260. if bContext is None: bContext = bpy.context # is this wise?
  261. m = get_mesh_from_curve(curve.name, self.base_tree.execution_id, bContext)
  262. from .utilities import data_from_ribbon_mesh
  263. #
  264. num_divisions = self.evaluate_input("Total Divisions")
  265. if num_divisions <= 0:
  266. raise GraphError("The number of divisions in the curve must be 1 or greater.")
  267. m_index = self.evaluate_input("Matrix Index")
  268. if m_index >= num_divisions:
  269. prRed(m_index, num_divisions)
  270. raise GraphError(f"{self} tried to get a matrix-index greater the total number of divisions."
  271. "The matrix index starts at 0. You're probably off by +1.")
  272. spline_index = self.evaluate_input("Spline Index")
  273. if spline_index > len(curve.data.splines)-1:
  274. raise GraphError(f"{self} is attempting to read from a spline in {curve.name} that does not exist."
  275. " Try and reduce the value of Spline Index.")
  276. splines_factors = [ [] for i in range (spline_index)]
  277. factors = [1/num_divisions*m_index, 1/num_divisions*(m_index+1)]
  278. splines_factors.append(factors)
  279. data = data_from_ribbon_mesh(m, splines_factors, curve.matrix_world)
  280. if data[spline_index][1][0] < FLOAT_EPSILON: # radius is None:
  281. raise RuntimeError(zero_radius_error_message(self, curve))
  282. head=data[spline_index][0][0]
  283. tail= data[spline_index][0][1]
  284. axis = (tail-head).normalized()
  285. if axis.length_squared < FLOAT_EPSILON:
  286. raise RuntimeError(f"Failed to read the curve {curve.name}.")
  287. normal=data[spline_index][2][0]
  288. # make sure the normal is perpendicular to the tail
  289. from .utilities import make_perpendicular
  290. normal = make_perpendicular(axis, normal)
  291. mat = matrix_from_head_tail(head, tail, normal)
  292. # this is in world space... let's just convert it back
  293. mat.translation = head - curve.location
  294. # TODO HACK TODO
  295. # all the nodes should work in world-space, and it should be the responsibility
  296. # of the xForm node to convert!
  297. self.parameters["Matrix"] = mat
  298. self.prepared = True
  299. self.executed = True
  300. def bFinalize(self, bContext=None):
  301. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  302. class UtilityPointFromCurve(MantisNode):
  303. '''Get a point from a curve'''
  304. def __init__(self, signature, base_tree):
  305. super().__init__(signature, base_tree, PointFromCurveSockets)
  306. self.init_parameters()
  307. self.node_type = "UTILITY"
  308. def bPrepare(self, bContext = None,):
  309. import bpy
  310. curve = bpy.data.objects.get(self.evaluate_input("Curve"))
  311. if not curve:
  312. raise RuntimeError(f"No curve found for {self}.")
  313. elif curve.type != "CURVE":
  314. raise GraphError(f"ERROR: Object {curve.name} is not a curve.")
  315. else:
  316. if bContext is None: bContext = bpy.context # is this wise?
  317. m = get_mesh_from_curve(curve.name, self.base_tree.execution_id, bContext)
  318. from .utilities import data_from_ribbon_mesh
  319. #
  320. num_divisions = 1
  321. spline_index = self.evaluate_input("Spline Index")
  322. splines_factors = [ [] for i in range (spline_index)]
  323. factors = [self.evaluate_input("Factor")]
  324. splines_factors.append(factors)
  325. data = data_from_ribbon_mesh(m, splines_factors, curve.matrix_world)
  326. p = data[spline_index][0][0] - curve.location
  327. self.parameters["Point"] = p
  328. self.prepared, self.executed = True, True
  329. def bFinalize(self, bContext=None):
  330. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  331. class UtilityMatricesFromCurve(MantisNode):
  332. '''Get matrices from a curve'''
  333. def __init__(self, signature, base_tree):
  334. super().__init__(signature, base_tree, MatricesFromCurveSockets)
  335. self.init_parameters()
  336. self.node_type = "UTILITY"
  337. def bPrepare(self, bContext = None,):
  338. import time
  339. # start_time = time.time()
  340. #
  341. from mathutils import Matrix
  342. import bpy
  343. m = Matrix.Identity(4)
  344. curve_name = self.evaluate_input("Curve")
  345. curve = bpy.data.objects.get(curve_name)
  346. if not curve:
  347. prRed(f"WARN: No curve found for {self}. Using an identity matrix instead.")
  348. m[3][3] = 1.0
  349. elif curve.type != "CURVE":
  350. prRed(f"WARN: Object {curve.name} is not a curve. Using an identity matrix instead.")
  351. m[3][3] = 1.0
  352. else:
  353. if bContext is None: bContext = bpy.context # is this wise?
  354. mesh = get_mesh_from_curve(curve.name, self.base_tree.execution_id, bContext)
  355. from .utilities import data_from_ribbon_mesh
  356. num_divisions = self.evaluate_input("Total Divisions")
  357. spline_index = self.evaluate_input("Spline Index")
  358. splines_factors = [ [] for i in range (spline_index)]
  359. factors = [0.0] + [(1/num_divisions*(i+1)) for i in range(num_divisions)]
  360. splines_factors.append(factors)
  361. data = data_from_ribbon_mesh(mesh, splines_factors, curve.matrix_world)
  362. # [spline_index][points,tangents,normals][datapoint_index]
  363. from .utilities import make_perpendicular
  364. matrices=[]
  365. for i in range(num_divisions):
  366. if data[spline_index][1][i] < FLOAT_EPSILON: # radius is None:
  367. raise RuntimeError(zero_radius_error_message(self, curve))
  368. m = matrix_from_head_tail (
  369. data[spline_index][0][i], data[spline_index][0][i+1],
  370. make_perpendicular((data[spline_index][0][i+1]-data[spline_index][0][i]).normalized(), data[spline_index][2][i]),)
  371. m.translation = data[spline_index][0][i] - curve.location
  372. matrices.append(m)
  373. for link in self.outputs["Matrices"].links:
  374. for i, m in enumerate(matrices):
  375. name = "Matrix"+str(i).zfill(4)
  376. if not (out := self.outputs.get(name)): # reuse them if there are multiple links.
  377. out = self.outputs[name] = NodeSocket(name = name, node=self)
  378. c = out.connect(link.to_node, link.to_socket)
  379. # prOrange(c)
  380. self.parameters[name] = m
  381. # print (mesh)
  382. link.die()
  383. self.prepared = True
  384. self.executed = True
  385. # prGreen(f"Matrices from curves took {time.time() - start_time} seconds.")
  386. def bFinalize(self, bContext=None):
  387. import bpy
  388. curve_name = self.evaluate_input("Curve")
  389. curve = bpy.data.objects.get(curve_name)
  390. m_name = curve.name+'.'+self.base_tree.execution_id
  391. if (mesh := bpy.data.meshes.get(m_name)):
  392. prGreen(f"Freeing mesh data {m_name}...")
  393. bpy.data.meshes.remove(mesh)
  394. class UtilityNumberOfCurveSegments(MantisNode):
  395. def __init__(self, signature, base_tree):
  396. super().__init__(signature, base_tree)
  397. inputs = [
  398. "Curve" ,
  399. "Spline Index" ,
  400. ]
  401. outputs = [
  402. "Number of Segments" ,
  403. ]
  404. self.inputs.init_sockets(inputs)
  405. self.outputs.init_sockets(outputs)
  406. self.init_parameters()
  407. self.node_type = "UTILITY"
  408. def bPrepare(self, bContext = None,):
  409. import bpy
  410. curve_name = self.evaluate_input("Curve")
  411. curve = bpy.data.objects.get(curve_name)
  412. spline = curve.data.splines[self.evaluate_input("Spline Index")]
  413. if spline.type == "BEZIER":
  414. self.parameters["Number of Segments"] = len(spline.bezier_points)-1
  415. else:
  416. self.parameters["Number of Segments"] = len(spline.points)-1
  417. self.prepared = True
  418. self.executed = True
  419. class UtilityMatrixFromCurveSegment(MantisNode):
  420. def __init__(self, signature, base_tree):
  421. super().__init__(signature, base_tree, MatrixFromCurveSegmentSockets)
  422. self.init_parameters()
  423. self.node_type = "UTILITY"
  424. def bPrepare(self, bContext = None,):
  425. import bpy
  426. curve = bpy.data.objects.get(self.evaluate_input("Curve"))
  427. if not curve:
  428. raise RuntimeError(f"No curve found for {self}.")
  429. elif curve.type != "CURVE":
  430. raise GraphError(f"ERROR: Object {curve.name} is not a curve.")
  431. else:
  432. if bContext is None: bContext = bpy.context # is this wise?
  433. m = get_mesh_from_curve(curve.name, self.base_tree.execution_id, bContext)
  434. from .utilities import data_from_ribbon_mesh
  435. # this section is dumb, but it is because the data_from_ribbon_mesh
  436. # function is designed to pull data from many splines at once (for optimization)
  437. # so we have to give it empty splines for each one we skip.
  438. # TODO: Refactor this to make it so I can select spline index
  439. spline_index = self.evaluate_input("Spline Index")
  440. spline = curve.data.splines[spline_index]
  441. splines_factors = [ [] for i in range (spline_index)]
  442. factors = [0.0]
  443. points = spline.bezier_points if spline.type == 'BEZIER' else spline.points
  444. total_length=0.0
  445. for i in range(len(points)-1):
  446. total_length+= (seg_length := (points[i+1].co - points[i].co).length)
  447. factors.append(seg_length)
  448. prev_length = 0.0
  449. for i in range(len(factors)):
  450. factors[i] = prev_length+factors[i]/total_length
  451. prev_length=factors[i]
  452. # Why does this happen? Floating point error?
  453. if factors[i]>1.0: factors[i] = 1.0
  454. splines_factors.append(factors)
  455. #
  456. data = data_from_ribbon_mesh(m, splines_factors, curve.matrix_world)
  457. segment_index = self.evaluate_input("Segment Index")
  458. if data[spline_index][1][segment_index] < FLOAT_EPSILON: # radius is None:
  459. raise RuntimeError(zero_radius_error_message(self, curve))
  460. head=data[spline_index][0][segment_index]
  461. tail= data[spline_index][0][segment_index+1]
  462. axis = (tail-head).normalized()
  463. normal=data[spline_index][2][segment_index]
  464. # make sure the normal is perpendicular to the tail
  465. from .utilities import make_perpendicular
  466. normal = make_perpendicular(axis, normal)
  467. m = matrix_from_head_tail(head, tail, normal)
  468. m.translation = head - curve.location
  469. self.parameters["Matrix"] = m
  470. self.prepared, self.executed = True, True
  471. def bFinalize(self, bContext=None):
  472. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  473. class UtilityGetCurvePoint(MantisNode):
  474. def __init__(self, signature, base_tree):
  475. super().__init__(signature, base_tree, GetCurvePointSockets)
  476. self.init_parameters()
  477. self.node_type = "UTILITY"
  478. def bPrepare(self, bContext=None):
  479. import bpy
  480. my_curve=self.evaluate_input("Curve")
  481. if my_curve is None:
  482. raise RuntimeError(f"Error with curve name for {self}, {my_curve}")
  483. curve = bpy.data.objects.get(my_curve)
  484. if not curve:
  485. raise RuntimeError(f"No curve found for {self}.")
  486. elif curve.type != "CURVE":
  487. raise GraphError(f"ERROR: Object {curve.name} is not a curve.")
  488. spline = curve.data.splines[self.evaluate_input("Spline Index")]
  489. if spline.type == 'BEZIER':
  490. bez_pt = spline.bezier_points[self.evaluate_input("Index")]
  491. self.parameters["Point"]=bez_pt.co
  492. self.parameters["Left Handle"]=bez_pt.handle_left
  493. self.parameters["Right Handle"]=bez_pt.handle_right
  494. else:
  495. pt = spline.points[self.evaluate_input("Index")]
  496. self.parameters["Point"]=(pt.co[0], pt.co[1], pt.co[2])
  497. self.prepared, self.executed = True, True
  498. class UtilityGetNearestFactorOnCurve(MantisNode):
  499. def __init__(self, signature, base_tree):
  500. super().__init__(signature, base_tree, GetNearestFactorOnCurveSockets)
  501. self.init_parameters()
  502. self.node_type = "UTILITY"
  503. def bPrepare(self, bContext = None,):
  504. import bpy
  505. curve = bpy.data.objects.get(self.evaluate_input("Curve"))
  506. if not curve:
  507. raise RuntimeError(f"No curve found for {self}.")
  508. elif curve.type != "CURVE":
  509. raise GraphError(f"ERROR: Object {curve.name} is not a curve.")
  510. else:
  511. if bContext is None: bContext = bpy.context # is this wise?
  512. m = get_mesh_from_curve(curve.name,
  513. self.base_tree.execution_id,
  514. bContext, ribbon=False)
  515. # this is confusing but I am not re-writing these old functions
  516. from .utilities import FindNearestPointOnWireMesh as nearest_point
  517. spline_index = self.evaluate_input("Spline Index")
  518. ref_pt = self.evaluate_input("Reference Point")
  519. splines_points = [ [] for i in range (spline_index)]
  520. splines_points.append([ref_pt])
  521. pt = nearest_point(m, splines_points)[spline_index][0]
  522. self.parameters["Factor"] = pt
  523. self.prepared, self.executed = True, True
  524. class UtilityKDChoosePoint(MantisNode):
  525. def __init__(self, signature, base_tree):
  526. super().__init__(signature, base_tree)
  527. inputs = [
  528. "Reference Point" ,
  529. "Points" ,
  530. "Number to Find" ,
  531. ]
  532. outputs = [
  533. "Result Point" ,
  534. "Result Index" ,
  535. "Result Distance" ,
  536. ]
  537. self.inputs.init_sockets(inputs)
  538. self.outputs.init_sockets(outputs)
  539. self.init_parameters()
  540. self.node_type = "UTILITY"
  541. def bPrepare(self, bContext = None,):
  542. from mathutils import Vector
  543. points= []
  544. ref_point = self.evaluate_input('Reference Point')
  545. num_points = self.evaluate_input('Number to Find')
  546. for i, l in enumerate(self.inputs['Points'].links):
  547. pt = self.evaluate_input('Points', i)
  548. points.append(pt)
  549. if not isinstance(pt, Vector):
  550. prRed(f"Cannot get point from {l.from_node} for {self}")
  551. assert ref_point is not None, wrapRed(f"Reference Point {ref_point} is invalid in node {self}")
  552. result = kd_find(self, points, ref_point, num_points)
  553. indices = [ found_point[1] for found_point in result ]
  554. distances = [ found_point[2] for found_point in result ]
  555. array_choose_relink(self, indices, "Points", "Result Point")
  556. array_choose_data(self, indices, "Result Index")
  557. array_choose_data(self, distances, "Result Distance")
  558. self.prepared, self.executed = True, True
  559. class UtilityKDChooseXForm(MantisNode):
  560. def __init__(self, signature, base_tree):
  561. super().__init__(signature, base_tree)
  562. inputs = [
  563. "Reference Point" ,
  564. "xForm Nodes" ,
  565. "Get Point Head/Tail" ,
  566. "Number to Find" ,
  567. ]
  568. outputs = [
  569. "Result xForm" ,
  570. "Result Index" ,
  571. "Result Distance" ,
  572. ]
  573. self.inputs.init_sockets(inputs)
  574. self.outputs.init_sockets(outputs)
  575. self.init_parameters()
  576. self.node_type = "UTILITY"
  577. def bPrepare(self, bContext = None,):
  578. if len(self.hierarchy_dependencies)==0 and len(self.hierarchy_connections)==0 and \
  579. len(self.connections)==0 and len(self.dependencies)==0:
  580. self.prepared, self.executed = True, True
  581. return #Either it is already done or it doesn't matter.
  582. from mathutils import Vector
  583. points= []
  584. ref_point = self.evaluate_input('Reference Point')
  585. num_points = self.evaluate_input('Number to Find')
  586. for i, l in enumerate(self.inputs['xForm Nodes'].links):
  587. matrix = l.from_node.evaluate_input('Matrix')
  588. if matrix is None:
  589. raise GraphError(f"Cannot get point from {l.from_node} for {self}. Does it have a matrix?")
  590. pt = matrix.translation
  591. if head_tail := self.evaluate_input("Get Point Head/Tail"):
  592. # get the Y-axis of the basis, assume it is normalized
  593. y_axis = Vector((matrix[0][1],matrix[1][1], matrix[2][1]))
  594. pt = pt.lerp(pt+y_axis*matrix[3][3], head_tail)
  595. points.append(pt)
  596. if not isinstance(pt, Vector):
  597. prRed(f"Cannot get point from {l.from_node} for {self}")
  598. assert ref_point is not None, wrapRed(f"Reference Point {ref_point} is invalid in node {self}")
  599. result = kd_find(self, points, ref_point, num_points)
  600. indices = [ found_point[1] for found_point in result ]
  601. distances = [ found_point[2] for found_point in result ]
  602. array_choose_relink(self, indices, "xForm Nodes", "Result xForm")
  603. array_choose_data(self, indices, "Result Index")
  604. array_choose_data(self, distances, "Result Distance")
  605. self.prepared, self.executed = True, True
  606. class UtilityMetaRig(MantisNode):
  607. '''A node representing an armature object'''
  608. def __init__(self, signature, base_tree):
  609. super().__init__(signature, base_tree)
  610. inputs = [
  611. "Meta-Armature" ,
  612. "Meta-Bone" ,
  613. ]
  614. outputs = [
  615. "Matrix" ,
  616. ]
  617. self.inputs.init_sockets(inputs)
  618. self.outputs.init_sockets(outputs)
  619. self.init_parameters()
  620. self.node_type = "UTILITY"
  621. def bPrepare(self, bContext = None,):
  622. #kinda clumsy, whatever
  623. import bpy
  624. from mathutils import Matrix
  625. m = Matrix.Identity(4)
  626. meta_rig = self.evaluate_input("Meta-Armature")
  627. meta_bone = self.evaluate_input("Meta-Bone")
  628. if meta_rig:
  629. if ( armOb := bpy.data.objects.get(meta_rig) ):
  630. m = armOb.matrix_world
  631. if ( b := armOb.data.bones.get(meta_bone)):
  632. # calculate the correct object-space matrix
  633. m = Matrix.Identity(3)
  634. bones = [] # from the last ancestor, mult the matrices until we get to b
  635. while (b): bones.append(b); b = b.parent
  636. while (bones): b = bones.pop(); m = m @ b.matrix
  637. m = Matrix.Translation(b.head_local) @ m.to_4x4()
  638. #
  639. m[3][3] = b.length # this is where I arbitrarily decided to store length
  640. # else:
  641. # prRed("no bone for MetaRig node ", self)
  642. else:
  643. raise RuntimeError(wrapRed(f"No meta-rig input for MetaRig node {self}"))
  644. self.parameters["Matrix"] = m
  645. self.prepared = True
  646. self.executed = True
  647. class UtilityBoneProperties(SimpleInputNode):
  648. '''A node representing a bone's gettable properties'''
  649. def __init__(self, signature, base_tree):
  650. super().__init__(signature, base_tree)
  651. outputs = [
  652. "matrix" ,
  653. "matrix_local" ,
  654. "matrix_basis" ,
  655. "head" ,
  656. "tail" ,
  657. "length" ,
  658. "rotation" ,
  659. "location" ,
  660. "scale" ,
  661. ]
  662. self.outputs.init_sockets(outputs)
  663. self.init_parameters()
  664. def fill_parameters(self, prototype=None):
  665. return
  666. # TODO this should probably be moved to Links
  667. class UtilityDriverVariable(MantisNode):
  668. '''A node representing an armature object'''
  669. def __init__(self, signature, base_tree):
  670. super().__init__(signature, base_tree)
  671. inputs = [
  672. "Variable Type" ,
  673. "Property" ,
  674. "Property Index" ,
  675. "Evaluation Space",
  676. "Rotation Mode" ,
  677. "xForm 1" ,
  678. "xForm 2" ,
  679. ]
  680. outputs = [
  681. "Driver Variable",
  682. ]
  683. self.inputs.init_sockets(inputs)
  684. self.outputs.init_sockets(outputs)
  685. self.init_parameters()
  686. self.node_type = "DRIVER" # MUST be run in Pose mode
  687. self.prepared = True
  688. def reset_execution(self):
  689. super().reset_execution()
  690. # clear this to ensure there are no stale reference pointers
  691. self.parameters["Driver Variable"] = None
  692. self.prepared=True
  693. def evaluate_input(self, input_name):
  694. if input_name == 'Property':
  695. if self.inputs.get('Property'):
  696. if self.inputs['Property'].is_linked:
  697. # get the name instead...
  698. trace = trace_single_line(self, input_name)
  699. return trace[1].name # the name of the socket
  700. return self.parameters["Property"]
  701. return super().evaluate_input(input_name)
  702. def GetxForm(self, index=1):
  703. trace = trace_single_line(self, "xForm 1" if index == 1 else "xForm 2")
  704. for node in trace[0]:
  705. if (node.__class__ in [xFormArmature, xFormBone]):
  706. return node #this will fetch the first one, that's good!
  707. return None
  708. def bExecute(self, bContext = None,):
  709. prepare_parameters(self)
  710. #prPurple ("Executing Driver Variable Node")
  711. xF1 = self.GetxForm()
  712. xF2 = self.GetxForm(index=2)
  713. # kinda clumsy
  714. xForm1, xForm2 = None, None
  715. if xF1 : xForm1 = xF1.bGetObject()
  716. if xF2 : xForm2 = xF2.bGetObject()
  717. v_type = self.evaluate_input("Variable Type")
  718. i = self.evaluate_input("Property Index"); dVarChannel = ""
  719. if (i >= 0): #negative values will use the vector property.
  720. if self.evaluate_input("Property") == 'location':
  721. if i == 0: dVarChannel = "LOC_X"
  722. elif i == 1: dVarChannel = "LOC_Y"
  723. elif i == 2: dVarChannel = "LOC_Z"
  724. else: raise RuntimeError("Invalid property index for %s" % self)
  725. if self.evaluate_input("Property") == 'rotation':
  726. if i == 0: dVarChannel = "ROT_X"
  727. elif i == 1: dVarChannel = "ROT_Y"
  728. elif i == 2: dVarChannel = "ROT_Z"
  729. elif i == 3: dVarChannel = "ROT_W"
  730. else: raise RuntimeError("Invalid property index for %s" % self)
  731. if self.evaluate_input("Property") == 'scale':
  732. if i == 0: dVarChannel = "SCALE_X"
  733. elif i == 1: dVarChannel = "SCALE_Y"
  734. elif i == 2: dVarChannel = "SCALE_Z"
  735. elif i == 3: dVarChannel = "SCALE_AVG"
  736. else: raise RuntimeError("Invalid property index for %s" % self)
  737. if self.evaluate_input("Property") == 'scale_average':
  738. dVarChannel = "SCALE_AVG"
  739. if dVarChannel: v_type = "TRANSFORMS"
  740. my_var = {
  741. "owner" : xForm1, # will be filled in by Driver
  742. "prop" : self.evaluate_input("Property"), # will be filled in by Driver
  743. "type" : v_type,
  744. "space" : self.evaluate_input("Evaluation Space"),
  745. "rotation_mode" : self.evaluate_input("Rotation Mode"),
  746. "xForm 1" : xForm1,#self.GetxForm(index = 1),
  747. "xForm 2" : xForm2,#self.GetxForm(index = 2),
  748. "channel" : dVarChannel,}
  749. self.parameters["Driver Variable"] = my_var
  750. self.executed = True
  751. class UtilityKeyframe(MantisNode):
  752. '''A node representing a keyframe for a F-Curve'''
  753. def __init__(self, signature, base_tree):
  754. super().__init__(signature, base_tree)
  755. inputs = [
  756. "Frame" ,
  757. "Value" ,
  758. ]
  759. outputs = [
  760. "Keyframe" ,
  761. ]
  762. additional_parameters = {"Keyframe":{}}
  763. self.inputs.init_sockets(inputs)
  764. self.outputs.init_sockets(outputs)
  765. self.init_parameters( additional_parameters=additional_parameters)
  766. self.node_type = "DRIVER" # MUST be run in Pose mode
  767. setup_custom_props(self)
  768. def bPrepare(self, bContext = None,):
  769. key = self.parameters["Keyframe"]
  770. from mathutils import Vector
  771. key["co"]= Vector( (self.evaluate_input("Frame"), self.evaluate_input("Value"),))
  772. key["type"]="GENERATED"
  773. key["interpolation"] = "LINEAR"
  774. # eventually this will have the right data, TODO
  775. # self.parameters["Keyframe"] = key
  776. self.prepared = True
  777. self.executed = True
  778. class UtilityFCurve(MantisNode):
  779. '''A node representing an armature object'''
  780. def __init__(self, signature, base_tree):
  781. super().__init__(signature, base_tree)
  782. inputs = [
  783. "Extrapolation Mode",
  784. ]
  785. outputs = [
  786. "fCurve",
  787. ]
  788. self.inputs.init_sockets(inputs)
  789. self.outputs.init_sockets(outputs)
  790. self.init_parameters()
  791. self.node_type = "UTILITY"
  792. setup_custom_props(self)
  793. self.prepared = True
  794. def reset_execution(self):
  795. super().reset_execution()
  796. self.prepared=True
  797. def evaluate_input(self, input_name):
  798. return super().evaluate_input(input_name)
  799. def bExecute(self, bContext = None,):
  800. prepare_parameters(self)
  801. from .utilities import get_node_prototype
  802. np = get_node_prototype(self.signature, self.base_tree)
  803. extrap_mode = self.evaluate_input("Extrapolation Mode")
  804. keys = [] # ugly but whatever
  805. #['amplitude', 'back', 'bl_rna', 'co', 'co_ui', 'easing', 'handle_left', 'handle_left_type', 'handle_right', 'handle_right_type',
  806. # 'interpolation', 'period', 'rna_type', 'select_control_point', 'select_left_handle', 'select_right_handle', 'type']
  807. for k in self.inputs.keys():
  808. if k == 'Extrapolation Mode' : continue
  809. # print (self.inputs[k])
  810. if (key := self.evaluate_input(k)) is None:
  811. prOrange(f"WARN: No keyframe connected to {self}:{k}. Skipping Link.")
  812. else:
  813. keys.append(key)
  814. if len(keys) <1:
  815. prOrange(f"WARN: no keys in fCurve {self}.")
  816. keys.append(extrap_mode)
  817. self.parameters["fCurve"] = keys
  818. self.executed = True
  819. #TODO make the fCurve data a data class instead of a dict
  820. class UtilityDriver(MantisNode):
  821. '''A node representing an armature object'''
  822. def __init__(self, signature, base_tree):
  823. super().__init__(signature, base_tree)
  824. inputs = [
  825. "Driver Type" ,
  826. "Expression" ,
  827. "fCurve" ,
  828. ]
  829. outputs = [
  830. "Driver",
  831. ]
  832. from .drivers import MantisDriver
  833. additional_parameters = {
  834. "Driver":MantisDriver(),
  835. }
  836. self.inputs.init_sockets(inputs)
  837. self.outputs.init_sockets(outputs)
  838. self.init_parameters(additional_parameters=additional_parameters)
  839. self.node_type = "DRIVER" # MUST be run in Pose mode
  840. setup_custom_props(self)
  841. self.prepared = True
  842. def reset_execution(self):
  843. super().reset_execution()
  844. from .drivers import MantisDriver
  845. self.parameters["Driver"]=MantisDriver()
  846. self.prepared=True
  847. def bExecute(self, bContext = None,):
  848. prepare_parameters(self)
  849. from .drivers import MantisDriver
  850. #prPurple("Executing Driver Node")
  851. my_vars = []
  852. keys = self.evaluate_input("fCurve")
  853. if keys is None or len(keys) <2:
  854. prWhite(f"INFO: no fCurve connected to {self}; using default fCurve.")
  855. from mathutils import Vector
  856. keys = [
  857. {"co":Vector( (0, 0,)), "type":"GENERATED", "interpolation":"LINEAR" },
  858. {"co":Vector( (1, 1,)), "type":"GENERATED", "interpolation":"LINEAR" },
  859. "CONSTANT",]
  860. for inp in list(self.inputs.keys() )[3:]:
  861. if (new_var := self.evaluate_input(inp)):
  862. new_var["name"] = inp
  863. my_vars.append(new_var)
  864. else:
  865. raise RuntimeError(f"Failed to initialize Driver variable for {self}")
  866. my_driver ={ "owner" : None,
  867. "prop" : None, # will be filled out in the node that uses the driver
  868. "expression" : self.evaluate_input("Expression"),
  869. "ind" : -1, # same here
  870. "type" : self.evaluate_input("Driver Type"),
  871. "vars" : my_vars,
  872. "keys" : keys[:-1],
  873. "extrapolation" : keys[-1] }
  874. my_driver = MantisDriver(my_driver)
  875. self.parameters["Driver"].update(my_driver)
  876. print("Initializing driver %s " % (wrapPurple(self.__repr__())) )
  877. self.executed = True
  878. class UtilitySwitch(MantisNode):
  879. '''A node representing an armature object'''
  880. def __init__(self, signature, base_tree):
  881. super().__init__(signature, base_tree)
  882. inputs = {
  883. "Parameter" ,
  884. "Parameter Index" ,
  885. "Invert Switch" ,
  886. }
  887. outputs = [
  888. "Driver",
  889. ]
  890. from .drivers import MantisDriver
  891. additional_parameters = {
  892. "Driver":MantisDriver(),
  893. }
  894. self.inputs.init_sockets(inputs)
  895. self.outputs.init_sockets(outputs)
  896. self.init_parameters(additional_parameters=additional_parameters)
  897. self.node_type = "DRIVER" # MUST be run in Pose mode
  898. self.prepared = True
  899. def evaluate_input(self, input_name):
  900. if input_name == 'Parameter':
  901. if self.inputs['Parameter'].is_connected:
  902. trace = trace_single_line(self, input_name)
  903. return trace[1].name # the name of the socket
  904. return self.parameters["Parameter"]
  905. return super().evaluate_input(input_name)
  906. def GetxForm(self,):
  907. trace = trace_single_line(self, "Parameter" )
  908. for node in trace[0]:
  909. if (node.__class__ in [xFormArmature, xFormBone]):
  910. return node #this will fetch the first one, that's good!
  911. return None
  912. def reset_execution(self):
  913. super().reset_execution()
  914. from .drivers import MantisDriver
  915. self.parameters["Driver"]=MantisDriver()
  916. self.prepared=True
  917. def bExecute(self, bContext = None,):
  918. #prepare_parameters(self)
  919. #prPurple ("Executing Switch Node")
  920. xForm = self.GetxForm()
  921. if xForm : xForm = xForm.bGetObject()
  922. if not xForm:
  923. raise RuntimeError("Could not evaluate xForm for %s" % self)
  924. from .drivers import MantisDriver
  925. my_driver ={ "owner" : None,
  926. "prop" : None, # will be filled out in the node that uses the driver
  927. "ind" : -1, # same here
  928. "type" : "SCRIPTED",
  929. "vars" : [ { "owner" : xForm,
  930. "prop" : self.evaluate_input("Parameter"),
  931. "name" : "a",
  932. "type" : "SINGLE_PROP", } ],
  933. "keys" : [ { "co":(0,0),
  934. "interpolation": "LINEAR",
  935. "type":"KEYFRAME",}, #display type
  936. { "co":(1,1),
  937. "interpolation": "LINEAR",
  938. "type":"KEYFRAME",},],
  939. "extrapolation": 'CONSTANT', }
  940. my_driver ["expression"] = "a"
  941. my_driver = MantisDriver(my_driver)
  942. # this makes it so I can check for type later!
  943. if self.evaluate_input("Invert Switch") == True:
  944. my_driver ["expression"] = "1 - a"
  945. # this way, regardless of what order things are handled, the
  946. # driver is sent to the next node.
  947. # In the case of some drivers, the parameter may be sent out
  948. # before it's filled in (because there is a circular dependency)
  949. # I want to support this behaviour because Blender supports it.
  950. # We do not make a copy. We update the driver, so that
  951. # the same instance is filled out.
  952. self.parameters["Driver"].update(my_driver)
  953. print("Initializing driver %s " % (wrapPurple(self.__repr__())) )
  954. self.executed = True
  955. class UtilityCombineThreeBool(MantisNode):
  956. '''A node for combining three booleans into a boolean three-tuple'''
  957. def __init__(self, signature, base_tree):
  958. super().__init__(signature, base_tree)
  959. inputs = [
  960. "X" ,
  961. "Y" ,
  962. "Z" ,
  963. ]
  964. outputs = [
  965. "Three-Bool",
  966. ]
  967. self.inputs.init_sockets(inputs)
  968. self.outputs.init_sockets(outputs)
  969. self.init_parameters()
  970. self.node_type = "UTILITY"
  971. def reset_execution(self): # need to make sure any references are deleted
  972. super().reset_execution() # so we prepare the node again to reset them
  973. if self.parameters["Three-Bool"] is not None:
  974. for param in self.parameters["Three-Bool"].values():
  975. if isinstance(param, dict):
  976. self.prepared=False; break
  977. def bPrepare(self, bContext = None,):
  978. self.parameters["Three-Bool"] = (
  979. self.evaluate_input("X"),
  980. self.evaluate_input("Y"),
  981. self.evaluate_input("Z"), )
  982. self.prepared = True
  983. self.executed = True
  984. # Note this is a copy of the above. This needs to be de-duplicated.
  985. class UtilityCombineVector(MantisNode):
  986. '''A node for combining three floats into a vector'''
  987. def __init__(self, signature, base_tree):
  988. super().__init__(signature, base_tree)
  989. super().__init__(signature, base_tree)
  990. inputs = [
  991. "X" ,
  992. "Y" ,
  993. "Z" ,
  994. ]
  995. outputs = [
  996. "Vector",
  997. ]
  998. self.inputs.init_sockets(inputs)
  999. self.outputs.init_sockets(outputs)
  1000. self.init_parameters()
  1001. self.node_type = "UTILITY"
  1002. def reset_execution(self): # need to make sure any references are deleted
  1003. super().reset_execution() # so we prepare the node again to reset them
  1004. if self.parameters["Vector"] is not None:
  1005. for param in self.parameters["Vector"]:
  1006. if isinstance(param, dict):
  1007. self.prepared=False; break
  1008. def bPrepare(self, bContext = None,):
  1009. #prPurple("Executing CombineVector Node")
  1010. prepare_parameters(self)
  1011. self.parameters["Vector"] = (
  1012. self.evaluate_input("X"),
  1013. self.evaluate_input("Y"),
  1014. self.evaluate_input("Z"), )
  1015. self.prepared, self.executed = True, True
  1016. class UtilitySeparateVector(MantisNode):
  1017. '''A node for separating a vector into three floats'''
  1018. def __init__(self, signature, base_tree):
  1019. super().__init__(signature, base_tree)
  1020. inputs = [
  1021. "Vector"
  1022. ]
  1023. outputs = [
  1024. "X" ,
  1025. "Y" ,
  1026. "Z" ,
  1027. ]
  1028. self.inputs.init_sockets(inputs)
  1029. self.outputs.init_sockets(outputs)
  1030. self.init_parameters()
  1031. self.node_type = "UTILITY"
  1032. def bPrepare(self, bContext = None,):
  1033. self.parameters["X"] = self.evaluate_input("Vector")[0]
  1034. self.parameters["Y"] = self.evaluate_input("Vector")[1]
  1035. self.parameters["Z"] = self.evaluate_input("Vector")[2]
  1036. self.prepared, self.executed = True, True
  1037. class UtilityCatStrings(MantisNode):
  1038. '''A node representing an armature object'''
  1039. def __init__(self, signature, base_tree):
  1040. super().__init__(signature, base_tree)
  1041. inputs = [
  1042. "String_1" ,
  1043. "String_2" ,
  1044. ]
  1045. outputs = [
  1046. "OutputString" ,
  1047. ]
  1048. self.inputs.init_sockets(inputs)
  1049. self.outputs.init_sockets(outputs)
  1050. self.init_parameters()
  1051. self.node_type = "UTILITY"
  1052. def bPrepare(self, bContext = None,):
  1053. self.parameters["OutputString"] = self.evaluate_input("String_1")+self.evaluate_input("String_2")
  1054. self.prepared, self.executed = True, True
  1055. # TODO move this to the Xform file
  1056. class InputExistingGeometryObject(MantisNode):
  1057. '''A node representing an existing object'''
  1058. def __init__(self, signature, base_tree):
  1059. super().__init__(signature, base_tree)
  1060. inputs = [
  1061. "Name" ,
  1062. ]
  1063. outputs = [
  1064. "Object" ,
  1065. ]
  1066. self.inputs.init_sockets(inputs)
  1067. self.outputs.init_sockets(outputs)
  1068. self.init_parameters()
  1069. self.node_type = "XFORM"
  1070. def reset_execution(self):
  1071. super().reset_execution()
  1072. self.prepared=False
  1073. def bPrepare(self, bContext=None):
  1074. from bpy import data
  1075. ob = None
  1076. if name := self.evaluate_input("Name"):
  1077. ob= data.objects.get( name )
  1078. if ob is None and name:
  1079. prRed(f"No object found with name {name} in {self}")
  1080. self.bObject=ob
  1081. self.prepared, self.executed = True, True
  1082. def bGetObject(self, mode=''):
  1083. return self.bObject
  1084. class InputExistingGeometryData(MantisNode):
  1085. '''A node representing existing object data'''
  1086. def __init__(self, signature, base_tree):
  1087. super().__init__(signature, base_tree)
  1088. inputs = [
  1089. "Name" ,
  1090. ]
  1091. outputs = [
  1092. "Geometry" ,
  1093. ]
  1094. self.inputs.init_sockets(inputs)
  1095. self.outputs.init_sockets(outputs)
  1096. self.init_parameters()
  1097. self.node_type = "UTILITY"
  1098. self.prepared = True; self.executed = True
  1099. def reset_execution(self):
  1100. super().reset_execution()
  1101. self.prepared, self.executed = True, True
  1102. # the mode argument is only for interface consistency
  1103. def bGetObject(self, mode=''):
  1104. from bpy import data
  1105. # first try Curve, then try Mesh
  1106. bObject = data.curves.get(self.evaluate_input("Name"))
  1107. if not bObject:
  1108. bObject = data.meshes.get(self.evaluate_input("Name"))
  1109. if bObject is None:
  1110. raise RuntimeError(f"Could not find a mesh or curve datablock named \"{self.evaluate_input('Name')}\" for node {self}")
  1111. return bObject
  1112. class UtilityGeometryOfXForm(MantisNode):
  1113. '''A node representing existing object data'''
  1114. def __init__(self, signature, base_tree):
  1115. super().__init__(signature, base_tree)
  1116. inputs = [
  1117. "xForm" ,
  1118. ]
  1119. outputs = [
  1120. "Geometry" ,
  1121. ]
  1122. self.inputs.init_sockets(inputs)
  1123. self.outputs.init_sockets(outputs)
  1124. self.init_parameters()
  1125. self.node_type = "UTILITY"
  1126. self.prepared = True
  1127. self.executed = True
  1128. def reset_execution(self):
  1129. super().reset_execution()
  1130. self.prepared, self.executed = True, True
  1131. # mode for interface consistency
  1132. def bGetObject(self, mode=''):
  1133. if not (self.inputs.get('xForm') and self.inputs['xForm'].links):
  1134. prOrange(f"WARN: Cannot retrieve data from {self}, there is no xForm node connected.")
  1135. return None
  1136. xf = self.inputs["xForm"].links[0].from_node
  1137. if xf.node_type == 'XFORM':
  1138. xf_ob = xf.bGetObject()
  1139. if (xf_ob is not None) and xf_ob.type in ['MESH', 'CURVE']:
  1140. return xf_ob.data
  1141. prOrange(f"WARN: Cannot retrieve data from {self}, the connected xForm is not a mesh or curve.")
  1142. return None
  1143. class UtilityNameOfXForm(MantisNode):
  1144. '''A node representing existing object data'''
  1145. def __init__(self, signature, base_tree):
  1146. super().__init__(signature, base_tree)
  1147. inputs = [
  1148. "xForm" ,
  1149. ]
  1150. outputs = [
  1151. "Name" ,
  1152. ]
  1153. self.inputs.init_sockets(inputs)
  1154. self.outputs.init_sockets(outputs)
  1155. self.init_parameters()
  1156. self.node_type = "UTILITY"
  1157. # mode for interface consistency
  1158. def bPrepare(self, bContext = None,):
  1159. if not (self.inputs.get('xForm') and self.inputs['xForm'].links):
  1160. raise RuntimeError( f"WARN: Cannot retrieve data from {self},"
  1161. " there is no xForm node connected.")
  1162. xf = self.inputs["xForm"].links[0].from_node
  1163. self.parameters["Name"] = xf.evaluate_input('Name')
  1164. self.prepared, self.executed = True, True
  1165. class UtilityGetBoneLength(MantisNode):
  1166. '''A node to get the length of a bone matrix'''
  1167. def __init__(self, signature, base_tree):
  1168. super().__init__(signature, base_tree)
  1169. inputs = [
  1170. "Bone Matrix" ,
  1171. ]
  1172. outputs = [
  1173. "Bone Length" ,
  1174. ]
  1175. self.inputs.init_sockets(inputs)
  1176. self.outputs.init_sockets(outputs)
  1177. self.init_parameters()
  1178. self.node_type = "UTILITY"
  1179. def bPrepare(self, bContext = None,):
  1180. if (l := self.evaluate_input("Bone Matrix")) is not None:
  1181. self.parameters["Bone Length"] = l[3][3]
  1182. else:
  1183. other = self.inputs["Bone Matrix"].links[0].from_node
  1184. raise RuntimeError(f"Cannot get matrix for {self} from {other}")
  1185. self.prepared, self.executed = True, True
  1186. class UtilityPointFromBoneMatrix(MantisNode):
  1187. '''A node representing an armature object'''
  1188. def __init__(self, signature, base_tree):
  1189. super().__init__(signature, base_tree)
  1190. inputs = [
  1191. "Bone Matrix" ,
  1192. "Head/Tail" ,
  1193. ]
  1194. outputs = [
  1195. "Point" ,
  1196. ]
  1197. self.inputs.init_sockets(inputs)
  1198. self.outputs.init_sockets(outputs)
  1199. self.init_parameters()
  1200. self.node_type = "UTILITY"
  1201. # TODO: find out why this is sometimes not ready at bPrepare phase
  1202. def bPrepare(self, bContext = None,):
  1203. from mathutils import Vector
  1204. matrix = self.evaluate_input("Bone Matrix")
  1205. head, rotation, _scale = matrix.copy().decompose()
  1206. tail = head.copy() + (rotation @ Vector((0,1,0)))*matrix[3][3]
  1207. self.parameters["Point"] = head.lerp(tail, self.evaluate_input("Head/Tail"))
  1208. self.prepared, self.executed = True, True
  1209. class UtilitySetBoneLength(MantisNode):
  1210. '''Sets the length of a Bone's matrix'''
  1211. def __init__(self, signature, base_tree):
  1212. super().__init__(signature, base_tree)
  1213. inputs = [
  1214. "Bone Matrix" ,
  1215. "Length" ,
  1216. ]
  1217. outputs = [
  1218. "Bone Matrix" ,
  1219. ]
  1220. self.inputs.init_sockets(inputs)
  1221. self.outputs.init_sockets(outputs)
  1222. self.init_parameters()
  1223. self.node_type = "UTILITY"
  1224. def bPrepare(self, bContext = None,):
  1225. from mathutils import Vector
  1226. if matrix := self.evaluate_input("Bone Matrix"):
  1227. matrix = matrix.copy()
  1228. # print (self.inputs["Length"].links)
  1229. matrix[3][3] = self.evaluate_input("Length")
  1230. self.parameters["Length"] = self.evaluate_input("Length")
  1231. self.parameters["Bone Matrix"] = matrix
  1232. else:
  1233. raise RuntimeError(f"Cannot get matrix for {self}")
  1234. self.prepared, self.executed = True, True
  1235. class UtilityMatrixSetLocation(MantisNode):
  1236. '''Sets the location of a matrix'''
  1237. def __init__(self, signature, base_tree):
  1238. super().__init__(signature, base_tree)
  1239. inputs = [
  1240. "Matrix" ,
  1241. "Location" ,
  1242. ]
  1243. outputs = [
  1244. "Matrix" ,
  1245. ]
  1246. self.inputs.init_sockets(inputs)
  1247. self.outputs.init_sockets(outputs)
  1248. self.init_parameters()
  1249. self.node_type = "UTILITY"
  1250. def bPrepare(self, bContext = None,):
  1251. from mathutils import Vector
  1252. if matrix := self.evaluate_input("Matrix"):
  1253. matrix = matrix.copy()
  1254. # print (self.inputs["Length"].links)
  1255. loc = self.evaluate_input("Location")
  1256. matrix[0][3] = loc[0]; matrix[1][3] = loc[1]; matrix[2][3] = loc[2]
  1257. self.parameters["Matrix"] = matrix
  1258. self.prepared, self.executed = True, True
  1259. class UtilityMatrixGetLocation(MantisNode):
  1260. '''Gets the location of a matrix'''
  1261. def __init__(self, signature, base_tree):
  1262. super().__init__(signature, base_tree)
  1263. inputs = [
  1264. "Matrix" ,
  1265. ]
  1266. outputs = [
  1267. "Location" ,
  1268. ]
  1269. self.inputs.init_sockets(inputs)
  1270. self.outputs.init_sockets(outputs)
  1271. self.init_parameters()
  1272. self.node_type = "UTILITY"
  1273. def bPrepare(self, bContext = None,):
  1274. from mathutils import Vector
  1275. if matrix := self.evaluate_input("Matrix"):
  1276. self.parameters["Location"] = matrix.to_translation()
  1277. self.prepared = True; self.executed = True
  1278. class UtilityMatrixFromXForm(MantisNode):
  1279. """Returns the matrix of the given xForm node."""
  1280. def __init__(self, signature, base_tree):
  1281. super().__init__(signature, base_tree)
  1282. inputs = [
  1283. "xForm" ,
  1284. ]
  1285. outputs = [
  1286. "Matrix" ,
  1287. ]
  1288. self.node_type = "UTILITY"
  1289. self.inputs.init_sockets(inputs)
  1290. self.outputs.init_sockets(outputs)
  1291. self.init_parameters()
  1292. def GetxForm(self):
  1293. trace = trace_single_line(self, "xForm")
  1294. for node in trace[0]:
  1295. if (node.node_type == 'XFORM'):
  1296. return node
  1297. raise GraphError("%s is not connected to an xForm" % self)
  1298. def bPrepare(self, bContext = None,):
  1299. from mathutils import Vector, Matrix
  1300. self.parameters["Matrix"] = Matrix.Identity(4)
  1301. if matrix := self.GetxForm().parameters.get("Matrix"):
  1302. self.parameters["Matrix"] = matrix.copy()
  1303. elif hasattr(self.GetxForm().bObject, "matrix"):
  1304. self.parameters["Matrix"] = self.GetxForm().bObject.matrix.copy()
  1305. elif hasattr(self.GetxForm().bObject, "matrix_world"):
  1306. self.parameters["Matrix"] = self.GetxForm().bObject.matrix_world.copy()
  1307. else:
  1308. prRed(f"Could not find matrix for {self} - check if the referenced object exists.")
  1309. self.prepared = True; self.executed = True
  1310. class UtilityAxesFromMatrix(MantisNode):
  1311. """Returns the axes of the given matrix."""
  1312. def __init__(self, signature, base_tree):
  1313. super().__init__(signature, base_tree)
  1314. inputs = [
  1315. "Matrix" ,
  1316. ]
  1317. outputs = [
  1318. "X Axis" ,
  1319. "Y Axis" ,
  1320. "Z Axis" ,
  1321. ]
  1322. self.inputs.init_sockets(inputs)
  1323. self.outputs.init_sockets(outputs)
  1324. self.init_parameters()
  1325. self.node_type = "UTILITY"
  1326. def bPrepare(self, bContext = None,):
  1327. from mathutils import Vector
  1328. if matrix := self.evaluate_input("Matrix"):
  1329. matrix= matrix.copy().to_3x3(); matrix.transpose()
  1330. self.parameters['X Axis'] = matrix[0]
  1331. self.parameters['Y Axis'] = matrix[1]
  1332. self.parameters['Z Axis'] = matrix[2]
  1333. self.prepared = True; self.executed = True
  1334. class UtilityBoneMatrixHeadTailFlip(MantisNode):
  1335. def __init__(self, signature, base_tree):
  1336. super().__init__(signature, base_tree)
  1337. inputs = [
  1338. "Bone Matrix" ,
  1339. ]
  1340. outputs = [
  1341. "Bone Matrix" ,
  1342. ]
  1343. self.inputs.init_sockets(inputs)
  1344. self.outputs.init_sockets(outputs)
  1345. self.init_parameters()
  1346. self.node_type = "UTILITY"
  1347. def bPrepare(self, bContext = None,):
  1348. from mathutils import Vector, Matrix, Quaternion
  1349. from bpy.types import Bone
  1350. if matrix := self.evaluate_input("Bone Matrix"):
  1351. axis, roll = Bone.AxisRollFromMatrix(matrix.to_3x3())
  1352. new_mat = Bone.MatrixFromAxisRoll(-1*axis, roll)
  1353. length = matrix[3][3]
  1354. new_mat.resize_4x4() # last column contains
  1355. new_mat[0][3] = matrix[0][3] + axis[0]*length # x location
  1356. new_mat[1][3] = matrix[1][3] + axis[1]*length # y location
  1357. new_mat[2][3] = matrix[2][3] + axis[2]*length # z location
  1358. new_mat[3][3] = length # length
  1359. self.parameters["Bone Matrix"] = new_mat
  1360. self.prepared, self.executed = True, True
  1361. class UtilityMatrixTransform(MantisNode):
  1362. def __init__(self, signature, base_tree):
  1363. super().__init__(signature, base_tree)
  1364. inputs = [
  1365. "Matrix 1" ,
  1366. "Matrix 2" ,
  1367. ]
  1368. outputs = [
  1369. "Out Matrix" ,
  1370. ]
  1371. self.inputs.init_sockets(inputs)
  1372. self.outputs.init_sockets(outputs)
  1373. self.init_parameters()
  1374. self.node_type = "UTILITY"
  1375. def bPrepare(self, bContext = None,):
  1376. from mathutils import Vector
  1377. mat1 = self.evaluate_input("Matrix 1"); mat2 = self.evaluate_input("Matrix 2")
  1378. if mat1 and mat2:
  1379. mat1copy = mat1.copy()
  1380. self.parameters["Out Matrix"] = mat2 @ mat1copy
  1381. self.parameters["Out Matrix"].translation = mat1copy.to_translation()+ mat2.to_translation()
  1382. else:
  1383. raise RuntimeError(wrapRed(f"Node {self} did not receive all matrix inputs..."
  1384. " found input 1? {mat1 is not None}, 2? {mat2 is not None}"))
  1385. self.prepared, self.executed = True, True
  1386. class UtilityMatrixInvert(MantisNode):
  1387. def __init__(self, signature, base_tree):
  1388. super().__init__(signature, base_tree, MatrixInvertSockets)
  1389. self.init_parameters()
  1390. self.node_type = "UTILITY"
  1391. def bPrepare(self, bContext = None,):
  1392. from mathutils import Vector
  1393. mat1 = self.evaluate_input("Matrix 1")
  1394. if mat1:
  1395. mat1copy = mat1.copy()
  1396. try:
  1397. self.parameters["Matrix"] = mat1copy.inverted()
  1398. except ValueError as e:
  1399. prRed(f"ERROR: {self}: The matrix cannot be inverted."); prOrange(mat1)
  1400. raise e
  1401. else:
  1402. raise RuntimeError(wrapRed(f"Node {self} did not receive all matrix inputs..."
  1403. " found input 1? {mat1 is not None}"))
  1404. self.prepared, self.executed = True, True
  1405. class UtilityMatrixCompose(MantisNode):
  1406. def __init__(self, signature, base_tree):
  1407. super().__init__(signature, base_tree, MatrixComposeSockets)
  1408. self.init_parameters()
  1409. self.node_type = "UTILITY"
  1410. def bPrepare(self, bContext = None,):
  1411. from mathutils import Matrix
  1412. matrix= Matrix.Identity(3)
  1413. matrix[0] = self.evaluate_input('X Basis Vector')
  1414. matrix[1] = self.evaluate_input('Y Basis Vector')
  1415. matrix[2] = self.evaluate_input('Z Basis Vector')
  1416. matrix.transpose(); matrix=matrix.to_4x4()
  1417. matrix.translation = self.evaluate_input('Translation')
  1418. self.parameters['Matrix']=matrix
  1419. self.prepared = True; self.executed = True
  1420. class UtilityMatrixAlignRoll(MantisNode):
  1421. def __init__(self, signature, base_tree):
  1422. super().__init__(signature, base_tree, MatrixAlignRollSockets)
  1423. self.init_parameters()
  1424. self.node_type = "UTILITY"
  1425. def bPrepare(self, bContext = None,):
  1426. from mathutils import Vector, Matrix
  1427. align_axis = Vector(self.evaluate_input('Alignment Vector'))
  1428. # why do I have to construct a vector here?
  1429. # why is the socket returning a bpy_prop_array ?
  1430. print(align_axis)
  1431. if align_axis.length_squared==0:
  1432. raise RuntimeError(f"WARN: cannot align matrix in {self}"
  1433. " because the alignment vector is zero.")
  1434. input=self.evaluate_input('Matrix').copy()
  1435. y_axis= input.to_3x3().transposed()[1]
  1436. from .utilities import project_point_to_plane
  1437. projected=project_point_to_plane(
  1438. align_axis.normalized(), Vector((0,0,0)), y_axis).normalized()
  1439. # now that we have the projected vector, transform the points from
  1440. # the plane of the y_axis to flat space and get the signed angle
  1441. from math import atan2
  1442. try:
  1443. flattened = (input.to_3x3().inverted() @ projected)
  1444. except ValueError:
  1445. raise ValueError(f"Cannot align the matrix in {self} because it is degenerate.")
  1446. rotation = Matrix.Rotation(atan2(flattened.x, flattened.z), 4, y_axis)
  1447. matrix = rotation @ input.copy()
  1448. matrix.translation=input.translation
  1449. matrix[3][3] = input[3][3]
  1450. self.parameters['Matrix'] = matrix
  1451. self.prepared = True; self.executed = True
  1452. # NOTE: I tried other ways of setting the matrix, including composing
  1453. # it directly from the Y axis, the normalized projection of the align
  1454. # axis, and their cross-product. That only nearly worked.
  1455. # this calculation should not work better, but it does. Why?
  1456. class UtilityTransformationMatrix(MantisNode):
  1457. def __init__(self, signature, base_tree):
  1458. super().__init__(signature, base_tree)
  1459. inputs = [
  1460. "Operation" ,
  1461. "Vector" ,
  1462. "W" ,
  1463. ]
  1464. outputs = [
  1465. "Matrix" ,
  1466. ]
  1467. self.inputs.init_sockets(inputs)
  1468. self.outputs.init_sockets(outputs)
  1469. self.init_parameters()
  1470. self.node_type = "UTILITY"
  1471. def bPrepare(self, bContext = None,):
  1472. from mathutils import Matrix, Vector
  1473. if (operation := self.evaluate_input("Operation")) == 'ROTATE_AXIS_ANGLE':
  1474. # this can, will, and should fail if the axis is 0,0,0
  1475. self.parameters["Matrix"] = rotMat = Matrix.Rotation(self.evaluate_input("W"), 4, Vector(self.evaluate_input("Vector")).normalized())
  1476. elif (operation := self.evaluate_input("Operation")) == 'TRANSLATE':
  1477. m = Matrix.Identity(4)
  1478. if axis := self.evaluate_input("Vector"):
  1479. m[0][3]=axis[0];m[1][3]=axis[1];m[2][3]=axis[2]
  1480. self.parameters['Matrix'] = m
  1481. elif (operation := self.evaluate_input("Operation")) == 'SCALE':
  1482. self.parameters["Matrix"] = Matrix.Scale(self.evaluate_input("W"), 4, Vector(self.evaluate_input("Vector")).normalized())
  1483. else:
  1484. raise NotImplementedError(self.evaluate_input("Operation").__repr__()+ " Operation not yet implemented.")
  1485. self.prepared = True; self.executed = True
  1486. class UtilityIntToString(MantisNode):
  1487. def __init__(self, signature, base_tree):
  1488. super().__init__(signature, base_tree)
  1489. inputs = [
  1490. "Number" ,
  1491. "Zero Padding" ,
  1492. ]
  1493. outputs = [
  1494. "String" ,
  1495. ]
  1496. self.inputs.init_sockets(inputs)
  1497. self.outputs.init_sockets(outputs)
  1498. self.init_parameters()
  1499. self.node_type = "UTILITY"
  1500. def bPrepare(self, bContext = None,):
  1501. number = self.evaluate_input("Number")
  1502. zeroes = self.evaluate_input("Zero Padding")
  1503. # I'm casting to int because I want to support any number, even though the node asks for int.
  1504. self.parameters["String"] = str(int(number)).zfill(int(zeroes))
  1505. self.prepared = True; self.executed = True
  1506. class UtilityArrayGet(MantisNode):
  1507. def __init__(self, signature, base_tree):
  1508. super().__init__(signature, base_tree)
  1509. inputs = [
  1510. "Index" ,
  1511. "OoB Behaviour" ,
  1512. "Array" ,
  1513. ]
  1514. outputs = [
  1515. "Output" ,
  1516. ]
  1517. self.inputs.init_sockets(inputs)
  1518. self.outputs.init_sockets(outputs)
  1519. self.init_parameters()
  1520. self.node_type = "UTILITY"
  1521. def bPrepare(self, bContext = None,):
  1522. if len(self.hierarchy_dependencies)==0 and len(self.hierarchy_connections)==0 and \
  1523. len(self.connections)==0 and len(self.dependencies)==0:
  1524. self.prepared, self.executed = True, True
  1525. return #Either it is already done or it doesn't matter.
  1526. elif self.prepared == False:
  1527. # sort the array entries
  1528. for inp in self.inputs.values():
  1529. inp.links.sort(key=lambda a : -a.multi_input_sort_id)
  1530. oob = self.evaluate_input("OoB Behaviour")
  1531. index = self.evaluate_input("Index")
  1532. from .utilities import cap, wrap
  1533. # we must assume that the array has sent the correct number of links
  1534. if oob == 'WRAP':
  1535. index = index % len(self.inputs['Array'].links)
  1536. if oob == 'HOLD':
  1537. index = cap(index, len(self.inputs['Array'].links)-1)
  1538. array_choose_relink(self, [index], "Array", "Output")
  1539. self.prepared, self.executed = True, True
  1540. class UtilityArrayLength(MantisNode):
  1541. def __init__(self, signature, base_tree):
  1542. super().__init__(signature, base_tree)
  1543. inputs = [
  1544. "Array" ,
  1545. ]
  1546. outputs = [
  1547. "Length" ,
  1548. ]
  1549. self.inputs.init_sockets(inputs)
  1550. self.outputs.init_sockets(outputs)
  1551. self.init_parameters()
  1552. self.node_type = "UTILITY"
  1553. def bPrepare(self, bContext = None,):
  1554. self.parameters["Length"] = len(self.inputs["Array"].links)
  1555. self.prepared, self.executed = True, True
  1556. class UtilitySetBoneMatrixTail(MantisNode):
  1557. def __init__(self, signature, base_tree):
  1558. super().__init__(signature, base_tree)
  1559. inputs = {
  1560. "Matrix" ,
  1561. "Tail Location" ,
  1562. }
  1563. outputs = [
  1564. "Result" ,
  1565. ]
  1566. self.inputs.init_sockets(inputs)
  1567. self.outputs.init_sockets(outputs)
  1568. self.init_parameters()
  1569. self.node_type = "UTILITY"
  1570. def bPrepare(self, bContext = None,):
  1571. from mathutils import Matrix
  1572. matrix = self.evaluate_input("Matrix")
  1573. if matrix is None: matrix = Matrix.Identity(4)
  1574. #just do this for now lol
  1575. self.parameters["Result"] = matrix_from_head_tail(matrix.translation, self.evaluate_input("Tail Location"))
  1576. self.prepared = True; self.executed = True
  1577. class UtilityPrint(MantisNode):
  1578. def __init__(self, signature, base_tree):
  1579. super().__init__(signature, base_tree)
  1580. inputs = [
  1581. "Input" ,
  1582. ]
  1583. self.inputs.init_sockets(inputs)
  1584. self.init_parameters()
  1585. self.node_type = "UTILITY"
  1586. def bPrepare(self, bContext = None,):
  1587. if my_input := self.evaluate_input("Input"):
  1588. print("Preparation phase: ", wrapWhite(self), wrapGreen(my_input))
  1589. self.prepared = True
  1590. def bExecute(self, bContext = None,):
  1591. if my_input := self.evaluate_input("Input"):
  1592. print("Execution phase: ", wrapWhite(self), wrapGreen(my_input))
  1593. self.executed = True
  1594. class UtilityCompare(MantisNode):
  1595. def __init__(self, signature, base_tree):
  1596. super().__init__(signature, base_tree, CompareSockets)
  1597. self.init_parameters()
  1598. self.node_type = "UTILITY"
  1599. def bPrepare(self, bContext = None,):
  1600. operation=self.evaluate_input("Comparison")
  1601. a = self.evaluate_input("A")
  1602. b = self.evaluate_input("B")
  1603. if isinstance(a, str) and isinstance(b, str) and \
  1604. operation not in ['EQUAL', 'NOT_EQUAL']:
  1605. raise GraphError("Strings do not have numerical value to"
  1606. " compute greater than or less than.")
  1607. match operation:
  1608. case "EQUAL":
  1609. self.parameters["Result"] = a == b
  1610. case "NOT_EQUAL":
  1611. self.parameters["Result"] = a != b
  1612. case "GREATER_THAN":
  1613. self.parameters["Result"] = a > b
  1614. case "GREATER_THAN_EQUAL":
  1615. self.parameters["Result"] = a >= b
  1616. case "LESS_THAN":
  1617. self.parameters["Result"] = a < b
  1618. case "LESS_THAN_EQUAL":
  1619. self.parameters["Result"] = a <= b
  1620. self.prepared = True; self.executed = True
  1621. class UtilityChoose(MantisNode):
  1622. def __init__(self, signature, base_tree):
  1623. super().__init__(signature, base_tree)
  1624. inputs = [
  1625. "Condition" ,
  1626. "A" ,
  1627. "B" ,
  1628. ]
  1629. outputs = [
  1630. "Result" ,
  1631. ]
  1632. self.inputs.init_sockets(inputs)
  1633. self.outputs.init_sockets(outputs)
  1634. self.init_parameters()
  1635. self.node_type = "UTILITY"
  1636. def reset_execution(self):
  1637. prepared=self.prepared
  1638. super().reset_execution()
  1639. # prevent this node from attempting to prepare again.
  1640. self.prepared, self.executed = prepared, prepared
  1641. def bPrepare(self, bContext = None,):
  1642. if self.outputs['Result'].links: # otherwise this doesn't matter as it is not connected.
  1643. prGreen(f"Executing Choose Node {self}")
  1644. condition = self.evaluate_input("Condition")
  1645. if self.evaluate_input('A') is not None and self.evaluate_input('B') is not None:
  1646. self.parameters['Result'] = self.evaluate_input('B') if condition else self.evaluate_input('A')
  1647. elif self.evaluate_input('A') is None and self.evaluate_input('B') is None:
  1648. if condition: link = self.inputs['B'].links[0]
  1649. else: link = self.inputs['A'].links[0]
  1650. from_node = link.from_node; from_socket = link.from_socket
  1651. for link in self.outputs['Result'].links:
  1652. from_node.outputs[from_socket].connect(link.to_node, link.to_socket)
  1653. link.die()
  1654. self.flush_links()
  1655. # attempting to init the connections seems more error prone than leaving them be.
  1656. else:
  1657. raise GraphError(f"Choose Node {self} has incorrect types.")
  1658. self.prepared = True; self.executed = True