xForm_nodes.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. from .utilities.node_common import *
  2. from .base_definitions import MantisNode, NodeSocket
  3. from .xForm_socket_templates import *
  4. from .mantis_dataclasses import xForm_info
  5. def TellClasses():
  6. return [
  7. # xForm
  8. xFormArmature,
  9. xFormBone,
  10. xFormGeometryObject,
  11. xFormObjectInstance,
  12. xFormCurvePin,
  13. xFormGetBone,
  14. ]
  15. #*#-------------------------------#++#-------------------------------#*#
  16. # X - F O R M N O D E S
  17. #*#-------------------------------#++#-------------------------------#*#
  18. def reset_object_data(ob):
  19. # moving this to a common function so I can figure out the details later
  20. ob.id_properties_clear() # we must remove the custom properties so we can make them again.
  21. ob.constraints.clear()
  22. ob.animation_data_clear() # this is a little dangerous. TODO find a better solution since this can wipe animation the user wants to keep
  23. ob.modifiers.clear() # I would also like a way to copy modifiers and their settings, or bake them down. oh well
  24. def get_parent_node(mantis_node, type = 'XFORM'):
  25. # type variable for selecting whether to get either
  26. # the parent xForm or the inheritance node
  27. node_line, _last_socket = trace_single_line(mantis_node, "Relationship")
  28. for i in range(len(node_line)):
  29. # check each of the possible parent types.
  30. if ( (node_line[ i ].__class__.__name__ == 'LinkInherit') ):
  31. try: # it's the next one
  32. if (type == 'XFORM'):
  33. return node_line[ i + 1 ]
  34. else: # type = 'LINK'
  35. return node_line[ i ]
  36. except IndexError: # if there is no next one...
  37. return None # then there's no parent!
  38. return None
  39. def get_matrix(node):
  40. matrix = node.evaluate_input('Matrix')
  41. if matrix is None:
  42. node_line, socket = trace_single_line(node, "Matrix")
  43. raise RuntimeError(wrapRed(f"No matrix found for Armature {node}"))
  44. return matrix
  45. def set_object_parent(node):
  46. from bpy import data
  47. parent_xForm_info = get_parent_xForm_info(node)
  48. if parent_xForm_info.object_type == '':
  49. return # no parent
  50. elif parent_xForm_info.object_type in ['armature', 'object']:
  51. parent = data.objects.get(parent_xForm_info.self_edit_name)
  52. if parent_xForm_info.parent_edit_name and parent is None:
  53. raise GraphError(f"Could not get parent object for node {node}.")
  54. node.bGetObject().parent = parent
  55. else: # it is a bone
  56. armOb = data.objects.get(parent_xForm_info.root_armature)
  57. node_ob = node.bGetObject()
  58. node_ob.parent = armOb; node_ob.parent_type = 'BONE'
  59. # this one expects a string.
  60. node_ob.parent_bone = parent_xForm_info.self_edit_name
  61. class xFormNode(MantisNode):
  62. def __init__(self, signature, base_tree, socket_templates=[]):
  63. super().__init__(signature, base_tree, socket_templates)
  64. self.node_type = 'XFORM'
  65. self.bObject=None
  66. # because new objects are created during prep phase
  67. def reset_execution(self):
  68. super().reset_execution()
  69. self.prepared=False
  70. def setup_custom_props(self, ob, input):
  71. from .mantis_dataclasses import custom_prop_template
  72. # detect custom inputs
  73. for i, l in enumerate(self.inputs[input].links):
  74. # we need to trace back all inputs
  75. custom_prop_data = self.evaluate_input(input, i)
  76. if not isinstance(custom_prop_data, custom_prop_template): continue
  77. from .utilities.drivers import MantisDriver
  78. name = custom_prop_data.name
  79. if name in ob.keys():
  80. raise RuntimeError("Error: cannot create a custom property with "
  81. "the same name as an existing property.")
  82. prop_type = custom_prop_data.prop_type
  83. match prop_type:
  84. case 'BOOL':
  85. value = custom_prop_data.default_value_bool
  86. case 'INT':
  87. value = custom_prop_data.default_value_int
  88. case 'FLOAT':
  89. value = custom_prop_data.default_value_float
  90. case 'VECTOR':
  91. value = custom_prop_data.default_value_vector
  92. case 'STRING':
  93. value = custom_prop_data.default_value_string
  94. if (value is None):
  95. raise RuntimeError("Could not set value of custom parameter")
  96. # it creates a more confusing error later sometimes, better to catch it here.
  97. ob[name] = value
  98. ui_data = ob.id_properties_ui(name)
  99. ui_data.update(
  100. default=value,
  101. description=custom_prop_data.description)
  102. #if a number, set the min/max values. it may overflow on the C side
  103. if type(value) in [float, int]:
  104. for prop_name in ['min', 'max', 'soft_min', 'soft_max', ]:
  105. prop_value = getattr(custom_prop_data, prop_name)
  106. if type(value) == int: prop_value = int(prop_value)
  107. # DO: figure out the right way to prevent an oveflow
  108. try: # we have to do this as a keyword argument like this
  109. ui_data.update( **{prop_name:prop_value} )
  110. except OverflowError: #this occurs when the value is inf
  111. prRed(f"invalid value {prop_value} for custom prop {prop_name}"
  112. f" of type {type(value)} in {self}. It will remain unset.")
  113. ob.property_overridable_library_set(f"[\"{name}\"]", True)
  114. pass
  115. class xFormArmature(xFormNode):
  116. '''A node representing an armature object'''
  117. def __init__(self, signature, base_tree):
  118. super().__init__(signature, base_tree, xFormArmatureSockets)
  119. self.init_parameters()
  120. self.set_traverse([("Relationship", "xForm Out")])
  121. setup_custom_property_inputs_outputs(self)
  122. def bPrepare(self, bContext=None):
  123. self.parameters['Matrix'] = get_matrix(self)
  124. self.prepared = True
  125. def bTransformPass(self, bContext = None,):
  126. # from .utilities import get_ui_node
  127. import bpy
  128. if (not isinstance(bContext, bpy.types.Context)):
  129. raise RuntimeError("Incorrect context")
  130. name = self.evaluate_input("Name")
  131. matrix = self.parameters['Matrix']
  132. reset_transforms = False
  133. #check if an object by the name exists
  134. if (name) and (ob := bpy.data.objects.get(name)):
  135. if (ob.animation_data):
  136. while (ob.animation_data.drivers):
  137. ob.animation_data.drivers.remove(ob.animation_data.drivers[-1])
  138. for pb in ob.pose.bones:
  139. # clear it, even after deleting the edit bones,
  140. # if we create them again the pose bones will be reused
  141. while (pb.constraints):
  142. pb.constraints.remove(pb.constraints[-1])
  143. if reset_transforms:
  144. pb.location = (0,0,0)
  145. pb.rotation_euler = (0,0,0)
  146. pb.rotation_quaternion = (1.0,0,0,0)
  147. pb.rotation_axis_angle = (0,0,1.0,0)
  148. pb.scale = (1.0,1.0,1.0)
  149. # feels ugly and bad, whatever
  150. collections = []
  151. for bc in ob.data.collections:
  152. collections.append(bc)
  153. for bc in collections:
  154. ob.data.collections.remove(bc)
  155. del collections
  156. # end ugly/bad
  157. else:
  158. # Create the Object
  159. ob = bpy.data.objects.new(name, bpy.data.armatures.new(name)) #create ob
  160. if (ob.name != name):
  161. raise RuntimeError("Could not create xForm object", name)
  162. # it seems this data sticks around even if the object was deleted, so clear it here.
  163. ob.id_properties_clear()
  164. self.bObject = ob.name
  165. ob.matrix_world = matrix.copy()
  166. ob.data.pose_position = 'REST'
  167. set_object_parent(self)
  168. # Link to Scene:
  169. if (ob.name not in bContext.view_layer.active_layer_collection.collection.objects):
  170. bContext.view_layer.active_layer_collection.collection.objects.link(ob)
  171. print( wrapGreen("Created Armature object: ")+ wrapWhite(ob.name))
  172. # Finalize the action
  173. # oddly, overriding context doesn't seem to work
  174. try:
  175. bpy.ops.object.select_all(action='DESELECT')
  176. except RuntimeError:
  177. pass # we're already in edit mode, should be OK to do this.
  178. bContext.view_layer.objects.active = ob
  179. selected=[]
  180. for other_ob in bpy.data.objects:
  181. if other_ob.mode == "EDIT":
  182. selected.append(other_ob)
  183. selected.append(ob)
  184. context_override = {"active_object":ob, "selected_objects":selected}
  185. print("Changing Armature Mode to " +wrapPurple("EDIT"))
  186. with bContext.temp_override(**context_override):
  187. bpy.ops.object.mode_set(mode='EDIT')
  188. if ob.mode != "EDIT":
  189. prRed("eh?")
  190. # clear it
  191. while (len(ob.data.edit_bones) > 0):
  192. ob.data.edit_bones.remove(ob.data.edit_bones[0])
  193. # bContext.view_layer.objects.active = prevAct
  194. # This will OVERWRITE the root armature since bones have to trace back to this one.
  195. root_armature = ob.name
  196. parent_xForm_info = get_parent_xForm_info(self)
  197. my_info = xForm_info(
  198. object_type='armature',
  199. root_armature= ob.name,
  200. parent_pose_name=parent_xForm_info.self_pose_name,
  201. parent_edit_name=parent_xForm_info.self_edit_name,
  202. self_pose_name=ob.name,
  203. self_edit_name=ob.name,
  204. )
  205. self.parameters['xForm Out'] = my_info
  206. self.executed = True
  207. def bFinalize(self, bContext = None):
  208. # custom properties
  209. self.setup_custom_props(self.bGetObject(), "Custom Properties")
  210. finish_drivers(self)
  211. def bGetObject(self, mode = ''):
  212. import bpy; return bpy.data.objects[self.parameters['xForm Out'].self_pose_name]
  213. class xFormBone(xFormNode):
  214. '''A node representing a bone in an armature'''
  215. # DO: make a way to identify which armature this belongs to
  216. def __init__(self, signature, base_tree):
  217. super().__init__(signature, base_tree, xFormBoneSockets)
  218. # TODO: implement socket templates completely for Bone
  219. # currently it is waiting on BBone and refactoring/cleanup.
  220. # the socket templates are being used now but not for mantis node execution.
  221. # because of edit/pose/objcet bone this will be a bit complex
  222. self.init_parameters()
  223. self.set_traverse([("Relationship", "xForm Out")])
  224. setup_custom_property_inputs_outputs(self)
  225. def bGetParentArmature(self):
  226. parent_xForm_info = get_parent_xForm_info(self)
  227. from bpy import data
  228. return data.objects.get(parent_xForm_info.root_armature)
  229. def bSetParent(self, eb):
  230. from bpy import data
  231. parent_xForm_info = get_parent_xForm_info(self)
  232. parent_armature = data.objects.get( parent_xForm_info.root_armature)
  233. if parent_xForm_info.self_edit_name != parent_xForm_info.root_armature:
  234. parent_bone = parent_armature.data.edit_bones.get( parent_xForm_info.self_edit_name)
  235. eb.parent = parent_bone
  236. parent_mantis_node = get_parent_node(self, type = 'LINK') # get the link node.
  237. # TODO probably need to send the parenting info or at least the signatures of intervening nodes.
  238. eb.use_connect = parent_mantis_node.evaluate_input("Connected")
  239. eb.use_inherit_rotation = parent_mantis_node.evaluate_input("Inherit Rotation")
  240. eb.inherit_scale = parent_mantis_node.evaluate_input("Inherit Scale")
  241. def bPrepare(self, bContext=None):
  242. self.parameters['Matrix'] = get_matrix(self)
  243. self.prepared = True
  244. def bTransformPass(self, bContext = None,): #possibly will need to pass context?
  245. import bpy
  246. from mathutils import Vector
  247. if not (name := self.evaluate_input("Name")):
  248. raise RuntimeError(wrapRed(f"Could not set name for bone in {self}"))
  249. if (not isinstance(bContext, bpy.types.Context)):
  250. raise RuntimeError("Incorrect context")
  251. if not (xF := self.bGetParentArmature()):
  252. raise RuntimeError("Could not create edit bone: ", name, " from node:", self, " Reason: No armature object to add bone to.")
  253. matrix = self.parameters['Matrix']
  254. length = matrix[3][3]
  255. if (xF):
  256. if (xF.mode != "EDIT"):
  257. raise RuntimeError("Armature Object Not in Edit Mode, exiting...")
  258. #
  259. # Create the Object
  260. d = xF.data
  261. eb = d.edit_bones.new(name)
  262. # Bone Collections:
  263. # We treat each separate string as a Bone Collection that this object belongs to
  264. # Bone Collections are fully qualified by their hierarchy.
  265. # Separate Strings with "|" and indicate hierarchy with ">". These are special characters.
  266. # NOTE: if the user names the collections differently at different times, this will take the FIRST definition and go with it
  267. if self.inputs['Bone Collection'].links:
  268. bCol_groups = []
  269. for i, l in enumerate(self.inputs['Bone Collection'].links):
  270. bCol_group = self.evaluate_input("Bone Collection", index=i)
  271. bCol_groups.append(bCol_group)
  272. bCols = '|'.join(bCol_groups)
  273. else:
  274. bCols = self.evaluate_input("Bone Collection")
  275. if bCols: # it is actually possible to add a bone to no collections. odd.
  276. bone_collections = bCols.split("|")
  277. for collection_list in bone_collections:
  278. hierarchy = collection_list.split(">")
  279. col_parent = None
  280. for bCol in hierarchy:
  281. if bCol is None: continue # I think this
  282. if bCol == '': continue
  283. if ( col := d.collections_all.get(bCol) ) is None:
  284. col = d.collections.new(bCol)
  285. col.parent = col_parent
  286. col_parent = col
  287. if hierarchy[-1]: # will be "" or None if the box is empty
  288. d.collections_all.get(hierarchy[-1]).assign(eb)
  289. if (eb.name != name):
  290. prRed(f"Expected bone of name: {name}, got {eb.name} instead.")
  291. raise RuntimeError("Could not create bone ", name, "; Perhaps there is a duplicate bone name in the node tree?")
  292. eb.matrix = matrix.copy()
  293. tailoffset = Vector((0,length,0)) #Vector((0,self.tailoffset, 0))
  294. tailoffset = matrix.copy().to_3x3() @ tailoffset
  295. eb.tail = eb.head + tailoffset
  296. if (eb.name != name):
  297. raise RuntimeError("Could not create edit bone: ", name)
  298. assert (eb.name), "Bone must have a name."
  299. self.bObject = eb.name
  300. # The bone should have relationships going in at this point.
  301. self.bSetParent(eb)
  302. if eb.head == eb.tail:
  303. raise RuntimeError(wrapRed(f"Could not create edit bone: {name} because bone head was located in the same place as bone tail."))
  304. # Setup Deform attributes...
  305. eb.use_deform = self.evaluate_input("Deform")
  306. eb.envelope_distance = self.evaluate_input("Envelope Distance")
  307. eb.envelope_weight = self.evaluate_input("Envelope Weight")
  308. eb.use_envelope_multiply = self.evaluate_input("Envelope Multiply")
  309. eb.head_radius = self.evaluate_input("Envelope Head Radius")
  310. eb.tail_radius = self.evaluate_input("Envelope Tail Radius")
  311. print( wrapGreen("Created Bone: ") + wrapOrange(eb.name) + wrapGreen(" in ") + wrapWhite(self.bGetParentArmature().name))
  312. parent_xForm_info = get_parent_xForm_info(self)
  313. my_info = xForm_info(
  314. object_type='bone',
  315. root_armature= xF.name,
  316. parent_pose_name=parent_xForm_info.self_pose_name,
  317. parent_edit_name=parent_xForm_info.self_edit_name,
  318. self_pose_name=eb.name,
  319. self_edit_name=eb.name,
  320. )
  321. self.parameters['xForm Out'] = my_info
  322. self.executed = True
  323. def set_bone_color(self, b, inherit_color, bContext):
  324. color_values = self.evaluate_input('Color')
  325. if color_values is None:
  326. prOrange(f"Warning: No color information found for {b.name}. This should not happen.")
  327. return
  328. if inherit_color and b.parent:
  329. b.color.palette=b.parent.color.palette
  330. if b.color.palette == 'CUSTOM':
  331. b.color.custom.active=b.parent.color.custom.active
  332. b.color.custom.normal=b.parent.color.custom.normal
  333. b.color.custom.select=b.parent.color.custom.select
  334. return
  335. from mathutils import Color
  336. color_active = Color(color_values[:3])
  337. color_normal = Color(color_values[3:6])
  338. color_select = Color(color_values[6:])
  339. is_theme_colors = False
  340. theme = bContext.preferences.themes[0]
  341. for i, color_set in enumerate(theme.bone_color_sets):
  342. if ((color_active == color_set.active) and
  343. (color_normal == color_set.normal) and
  344. (color_select == color_set.select) ):
  345. is_theme_colors=True; break
  346. if is_theme_colors: # add 1, not 0-indexed
  347. b.color.palette = 'THEME'+str(i+1).zfill(2)
  348. elif ((color_active == theme.view_3d.bone_pose_active) and
  349. (color_normal == theme.view_3d.bone_solid) and
  350. (color_select == theme.view_3d.bone_pose) ):
  351. b.color.palette = 'DEFAULT'
  352. else:
  353. b.color.palette = 'CUSTOM'
  354. b.color.custom.active=color_active
  355. b.color.custom.normal=color_normal
  356. b.color.custom.select=color_select
  357. def bFinalize(self, bContext = None):
  358. b = self.bGetParentArmature().data.bones[self.bObject]
  359. # let's do bone colors first
  360. inherit_color = self.evaluate_input("Inherit Color")
  361. if len(self.inputs['Color'].links) > 0:
  362. inherit_color = False # use the link instead
  363. # try: # just in case, this shouldn't cause a failure
  364. self.set_bone_color(b, inherit_color, bContext)
  365. # except Exception as e:
  366. # prRed("WARNING: failed to set color because of error, see report below:")
  367. # prOrange(e)
  368. #
  369. do_bb=False
  370. b.bbone_x = self.evaluate_input("BBone X Size"); b.bbone_x = max(b.bbone_x, 0.0002)
  371. b.bbone_z = self.evaluate_input("BBone Z Size"); b.bbone_z = max(b.bbone_z, 0.0002)
  372. if (segs := self.evaluate_input("BBone Segments")) > 1:
  373. do_bb=True
  374. b.bbone_segments = segs
  375. b.bbone_x = self.evaluate_input("BBone X Size")
  376. b.bbone_z = self.evaluate_input("BBone Z Size")
  377. if self.evaluate_input("BBone HQ Deformation"):
  378. b.bbone_mapping_mode = "CURVED"
  379. # 'bbone_handle_type_start' : ("BBone Start Handle Type", "AUTO"),
  380. # 'bbone_handle_type_end' : ("BBone End Handle Type", "AUTO"),
  381. # 'bbone_custom_handle_start' : ("BBone Custom Start Handle", "AUTO"),
  382. # 'bbone_custom_handle_end' : ("BBone Custom End Handle", "AUTO"),
  383. if handle_type := self.evaluate_input("BBone Start Handle Type"):
  384. b.bbone_handle_type_start = handle_type
  385. if handle_type := self.evaluate_input("BBone End Handle Type"):
  386. b.bbone_handle_type_end = handle_type
  387. try:
  388. if (custom_handle := self.evaluate_input("BBone Custom Start Handle")):
  389. b.bbone_custom_handle_start = self.bGetParentArmature().data.bones[custom_handle]
  390. if (custom_handle := self.evaluate_input("BBone Custom End Handle")):
  391. b.bbone_custom_handle_end = self.bGetParentArmature().data.bones[custom_handle]
  392. except KeyError:
  393. prRed("Warning: BBone start or end handle not set because of missing bone in armature.")
  394. bone_props_socket= {
  395. 'bbone_curveinx' : ("BBone X Curve-In", 0.0),
  396. 'bbone_curveinz' : ("BBone Z Curve-In", 0.0),
  397. 'bbone_curveoutx' : ("BBone X Curve-Out", 0.0),
  398. 'bbone_curveoutz' : ("BBone Z Curve-Out", 0.0),
  399. }
  400. evaluate_sockets(self, b, bone_props_socket)
  401. # TODO this section should be done with props-socket thing
  402. b.bbone_handle_use_scale_start = self.evaluate_input("BBone Start Handle Scale")
  403. b.bbone_handle_use_scale_end = self.evaluate_input("BBone End Handle Scale")
  404. import bpy
  405. pb = self.bGetParentArmature().pose.bones[self.bObject]
  406. rotation_mode = self.evaluate_input("Rotation Order")
  407. if rotation_mode == "AUTO": rotation_mode = "XYZ"
  408. pb.rotation_mode = rotation_mode
  409. pb.id_properties_clear()
  410. self.setup_custom_props(pb, "Custom Properties")
  411. if (pb.is_in_ik_chain):
  412. # this props_socket thing wasn't really meant to work here but it does, neat
  413. props_sockets = {
  414. 'ik_stretch' : ("IK Stretch", 0),
  415. 'lock_ik_x' : (("Lock IK", 0), False),
  416. 'lock_ik_y' : (("Lock IK", 1), False),
  417. 'lock_ik_z' : (("Lock IK", 2), False),
  418. 'ik_stiffness_x' : (("IK Stiffness", 0), 0.0),
  419. 'ik_stiffness_y' : (("IK Stiffness", 1), 0.0),
  420. 'ik_stiffness_z' : (("IK Stiffness", 2), 0.0),
  421. 'use_ik_limit_x' : (("Limit IK", 0), False),
  422. 'use_ik_limit_y' : (("Limit IK", 1), False),
  423. 'use_ik_limit_z' : (("Limit IK", 2), False),
  424. 'ik_min_x' : ("X Min", 0),
  425. 'ik_max_x' : ("X Max", 0),
  426. 'ik_min_y' : ("Y Min", 0),
  427. 'ik_max_y' : ("Y Max", 0),
  428. 'ik_min_z' : ("Z Min", 0),
  429. 'ik_max_z' : ("Z Max", 0),
  430. }
  431. evaluate_sockets(self, pb, props_sockets)
  432. if do_bb:
  433. props_sockets = {
  434. 'bbone_curveinx' : ("BBone X Curve-In", pb.bone.bbone_curveinx),
  435. 'bbone_curveinz' : ("BBone Z Curve-In", pb.bone.bbone_curveinz),
  436. 'bbone_curveoutx' : ("BBone X Curve-Out", pb.bone.bbone_curveoutx),
  437. 'bbone_curveoutz' : ("BBone Z Curve-Out", pb.bone.bbone_curveoutz),
  438. 'bbone_easein' : ("BBone Ease-In", 0),
  439. 'bbone_easeout' : ("BBone Ease-Out", 0),
  440. 'bbone_rollin' : ("BBone Roll-In", 0),
  441. 'bbone_rollout' : ("BBone Roll-Out", 0),
  442. 'bbone_scalein' : ("BBone Scale-In", (1,1,1)),
  443. 'bbone_scaleout' : ("BBone Scale-Out", (1,1,1)),
  444. }
  445. evaluate_sockets(self, pb, props_sockets)
  446. # we need to clear this stuff since our only real goal was to get some drivers from the above
  447. for attr_name in props_sockets.keys():
  448. try:
  449. setattr(pb, attr_name, 0) # just clear it
  450. except (ValueError, TypeError): # Blender 5.2 raises TypeError for scalar -> vector
  451. setattr(pb, attr_name, (1.0,1.0,1.0)) # scale needs to be set to 1
  452. # important TODO... all of the drivers and stuff should be handled this way, right?
  453. # time to set up drivers!
  454. # just gonna add this to the end and build off it I guess
  455. props_sockets = {
  456. "lock_location" : ("Lock Location", [False, False, False]),
  457. "lock_rotation" : ("Lock Rotation", [False, False, False]),
  458. "lock_scale" : ("Lock Scale", [False, False, False]),
  459. 'custom_shape_scale_xyz' : ("Custom Object Scale", (0.0,0.0,0.0) ),
  460. 'custom_shape_translation' : ("Custom Object Translation", (0.0,0.0,0.0) ),
  461. 'custom_shape_rotation_euler' : ("Custom Object Rotation", (0.0,0.0,0.0) ),
  462. 'use_custom_shape_bone_size' : ("Custom Object Scale to Bone Length", True,),
  463. }
  464. # in 5.0.0 and newer I have to do pose bone, this is an error in < 5.0
  465. if bpy_version >=(5,0,0):
  466. props_sockets['hide'] = ("Hide", False)
  467. evaluate_sockets(self, pb, props_sockets)
  468. # this could probably be moved to bTransformPass
  469. # TODO VERSIONING: newer (5.0+ ?) Blenders need to use PoseBone for this
  470. props_sockets = {
  471. 'hide' : ("Hide", False),
  472. 'show_wire' : ("Custom Object Wireframe", False),
  473. }
  474. evaluate_sockets(self, pb.bone, props_sockets)
  475. # whatever I was doing there.... was stupid. CLEAN UP TODO
  476. # this is the right thing to do.
  477. finish_drivers(self)
  478. #
  479. # OK, visual settings
  480. #
  481. # Get the override xform's bone:
  482. pb.custom_shape_transform = None
  483. pb.custom_shape = None
  484. if len(self.inputs["Custom Object xForm Override"].links) > 0:
  485. trace = trace_single_line(self, "Custom Object xForm Override")
  486. try:
  487. pb.custom_shape_transform = trace[0][1].bGetObject()
  488. except AttributeError:
  489. pass
  490. if len(self.inputs["Custom Object"].links) > 0:
  491. trace = trace_single_line(self, "Custom Object")
  492. try:
  493. ob = trace[0][1].bGetObject()
  494. except AttributeError:
  495. ob=None
  496. if type(ob) in [bpy.types.Object]:
  497. pb.custom_shape = ob
  498. def bGetObject(self, mode = 'POSE'):
  499. if self.bObject is None: return None
  500. if mode in ["POSE", "OBJECT"] and self.bGetParentArmature().mode == "EDIT":
  501. raise RuntimeError("Cannot get Bone or PoseBone in Edit mode.")
  502. elif mode == "EDIT" and self.bGetParentArmature().mode != "EDIT":
  503. raise RuntimeError("Cannot get EditBone except in Edit mode.")
  504. try:
  505. if (mode == 'EDIT'):
  506. return self.bGetParentArmature().data.edit_bones[self.bObject]
  507. elif (mode == 'OBJECT'):
  508. return self.bGetParentArmature().data.bones[self.bObject]
  509. elif (mode == 'POSE'):
  510. return self.bGetParentArmature().pose.bones[self.bObject]
  511. except Exception as e:
  512. prRed ("Cannot get bone for %s" % self)
  513. raise e
  514. class xFormGeometryObject(xFormNode):
  515. '''A node representing an armature object'''
  516. def __init__(self, signature, base_tree):
  517. super().__init__(signature, base_tree, xFormGeometryObjectSockets)
  518. self.init_parameters()
  519. self.set_traverse([("Relationship", "xForm Out")])
  520. self.has_shape_keys = False
  521. setup_custom_property_inputs_outputs(self)
  522. def bPrepare(self, bContext = None,):
  523. import bpy
  524. if not self.evaluate_input("Name"):
  525. self.prepared = True
  526. self.executed = True
  527. # and return an error if there are any dependencies:
  528. if self.hierarchy_connections:
  529. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  530. return
  531. self.bObject = bpy.data.objects.get(self.evaluate_input("Name"))
  532. trace = trace_single_line(self, "Geometry")
  533. if (not self.bObject):
  534. if trace[-1]:
  535. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), trace[-1].node.bGetObject())
  536. # handle mismatched data.
  537. data_wrong = False; data = None
  538. if (self.inputs["Geometry"].is_linked and self.bObject.type == "EMPTY"):
  539. data_wrong = True; data = trace[-1].node.bGetObject()
  540. elif (not self.inputs["Geometry"].is_linked and not self.bObject.type == "EMPTY"):
  541. data_wrong = True
  542. # clumsy but functional
  543. if data_wrong:
  544. unlink_me = self.bObject
  545. unlink_me.name = "MANTIS_TRASH.000"
  546. for col in unlink_me.users_collection:
  547. col.objects.unlink(unlink_me)
  548. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), data)
  549. if self.bObject and (self.inputs["Geometry"].is_linked and self.bObject.type in ["MESH", "CURVE"]):
  550. self.bObject.data = trace[-1].node.bGetObject()
  551. # NOW: find out if we need to duplicate the object data.
  552. dupe_data=False
  553. node_line = trace_single_line(self, "Deformer")[0]
  554. from .deformer_nodes import DeformerHook
  555. for deformer in node_line:
  556. if isinstance(deformer, DeformerHook) and \
  557. deformer.evaluate_input("Affect Curve Radius") == True and \
  558. self.bObject.type == 'CURVE':
  559. print(f"INFO: Duplicating data {self.bObject.data.name} in {self} so it can be used for drivers.")
  560. dupe_data=True; break
  561. if dupe_data:
  562. name = self.bObject.data.name
  563. # it has to be a curve
  564. data = bpy.data.curves.get(self.bObject.data.name+"_MANTIS")
  565. if data: # Delete it and regenerate it if it exists.
  566. data.name+="_TRASH.000" # but we can't actually delete it here
  567. # since previous executions of the graph may be using it.
  568. # instead, we'll rename it and use a new copy. This will probably
  569. # be deleted on its own by Blender's garbage collector.
  570. # if it isn't, then it is still in use and I may NOT touch it.
  571. data=self.bObject.data.copy(); data.animation_data_clear()
  572. data.name = name+"_MANTIS"
  573. self.bObject.data = data
  574. reset_object_data(self.bObject)
  575. matrix= get_matrix(self)
  576. self.parameters['Matrix'] = matrix
  577. try:
  578. set_object_parent(self)
  579. except: # I guess it isn't ready yet. we'll do it later
  580. pass # (This can happen when solving schema.)
  581. self.bObject.matrix_world = matrix
  582. parent_xForm_info = get_parent_xForm_info(self)
  583. root_armature = parent_xForm_info.root_armature
  584. my_info = xForm_info(
  585. object_type='object',
  586. root_armature= root_armature,
  587. parent_pose_name=parent_xForm_info.self_edit_name,
  588. parent_edit_name=parent_xForm_info.self_pose_name,
  589. self_pose_name=self.bObject.name,
  590. self_edit_name=self.bObject.name,
  591. )
  592. self.parameters['xForm Out'] = my_info
  593. self.prepared = True
  594. def bTransformPass(self, bContext = None,):
  595. try:
  596. bContext.collection.objects.link(self.bObject)
  597. except RuntimeError: #already in; but a dangerous thing to pass.
  598. pass
  599. self.has_shape_keys = False
  600. # putting this in bTransformPass simply prevents it from being run more than once.
  601. # maybe I should do that with the rest of bPrepare, too.
  602. props_sockets = {
  603. 'hide_viewport' : ("Hide in Viewport", False),
  604. 'hide_render' : ("Hide in Render", False),
  605. }
  606. evaluate_sockets(self, self.bObject, props_sockets)
  607. self.executed = True
  608. def bFinalize(self, bContext = None):
  609. matrix= get_matrix(self)
  610. set_object_parent(self)
  611. self.bObject.matrix_world = matrix
  612. # custom properties
  613. self.setup_custom_props(self.bGetObject(), "Custom Properties")
  614. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  615. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  616. prOrange(driver_item)
  617. finish_drivers(self)
  618. def bGetObject(self, mode = 'POSE'):
  619. return self.bObject
  620. class xFormObjectInstance(xFormNode):
  621. """Represents an instance of an existing geometry object."""
  622. def __init__(self, signature, base_tree):
  623. super().__init__(signature, base_tree, xFormGeometryObjectInstanceSockets)
  624. self.init_parameters()
  625. # TODO: I think this field is a leftover from a test or something. see if it can be removed.
  626. self.links = {} # leave this empty for now!
  627. self.set_traverse([("Relationship", "xForm Out")])
  628. self.has_shape_keys = False # Shape Keys will make a dupe so this is OK
  629. setup_custom_property_inputs_outputs(self)
  630. def ui_modify_socket(self, ui_socket, socket_name=None):
  631. if ui_socket.name == 'As Instance':
  632. change_handled = True
  633. try:
  634. self.bObject.modifiers[0]['Socket_1'] = ui_socket.default_value
  635. except Exception as e:
  636. print("Failed to update mantis socket because of %s" % e,
  637. "Updating tree instead.")
  638. return change_handled
  639. else:
  640. return super().ui_modify_socket(ui_socket, socket_name)
  641. def bPrepare(self, bContext = None,):
  642. from bpy import data
  643. empty_mesh = data.meshes.get("MANTIS_EMPTY_MESH")
  644. if not empty_mesh:
  645. empty_mesh = data.meshes.new("MANTIS_EMPTY_MESH")
  646. if not self.evaluate_input("Name"):
  647. self.prepared = True
  648. self.executed = True
  649. # and return an error if there are any dependencies:
  650. if self.hierarchy_connections:
  651. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  652. return
  653. self.bObject = data.objects.get(self.evaluate_input("Name"))
  654. if (not self.bObject):
  655. self.bObject = data.objects.new(self.evaluate_input("Name"), empty_mesh)
  656. reset_object_data(self.bObject)
  657. matrix= get_matrix(self)
  658. self.parameters['Matrix'] = matrix
  659. set_object_parent(self)
  660. self.bObject.matrix_world = matrix
  661. parent_xForm_info = get_parent_xForm_info(self)
  662. root_armature = parent_xForm_info.root_armature
  663. my_info = xForm_info(
  664. object_type='object',
  665. root_armature= root_armature,
  666. parent_pose_name=parent_xForm_info.self_edit_name,
  667. parent_edit_name=parent_xForm_info.self_pose_name,
  668. self_pose_name=self.bObject.name,
  669. self_edit_name=self.bObject.name,
  670. )
  671. self.parameters['xForm Out'] = my_info
  672. self.prepared = True
  673. def bTransformPass(self, bContext = None,):
  674. try:
  675. bContext.collection.objects.link(self.bObject)
  676. except RuntimeError: #already in; but a dangerous thing to pass.
  677. pass
  678. self.has_shape_keys = False
  679. # putting this in bTransformPass simply prevents it from being run more than once.
  680. # maybe I should do that with the rest of bPrepare, too.
  681. props_sockets = {
  682. 'hide_viewport' : ("Hide in Viewport", False),
  683. 'hide_render' : ("Hide in Render", False),
  684. }
  685. evaluate_sockets(self, self.bObject, props_sockets)
  686. self.executed = True
  687. def bFinalize(self, bContext = None):
  688. # now we need to set the object instance up.
  689. from bpy import data
  690. trace = trace_single_line(self, "Source Object")
  691. for node in trace[0]:
  692. if node is self: continue # lol
  693. if (node.node_type == 'XFORM'):
  694. source_ob = node.bGetObject(); break
  695. modifier = self.bObject.modifiers.new("Object Instance", type='NODES')
  696. ng = data.node_groups.get("Object Instance")
  697. if ng is None:
  698. from .utilities.geometry_node_graphgen import gen_object_instance_node_group
  699. ng = gen_object_instance_node_group()
  700. modifier.node_group = ng
  701. modifier["Socket_0"] = source_ob
  702. modifier["Socket_1"] = self.evaluate_input("As Instance")
  703. # custom properties
  704. self.setup_custom_props(self.bGetObject(), "Custom Properties")
  705. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  706. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  707. prOrange(driver_item)
  708. finish_drivers(self)
  709. def bGetObject(self, mode = 'POSE'):
  710. return self.bObject
  711. class xFormCurvePin(xFormNode):
  712. """An xForm pinned to a specific location on a curve."""
  713. def __init__(self, signature, base_tree):
  714. super().__init__(signature, base_tree,xFormCurvePinSockets)
  715. self.init_parameters(additional_parameters={"Matrix":None})
  716. setup_custom_property_inputs_outputs(self)
  717. def prep_driver_values(self, constraint):
  718. from .misc_nodes import UtilityDriver, UtilitySwitch
  719. for socket_name in ["Curve Pin Factor", "Forward Axis","Up Axis",]:
  720. if self.inputs.get(socket_name) is None: continue # in case it has been bypassed
  721. if self.inputs[socket_name].is_linked:
  722. node_line, _last_socket = trace_single_line(self, socket_name)
  723. driver = None
  724. for other_node in node_line:
  725. if other_node.node_type == 'DRIVER':
  726. driver = other_node; break
  727. if isinstance(driver, UtilityDriver):
  728. prop_amount = driver.evaluate_input("Property")
  729. elif isinstance(driver, UtilitySwitch):
  730. xf=driver.GetxForm()
  731. prop_amount = xf.evaluate_input(driver.evaluate_input('Parameter'))
  732. else:
  733. return
  734. for template in self.socket_templates:
  735. if template.name == socket_name: break
  736. setattr(constraint, template.blender_property, prop_amount )
  737. def bPrepare(self, bContext = None,):
  738. from bpy import data
  739. if not bContext: # lol
  740. import bpy
  741. bContext = bpy.context
  742. ob = data.objects.get(self.evaluate_input("Name"))
  743. if not ob:
  744. ob = data.objects.new(self.evaluate_input("Name"), None)
  745. ob.lock_location = [True, True, True]
  746. ob.lock_rotation = [True, True, True]
  747. ob.lock_scale = [True, True, True]
  748. ob.lock_rotation_w = True
  749. ob.empty_display_type = 'CONE'
  750. ob.empty_display_size = 0.10
  751. self.bObject = ob
  752. reset_object_data(ob)
  753. node_line = trace_single_line(self, "Parent Curve")[0][1:] # slice excludes self
  754. for other_node in node_line:
  755. if other_node.node_type == 'XFORM':
  756. break
  757. else:
  758. raise GraphError(f"ERROR: {self} is not connected to a parent curve")
  759. if isinstance(other_node, (xFormArmature, xFormBone, xFormObjectInstance,)):
  760. raise GraphError(f"ERROR: {self} must be connected to curve,"
  761. " not {other_node.__class__.__name__}")
  762. curve=other_node.bGetObject()
  763. if curve.type != 'CURVE':
  764. raise GraphError(f"ERROR: {self} must be connected to curve,"
  765. " not {curve.type}")
  766. # we'll limit all the transforms so we can parent it
  767. # because it is annoying to have a cluttered outliner.
  768. #
  769. # always do this so that everything stays consistent.
  770. spline_index = self.evaluate_input("Spline Index")
  771. from .utilities.utilities import get_extracted_spline_object
  772. curve = get_extracted_spline_object(curve, spline_index, self.mContext)
  773. # Link to Scene:
  774. for link_me in [ob, curve]:
  775. if (link_me.name not in bContext.view_layer.active_layer_collection.collection.objects):
  776. bContext.view_layer.active_layer_collection.collection.objects.link(link_me)
  777. c = ob.constraints.new("LIMIT_LOCATION")
  778. for max_min in ['max','min']:
  779. for axis in "xyz":
  780. setattr(c, "use_"+max_min+"_"+axis, True)
  781. setattr(c, max_min+"_"+axis, 0.0)
  782. c = ob.constraints.new("LIMIT_ROTATION")
  783. for axis in "xyz":
  784. setattr(c, "use_limit_"+axis, True)
  785. setattr(c, max_min+"_"+axis, 0.0)
  786. c = ob.constraints.new("LIMIT_SCALE")
  787. for max_min in ['max','min']:
  788. for axis in "xyz":
  789. setattr(c, "use_"+max_min+"_"+axis, True)
  790. setattr(c, max_min+"_"+axis, 1.0)
  791. c = ob.constraints.new("FOLLOW_PATH")
  792. c.target = curve
  793. c.use_fixed_location = True
  794. c.use_curve_radius = True
  795. c.use_curve_follow = True
  796. c.name = "Curve Pin"
  797. props_sockets = self.gen_property_socket_map()
  798. constraint_props_sockets = props_sockets.copy()
  799. del constraint_props_sockets['name']; del constraint_props_sockets['empty_display_size']
  800. del props_sockets['offset_factor']; del props_sockets['forward_axis']
  801. del props_sockets['up_axis']
  802. evaluate_sockets(self, c, constraint_props_sockets)
  803. evaluate_sockets(self, self.bObject, props_sockets)
  804. # this isn't usually run on xForm nodes so for now I need to set the
  805. # driver's default values manually if I want a matrix now.
  806. # because the drivers may not have initialized yet.
  807. self.prep_driver_values(c)
  808. # now if all goes well... the matrix will be correct.
  809. dg = bContext.view_layer.depsgraph
  810. dg.update()
  811. # and the matrix should be correct now - copy because it may be modified
  812. self.parameters['Matrix'] = ob.matrix_world.copy()
  813. ob.parent=curve
  814. print( wrapGreen("Created Curve Pin: ") + wrapOrange(self.bObject.name) )
  815. parent_xForm_info = get_parent_xForm_info(self)
  816. root_armature = parent_xForm_info.root_armature
  817. my_info = xForm_info(
  818. object_type='object',
  819. root_armature= root_armature,
  820. parent_pose_name=curve.name,
  821. parent_edit_name=curve.name,
  822. self_pose_name=self.bObject.name,
  823. self_edit_name=self.bObject.name,
  824. )
  825. self.parameters['xForm Out'] = my_info
  826. self.prepared = True; self.executed = True
  827. def bFinalize(self, bContext = None):
  828. # custom properties
  829. self.setup_custom_props(self.bGetObject(), "Custom Properties")
  830. finish_drivers(self)
  831. def bGetObject(self, mode = 'POSE'):
  832. return self.bObject
  833. # special thank-you to Natalie Cuthbert, who submitted a patch for this
  834. # it turned out, I already had this patch laying around
  835. # because I was too busy with grad school I didn't succeed in collaborating
  836. # so while I apologize for failing to get your name in the commit history
  837. # now you get a special thank-you in Mantis instead!
  838. class xFormGetBone(xFormNode):
  839. """Represents an instance of an existing geometry object."""
  840. def __init__(self, signature, base_tree):
  841. super().__init__(signature, base_tree, xFormGetBoneSockets)
  842. self.init_parameters()
  843. # this is just a getter
  844. self.prepared=True; self.executed=True; self.execution_prepared=True
  845. def bGetParentArmature(self):
  846. from bpy import data
  847. # the below function may return None, but data.objects.get expects a string
  848. return data.objects.get(self.evaluate_input("Parent Armature") or "")
  849. def bGetObject(self, mode = 'POSE'):
  850. bone = None
  851. self.bObject = self.evaluate_input("Bone")
  852. armature = self.bGetParentArmature()
  853. from bpy.types import Object
  854. assert armature is not None, f"{self} requires a parent armature input to operate."
  855. assert isinstance(armature, Object), f"{self}: The parent armature must be an armature object."
  856. if armature:
  857. assert armature.type == 'ARMATURE', f"{self}: The parent armature must be an armature object."
  858. match mode:
  859. case 'EDIT':
  860. bone = armature.data.edit_bones.get(self.evaluate_input("Bone"))
  861. case 'OBJECT':
  862. bone = armature.bones.get(self.evaluate_input("Bone"))
  863. case 'POSE':
  864. bone = armature.pose.bones.get(self.evaluate_input("Bone"))
  865. assert self.bObject is not None, f"{self} failed to get the desired bone. Check if the bone name exists."
  866. return bone