misc_nodes.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. from .node_container_common import *
  2. from .base_definitions import MantisNode, NodeSocket
  3. from .xForm_containers import xFormArmature, xFormBone
  4. from math import pi, tau
  5. def TellClasses():
  6. return [
  7. # utility
  8. InputFloat,
  9. InputIntNode,
  10. InputVector,
  11. InputBoolean,
  12. InputBooleanThreeTuple,
  13. InputRotationOrder,
  14. InputTransformSpace,
  15. InputString,
  16. InputMatrix,
  17. InputExistingGeometryObject,
  18. InputExistingGeometryData,
  19. UtilityGeometryOfXForm,
  20. UtilityNameOfXForm,
  21. UtilityPointFromCurve,
  22. UtilityMatrixFromCurve,
  23. UtilityMatricesFromCurve,
  24. UtilityNumberOfCurveSegments,
  25. UtilityMatrixFromCurveSegment,
  26. UtilityMetaRig,
  27. UtilityBoneProperties,
  28. UtilityDriverVariable,
  29. UtilityDriver,
  30. UtilityFCurve,
  31. UtilityKeyframe,
  32. UtilitySwitch,
  33. UtilityCombineThreeBool,
  34. UtilityCombineVector,
  35. UtilitySeparateVector,
  36. UtilityCatStrings,
  37. UtilityGetBoneLength,
  38. UtilityPointFromBoneMatrix,
  39. UtilitySetBoneLength,
  40. UtilityMatrixSetLocation,
  41. UtilityMatrixGetLocation,
  42. UtilityMatrixFromXForm,
  43. UtilityAxesFromMatrix,
  44. UtilityBoneMatrixHeadTailFlip,
  45. UtilityMatrixTransform,
  46. UtilityTransformationMatrix,
  47. UtilityIntToString,
  48. UtilityArrayGet,
  49. UtilitySetBoneMatrixTail,
  50. # Control flow switches
  51. UtilityCompare,
  52. UtilityChoose,
  53. # useful NoOp:
  54. UtilityPrint,
  55. ]
  56. def matrix_from_head_tail(head, tail, normal=None):
  57. from mathutils import Vector, Quaternion, Matrix
  58. if normal is None:
  59. rotation = Vector((0,1,0)).rotation_difference((tail-head).normalized()).to_matrix()
  60. m= Matrix.LocRotScale(head, rotation, None)
  61. m[3][3] = (tail-head).length
  62. else: # construct a basis matrix
  63. m = Matrix.Identity(3)
  64. axis = (tail-head).normalized()
  65. conormal = axis.cross(normal)
  66. m[0]=conormal
  67. m[1]=axis
  68. m[2]=normal
  69. m = m.transposed().to_4x4()
  70. return m
  71. def cleanup_curve(curve_name : str, execution_id : str) -> None:
  72. import bpy
  73. curve = bpy.data.objects.get(curve_name)
  74. m_name = curve.name+'.'+ execution_id
  75. if (mesh := bpy.data.meshes.get(m_name)):
  76. bpy.data.meshes.remove(mesh)
  77. #*#-------------------------------#++#-------------------------------#*#
  78. # U T I L I T Y N O D E S
  79. #*#-------------------------------#++#-------------------------------#*#
  80. class InputFloat(MantisNode):
  81. '''A node representing float input'''
  82. def __init__(self, signature, base_tree):
  83. super().__init__(signature, base_tree)
  84. outputs = ["Float Input"]
  85. self.outputs.init_sockets(outputs)
  86. self.init_parameters()
  87. self.node_type = 'UTILITY'
  88. self.prepared = True
  89. self.executed = True
  90. class InputIntNode(MantisNode):
  91. '''A node representing integer input'''
  92. def __init__(self, signature, base_tree):
  93. super().__init__(signature, base_tree)
  94. outputs = ["Integer"]
  95. self.outputs.init_sockets(outputs)
  96. self.init_parameters()
  97. self.node_type = 'UTILITY'
  98. self.prepared = True
  99. self.executed = True
  100. class InputVector(MantisNode):
  101. '''A node representing vector input'''
  102. def __init__(self, signature, base_tree):
  103. super().__init__(signature, base_tree)
  104. outputs = [""]
  105. self.outputs.init_sockets(outputs)
  106. self.init_parameters()
  107. self.node_type = 'UTILITY'
  108. self.prepared = True
  109. self.executed = True
  110. class InputBoolean(MantisNode):
  111. '''A node representing boolean input'''
  112. def __init__(self, signature, base_tree):
  113. super().__init__(signature, base_tree)
  114. outputs = [""]
  115. self.outputs.init_sockets(outputs)
  116. self.init_parameters()
  117. self.node_type = 'UTILITY'
  118. self.prepared = True
  119. self.executed = True
  120. class InputBooleanThreeTuple(MantisNode):
  121. '''A node representing a tuple of three booleans'''
  122. def __init__(self, signature, base_tree):
  123. super().__init__(signature, base_tree)
  124. outputs = [""]
  125. self.outputs.init_sockets(outputs)
  126. self.init_parameters()
  127. self.node_type = 'UTILITY'
  128. self.prepared = True
  129. self.executed = True
  130. class InputRotationOrder(MantisNode):
  131. '''A node representing string input for rotation order'''
  132. def __init__(self, signature, base_tree):
  133. super().__init__(signature, base_tree)
  134. outputs = [""]
  135. self.outputs.init_sockets(outputs)
  136. self.init_parameters()
  137. self.node_type = 'UTILITY'
  138. self.prepared = True
  139. self.executed = True
  140. class InputTransformSpace(MantisNode):
  141. '''A node representing string input for transform space'''
  142. def __init__(self, signature, base_tree):
  143. super().__init__(signature, base_tree)
  144. outputs = [""]
  145. self.outputs.init_sockets(outputs)
  146. self.init_parameters()
  147. self.node_type = 'UTILITY'
  148. self.prepared = True
  149. self.executed = True
  150. def evaluate_input(self, input_name):
  151. return self.parameters[""]
  152. class InputString(MantisNode):
  153. '''A node representing string input'''
  154. def __init__(self, signature, base_tree):
  155. super().__init__(signature, base_tree)
  156. outputs = [""]
  157. self.outputs.init_sockets(outputs)
  158. self.init_parameters()
  159. self.node_type = 'UTILITY'
  160. self.prepared = True
  161. self.executed = True
  162. class InputMatrix(MantisNode):
  163. '''A node representing axis-angle quaternion input'''
  164. def __init__(self, signature, base_tree):
  165. super().__init__(signature, base_tree)
  166. outputs = ["Matrix",]
  167. self.outputs.init_sockets(outputs)
  168. self.init_parameters()
  169. self.node_type = 'UTILITY'
  170. self.prepared = True
  171. self.executed = True
  172. class UtilityMatrixFromCurve(MantisNode):
  173. '''Get a matrix from a curve'''
  174. def __init__(self, signature, base_tree):
  175. super().__init__(signature, base_tree)
  176. inputs = [
  177. "Curve" ,
  178. "Total Divisions" ,
  179. "Matrix Index" ,
  180. ]
  181. outputs = [
  182. "Matrix" ,
  183. ]
  184. self.inputs.init_sockets(inputs)
  185. self.outputs.init_sockets(outputs)
  186. self.init_parameters()
  187. self.node_type = "UTILITY"
  188. def bPrepare(self, bContext = None,):
  189. from mathutils import Matrix
  190. import bpy
  191. m = Matrix.Identity(4)
  192. curve = bpy.data.objects.get(self.evaluate_input("Curve"))
  193. if not curve:
  194. prRed(f"No curve found for {self}. Using an Identity matrix instead.")
  195. m[3][3] = 1.0
  196. else:
  197. from .utilities import mesh_from_curve, data_from_ribbon_mesh
  198. if not bContext:
  199. # TODO find out if this is bad or a HACK or if it is OK
  200. bContext = bpy.context
  201. # IMPORTANT TODO: I need to be able to reuse this m
  202. # First, try to get the one we made before
  203. m_name = curve.name+'.'+self.base_tree.execution_id
  204. if not (m := bpy.data.meshes.get(m_name)):
  205. m = mesh_from_curve(curve, bContext)
  206. m.name = m_name
  207. #
  208. num_divisions = self.evaluate_input("Total Divisions")
  209. m_index = self.evaluate_input("Matrix Index")
  210. factors = [1/num_divisions*m_index, 1/num_divisions*(m_index+1)]
  211. data = data_from_ribbon_mesh(m, [factors], curve.matrix_world)
  212. head=data[0][0][0]
  213. tail= data[0][0][1]
  214. axis = (tail-head).normalized()
  215. normal=data[0][2][0]
  216. # make sure the normal is perpendicular to the tail
  217. from .utilities import make_perpendicular
  218. normal = make_perpendicular(axis, normal)
  219. m = matrix_from_head_tail(head, tail, normal)
  220. # this is in world space... let's just convert it back
  221. m.translation = head - curve.location
  222. m[3][3]=(tail-head).length
  223. # TODO HACK TODO
  224. # all the nodes should work in world-space, and it should be the responsibility
  225. # of the xForm node to convert!
  226. self.parameters["Matrix"] = m
  227. self.prepared = True
  228. self.executed = True
  229. def bFinalize(self, bContext=None):
  230. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  231. class UtilityPointFromCurve(MantisNode):
  232. '''Get a point from a curve'''
  233. def __init__(self, signature, base_tree):
  234. super().__init__(signature, base_tree)
  235. inputs = [
  236. "Curve" ,
  237. "Factor" ,
  238. ]
  239. outputs = [
  240. "Point" ,
  241. ]
  242. self.inputs.init_sockets(inputs)
  243. self.outputs.init_sockets(outputs)
  244. self.init_parameters()
  245. self.node_type = "UTILITY"
  246. def bPrepare(self, bContext = None,):
  247. import bpy
  248. curve = bpy.data.objects.get(self.evaluate_input("Curve"))
  249. if not curve:
  250. raise RuntimeError(f"No curve found for {self}.")
  251. else:
  252. from .utilities import mesh_from_curve, data_from_ribbon_mesh
  253. if not bContext:
  254. # TODO find out if this is bad or a HACK or if it is OK
  255. bContext = bpy.context
  256. # IMPORTANT TODO: I need to be able to reuse this m
  257. # First, try to get the one we made before
  258. m_name = curve.name+'.'+self.base_tree.execution_id
  259. if not (m := bpy.data.meshes.get(m_name)):
  260. m = mesh_from_curve(curve, bContext)
  261. m.name = m_name
  262. #
  263. num_divisions = 1
  264. factors = [self.evaluate_input("Factor")]
  265. data = data_from_ribbon_mesh(m, [factors], curve.matrix_world)
  266. p = data[0][0][0] - curve.location
  267. self.parameters["Point"] = p
  268. self.prepared, self.executed = True, True
  269. def bFinalize(self, bContext=None):
  270. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  271. class UtilityMatricesFromCurve(MantisNode):
  272. '''Get matrices from a curve'''
  273. def __init__(self, signature, base_tree):
  274. super().__init__(signature, base_tree)
  275. inputs = [
  276. "Curve" ,
  277. "Total Divisions" ,
  278. ]
  279. outputs = [
  280. "Matrices" ,
  281. ]
  282. self.inputs.init_sockets(inputs)
  283. self.outputs.init_sockets(outputs)
  284. self.init_parameters()
  285. self.node_type = "UTILITY"
  286. def bPrepare(self, bContext = None,):
  287. import time
  288. # start_time = time.time()
  289. #
  290. from mathutils import Matrix
  291. import bpy
  292. m = Matrix.Identity(4)
  293. curve_name = self.evaluate_input("Curve")
  294. curve = bpy.data.objects.get(curve_name)
  295. if not curve:
  296. prRed(f"No curve found for {self}. Using an Identity matrix instead.")
  297. m[3][3] = 1.0
  298. else:
  299. from .utilities import mesh_from_curve, data_from_ribbon_mesh
  300. if not bContext:
  301. bContext = bpy.context
  302. m_name = curve.name+'.'+self.base_tree.execution_id
  303. if not (mesh := bpy.data.meshes.get(m_name)):
  304. mesh = mesh_from_curve(curve, bContext)
  305. mesh.name = m_name
  306. num_divisions = self.evaluate_input("Total Divisions")
  307. factors = [0.0] + [(1/num_divisions*(i+1)) for i in range(num_divisions)]
  308. data = data_from_ribbon_mesh(mesh, [factors], curve.matrix_world)
  309. # 0 is the spline index. 0 selects points as opposed to normals or whatever.
  310. from .utilities import make_perpendicular
  311. matrices = [matrix_from_head_tail(
  312. data[0][0][i],
  313. data[0][0][i+1],
  314. make_perpendicular((data[0][0][i+1]-data[0][0][i]).normalized(), data[0][2][i]),) \
  315. for i in range(num_divisions)]
  316. for link in self.outputs["Matrices"].links:
  317. for i, m in enumerate(matrices):
  318. name = "Matrix"+str(i).zfill(4)
  319. if not (out := self.outputs.get(name)): # reuse them if there are multiple links.
  320. out = self.outputs[name] = NodeSocket(name = name, node=self)
  321. c = out.connect(link.to_node, link.to_socket)
  322. # prOrange(c)
  323. self.parameters[name] = m
  324. # print (mesh)
  325. link.die()
  326. self.prepared = True
  327. self.executed = True
  328. # prGreen(f"Matrices from curves took {time.time() - start_time} seconds.")
  329. def bFinalize(self, bContext=None):
  330. import bpy
  331. curve_name = self.evaluate_input("Curve")
  332. curve = bpy.data.objects.get(curve_name)
  333. m_name = curve.name+'.'+self.base_tree.execution_id
  334. if (mesh := bpy.data.meshes.get(m_name)):
  335. prGreen(f"Freeing mesh data {m_name}...")
  336. bpy.data.meshes.remove(mesh)
  337. class UtilityNumberOfCurveSegments(MantisNode):
  338. def __init__(self, signature, base_tree):
  339. super().__init__(signature, base_tree)
  340. inputs = [
  341. "Curve" ,
  342. "Spline Index" ,
  343. ]
  344. outputs = [
  345. "Number of Segments" ,
  346. ]
  347. self.inputs.init_sockets(inputs)
  348. self.outputs.init_sockets(outputs)
  349. self.init_parameters()
  350. self.node_type = "UTILITY"
  351. def bPrepare(self, bContext = None,):
  352. import bpy
  353. curve_name = self.evaluate_input("Curve")
  354. curve = bpy.data.objects.get(curve_name)
  355. spline = curve.data.splines[self.evaluate_input("Spline Index")]
  356. if spline.type == "BEZIER":
  357. self.parameters["Number of Segments"] = len(spline.bezier_points)-1
  358. else:
  359. self.parameters["Number of Segments"] = len(spline.points)-1
  360. self.prepared = True
  361. self.executed = True
  362. class UtilityMatrixFromCurveSegment(MantisNode):
  363. def __init__(self, signature, base_tree):
  364. super().__init__(signature, base_tree)
  365. inputs = [
  366. "Curve" ,
  367. "Spline Index" ,
  368. "Segment Index" ,
  369. ]
  370. outputs = [
  371. "Matrix" ,
  372. ]
  373. self.inputs.init_sockets(inputs)
  374. self.outputs.init_sockets(outputs)
  375. self.init_parameters()
  376. self.node_type = "UTILITY"
  377. def bPrepare(self, bContext = None,):
  378. from mathutils import Matrix
  379. import bpy
  380. curve = bpy.data.objects.get(self.evaluate_input("Curve"))
  381. if not curve:
  382. raise RuntimeError(f"No curve found for {self}.")
  383. else:
  384. from .utilities import mesh_from_curve, data_from_ribbon_mesh
  385. if not bContext: bContext = bpy.context
  386. m_name = curve.name+'.'+self.base_tree.execution_id
  387. if not (m := bpy.data.meshes.get(m_name)):
  388. m = mesh_from_curve(curve, bContext)
  389. m.name = m_name
  390. # this section is dumb, but it is because the data_from_ribbon_mesh
  391. # function is designed to pull data from many splines at once (for optimization)
  392. # so we have to give it empty splines for each one we skip.
  393. # TODO: Refactor this to make it so I can select spline index
  394. spline_index = self.evaluate_input("Spline Index")
  395. spline = curve.data.splines[spline_index]
  396. splines_factors = [ [] for i in range (spline_index)]
  397. factors = [0.0]
  398. points = spline.bezier_points if spline.type == 'BEZIER' else spline.points
  399. total_length=0.0
  400. for i in range(len(points)-1):
  401. total_length+= (seg_length := (points[i+1].co - points[i].co).length)
  402. factors.append(seg_length)
  403. prev_length = 0.0
  404. for i in range(len(factors)):
  405. factors[i] = prev_length+factors[i]/total_length
  406. prev_length=factors[i]
  407. # Why does this happen? Floating point error?
  408. if factors[i]>1.0: factors[i] = 1.0
  409. splines_factors.append(factors)
  410. #
  411. data = data_from_ribbon_mesh(m, splines_factors, curve.matrix_world)
  412. segment_index = self.evaluate_input("Segment Index")
  413. head=data[spline_index][0][segment_index]
  414. tail= data[spline_index][0][segment_index+1]
  415. axis = (tail-head).normalized()
  416. normal=data[spline_index][2][segment_index]
  417. # make sure the normal is perpendicular to the tail
  418. from .utilities import make_perpendicular
  419. normal = make_perpendicular(axis, normal)
  420. m = matrix_from_head_tail(head, tail, normal)
  421. m.translation = head - curve.location
  422. m[3][3]=(tail-head).length
  423. self.parameters["Matrix"] = m
  424. self.prepared, self.executed = True, True
  425. def bFinalize(self, bContext=None):
  426. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  427. class UtilityMetaRig(MantisNode):
  428. '''A node representing an armature object'''
  429. def __init__(self, signature, base_tree):
  430. super().__init__(signature, base_tree)
  431. inputs = [
  432. "Meta-Armature" ,
  433. "Meta-Bone" ,
  434. ]
  435. outputs = [
  436. "Matrix" ,
  437. ]
  438. self.inputs.init_sockets(inputs)
  439. self.outputs.init_sockets(outputs)
  440. self.init_parameters()
  441. self.node_type = "UTILITY"
  442. def bPrepare(self, bContext = None,):
  443. #kinda clumsy, whatever
  444. import bpy
  445. from mathutils import Matrix
  446. m = Matrix.Identity(4)
  447. meta_rig = self.evaluate_input("Meta-Armature")
  448. meta_bone = self.evaluate_input("Meta-Bone")
  449. if meta_rig:
  450. if ( armOb := bpy.data.objects.get(meta_rig) ):
  451. m = armOb.matrix_world
  452. if ( b := armOb.data.bones.get(meta_bone)):
  453. # calculate the correct object-space matrix
  454. m = Matrix.Identity(3)
  455. bones = [] # from the last ancestor, mult the matrices until we get to b
  456. while (b): bones.append(b); b = b.parent
  457. while (bones): b = bones.pop(); m = m @ b.matrix
  458. m = Matrix.Translation(b.head_local) @ m.to_4x4()
  459. #
  460. m[3][3] = b.length # this is where I arbitrarily decided to store length
  461. # else:
  462. # prRed("no bone for MetaRig node ", self)
  463. else:
  464. raise RuntimeError(wrapRed(f"No meta-rig input for MetaRig node {self}"))
  465. self.parameters["Matrix"] = m
  466. self.prepared = True
  467. self.executed = True
  468. class UtilityBoneProperties(MantisNode):
  469. '''A node representing a bone's gettable properties'''
  470. def __init__(self, signature, base_tree):
  471. super().__init__(signature, base_tree)
  472. outputs = [
  473. "matrix" ,
  474. "matrix_local" ,
  475. "matrix_basis" ,
  476. "head" ,
  477. "tail" ,
  478. "length" ,
  479. "rotation" ,
  480. "location" ,
  481. "scale" ,
  482. ]
  483. self.outputs.init_sockets(outputs)
  484. self.init_parameters()
  485. self.node_type = "UTILITY"
  486. self.prepared = True
  487. self.executed = True
  488. def fill_parameters(self, prototype=None):
  489. return
  490. # TODO this should probably be moved to Links
  491. class UtilityDriverVariable(MantisNode):
  492. '''A node representing an armature object'''
  493. def __init__(self, signature, base_tree):
  494. super().__init__(signature, base_tree)
  495. inputs = [
  496. "Variable Type" ,
  497. "Property" ,
  498. "Property Index" ,
  499. "Evaluation Space",
  500. "Rotation Mode" ,
  501. "xForm 1" ,
  502. "xForm 2" ,
  503. ]
  504. outputs = [
  505. "Driver Variable",
  506. ]
  507. self.inputs.init_sockets(inputs)
  508. self.outputs.init_sockets(outputs)
  509. self.init_parameters()
  510. self.node_type = "DRIVER" # MUST be run in Pose mode
  511. self.prepared = True
  512. def evaluate_input(self, input_name):
  513. if input_name == 'Property':
  514. if self.inputs.get('Property'):
  515. if self.inputs['Property'].is_linked:
  516. # get the name instead...
  517. trace = trace_single_line(self, input_name)
  518. return trace[1].name # the name of the socket
  519. return self.parameters["Property"]
  520. return super().evaluate_input(input_name)
  521. def GetxForm(self, index=1):
  522. trace = trace_single_line(self, "xForm 1" if index == 1 else "xForm 2")
  523. for node in trace[0]:
  524. if (node.__class__ in [xFormArmature, xFormBone]):
  525. return node #this will fetch the first one, that's good!
  526. return None
  527. def bExecute(self, bContext = None,):
  528. prepare_parameters(self)
  529. #prPurple ("Executing Driver Variable Node")
  530. xForm1 = self.GetxForm()
  531. xForm2 = self.GetxForm(index=2)
  532. # kinda clumsy
  533. if xForm1 : xForm1 = xForm1.bGetObject()
  534. if xForm2 : xForm2 = xForm2.bGetObject()
  535. v_type = self.evaluate_input("Variable Type")
  536. i = self.evaluate_input("Property Index"); dVarChannel = ""
  537. if (i >= 0): #negative values will use the vector property.
  538. if self.evaluate_input("Property") == 'location':
  539. if i == 0: dVarChannel = "LOC_X"
  540. elif i == 1: dVarChannel = "LOC_Y"
  541. elif i == 2: dVarChannel = "LOC_Z"
  542. else: raise RuntimeError("Invalid property index for %s" % self)
  543. if self.evaluate_input("Property") == 'rotation':
  544. if i == 0: dVarChannel = "ROT_X"
  545. elif i == 1: dVarChannel = "ROT_Y"
  546. elif i == 2: dVarChannel = "ROT_Z"
  547. elif i == 3: dVarChannel = "ROT_W"
  548. else: raise RuntimeError("Invalid property index for %s" % self)
  549. if self.evaluate_input("Property") == 'scale':
  550. if i == 0: dVarChannel = "SCALE_X"
  551. elif i == 1: dVarChannel = "SCALE_Y"
  552. elif i == 2: dVarChannel = "SCALE_Z"
  553. elif i == 3: dVarChannel = "SCALE_AVG"
  554. else: raise RuntimeError("Invalid property index for %s" % self)
  555. if self.evaluate_input("Property") == 'scale_average':
  556. dVarChannel = "SCALE_AVG"
  557. if dVarChannel: v_type = "TRANSFORMS"
  558. my_var = {
  559. "owner" : xForm1, # will be filled in by Driver
  560. "prop" : self.evaluate_input("Property"), # will be filled in by Driver
  561. "type" : v_type,
  562. "space" : self.evaluate_input("Evaluation Space"),
  563. "rotation_mode" : self.evaluate_input("Rotation Mode"),
  564. "xForm 1" : xForm1,#self.GetxForm(index = 1),
  565. "xForm 2" : xForm2,#self.GetxForm(index = 2),
  566. "channel" : dVarChannel,}
  567. # Push parameter to downstream connected node.connected:
  568. if (out := self.outputs["Driver Variable"]).is_linked:
  569. self.parameters[out.name] = my_var
  570. for link in out.links:
  571. link.to_node.parameters[link.to_socket] = my_var
  572. self.executed = True
  573. class UtilityKeyframe(MantisNode):
  574. '''A node representing a keyframe for a F-Curve'''
  575. def __init__(self, signature, base_tree):
  576. super().__init__(signature, base_tree)
  577. inputs = [
  578. "Frame" ,
  579. "Value" ,
  580. ]
  581. outputs = [
  582. "Keyframe" ,
  583. ]
  584. additional_parameters = {"Keyframe":{}}
  585. self.inputs.init_sockets(inputs)
  586. self.outputs.init_sockets(outputs)
  587. self.init_parameters( additional_parameters=additional_parameters)
  588. self.node_type = "DRIVER" # MUST be run in Pose mode
  589. setup_custom_props(self)
  590. def bPrepare(self, bContext = None,):
  591. key = self.parameters["Keyframe"]
  592. from mathutils import Vector
  593. key["co"]= Vector( (self.evaluate_input("Frame"), self.evaluate_input("Value"),))
  594. key["type"]="GENERATED"
  595. key["interpolation"] = "LINEAR"
  596. # eventually this will have the right data, TODO
  597. # self.parameters["Keyframe"] = key
  598. self.prepared = True
  599. self.executed = True
  600. class UtilityFCurve(MantisNode):
  601. '''A node representing an armature object'''
  602. def __init__(self, signature, base_tree):
  603. super().__init__(signature, base_tree)
  604. inputs = [
  605. "Extrapolation Mode",
  606. ]
  607. outputs = [
  608. "fCurve",
  609. ]
  610. self.inputs.init_sockets(inputs)
  611. self.outputs.init_sockets(outputs)
  612. self.init_parameters()
  613. self.node_type = "UTILITY"
  614. setup_custom_props(self)
  615. self.prepared = True
  616. def evaluate_input(self, input_name):
  617. return super().evaluate_input(input_name)
  618. def bExecute(self, bContext = None,):
  619. prepare_parameters(self)
  620. from .utilities import get_node_prototype
  621. np = get_node_prototype(self.signature, self.base_tree)
  622. extrap_mode = self.evaluate_input("Extrapolation Mode")
  623. keys = [] # ugly but whatever
  624. #['amplitude', 'back', 'bl_rna', 'co', 'co_ui', 'easing', 'handle_left', 'handle_left_type', 'handle_right', 'handle_right_type',
  625. # 'interpolation', 'period', 'rna_type', 'select_control_point', 'select_left_handle', 'select_right_handle', 'type']
  626. for k in self.inputs.keys():
  627. if k == 'Extrapolation Mode' : continue
  628. # print (self.inputs[k])
  629. if (key := self.evaluate_input(k)) is None:
  630. prOrange(f"WARN: No keyframe connected to {self}:{k}. Skipping Link.")
  631. else:
  632. keys.append(key)
  633. if len(keys) <1:
  634. prOrange(f"WARN: no keys in fCurve {self}.")
  635. keys.append(extrap_mode)
  636. self.parameters["fCurve"] = keys
  637. self.executed = True
  638. #TODO make the fCurve data a data class instead of a dict
  639. class UtilityDriver(MantisNode):
  640. '''A node representing an armature object'''
  641. def __init__(self, signature, base_tree):
  642. super().__init__(signature, base_tree)
  643. inputs = [
  644. "Driver Type" ,
  645. "Expression" ,
  646. "fCurve" ,
  647. ]
  648. outputs = [
  649. "Driver",
  650. ]
  651. from .drivers import MantisDriver
  652. additional_parameters = {
  653. "Driver":MantisDriver(),
  654. }
  655. self.inputs.init_sockets(inputs)
  656. self.outputs.init_sockets(outputs)
  657. self.init_parameters(additional_parameters=additional_parameters)
  658. self.node_type = "DRIVER" # MUST be run in Pose mode
  659. setup_custom_props(self)
  660. self.prepared = True
  661. def bExecute(self, bContext = None,):
  662. prepare_parameters(self)
  663. from .drivers import MantisDriver
  664. #prPurple("Executing Driver Node")
  665. my_vars = []
  666. keys = self.evaluate_input("fCurve")
  667. if keys is None or len(keys) <2:
  668. prWhite(f"INFO: no fCurve connected to {self}; using default fCurve.")
  669. from mathutils import Vector
  670. keys = [
  671. {"co":Vector( (0, 0,)), "type":"GENERATED", "interpolation":"LINEAR" },
  672. {"co":Vector( (1, 1,)), "type":"GENERATED", "interpolation":"LINEAR" },
  673. "CONSTANT",]
  674. for inp in list(self.inputs.keys() )[3:]:
  675. if (new_var := self.evaluate_input(inp)):
  676. new_var["name"] = inp
  677. my_vars.append(new_var)
  678. else:
  679. raise RuntimeError(f"Failed to initialize Driver variable for {self}")
  680. my_driver ={ "owner" : None,
  681. "prop" : None, # will be filled out in the node that uses the driver
  682. "expression" : self.evaluate_input("Expression"),
  683. "ind" : -1, # same here
  684. "type" : self.evaluate_input("Driver Type"),
  685. "vars" : my_vars,
  686. "keys" : keys[:-1],
  687. "extrapolation" : keys[-1] }
  688. my_driver = MantisDriver(my_driver)
  689. self.parameters["Driver"].update(my_driver)
  690. print("Initializing driver %s " % (wrapPurple(self.__repr__())) )
  691. self.executed = True
  692. class UtilitySwitch(MantisNode):
  693. '''A node representing an armature object'''
  694. def __init__(self, signature, base_tree):
  695. super().__init__(signature, base_tree)
  696. inputs = {
  697. "Parameter" ,
  698. "Parameter Index" ,
  699. "Invert Switch" ,
  700. }
  701. outputs = [
  702. "Driver",
  703. ]
  704. from .drivers import MantisDriver
  705. additional_parameters = {
  706. "Driver":MantisDriver(),
  707. }
  708. self.inputs.init_sockets(inputs)
  709. self.outputs.init_sockets(outputs)
  710. self.init_parameters(additional_parameters=additional_parameters)
  711. self.node_type = "DRIVER" # MUST be run in Pose mode
  712. self.prepared = True
  713. def evaluate_input(self, input_name):
  714. if input_name == 'Parameter':
  715. if self.inputs['Parameter'].is_connected:
  716. trace = trace_single_line(self, input_name)
  717. return trace[1].name # the name of the socket
  718. return self.parameters["Parameter"]
  719. return super().evaluate_input(input_name)
  720. def GetxForm(self,):
  721. trace = trace_single_line(self, "Parameter" )
  722. for node in trace[0]:
  723. if (node.__class__ in [xFormArmature, xFormBone]):
  724. return node #this will fetch the first one, that's good!
  725. return None
  726. def bExecute(self, bContext = None,):
  727. #prepare_parameters(self)
  728. #prPurple ("Executing Switch Node")
  729. xForm = self.GetxForm()
  730. if xForm : xForm = xForm.bGetObject()
  731. if not xForm:
  732. raise RuntimeError("Could not evaluate xForm for %s" % self)
  733. from .drivers import MantisDriver
  734. my_driver ={ "owner" : None,
  735. "prop" : None, # will be filled out in the node that uses the driver
  736. "ind" : -1, # same here
  737. "type" : "SCRIPTED",
  738. "vars" : [ { "owner" : xForm,
  739. "prop" : self.evaluate_input("Parameter"),
  740. "name" : "a",
  741. "type" : "SINGLE_PROP", } ],
  742. "keys" : [ { "co":(0,0),
  743. "interpolation": "LINEAR",
  744. "type":"KEYFRAME",}, #display type
  745. { "co":(1,1),
  746. "interpolation": "LINEAR",
  747. "type":"KEYFRAME",},],
  748. "extrapolation": 'CONSTANT', }
  749. my_driver ["expression"] = "a"
  750. my_driver = MantisDriver(my_driver)
  751. # this makes it so I can check for type later!
  752. if self.evaluate_input("Invert Switch") == True:
  753. my_driver ["expression"] = "1 - a"
  754. # this way, regardless of what order things are handled, the
  755. # driver is sent to the next node.
  756. # In the case of some drivers, the parameter may be sent out
  757. # before it's filled in (because there is a circular dependency)
  758. # I want to support this behaviour because Blender supports it.
  759. # We do not make a copy. We update the driver, so that
  760. # the same instance is filled out.
  761. self.parameters["Driver"].update(my_driver)
  762. print("Initializing driver %s " % (wrapPurple(self.__repr__())) )
  763. self.executed = True
  764. class UtilityCombineThreeBool(MantisNode):
  765. '''A node for combining three booleans into a boolean three-tuple'''
  766. def __init__(self, signature, base_tree):
  767. super().__init__(signature, base_tree)
  768. inputs = [
  769. "X" ,
  770. "Y" ,
  771. "Z" ,
  772. ]
  773. outputs = [
  774. "Three-Bool",
  775. ]
  776. self.inputs.init_sockets(inputs)
  777. self.outputs.init_sockets(outputs)
  778. self.init_parameters()
  779. self.node_type = "UTILITY"
  780. def bPrepare(self, bContext = None,):
  781. self.parameters["Three-Bool"] = (
  782. self.evaluate_input("X"),
  783. self.evaluate_input("Y"),
  784. self.evaluate_input("Z"), )
  785. self.prepared = True
  786. self.executed = True
  787. # Note this is a copy of the above. This needs to be de-duplicated.
  788. class UtilityCombineVector(MantisNode):
  789. '''A node for combining three floats into a vector'''
  790. def __init__(self, signature, base_tree):
  791. super().__init__(signature, base_tree)
  792. super().__init__(signature, base_tree)
  793. inputs = [
  794. "X" ,
  795. "Y" ,
  796. "Z" ,
  797. ]
  798. outputs = [
  799. "Vector",
  800. ]
  801. self.inputs.init_sockets(inputs)
  802. self.outputs.init_sockets(outputs)
  803. self.init_parameters()
  804. self.node_type = "UTILITY"
  805. def bPrepare(self, bContext = None,):
  806. #prPurple("Executing CombineVector Node")
  807. prepare_parameters(self)
  808. self.parameters["Vector"] = (
  809. self.evaluate_input("X"),
  810. self.evaluate_input("Y"),
  811. self.evaluate_input("Z"), )
  812. self.prepared = True
  813. self.executed = True
  814. class UtilitySeparateVector(MantisNode):
  815. '''A node for separating a vector into three floats'''
  816. def __init__(self, signature, base_tree):
  817. super().__init__(signature, base_tree)
  818. inputs = [
  819. "Vector"
  820. ]
  821. outputs = [
  822. "X" ,
  823. "Y" ,
  824. "Z" ,
  825. ]
  826. self.inputs.init_sockets(inputs)
  827. self.outputs.init_sockets(outputs)
  828. self.init_parameters()
  829. self.node_type = "UTILITY"
  830. def bPrepare(self, bContext = None,):
  831. self.parameters["X"] = self.evaluate_input("Vector")[0]
  832. self.parameters["Y"] = self.evaluate_input("Vector")[1]
  833. self.parameters["Z"] = self.evaluate_input("Vector")[2]
  834. self.prepared = True
  835. self.executed = True
  836. class UtilityCatStrings(MantisNode):
  837. '''A node representing an armature object'''
  838. def __init__(self, signature, base_tree):
  839. super().__init__(signature, base_tree)
  840. inputs = [
  841. "String_1" ,
  842. "String_2" ,
  843. ]
  844. outputs = [
  845. "OutputString" ,
  846. ]
  847. self.inputs.init_sockets(inputs)
  848. self.outputs.init_sockets(outputs)
  849. self.init_parameters()
  850. self.node_type = "UTILITY"
  851. def bPrepare(self, bContext = None,):
  852. self.parameters["OutputString"] = self.evaluate_input("String_1")+self.evaluate_input("String_2")
  853. self.prepared = True
  854. self.executed = True
  855. class InputExistingGeometryObject(MantisNode):
  856. '''A node representing an existing object'''
  857. def __init__(self, signature, base_tree):
  858. super().__init__(signature, base_tree)
  859. inputs = [
  860. "Name" ,
  861. ]
  862. outputs = [
  863. "Object" ,
  864. ]
  865. self.inputs.init_sockets(inputs)
  866. self.outputs.init_sockets(outputs)
  867. self.init_parameters()
  868. self.node_type = "XFORM"
  869. def bPrepare(self, bContext=None):
  870. from bpy import data
  871. name = self.evaluate_input("Name")
  872. if name:
  873. self.bObject = data.objects.get( name )
  874. else:
  875. self.bObject = None
  876. if self is None and (name := self.evaluate_input("Name")):
  877. prRed(f"No object found with name {name} in {self}")
  878. self.prepared = True; self.executed = True
  879. def bGetObject(self, mode=''):
  880. return self.bObject
  881. class InputExistingGeometryData(MantisNode):
  882. '''A node representing existing object data'''
  883. def __init__(self, signature, base_tree):
  884. super().__init__(signature, base_tree)
  885. inputs = [
  886. "Name" ,
  887. ]
  888. outputs = [
  889. "Geometry" ,
  890. ]
  891. self.inputs.init_sockets(inputs)
  892. self.outputs.init_sockets(outputs)
  893. self.init_parameters()
  894. self.node_type = "UTILITY"
  895. self.prepared = True
  896. self.executed = True
  897. # the mode argument is only for interface consistency
  898. def bGetObject(self, mode=''):
  899. from bpy import data
  900. # first try Curve, then try Mesh
  901. bObject = data.curves.get(self.evaluate_input("Name"))
  902. if not bObject:
  903. bObject = data.meshes.get(self.evaluate_input("Name"))
  904. if bObject is None:
  905. raise RuntimeError(f"Could not find a mesh or curve datablock named \"{self.evaluate_input('Name')}\" for node {self}")
  906. return bObject
  907. class UtilityGeometryOfXForm(MantisNode):
  908. '''A node representing existing object data'''
  909. def __init__(self, signature, base_tree):
  910. super().__init__(signature, base_tree)
  911. inputs = [
  912. "xForm" ,
  913. ]
  914. outputs = [
  915. "Geometry" ,
  916. ]
  917. self.inputs.init_sockets(inputs)
  918. self.outputs.init_sockets(outputs)
  919. self.init_parameters()
  920. self.node_type = "UTILITY"
  921. self.prepared = True
  922. self.executed = True
  923. # mode for interface consistency
  924. def bGetObject(self, mode=''):
  925. if not (self.inputs.get('xForm') and self.inputs['xForm'].links):
  926. prOrange(f"WARN: Cannot retrieve data from {self}, there is no xForm node connected.")
  927. return None
  928. xf = self.inputs["xForm"].links[0].from_node
  929. if xf.node_type == 'XFORM':
  930. xf_ob = xf.bGetObject()
  931. if xf_ob.type in ['MESH', 'CURVE']:
  932. return xf_ob.data
  933. prOrange(f"WARN: Cannot retrieve data from {self}, the connected xForm is not a mesh or curve.")
  934. return None
  935. class UtilityNameOfXForm(MantisNode):
  936. '''A node representing existing object data'''
  937. def __init__(self, signature, base_tree):
  938. super().__init__(signature, base_tree)
  939. inputs = [
  940. "xForm" ,
  941. ]
  942. outputs = [
  943. "Name" ,
  944. ]
  945. self.inputs.init_sockets(inputs)
  946. self.outputs.init_sockets(outputs)
  947. self.init_parameters()
  948. self.node_type = "UTILITY"
  949. # mode for interface consistency
  950. def bPrepare(self, bContext = None,):
  951. if not (self.inputs.get('xForm') and self.inputs['xForm'].links):
  952. prOrange(f"WARN: Cannot retrieve data from {self}, there is no xForm node connected.")
  953. return ''
  954. xf = self.inputs["xForm"].links[0].from_node
  955. self.parameters["Name"] = xf.evaluate_input('Name')
  956. self.prepared, self.executed = True, True
  957. class UtilityGetBoneLength(MantisNode):
  958. '''A node to get the length of a bone matrix'''
  959. def __init__(self, signature, base_tree):
  960. super().__init__(signature, base_tree)
  961. inputs = [
  962. "Bone Matrix" ,
  963. ]
  964. outputs = [
  965. "Bone Length" ,
  966. ]
  967. self.inputs.init_sockets(inputs)
  968. self.outputs.init_sockets(outputs)
  969. self.init_parameters()
  970. self.node_type = "UTILITY"
  971. def bPrepare(self, bContext = None,):
  972. if l := self.evaluate_input("Bone Matrix"):
  973. self.parameters["Bone Length"] = l[3][3]
  974. self.prepared = True
  975. self.executed = True
  976. class UtilityPointFromBoneMatrix(MantisNode):
  977. '''A node representing an armature object'''
  978. def __init__(self, signature, base_tree):
  979. super().__init__(signature, base_tree)
  980. inputs = [
  981. "Bone Matrix" ,
  982. "Head/Tail" ,
  983. ]
  984. outputs = [
  985. "Point" ,
  986. ]
  987. self.inputs.init_sockets(inputs)
  988. self.outputs.init_sockets(outputs)
  989. self.init_parameters()
  990. self.node_type = "UTILITY"
  991. # TODO: find out why this is sometimes not ready at bPrepare phase
  992. def bPrepare(self, bContext = None,):
  993. from mathutils import Vector
  994. matrix = self.evaluate_input("Bone Matrix")
  995. head, rotation, _scale = matrix.copy().decompose()
  996. tail = head.copy() + (rotation @ Vector((0,1,0)))*matrix[3][3]
  997. self.parameters["Point"] = head.lerp(tail, self.evaluate_input("Head/Tail"))
  998. self.prepared = True
  999. self.executed = True
  1000. class UtilitySetBoneLength(MantisNode):
  1001. '''Sets the length of a Bone's matrix'''
  1002. def __init__(self, signature, base_tree):
  1003. super().__init__(signature, base_tree)
  1004. inputs = [
  1005. "Bone Matrix" ,
  1006. "Length" ,
  1007. ]
  1008. outputs = [
  1009. "Bone Matrix" ,
  1010. ]
  1011. self.inputs.init_sockets(inputs)
  1012. self.outputs.init_sockets(outputs)
  1013. self.init_parameters()
  1014. self.node_type = "UTILITY"
  1015. def bPrepare(self, bContext = None,):
  1016. from mathutils import Vector
  1017. if matrix := self.evaluate_input("Bone Matrix"):
  1018. matrix = matrix.copy()
  1019. # print (self.inputs["Length"].links)
  1020. matrix[3][3] = self.evaluate_input("Length")
  1021. self.parameters["Length"] = self.evaluate_input("Length")
  1022. self.parameters["Bone Matrix"] = matrix
  1023. self.prepared = True
  1024. self.executed = True
  1025. class UtilityMatrixSetLocation(MantisNode):
  1026. '''Sets the location of a matrix'''
  1027. def __init__(self, signature, base_tree):
  1028. super().__init__(signature, base_tree)
  1029. inputs = [
  1030. "Matrix" ,
  1031. "Location" ,
  1032. ]
  1033. outputs = [
  1034. "Matrix" ,
  1035. ]
  1036. self.inputs.init_sockets(inputs)
  1037. self.outputs.init_sockets(outputs)
  1038. self.init_parameters()
  1039. self.node_type = "UTILITY"
  1040. def bPrepare(self, bContext = None,):
  1041. from mathutils import Vector
  1042. if matrix := self.evaluate_input("Matrix"):
  1043. matrix = matrix.copy()
  1044. # print (self.inputs["Length"].links)
  1045. loc = self.evaluate_input("Location")
  1046. matrix[0][3] = loc[0]; matrix[1][3] = loc[1]; matrix[2][3] = loc[2]
  1047. self.parameters["Matrix"] = matrix
  1048. self.prepared = True
  1049. self.executed = True
  1050. class UtilityMatrixGetLocation(MantisNode):
  1051. '''Gets the location of a matrix'''
  1052. def __init__(self, signature, base_tree):
  1053. super().__init__(signature, base_tree)
  1054. inputs = [
  1055. "Matrix" ,
  1056. ]
  1057. outputs = [
  1058. "Location" ,
  1059. ]
  1060. self.inputs.init_sockets(inputs)
  1061. self.outputs.init_sockets(outputs)
  1062. self.init_parameters()
  1063. self.node_type = "UTILITY"
  1064. def bPrepare(self, bContext = None,):
  1065. from mathutils import Vector
  1066. if matrix := self.evaluate_input("Matrix"):
  1067. self.parameters["Location"] = matrix.to_translation()
  1068. self.prepared = True; self.executed = True
  1069. class UtilityMatrixFromXForm(MantisNode):
  1070. """Returns the matrix of the given xForm node."""
  1071. def __init__(self, signature, base_tree):
  1072. super().__init__(signature, base_tree)
  1073. inputs = [
  1074. "xForm" ,
  1075. ]
  1076. outputs = [
  1077. "Matrix" ,
  1078. ]
  1079. self.node_type = "UTILITY"
  1080. self.inputs.init_sockets(inputs)
  1081. self.outputs.init_sockets(outputs)
  1082. self.init_parameters()
  1083. def GetxForm(self):
  1084. trace = trace_single_line(self, "xForm")
  1085. for node in trace[0]:
  1086. if (node.node_type == 'XFORM'):
  1087. return node
  1088. raise GraphError("%s is not connected to an xForm" % self)
  1089. def bPrepare(self, bContext = None,):
  1090. from mathutils import Vector, Matrix
  1091. self.parameters["Matrix"] = Matrix.Identity(4)
  1092. if matrix := self.GetxForm().parameters.get("Matrix"):
  1093. self.parameters["Matrix"] = matrix.copy()
  1094. elif hasattr(self.GetxForm().bObject, "matrix"):
  1095. self.parameters["Matrix"] = self.GetxForm().bObject.matrix.copy()
  1096. elif hasattr(self.GetxForm().bObject, "matrix_world"):
  1097. self.parameters["Matrix"] = self.GetxForm().bObject.matrix_world.copy()
  1098. else:
  1099. prRed(f"Could not find matrix for {self} - check if the referenced object exists.")
  1100. self.prepared = True; self.executed = True
  1101. class UtilityAxesFromMatrix(MantisNode):
  1102. """Returns the axes of the given matrix."""
  1103. def __init__(self, signature, base_tree):
  1104. super().__init__(signature, base_tree)
  1105. inputs = [
  1106. "Matrix" ,
  1107. ]
  1108. outputs = [
  1109. "X Axis" ,
  1110. "Y Axis" ,
  1111. "Z Axis" ,
  1112. ]
  1113. self.inputs.init_sockets(inputs)
  1114. self.outputs.init_sockets(outputs)
  1115. self.init_parameters()
  1116. self.node_type = "UTILITY"
  1117. def bPrepare(self, bContext = None,):
  1118. from mathutils import Vector
  1119. if matrix := self.evaluate_input("Matrix"):
  1120. matrix= matrix.copy().to_3x3()
  1121. self.parameters['X Axis'] = matrix @ Vector((1,0,0))
  1122. self.parameters['Y Axis'] = matrix @ Vector((0,1,0))
  1123. self.parameters['Z Axis'] = matrix @ Vector((0,0,1))
  1124. self.prepared = True; self.executed = True
  1125. class UtilityBoneMatrixHeadTailFlip(MantisNode):
  1126. def __init__(self, signature, base_tree):
  1127. super().__init__(signature, base_tree)
  1128. inputs = [
  1129. "Bone Matrix" ,
  1130. ]
  1131. outputs = [
  1132. "Bone Matrix" ,
  1133. ]
  1134. self.inputs.init_sockets(inputs)
  1135. self.outputs.init_sockets(outputs)
  1136. self.init_parameters()
  1137. self.node_type = "UTILITY"
  1138. def bPrepare(self, bContext = None,):
  1139. from mathutils import Vector, Matrix, Quaternion
  1140. from bpy.types import Bone
  1141. if matrix := self.evaluate_input("Bone Matrix"):
  1142. axis, roll = Bone.AxisRollFromMatrix(matrix.to_3x3())
  1143. new_mat = Bone.MatrixFromAxisRoll(-1*axis, roll)
  1144. length = matrix[3][3]
  1145. new_mat.resize_4x4() # last column contains
  1146. new_mat[0][3] = matrix[0][3] + axis[0]*length # x location
  1147. new_mat[1][3] = matrix[1][3] + axis[1]*length # y location
  1148. new_mat[2][3] = matrix[2][3] + axis[2]*length # z location
  1149. new_mat[3][3] = length # length
  1150. self.parameters["Bone Matrix"] = new_mat
  1151. self.prepared, self.executed = True, True
  1152. class UtilityMatrixTransform(MantisNode):
  1153. def __init__(self, signature, base_tree):
  1154. super().__init__(signature, base_tree)
  1155. inputs = [
  1156. "Matrix 1" ,
  1157. "Matrix 2" ,
  1158. ]
  1159. outputs = [
  1160. "Out Matrix" ,
  1161. ]
  1162. self.inputs.init_sockets(inputs)
  1163. self.outputs.init_sockets(outputs)
  1164. self.init_parameters()
  1165. self.node_type = "UTILITY"
  1166. def bPrepare(self, bContext = None,):
  1167. from mathutils import Vector
  1168. mat1 = self.evaluate_input("Matrix 1"); mat2 = self.evaluate_input("Matrix 2")
  1169. if mat1 and mat2:
  1170. mat1copy = mat1.copy()
  1171. self.parameters["Out Matrix"] = mat2 @ mat1copy
  1172. self.parameters["Out Matrix"].translation = mat1copy.to_translation()+ mat2.to_translation()
  1173. else:
  1174. raise RuntimeError(wrapRed(f"Node {self} did not receive all matrix inputs... found input 1? {mat1 is not None}, 2? {mat2 is not None}"))
  1175. self.prepared = True
  1176. self.executed = True
  1177. class UtilityTransformationMatrix(MantisNode):
  1178. def __init__(self, signature, base_tree):
  1179. super().__init__(signature, base_tree)
  1180. inputs = [
  1181. "Operation" ,
  1182. "Vector" ,
  1183. "W" ,
  1184. ]
  1185. outputs = [
  1186. "Matrix" ,
  1187. ]
  1188. self.inputs.init_sockets(inputs)
  1189. self.outputs.init_sockets(outputs)
  1190. self.init_parameters()
  1191. self.node_type = "UTILITY"
  1192. def bPrepare(self, bContext = None,):
  1193. from mathutils import Matrix, Vector
  1194. if (operation := self.evaluate_input("Operation")) == 'ROTATE_AXIS_ANGLE':
  1195. # this can, will, and should fail if the axis is 0,0,0
  1196. self.parameters["Matrix"] = rotMat = Matrix.Rotation(self.evaluate_input("W"), 4, Vector(self.evaluate_input("Vector")).normalized())
  1197. elif (operation := self.evaluate_input("Operation")) == 'TRANSLATE':
  1198. m = Matrix.Identity(4)
  1199. if axis := self.evaluate_input("Vector"):
  1200. m[0][3]=axis[0];m[1][3]=axis[1];m[2][3]=axis[2]
  1201. self.parameters['Matrix'] = m
  1202. elif (operation := self.evaluate_input("Operation")) == 'SCALE':
  1203. self.parameters["Matrix"] = Matrix.Scale(self.evaluate_input("W"), 4, Vector(self.evaluate_input("Vector")).normalized())
  1204. else:
  1205. raise NotImplementedError(self.evaluate_input("Operation").__repr__()+ " Operation not yet implemented.")
  1206. self.prepared = True
  1207. self.executed = True
  1208. class UtilityIntToString(MantisNode):
  1209. def __init__(self, signature, base_tree):
  1210. super().__init__(signature, base_tree)
  1211. inputs = [
  1212. "Number" ,
  1213. "Zero Padding" ,
  1214. ]
  1215. outputs = [
  1216. "String" ,
  1217. ]
  1218. self.inputs.init_sockets(inputs)
  1219. self.outputs.init_sockets(outputs)
  1220. self.init_parameters()
  1221. self.node_type = "UTILITY"
  1222. def bPrepare(self, bContext = None,):
  1223. number = self.evaluate_input("Number")
  1224. zeroes = self.evaluate_input("Zero Padding")
  1225. # I'm casting to int because I want to support any number, even though the node asks for int.
  1226. self.parameters["String"] = str(int(number)).zfill(int(zeroes))
  1227. self.prepared = True
  1228. self.executed = True
  1229. class UtilityArrayGet(MantisNode):
  1230. def __init__(self, signature, base_tree):
  1231. super().__init__(signature, base_tree)
  1232. inputs = [
  1233. "Index" ,
  1234. "OoB Behaviour" ,
  1235. "Array" ,
  1236. ]
  1237. outputs = [
  1238. "Output" ,
  1239. ]
  1240. self.inputs.init_sockets(inputs)
  1241. self.outputs.init_sockets(outputs)
  1242. self.init_parameters()
  1243. self.node_type = "UTILITY"
  1244. def bPrepare(self, bContext = None,):
  1245. if self.prepared == False:
  1246. # sort the array entries
  1247. for inp in self.inputs.values():
  1248. inp.links.sort(key=lambda a : -a.multi_input_sort_id)
  1249. oob = self.evaluate_input("OoB Behaviour")
  1250. index = self.evaluate_input("Index")
  1251. from .utilities import cap, wrap
  1252. # we must assume that the array has sent the correct number of links
  1253. if oob == 'WRAP':
  1254. index = index % len(self.inputs['Array'].links)
  1255. if oob == 'HOLD':
  1256. index = cap(index, len(self.inputs['Array'].links)-1)
  1257. # relink the connections and then kill all the links to and from the array
  1258. from .utilities import init_connections, init_dependencies
  1259. l = self.inputs["Array"].links[index]
  1260. for link in self.outputs["Output"].links:
  1261. to_node = link.to_node
  1262. l.from_node.outputs[l.from_socket].connect(to_node, link.to_socket)
  1263. link.die()
  1264. init_dependencies(to_node)
  1265. from_node=l.from_node
  1266. for inp in self.inputs.values():
  1267. for l in inp.links:
  1268. l.die()
  1269. init_connections(from_node)
  1270. if self in from_node.hierarchy_connections:
  1271. raise RuntimeError()
  1272. # this is intentional because the Array Get is kind of a weird hybrid between a Utility and a Schema
  1273. # so it should be removed from the tree when it is done. it has already dealt with the actual links.
  1274. # however I think this is redundant. Check.
  1275. self.hierarchy_connections, self.connections = [], []
  1276. self.hierarchy_dependencies, self.dependencies = [], []
  1277. self.prepared = True
  1278. self.executed = True
  1279. class UtilitySetBoneMatrixTail(MantisNode):
  1280. def __init__(self, signature, base_tree):
  1281. super().__init__(signature, base_tree)
  1282. inputs = {
  1283. "Matrix" ,
  1284. "Tail Location" ,
  1285. }
  1286. outputs = [
  1287. "Result" ,
  1288. ]
  1289. self.inputs.init_sockets(inputs)
  1290. self.outputs.init_sockets(outputs)
  1291. self.init_parameters()
  1292. self.node_type = "UTILITY"
  1293. def bPrepare(self, bContext = None,):
  1294. from mathutils import Matrix
  1295. matrix = self.evaluate_input("Matrix")
  1296. if matrix is None: matrix = Matrix.Identity(4)
  1297. #just do this for now lol
  1298. self.parameters["Result"] = matrix_from_head_tail(matrix.translation, self.evaluate_input("Tail Location"))
  1299. self.prepared = True
  1300. self.executed = True
  1301. class UtilityPrint(MantisNode):
  1302. def __init__(self, signature, base_tree):
  1303. super().__init__(signature, base_tree)
  1304. inputs = [
  1305. "Input" ,
  1306. ]
  1307. self.inputs.init_sockets(inputs)
  1308. self.outputs.init_sockets(outputs)
  1309. self.init_parameters()
  1310. self.node_type = "UTILITY"
  1311. def bPrepare(self, bContext = None,):
  1312. if my_input := self.evaluate_input("Input"):
  1313. print("Preparation phase: ", wrapWhite(self), wrapGreen(my_input))
  1314. # else:
  1315. # prRed("No input to print.")
  1316. self.prepared = True
  1317. def bExecute(self, bContext = None,):
  1318. if my_input := self.evaluate_input("Input"):
  1319. print("Execution phase: ", wrapWhite(self), wrapGreen(my_input))
  1320. # else:
  1321. # prRed("No input to print.")
  1322. self.executed = True
  1323. class UtilityCompare(MantisNode):
  1324. def __init__(self, signature, base_tree):
  1325. super().__init__(signature, base_tree)
  1326. inputs = [
  1327. "A" ,
  1328. "B" ,
  1329. ]
  1330. outputs = [
  1331. "Result" ,
  1332. ]
  1333. self.inputs.init_sockets(inputs)
  1334. self.outputs.init_sockets(outputs)
  1335. self.init_parameters()
  1336. self.node_type = "UTILITY"
  1337. def bPrepare(self, bContext = None,):
  1338. self.parameters["Result"] = self.evaluate_input("A") == self.evaluate_input("B")
  1339. self.prepared = True; self.executed = True
  1340. class UtilityChoose(MantisNode):
  1341. def __init__(self, signature, base_tree):
  1342. super().__init__(signature, base_tree)
  1343. inputs = [
  1344. "Condition" ,
  1345. "A" ,
  1346. "B" ,
  1347. ]
  1348. outputs = [
  1349. "Result" ,
  1350. ]
  1351. self.inputs.init_sockets(inputs)
  1352. self.outputs.init_sockets(outputs)
  1353. self.init_parameters()
  1354. self.node_type = "UTILITY"
  1355. def bPrepare(self, bContext = None,):
  1356. condition = self.evaluate_input("Condition")
  1357. if condition:
  1358. self.parameters["Result"] = self.evaluate_input("B")
  1359. else:
  1360. self.parameters["Result"] = self.evaluate_input("A")
  1361. self.prepared = True
  1362. self.executed = True