xForm_nodes.py 43 KB

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