misc_nodes.py 79 KB

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