link_nodes.py 43 KB

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