xForm_containers.py 40 KB

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