//
// Created by martin on 10.12.21.
//

#include "ozzutils.h"

#include <ozz/base/maths/simd_math.h>
#define OZZ_INCLUDE_PRIVATE_HEADER
#include "../src/animation/runtime/animation_keyframe.h"
#undef OZZ_INCLUDE_PRIVATE_HEADER

void calc_bone_translation(
    float ratio,
    int i_bone_idx,
    const ozz::animation::Animation* i_animation,
    ozz::math::Transform& o_transform) {
  int key_idx = 1;
  const ozz::span<const ozz::animation::Float3Key>& translations =
      i_animation->translations();

  int key_idx_prev = 0;
  int key_idx_next = 0;
  while (key_idx < translations.size()) {
    key_idx_next = key_idx;
    if (translations[key_idx].track == i_bone_idx) {
      if (translations[key_idx].ratio < ratio) {
        key_idx_prev = key_idx;
      } else {
        break;
      }
    }
    key_idx++;
  }

  const ozz::animation::Float3Key& key_prev = translations[key_idx_prev];
  const ozz::animation::Float3Key& key_next = translations[key_idx_next];

  float r = 0.f;
  if (key_prev.ratio != key_next.ratio) {
    r = (ratio - key_prev.ratio) / (key_next.ratio - key_prev.ratio);
  }
  o_transform.translation.x =
      ozz::math::HalfToFloat(key_prev.value[0])
      + r
            * (ozz::math::HalfToFloat(key_next.value[0])
               - ozz::math::HalfToFloat(key_prev.value[0]));
  o_transform.translation.y =
      ozz::math::HalfToFloat(key_prev.value[1])
      + r
            * (ozz::math::HalfToFloat(key_next.value[1])
               - ozz::math::HalfToFloat(key_prev.value[1]));
  o_transform.translation.z =
      ozz::math::HalfToFloat(key_prev.value[2])
      + r
            * (ozz::math::HalfToFloat(key_next.value[2])
               - ozz::math::HalfToFloat(key_prev.value[2]));
}
