/* PositionInterpolator.C: PositionInterpolator nodes (public source) */

#include <math.h>
#include "PositionInterpolator.H"

namespace xrml {

static SFVec3f SFVec3f_interpolate(const SFVec3f& v1, const SFVec3f& v2, float t)
{
  float s = 1.-t;
  return SFVec3f(v1.x * s + v2.x * t,
		 v1.y * s + v2.y * t,
		 v1.z * s + v2.z * t);
}

SFVec3f PositionInterpolator::interpolate(float t)
{
  int i = (int)floor(t);
  int ip1 = (int)ceil(t);
  if (i == ip1)
    return keyValue[i];
  else
    return SFVec3f_interpolate(keyValue[i], keyValue[ip1], t - floor(t));
}

void PositionInterpolator::set_fraction(const SFFloat& t)
{
  if (!initialised)
    return;
  float index = get_index(t);
  if (index >= 0. && index <= (float)(keyValue.size-1))
    post_value_changed(interpolate(index));
}

void PositionInterpolator::render(void)
{
  if (key.size != keyValue.size) {
    Error(NULL, "%s: number of key frames and values doesn't match", name());
    return;
  }

  if (!initialised) {
    if (keyValue.size > 0)
      value_changed = keyValue[0];
    initialised = true;
  }
}

}  // namespace xrml
