//
// Created by martin on 12.11.21.
//

#include "AnimSamplerNode.h"

#include <imgui.h>

#include "../SkinnedMesh.h"

void AnimSamplerNode::SetAnimation(ozz::animation::Animation* animation) {
  m_animation = animation;

  const SkinnedMesh* skinned_mesh = m_animation_controller->m_skinned_mesh;
  const int num_soa_joints = skinned_mesh->m_skeleton.num_soa_joints();
  const int num_joints = skinned_mesh->m_skeleton.num_joints();
  m_local_matrices.resize(num_soa_joints);
  m_sampling_cache.Resize(num_joints);
}



void AnimSamplerNode::Evaluate(ozz::vector<ozz::math::SoaTransform>* local_matrices) {
  ozz::animation::SamplingJob sampling_job;
  sampling_job.animation = m_animation;
  sampling_job.cache = &m_sampling_cache;
  sampling_job.ratio = m_anim_ratio;
  sampling_job.output = make_span(*local_matrices);
  if (!sampling_job.Run()) {
    ozz::log::Err() << "Error sampling animation." << std::endl;
  }
}



void AnimSamplerNode::DrawDebugUi() {
  std::string node_name = "AnimSamplerNode: " + m_name;
  if (ImGui::TreeNode(node_name.c_str())) {
    const SkinnedMesh* skinned_mesh = m_animation_controller->m_skinned_mesh;
    int anim_count = skinned_mesh->m_animation_names.size();
    const char* items[255] = {0};
    int item_current = 0;
    for (int i = 0; i < anim_count; i++) {
      items[i] = skinned_mesh->m_animation_names[i].c_str();
      if (skinned_mesh->m_animations[i] == m_animation) {
        item_current = i;
      }
    }

    if (ImGui::Combo("Animation", &item_current, items, anim_count)) {
      m_animation = skinned_mesh->m_animations[item_current];
    }
    ImGui::Checkbox("Override", &m_override_ratio);
    ImGui::SameLine();
    ImGui::SliderFloat("Ratio", &m_anim_ratio, 0.f, 1.f);

    ImGui::TreePop();
  }
}