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