###########################################################
# FPSmeter - Railshooter Module
# Framerate Meter written by Jason Pratt
###########################################################

# DESCRIPTION:
# This Class creates Framerate Meter that is can be easily used 
# in other projects.  This Python File has no other dependencies, so it
# can simply be moved into your own project directory and used immediately.  
# To start the FPS Meter, type the following:

# import FPSMeter
# fpsMeter = FPSMeter.FPSMeter()


from direct.showbase.ShowBaseGlobal import *
from direct.gui.DirectGui import *
from direct.task import Task
from direct.showbase.DirectObject import DirectObject
import time

class FPSMeter(DirectObject):
    def __init__(self, displayFPS=True, numSamples=20):
        self.displayFPS = displayFPS
        self.numSamples = numSamples
        self.fps = 0.0
        self.samples = []
        if( displayFPS ):
            self.initLabel()

    def initLabel(self):
        self.fpsLabel = DirectLabel(
            relief = None,
            pos = (-0.95, 0, 0.90),
            text = "0.0 fps",
            color = Vec4(0, 0, 1, 1),
            text_scale = 0.1,
            )
        self.fpsLabel.hide()

    def enable(self):
        self.disable() # just in case
        self.samples = []
        self.lastTime = time.time()
        if( self.displayFPS ):
            self.fpsLabel.show()
        task = Task.Task(self.fpsTask)
        taskMgr.add(task, "fpsTask")

    def disable(self):
        if( self.displayFPS ):
            self.fpsLabel.hide()
        taskMgr.remove("fpsTask")

    def fpsTask(self, task):
        self.updateFPS()
        if( self.displayFPS ):
            self.updateDisplay()
        return Task.cont

    def updateFPS(self):
        t = time.time()
        dt = t - self.lastTime
        self.samples.append(dt)
        if( len(self.samples) > self.numSamples ):
            self.samples.pop( 0 )
        self.lastTime = t
        denom = reduce(lambda x, y: x+y, self.samples)
        if( denom != 0 ):
            self.fps = len(self.samples)/denom
        else:
            self.fps = 100.0

    def updateDisplay(self):
        self.fpsLabel['text'] = "% 3.1f fps" % self.fps





