misc_nodes.py 83 KB

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