xForm_containers.py 35 KB

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