xForm_containers.py 34 KB

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