xForm_nodes.py 42 KB

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