using UnityEngine;
using System.Collections;
namespace FOHEART_Mocap
{


    [AddComponentMenu("Utilities/HUDFPS")]
    public class showfps : MonoBehaviour
    {
        //fps ʾĳʼλúʹС
        public Rect startRect = new Rect(0,0, 75f, 50f);
        //fps ʱǷıUIɫ
        public bool updateColor = true;
        //fps UI Ƿ϶ 
        public bool allowDrag = true;
        //fps µƵ
        public float frequency = 0.5F;
        //fps ʾľ
        public int nbDecimal = 1;
        //һʱڵfps
        private float accum = 0f;
        //fpsʱ
        private int frames = 0;
        //GUI fpsɫ fps<10 ɫ fps<30 ɫ fps>=30 ɫ
        private Color color = Color.white;
        //fps 
        private string sFPS = "";
        //GUI ʽ
        private GUIStyle style;

        void Start()
        {
            StartCoroutine(FPS());
        }

        void Update()
        {
            accum += Time.timeScale / Time.deltaTime;
            ++frames;
        }

        IEnumerator FPS()
        {
            while (true)
            {
                //fps
                float fps = accum / frames;
                sFPS = fps.ToString("f" + Mathf.Clamp(nbDecimal, 0, 10));

                //ɫ
                color = (fps >= 30) ? Color.green : ((fps > 10) ? Color.yellow : Color.red);

                accum = 0.0F;
                frames = 0;

                yield return new WaitForSeconds(frequency);
            }
        }

        void OnGUI()
        {
            if (style == null)
            {
                style = new GUIStyle(GUI.skin.label);
                style.normal.textColor = Color.white;
                style.alignment = TextAnchor.MiddleCenter;
            }

            GUI.color = updateColor ? color : Color.white;
            startRect = GUI.Window(0, startRect, DoMyWindow, "");
        }

        void DoMyWindow(int windowID)
        {
            GUI.Label(new Rect(0, 0, startRect.width, startRect.height), sFPS + " FPS", style);
            if (allowDrag) GUI.DragWindow(new Rect(0, 0, Screen.width, Screen.height));
        }
    }
}