misc_nodes.py 75 KB

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