misc_nodes.py 77 KB

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