misc_nodes.py 79 KB

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