00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include "LampBasic.h"
00026 #include "Core/Utility/FPSController.h"
00027 #include "Core/Thread/Thread.h"
00028 #include "Core/Thread/SynchronizedBlock.h"
00029
00030 namespace Lamp{
00031
00032
00033 const float FPSController::interval60FPS = 16.6666666f;
00034
00035 const float FPSController::interval30FPS = 33.3333333f;
00036
00037
00038
00039 FPSController::FPSController(float targetInterval){
00040 setTargetInterval(targetInterval);
00041 tick_ = Timer::getTick();
00042 }
00043
00044
00045 FPSController::~FPSController(){
00046 Assert(backgroundThreads_.getCount() == 0);
00047 }
00048
00049
00050 float FPSController::sleep(){
00051
00052 intervalTime_ = Timer::getInterval(tick_);
00053 tick_ = Timer::getTick();
00054 sleepTime_ += (targetInterval_ - intervalTime_);
00055 if(sleepTime_ < 0.f){ sleepTime_ = 0.f; }
00056 else if(sleepTime_ > targetInterval_){ sleepTime_ = targetInterval_; }
00057
00058 bool hasBackgroundTask = false;
00059 {
00060 SynchronizedBlock synchronizedBlock(criticalSection_);
00061 if(backgroundThreads_.getCount() > 0){
00062 hasBackgroundTask = true;
00063 backgroundThreads_[0]->resume();
00064 }
00065 }
00066
00067 u_int correctedSleepTime = (u_int)sleepTime_;
00068 if(hasBackgroundTask && (correctedSleepTime == 0)){
00069 correctedSleepTime = 1;
00070 }
00071 Thread::sleep(correctedSleepTime);
00072
00073 {
00074 SynchronizedBlock synchronizedBlock(criticalSection_);
00075 if(hasBackgroundTask){
00076 Thread* backgroundThread = backgroundThreads_[0];
00077 if(backgroundThread->isFinished()){
00078 backgroundThreads_.remove(0);
00079 }else{
00080 backgroundThread->suspend();
00081 }
00082 }
00083 }
00084 return intervalTime_;
00085 }
00086
00087
00088 void FPSController::registerBackgroundThread(Thread* backgroundThread){
00089 SynchronizedBlock synchronizedBlock(criticalSection_);
00090 Assert(!backgroundThread->isFinished());
00091 backgroundThreads_.pushBack(backgroundThread);
00092 }
00093
00094
00095 int FPSController::getBackgroundThreadCount(){
00096 SynchronizedBlock synchronizedBlock(criticalSection_);
00097 return backgroundThreads_.getCount();
00098 }
00099
00100
00101 Thread* FPSController::getBackgroundThread(int index){
00102 SynchronizedBlock synchronizedBlock(criticalSection_);
00103 return backgroundThreads_[index];
00104 }
00105
00106
00107 String FPSController::toString() const{
00108 String result;
00109 result.format("interval %5.2f sleep %5.2f processing %5.2f%%",
00110 getIntervalTime(), getSleepTime(),
00111 getProcessingTime() / getIntervalTime() * 100.f);
00112 return result;
00113 }
00114
00115 }
00116