misc_nodes.py 70 KB

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