xForm_nodes.py 41 KB

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