misc_nodes.py 83 KB

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