link_containers.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. from .node_container_common import *
  2. from bpy.types import Bone, NodeTree
  3. from .base_definitions import MantisNode, GraphError, FLOAT_EPSILON
  4. from .link_socket_templates import *
  5. def TellClasses():
  6. return [
  7. # special
  8. LinkInherit,
  9. # copy
  10. LinkCopyLocation,
  11. LinkCopyRotation,
  12. LinkCopyScale,
  13. LinkCopyTransforms,
  14. LinkTransformation,
  15. # limit
  16. LinkLimitLocation,
  17. LinkLimitRotation,
  18. LinkLimitScale,
  19. LinkLimitDistance,
  20. # tracking
  21. LinkStretchTo,
  22. LinkDampedTrack,
  23. LinkLockedTrack,
  24. LinkTrackTo,
  25. #misc
  26. LinkInheritConstraint,
  27. LinkArmature,
  28. # IK
  29. LinkInverseKinematics,
  30. LinkSplineIK,
  31. # Drivers
  32. LinkDrivenParameter,
  33. ]
  34. # set the name if it is available, otherwise just use the constraint's nice name
  35. set_constraint_name = lambda nc : nc.evaluate_input("Name") if nc.evaluate_input("Name") else nc.__class__.__name__
  36. class MantisLinkNode(MantisNode):
  37. def __init__(self, signature : tuple,
  38. base_tree : NodeTree,
  39. socket_templates : list[SockTemplate]=[]):
  40. super().__init__(signature, base_tree, socket_templates)
  41. self.node_type = 'LINK'
  42. self.prepared = True
  43. self.bObject=[]
  44. def evaluate_input(self, input_name, index=0):
  45. # should catch 'Target', 'Pole Target' and ArmatureConstraint targets, too
  46. if ('Target' in input_name) and input_name not in ["Target Space", "Use Target Z"]:
  47. socket = self.inputs.get(input_name)
  48. if socket.is_linked:
  49. return socket.links[0].from_node
  50. return None
  51. else:
  52. return super().evaluate_input(input_name)
  53. def gen_property_socket_map(self) -> dict:
  54. props_sockets = super().gen_property_socket_map()
  55. if (os := self.inputs.get("Owner Space")) and os.is_connected and os.links[0].from_node.node_type == 'XFORM':
  56. del props_sockets['owner_space']
  57. if ts := self.inputs.get("Target_Space") and ts.is_connected and ts.links[0].from_node.node_type == 'XFORM':
  58. del props_sockets['target_space']
  59. return props_sockets
  60. def set_custom_space(self):
  61. c = self.bObject
  62. if (os := self.inputs.get("Owner Space")) and os.is_connected and os.links[0].from_node.node_type == 'XFORM':
  63. c.owner_space='CUSTOM'
  64. xf = self.inputs["Owner Space"].links[0].from_node.bGetObject(mode="OBJECT")
  65. if isinstance(xf, Bone):
  66. c.space_object=self.inputs["Owner Space"].links[0].from_node.bGetParentArmature(); c.space_subtarget=xf.name
  67. else:
  68. c.space_object=xf
  69. if ts := self.inputs.get("Target_Space") and ts.is_connected and ts.links[0].from_node.node_type == 'XFORM':
  70. c.owner_space='CUSTOM'
  71. xf = self.inputs["Target_Space Space"].links[0].from_node.bGetObject(mode="OBJECT")
  72. if isinstance(xf, Bone):
  73. c.space_object=self.inputs["Target_Space Space"].links[0].from_node.bGetParentArmature(); c.space_subtarget=xf.name
  74. else:
  75. c.space_object=xf
  76. def GetxForm(nc, output_name="Output Relationship"):
  77. break_condition= lambda node : node.node_type=='XFORM'
  78. xforms = trace_line_up_branching(nc, output_name, break_condition)
  79. return_me=[]
  80. for xf in xforms:
  81. if xf.node_type != 'XFORM':
  82. continue
  83. return_me.append(xf)
  84. return return_me
  85. def bFinalize(self, bContext=None):
  86. finish_drivers(self)
  87. #*#-------------------------------#++#-------------------------------#*#
  88. # L I N K N O D E S
  89. #*#-------------------------------#++#-------------------------------#*#
  90. class LinkInherit(MantisLinkNode):
  91. '''A node representing inheritance'''
  92. def __init__(self, signature, base_tree):
  93. super().__init__(signature, base_tree, LinkInheritSockets)
  94. self.init_parameters()
  95. self.set_traverse([('Parent', 'Inheritance')])
  96. self.executed = True
  97. def GetxForm(self):
  98. # I think this is only run in display update.
  99. trace = trace_single_line_up(self, "Inheritance")
  100. for node in trace[0]:
  101. if (node.node_type == 'XFORM'):
  102. return node
  103. raise GraphError("%s is not connected to a downstream xForm" % self)
  104. class LinkCopyLocation(MantisLinkNode):
  105. '''A node representing Copy Location'''
  106. def __init__(self, signature : tuple,
  107. base_tree : NodeTree,):
  108. super().__init__(signature, base_tree, LinkCopyLocationSockets)
  109. additional_parameters = { "Name":None }
  110. self.init_parameters(additional_parameters=additional_parameters)
  111. self.set_traverse([("Input Relationship", "Output Relationship")])
  112. def bExecute(self, context):
  113. prepare_parameters(self)
  114. for xf in self.GetxForm():
  115. c = xf.bGetObject().constraints.new('COPY_LOCATION')
  116. self.get_target_and_subtarget(c)
  117. print(wrapGreen("Creating ")+wrapWhite("Copy Location")+
  118. wrapGreen(" Constraint for bone: ") +
  119. wrapOrange(xf.bGetObject().name))
  120. if constraint_name := self.evaluate_input("Name"):
  121. c.name = constraint_name
  122. self.bObject.append(c)
  123. self.set_custom_space()
  124. props_sockets = self.gen_property_socket_map()
  125. evaluate_sockets(self, c, props_sockets)
  126. self.executed = True
  127. class LinkCopyRotation(MantisLinkNode):
  128. '''A node representing Copy Rotation'''
  129. def __init__(self, signature, base_tree):
  130. super().__init__(signature, base_tree, LinkCopyRotationSockets)
  131. additional_parameters = { "Name":None }
  132. self.init_parameters(additional_parameters=additional_parameters)
  133. self.set_traverse([("Input Relationship", "Output Relationship")])
  134. def bExecute(self, context):
  135. prepare_parameters(self)
  136. for xf in self.GetxForm():
  137. c = xf.bGetObject().constraints.new('COPY_ROTATION')
  138. self.get_target_and_subtarget(c)
  139. print(wrapGreen("Creating ")+wrapWhite("Copy Rotation")+
  140. wrapGreen(" Constraint for bone: ") +
  141. wrapOrange(xf.bGetObject().name))
  142. rotation_order = self.evaluate_input("RotationOrder")
  143. if ((rotation_order == 'QUATERNION') or (rotation_order == 'AXIS_ANGLE')):
  144. c.euler_order = 'AUTO'
  145. else:
  146. try:
  147. c.euler_order = rotation_order
  148. except TypeError: # it's a driver or incorrect
  149. c.euler_order = 'AUTO'
  150. if constraint_name := self.evaluate_input("Name"):
  151. c.name = constraint_name
  152. self.bObject.append(c)
  153. self.set_custom_space()
  154. props_sockets = self.gen_property_socket_map()
  155. evaluate_sockets(self, c, props_sockets)
  156. self.executed = True
  157. class LinkCopyScale(MantisLinkNode):
  158. '''A node representing Copy Scale'''
  159. def __init__(self, signature, base_tree):
  160. super().__init__(signature, base_tree, LinkCopyScaleSockets)
  161. additional_parameters = { "Name":None }
  162. self.init_parameters(additional_parameters=additional_parameters)
  163. self.set_traverse([("Input Relationship", "Output Relationship")])
  164. def bExecute(self, context):
  165. prepare_parameters(self)
  166. for xf in self.GetxForm():
  167. c = xf.bGetObject().constraints.new('COPY_SCALE')
  168. self.get_target_and_subtarget(c)
  169. print(wrapGreen("Creating ")+wrapWhite("Copy Scale")+
  170. wrapGreen(" Constraint for bone: ") +
  171. wrapOrange(xf.bGetObject().name))
  172. if constraint_name := self.evaluate_input("Name"):
  173. c.name = constraint_name
  174. self.bObject.append(c)
  175. if self.inputs["Owner Space"].is_connected and self.inputs["Owner Space"].links[0].from_node.node_type == 'XFORM':
  176. c.owner_space='CUSTOM'
  177. xf = self.inputs["Owner Space"].links[0].from_node.bGetObject(mode="OBJECT")
  178. if isinstance(xf, Bone):
  179. c.space_object=self.inputs["Owner Space"].links[0].from_node.bGetParentArmature(); c.space_subtarget=xf.name
  180. else:
  181. c.space_object=xf
  182. if self.inputs["Target Space"].is_connected and self.inputs["Target Space"].links[0].from_node.node_type == 'XFORM':
  183. c.target_space='CUSTOM'
  184. xf = self.inputs["Target Space"].links[0].from_node.bGetObject(mode="OBJECT")
  185. if isinstance(xf, Bone):
  186. c.space_object=self.inputs["Owner Space"].links[0].from_node.bGetParentArmature(); c.space_subtarget=xf.name
  187. else:
  188. c.space_object=xf
  189. props_sockets = self.gen_property_socket_map()
  190. evaluate_sockets(self, c, props_sockets)
  191. self.executed = True
  192. class LinkCopyTransforms(MantisLinkNode):
  193. '''A node representing Copy Transfoms'''
  194. def __init__(self, signature, base_tree):
  195. super().__init__(signature, base_tree, LinkCopyTransformsSockets)
  196. additional_parameters = { "Name":None }
  197. self.init_parameters(additional_parameters=additional_parameters)
  198. self.set_traverse([("Input Relationship", "Output Relationship")])
  199. def bExecute(self, context):
  200. prepare_parameters(self)
  201. for xf in self.GetxForm():
  202. c = xf.bGetObject().constraints.new('COPY_TRANSFORMS')
  203. self.get_target_and_subtarget(c)
  204. print(wrapGreen("Creating ")+wrapWhite("Copy Transforms")+
  205. wrapGreen(" Constraint for bone: ") +
  206. wrapOrange(xf.bGetObject().name))
  207. if constraint_name := self.evaluate_input("Name"):
  208. c.name = constraint_name
  209. self.bObject.append(c)
  210. self.set_custom_space()
  211. props_sockets = self.gen_property_socket_map()
  212. evaluate_sockets(self, c, props_sockets)
  213. self.executed = True
  214. class LinkTransformation(MantisLinkNode):
  215. '''A node representing Copy Transfoms'''
  216. def __init__(self, signature, base_tree):
  217. super().__init__(signature, base_tree, LinkTransformationSockets)
  218. self.init_parameters(additional_parameters={"Name":None })
  219. self.set_traverse([("Input Relationship", "Output Relationship")])
  220. def bExecute(self, context):
  221. prepare_parameters(self)
  222. for xf in self.GetxForm():
  223. c = xf.bGetObject().constraints.new('TRANSFORM')
  224. self.get_target_and_subtarget(c)
  225. print(wrapGreen("Creating ")+wrapWhite("Transformation")+
  226. wrapGreen(" Constraint for bone: ") +
  227. wrapOrange(xf.bGetObject().name))
  228. if constraint_name := self.evaluate_input("Name"):
  229. c.name = constraint_name
  230. self.bObject.append(c)
  231. self.set_custom_space()
  232. props_sockets = self.gen_property_socket_map()
  233. # we have to fix the blender-property for scale/rotation
  234. # because Blender stores these separately.
  235. # I do not care that this code is ugly.
  236. from_replace, to_replace = '', ''
  237. if self.evaluate_input("Map From") == 'ROTATION':
  238. from_replace='_rot'
  239. elif self.evaluate_input("Map From") == 'SCALE':
  240. from_replace='_scale'
  241. if self.evaluate_input("Map To") == 'ROTATION':
  242. to_replace='_rot'
  243. elif self.evaluate_input("Map To") == 'SCALE':
  244. to_replace='_scale'
  245. if from_replace:
  246. for axis in ['x', 'y', 'z']:
  247. stub='from_min_'+axis
  248. props_sockets[stub+from_replace]=props_sockets[stub]
  249. del props_sockets[stub]
  250. stub='from_max_'+axis
  251. props_sockets[stub+from_replace]=props_sockets[stub]
  252. del props_sockets[stub]
  253. if to_replace:
  254. for axis in ['x', 'y', 'z']:
  255. stub='to_min_'+axis
  256. props_sockets[stub+to_replace]=props_sockets[stub]
  257. del props_sockets[stub]
  258. stub='to_max_'+axis
  259. props_sockets[stub+to_replace]=props_sockets[stub]
  260. del props_sockets[stub]
  261. evaluate_sockets(self, c, props_sockets)
  262. self.executed = True
  263. class LinkLimitLocation(MantisLinkNode):
  264. def __init__(self, signature, base_tree):
  265. super().__init__(signature, base_tree, LinkLimitLocationScaleSockets)
  266. self.init_parameters(additional_parameters={ "Name":None })
  267. self.set_traverse([("Input Relationship", "Output Relationship")])
  268. def bExecute(self, context):
  269. prepare_parameters(self)
  270. for xf in self.GetxForm():
  271. c = xf.bGetObject().constraints.new('LIMIT_LOCATION')
  272. print(wrapGreen("Creating ")+wrapWhite("Limit Location")+
  273. wrapGreen(" Constraint for bone: ") +
  274. wrapOrange(xf.bGetObject().name))
  275. if constraint_name := self.evaluate_input("Name"):
  276. c.name = constraint_name
  277. self.bObject.append(c)
  278. self.set_custom_space()
  279. props_sockets = self.gen_property_socket_map()
  280. evaluate_sockets(self, c, props_sockets)
  281. self.executed = True
  282. class LinkLimitRotation(MantisLinkNode):
  283. def __init__(self, signature, base_tree):
  284. super().__init__(signature, base_tree, LinkLimitRotationSockets)
  285. self.init_parameters(additional_parameters={ "Name":None })
  286. self.set_traverse([("Input Relationship", "Output Relationship")])
  287. def bExecute(self, context):
  288. prepare_parameters(self)
  289. for xf in self.GetxForm():
  290. c = xf.bGetObject().constraints.new('LIMIT_ROTATION')
  291. print(wrapGreen("Creating ")+wrapWhite("Limit Rotation")+
  292. wrapGreen(" Constraint for bone: ") +
  293. wrapOrange(xf.bGetObject().name))
  294. if constraint_name := self.evaluate_input("Name"):
  295. c.name = constraint_name
  296. self.bObject.append(c)
  297. self.set_custom_space()
  298. props_sockets = self.gen_property_socket_map()
  299. evaluate_sockets(self, c, props_sockets)
  300. self.executed = True
  301. class LinkLimitScale(MantisLinkNode):
  302. def __init__(self, signature, base_tree):
  303. super().__init__(signature, base_tree, LinkLimitLocationScaleSockets)
  304. self.init_parameters(additional_parameters={ "Name":None })
  305. self.set_traverse([("Input Relationship", "Output Relationship")])
  306. def bExecute(self, context):
  307. prepare_parameters(self)
  308. for xf in self.GetxForm():
  309. c = xf.bGetObject().constraints.new('LIMIT_SCALE')
  310. print(wrapGreen("Creating ")+wrapWhite("Limit Scale")+
  311. wrapGreen(" Constraint for bone: ") +
  312. wrapOrange(xf.bGetObject().name))
  313. if constraint_name := self.evaluate_input("Name"):
  314. c.name = constraint_name
  315. self.bObject.append(c)
  316. self.set_custom_space()
  317. props_sockets = self.gen_property_socket_map()
  318. evaluate_sockets(self, c, props_sockets)
  319. self.executed = True
  320. class LinkLimitDistance(MantisLinkNode):
  321. def __init__(self, signature, base_tree):
  322. super().__init__(signature, base_tree, LinkLimitDistanceSockets)
  323. self.init_parameters(additional_parameters={ "Name":None })
  324. self.set_traverse([("Input Relationship", "Output Relationship")])
  325. def bExecute(self, context):
  326. prepare_parameters(self)
  327. for xf in self.GetxForm():
  328. print(wrapGreen("Creating ")+wrapWhite("Limit Distance")+
  329. wrapGreen(" Constraint for bone: ") +
  330. wrapOrange(xf.bGetObject().name))
  331. c = xf.bGetObject().constraints.new('LIMIT_DISTANCE')
  332. self.get_target_and_subtarget(c)
  333. if constraint_name := self.evaluate_input("Name"):
  334. c.name = constraint_name
  335. self.bObject.append(c)
  336. self.set_custom_space()
  337. props_sockets = self.gen_property_socket_map()
  338. evaluate_sockets(self, c, props_sockets)
  339. self.executed = True
  340. # Tracking
  341. class LinkStretchTo(MantisLinkNode):
  342. def __init__(self, signature, base_tree):
  343. super().__init__(signature, base_tree, LinkStretchToSockets)
  344. self.init_parameters(additional_parameters={ "Name":None })
  345. self.set_traverse([("Input Relationship", "Output Relationship")])
  346. def bExecute(self, context):
  347. prepare_parameters(self)
  348. for xf in self.GetxForm():
  349. print(wrapGreen("Creating ")+wrapWhite("Stretch-To")+
  350. wrapGreen(" Constraint for bone: ") +
  351. wrapOrange(xf.bGetObject().name))
  352. c = xf.bGetObject().constraints.new('STRETCH_TO')
  353. self.get_target_and_subtarget(c)
  354. if constraint_name := self.evaluate_input("Name"):
  355. c.name = constraint_name
  356. self.bObject.append(c)
  357. props_sockets = self.gen_property_socket_map()
  358. evaluate_sockets(self, c, props_sockets)
  359. if (self.evaluate_input("Original Length") == 0):
  360. # this is meant to be set automatically.
  361. c.rest_length = xf.bGetObject().bone.length
  362. self.executed = True
  363. class LinkDampedTrack(MantisLinkNode):
  364. def __init__(self, signature, base_tree):
  365. super().__init__(signature, base_tree, LinkDampedTrackSockets)
  366. self.init_parameters(additional_parameters={ "Name":None })
  367. self.set_traverse([("Input Relationship", "Output Relationship")])
  368. def bExecute(self, context):
  369. prepare_parameters(self)
  370. for xf in self.GetxForm():
  371. print(wrapGreen("Creating ")+wrapWhite("Damped Track")+
  372. wrapGreen(" Constraint for bone: ") +
  373. wrapOrange(xf.bGetObject().name))
  374. c = xf.bGetObject().constraints.new('DAMPED_TRACK')
  375. self.get_target_and_subtarget(c)
  376. if constraint_name := self.evaluate_input("Name"):
  377. c.name = constraint_name
  378. self.bObject.append(c)
  379. props_sockets = self.gen_property_socket_map()
  380. evaluate_sockets(self, c, props_sockets)
  381. self.executed = True
  382. class LinkLockedTrack(MantisLinkNode):
  383. def __init__(self, signature, base_tree):
  384. super().__init__(signature, base_tree,LinkLockedTrackSockets)
  385. self.init_parameters(additional_parameters={"Name":None })
  386. self.set_traverse([("Input Relationship", "Output Relationship")])
  387. def bExecute(self, context):
  388. prepare_parameters(self)
  389. for xf in self.GetxForm():
  390. print(wrapGreen("Creating ")+wrapWhite("Locked Track")+
  391. wrapGreen(" Constraint for bone: ") +
  392. wrapOrange(xf.bGetObject().name))
  393. c = xf.bGetObject().constraints.new('LOCKED_TRACK')
  394. self.get_target_and_subtarget(c)
  395. if constraint_name := self.evaluate_input("Name"):
  396. c.name = constraint_name
  397. self.bObject.append(c)
  398. props_sockets = self.gen_property_socket_map()
  399. evaluate_sockets(self, c, props_sockets)
  400. self.executed = True
  401. class LinkTrackTo(MantisLinkNode):
  402. def __init__(self, signature, base_tree):
  403. super().__init__(signature, base_tree, LinkTrackToSockets)
  404. self.init_parameters(additional_parameters={"Name":None })
  405. self.set_traverse([("Input Relationship", "Output Relationship")])
  406. def bExecute(self, context):
  407. prepare_parameters(self)
  408. for xf in self.GetxForm():
  409. print(wrapGreen("Creating ")+wrapWhite("Track-To")+
  410. wrapGreen(" Constraint for bone: ") +
  411. wrapOrange(xf.bGetObject().name))
  412. c = xf.bGetObject().constraints.new('TRACK_TO')
  413. self.get_target_and_subtarget(c)
  414. if constraint_name := self.evaluate_input("Name"):
  415. c.name = constraint_name
  416. self.bObject.append(c)
  417. props_sockets = self.gen_property_socket_map()
  418. evaluate_sockets(self, c, props_sockets)
  419. self.executed = True
  420. class LinkInheritConstraint(MantisLinkNode):
  421. def __init__(self, signature, base_tree):
  422. super().__init__(signature, base_tree, LinkInheritConstraintSockets)
  423. self.init_parameters(additional_parameters={"Name":None })
  424. self.set_traverse([("Input Relationship", "Output Relationship")])
  425. def bExecute(self, context):
  426. prepare_parameters(self)
  427. for xf in self.GetxForm():
  428. print(wrapGreen("Creating ")+wrapWhite("Child-Of")+
  429. wrapGreen(" Constraint for bone: ") +
  430. wrapOrange(xf.bGetObject().name))
  431. c = xf.bGetObject().constraints.new('CHILD_OF')
  432. self.get_target_and_subtarget(c)
  433. if constraint_name := self.evaluate_input("Name"):
  434. c.name = constraint_name
  435. self.bObject.append(c)
  436. props_sockets = self.gen_property_socket_map()
  437. evaluate_sockets(self, c, props_sockets)
  438. c.set_inverse_pending
  439. self.executed = True
  440. class LinkInverseKinematics(MantisLinkNode):
  441. def __init__(self, signature, base_tree):
  442. super().__init__(signature, base_tree, LinkInverseKinematicsSockets)
  443. self.init_parameters(additional_parameters={"Name":None })
  444. self.set_traverse([("Input Relationship", "Output Relationship")])
  445. def get_base_ik_bone(self, ik_bone):
  446. chain_length : int = (self.evaluate_input("Chain Length"))
  447. if not isinstance(chain_length, (int, float)):
  448. raise GraphError(f"Chain Length must be an integer number in {self}::Chain Length")
  449. if chain_length == 0:
  450. chain_length = int("inf")
  451. base_ik_bone = ik_bone; i=1
  452. while (i<chain_length) and (base_ik_bone.parent):
  453. base_ik_bone=base_ik_bone.parent; i+=1
  454. return base_ik_bone
  455. # We need to do the calculation in a "full circle", meaning the pole_angle
  456. # can go over pi or less than -pi - but the actuall constraint value must
  457. # be clamped in that range.
  458. # so we simply wrap the value.
  459. # not very efficient but it's OK
  460. def set_pole_angle(self, constraint, angle: float) -> None:
  461. from math import pi
  462. from .utilities import wrap
  463. constraint.pole_angle = wrap(-pi, pi, angle)
  464. def calc_pole_angle_pre(self, c, ik_bone):
  465. """
  466. This function gets us most of the way to a correct IK pole angle. Unfortunately,
  467. due to the unpredictable nature of the iterative IK calculation, I can't figure
  468. out an exact solution. So we do a bisect search in calc_pole_angle_post().
  469. """
  470. # TODO: instead of these checks, convert all to armature local space. But this is tedious.
  471. if not c.target:
  472. raise GraphError(f"IK Constraint {self} must have target.")
  473. elif c.target.type != "ARMATURE":
  474. raise NotImplementedError(f"Currently, IK Constraint Target for {self} must be a bone within the same armature.")
  475. if c.pole_target.type != "ARMATURE":
  476. raise NotImplementedError(f"Currently, IK Constraint Pole Target for {self} must be a bone within the same armature.")
  477. ik_handle = c.target.pose.bones[c.subtarget]
  478. if ik_handle.id_data != ik_bone.id_data:
  479. raise NotImplementedError(f"Currently, IK Constraint Target for {self} must be a bone within the same armature.")
  480. ik_pole = c.pole_target.pose.bones[c.pole_subtarget]
  481. if ik_pole.id_data != ik_bone.id_data:
  482. raise NotImplementedError(f"Currently,IK Constraint Pole Target for {self} must be a bone within the same armature.")
  483. base_ik_bone = self.get_base_ik_bone(ik_bone)
  484. start_effector = base_ik_bone.bone.head_local
  485. end_effector = ik_handle.bone.head_local
  486. pole_location = ik_pole.bone.head_local
  487. # this is the X-Axis of the bone's rest-pose, added to its bone
  488. knee_location = base_ik_bone.bone.matrix_local.col[0].xyz+start_effector
  489. ik_axis = (end_effector-start_effector).normalized()
  490. from .utilities import project_point_to_plane
  491. pole_planar_projection = project_point_to_plane(pole_location, start_effector, ik_axis)
  492. # this planar projection is necessary because the IK axis is different than the base_bone's y axis
  493. planar_projection = project_point_to_plane(knee_location, start_effector, ik_axis)
  494. knee_direction =(planar_projection - start_effector).normalized()
  495. pole_direction =(pole_planar_projection - start_effector).normalized()
  496. return knee_direction.angle(pole_direction)
  497. def calc_pole_angle_post(self, c, ik_bone, context):
  498. """
  499. This function should give us a completely accurate result for IK.
  500. """
  501. from time import time
  502. start_time=time()
  503. def signed_angle(vector_u, vector_v, normal):
  504. # it seems that this fails if the vectors are exactly aligned under certain circumstances.
  505. angle = vector_u.angle(vector_v, 0.0) # So we use a fallback of 0
  506. # Normal specifies orientation
  507. if angle != 0 and vector_u.cross(vector_v).angle(normal) < 1:
  508. angle = -angle
  509. return angle
  510. # we have already checked for valid data.
  511. ik_handle = c.target.pose.bones[c.subtarget]
  512. base_ik_bone = self.get_base_ik_bone(ik_bone)
  513. start_effector = base_ik_bone.bone.head_local
  514. angle = c.pole_angle
  515. dg = context.view_layer.depsgraph
  516. dg.update()
  517. ik_axis = (ik_handle.bone.head_local-start_effector).normalized()
  518. center_point = start_effector +(ik_axis*base_ik_bone.bone.length)
  519. knee_direction = base_ik_bone.bone.tail_local - center_point
  520. current_knee_direction = base_ik_bone.tail-center_point
  521. error=signed_angle(current_knee_direction, knee_direction, ik_axis)
  522. if error == 0:
  523. prGreen("No Fine-tuning needed."); return
  524. # Flip it if needed
  525. dot_before=current_knee_direction.dot(knee_direction)
  526. if dot_before < 0 and angle!=0: # then it is not aligned and we should check the inverse
  527. angle = -angle; c.pole_angle=angle
  528. dg.update()
  529. current_knee_direction = base_ik_bone.tail-center_point
  530. dot_after=current_knee_direction.dot(knee_direction)
  531. if dot_after < dot_before: # they are somehow less aligned
  532. prPurple("Mantis has gone down an unexpected code path. Please report this as a bug.")
  533. angle = -angle; self.set_pole_angle(c, angle)
  534. dg.update()
  535. # now we can do a bisect search to find the best value.
  536. error_threshhold = FLOAT_EPSILON
  537. max_iterations=600
  538. error=signed_angle(current_knee_direction, knee_direction, ik_axis)
  539. if error == 0:
  540. prGreen("No Fine-tuning needed."); return
  541. angle+=error
  542. alt_angle = angle+(error*-2) # should be very near the center when flipped here
  543. # we still need to bisect search because the relationship of pole_angle <==> error is somewhat unpredictable
  544. upper_bounds = alt_angle if alt_angle > angle else angle
  545. lower_bounds = alt_angle if alt_angle < angle else angle
  546. i, error_identical = 0, 0
  547. while ( True ):
  548. if (i>=max_iterations):
  549. prOrange(f"IK Pole Angle Set reached max iterations of {i-error_identical} in {time()-start_time} seconds")
  550. break
  551. if (abs(error)<error_threshhold) or (upper_bounds<=lower_bounds) or (error_identical > 3):
  552. prPurple(f"IK Pole Angle Set converged after {i-error_identical} iterations with error={error} in {time()-start_time} seconds")
  553. break
  554. # get the center-point betweeen the bounds
  555. try_angle = lower_bounds + (upper_bounds-lower_bounds)/2
  556. self.set_pole_angle(c, try_angle); dg.update()
  557. prev_error = error
  558. error = signed_angle((base_ik_bone.tail-center_point), knee_direction, ik_axis)
  559. error_identical+= int(error == prev_error)
  560. if error>0: upper_bounds=try_angle
  561. if error<0: lower_bounds=try_angle
  562. i+=1
  563. def bExecute(self, context):
  564. prepare_parameters(self)
  565. for xf in self.GetxForm():
  566. print(wrapGreen("Creating ")+wrapOrange("Inverse Kinematics")+
  567. wrapGreen(" Constraint for bone: ") +
  568. wrapOrange(xf.bGetObject().name))
  569. ik_bone = xf.bGetObject()
  570. c = xf.bGetObject().constraints.new('IK')
  571. self.get_target_and_subtarget(c)
  572. self.get_target_and_subtarget(c, input_name = 'Pole Target')
  573. if constraint_name := self.evaluate_input("Name"):
  574. c.name = constraint_name
  575. self.bObject.append(c)
  576. c.chain_count = 1 # so that, if there are errors, this doesn't print
  577. # a whole bunch of circular dependency crap from having infinite chain length
  578. if (c.pole_target):
  579. self.set_pole_angle(c, self.calc_pole_angle_pre(c, ik_bone))
  580. props_sockets = self.gen_property_socket_map()
  581. evaluate_sockets(self, c, props_sockets)
  582. c.use_location = self.evaluate_input("Position") > 0
  583. c.use_rotation = self.evaluate_input("Rotation") > 0
  584. self.executed = True
  585. def bFinalize(self, bContext = None):
  586. # adding a test here
  587. if bContext:
  588. for i, constraint in enumerate(self.bObject):
  589. ik_bone = self.GetxForm()[i].bGetObject(mode='POSE')
  590. if constraint.pole_target:
  591. prWhite(f"Fine-tuning IK Pole Angle for {self}")
  592. # make sure to enable it first
  593. enabled_before = constraint.mute
  594. constraint.mute = False
  595. self.calc_pole_angle_post(constraint, ik_bone, bContext)
  596. constraint.mute = enabled_before
  597. super().bFinalize(bContext)
  598. def ik_report_error(pb, context, do_print=False):
  599. dg = context.view_layer.depsgraph
  600. dg.update()
  601. loc1, rot_quaternion1, scl1 = pb.matrix.decompose()
  602. loc2, rot_quaternion2, scl2 = pb.bone.matrix_local.decompose()
  603. location_error=(loc1-loc2).length
  604. rotation_error = rot_quaternion1.rotation_difference(rot_quaternion2).angle
  605. scale_error = (scl1-scl2).length
  606. if location_error < FLOAT_EPSILON: location_error = 0
  607. if abs(rotation_error) < FLOAT_EPSILON: rotation_error = 0
  608. if scale_error < FLOAT_EPSILON: scale_error = 0
  609. if do_print:
  610. print (f"IK Location Error: {location_error}")
  611. print (f"IK Rotation Error: {rotation_error}")
  612. print (f"IK Scale Error : {scale_error}")
  613. return (location_error, rotation_error, scale_error)
  614. # This is kinda a weird design decision?
  615. class LinkDrivenParameter(MantisLinkNode):
  616. '''A node representing an armature object'''
  617. def __init__(self, signature, base_tree):
  618. super().__init__(signature, base_tree, LinkDrivenParameterSockets)
  619. self.init_parameters(additional_parameters={ "Name":None })
  620. self.set_traverse([("Input Relationship", "Output Relationship")])
  621. def bExecute(self, bContext = None,):
  622. prepare_parameters(self)
  623. prGreen("Executing Driven Parameter node")
  624. prop = self.evaluate_input("Parameter")
  625. index = self.evaluate_input("Index")
  626. value = self.evaluate_input("Value")
  627. for xf in self.GetxForm():
  628. ob = xf.bGetObject(mode="POSE")
  629. # IMPORTANT: this node only works on pose bone attributes.
  630. self.bObject.append(ob)
  631. length=1
  632. if hasattr(ob, prop):
  633. try:
  634. length = len(getattr(ob, prop))
  635. except TypeError:
  636. pass
  637. except AttributeError:
  638. pass
  639. else:
  640. raise AttributeError(f"Cannot Set value {prop} on object because it does not exist.")
  641. def_value = 0.0
  642. if length>1:
  643. def_value=[0.0]*length
  644. self.parameters["Value"] = tuple( 0.0 if i != index else value for i in range(length))
  645. props_sockets = {
  646. prop: ("Value", def_value)
  647. }
  648. evaluate_sockets(self, ob, props_sockets)
  649. self.executed = True
  650. def bFinalize(self, bContext = None):
  651. driver = self.evaluate_input("Value")
  652. try:
  653. for i, val in enumerate(self.parameters["Value"]):
  654. from .drivers import MantisDriver
  655. if isinstance(val, MantisDriver):
  656. driver["ind"] = i
  657. val = driver
  658. except AttributeError:
  659. self.parameters["Value"] = driver
  660. except TypeError:
  661. self.parameters["Value"] = driver
  662. super().bFinalize(bContext)
  663. class LinkArmature(MantisLinkNode):
  664. '''A node representing an armature object'''
  665. def __init__(self, signature, base_tree,):
  666. super().__init__(signature, base_tree, LinkArmatureSockets)
  667. self.init_parameters(additional_parameters={"Name":None })
  668. self.set_traverse([("Input Relationship", "Output Relationship")])
  669. setup_custom_props(self) # <-- this takes care of the runtime-added sockets
  670. def bExecute(self, bContext = None,):
  671. prepare_parameters(self)
  672. for xf in self.GetxForm():
  673. print(wrapGreen("Creating ")+wrapOrange("Armature")+
  674. wrapGreen(" Constraint for bone: ") +
  675. wrapOrange(xf.bGetObject().name))
  676. c = xf.bGetObject().constraints.new('ARMATURE')
  677. if constraint_name := self.evaluate_input("Name"):
  678. c.name = constraint_name
  679. self.bObject.append(c)
  680. # get number of targets
  681. num_targets = len( list(self.inputs.values())[6:] )//2
  682. props_sockets = self.gen_property_socket_map()
  683. targets_weights = {}
  684. for i in range(num_targets):
  685. target = c.targets.new()
  686. target_input_name = list(self.inputs.keys())[i*2+6 ]
  687. weight_input_name = list(self.inputs.keys())[i*2+6+1]
  688. self.get_target_and_subtarget(target, target_input_name)
  689. weight_value=self.evaluate_input(weight_input_name)
  690. if not isinstance(weight_value, float):
  691. weight_value=0
  692. targets_weights[i]=weight_value
  693. props_sockets["targets[%d].weight" % i] = (weight_input_name, 0)
  694. # targets_weights.append({"weight":(weight_input_name, 0)})
  695. evaluate_sockets(self, c, props_sockets)
  696. for target, value in targets_weights.items():
  697. c.targets[target].weight=value
  698. self.executed = True
  699. class LinkSplineIK(MantisLinkNode):
  700. '''A node representing an armature object'''
  701. def __init__(self, signature, base_tree):
  702. super().__init__(signature, base_tree, LinkSplineIKSockets)
  703. self.init_parameters(additional_parameters={"Name":None })
  704. self.set_traverse([("Input Relationship", "Output Relationship")])
  705. def bExecute(self, bContext = None,):
  706. prepare_parameters(self)
  707. for xf in self.GetxForm():
  708. print(wrapGreen("Creating ")+wrapOrange("Spline-IK")+
  709. wrapGreen(" Constraint for bone: ") +
  710. wrapOrange(xf.bGetObject().name))
  711. c = xf.bGetObject().constraints.new('SPLINE_IK')
  712. # set the spline - we need to get the right one
  713. spline_index = self.evaluate_input("Spline Index")
  714. from .utilities import get_extracted_spline_object
  715. proto_curve = self.inputs['Target'].links[0].from_node.bGetObject()
  716. curve = get_extracted_spline_object(proto_curve, spline_index, self.mContext)
  717. # link it to the view layer
  718. if (curve.name not in bContext.view_layer.active_layer_collection.collection.objects):
  719. bContext.view_layer.active_layer_collection.collection.objects.link(curve)
  720. c.target=curve
  721. if constraint_name := self.evaluate_input("Name"):
  722. c.name = constraint_name
  723. self.bObject.append(c)
  724. props_sockets = self.gen_property_socket_map()
  725. evaluate_sockets(self, c, props_sockets)
  726. self.executed = True