misc_nodes.py 69 KB

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