xForm_nodes.py 40 KB

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