misc_nodes.py 54 KB

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