misc_nodes.py 78 KB

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