misc_nodes.py 66 KB

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