misc_nodes.py 78 KB

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