xForm_containers.py 39 KB

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