link_nodes.py 39 KB

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