using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 3D鼠标平滑
    /// </summary>
    public class Navigation3DSmooth
    {
        private double min_cutoff;
        private double beta;
        private double d_cutoff;
        private double x_prev;
        private double dx_prev;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="x0">开始值</param>
        /// <param name="dx0">之前的X值</param>
        /// <param name="min_cutoff">终止值</param>
        /// <param name="beta"></param>
        /// <param name="d_cutoff"></param>
        public void Init(double x0, double dx0 = 0, double min_cutoff = 0.015, double beta = 0, double d_cutoff = 1)
        {
            this.min_cutoff = min_cutoff;
            this.beta = beta;
            this.d_cutoff = d_cutoff;
            this.x_prev = x0;
            this.dx_prev = dx0;
        }

        /// <summary>
        /// 根据实际值获取平滑值
        /// </summary>
        /// <param name="x">实际值</param>
        /// <returns>平滑后的值</returns>
        public double Call(double x)
        {
            double t_e = 1;
            double a_d = smoothing_factor(t_e, this.d_cutoff);
            double dx = (x - this.x_prev) / t_e;
            double dx_hat = exponential_smoothing(a_d, dx, this.x_prev);

            double cutoff = this.min_cutoff + this.beta * Math.Abs(dx_hat);
            double a = smoothing_factor(t_e, cutoff);
            double x_hat = exponential_smoothing(a, x, this.x_prev);

            this.x_prev = x_hat;
            this.dx_prev = dx_hat;

            return x_hat;
        }

        private double smoothing_factor(double t_e, double cutoff)
        {
            double r = 2 * Math.PI * cutoff * t_e;
            return r;
        }

        private double exponential_smoothing(double a, double x, double x_prev)
        {
            return a * x + (1 - a) * x_prev;
        }
    }
}
