xForm_nodes.py 41 KB

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