misc_nodes.py 77 KB

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