misc_nodes.py 73 KB

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