xForm_nodes.py 44 KB

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