link_containers.py 34 KB

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