xForm_nodes.py 44 KB

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