misc_nodes.py 74 KB

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