Index   Main   Namespaces   Classes   Hierarchy   Annotated   Files   Compound   Global   Pages  

SgRandom.cpp

Go to the documentation of this file.
00001 //----------------------------------------------------------------------------
00002 /** @file SgRandom.cpp
00003     See SgRandom.h.
00004 */
00005 //----------------------------------------------------------------------------
00006 
00007 #include "SgSystem.h"
00008 #include "SgRandom.h"
00009 
00010 #include <cstdlib>
00011 #include <functional>
00012 #include "SgDebug.h"
00013 
00014 using namespace std;
00015 
00016 //----------------------------------------------------------------------------
00017 
00018 SgRandom::GlobalData::GlobalData()
00019 {
00020     m_seed = 0;
00021 }
00022 
00023 //----------------------------------------------------------------------------
00024 
00025 SgRandom::SgRandom()
00026 {
00027     SetSeed();
00028     GetGlobalData().m_allGenerators.push_back(this);
00029 }
00030 
00031 SgRandom::~SgRandom()
00032 {
00033     GetGlobalData().m_allGenerators.remove(this);
00034 }
00035 
00036 SgRandom& SgRandom::Global()
00037 {
00038     static SgRandom s_globalGenerator;
00039     return s_globalGenerator;
00040 }
00041 
00042 SgRandom::GlobalData& SgRandom::GetGlobalData()
00043 {
00044     static GlobalData s_data;
00045     return s_data;
00046 }
00047 
00048 int SgRandom::Seed()
00049 {
00050     return GetGlobalData().m_seed;
00051 }
00052 
00053 void SgRandom::SetSeed()
00054 {
00055     boost::mt19937::result_type seed = GetGlobalData().m_seed;
00056     if (seed == 0)
00057         return;
00058     m_generator.seed(seed);
00059 }
00060 
00061 void SgRandom::SetSeed(int seed)
00062 {
00063     if (seed < 0)
00064     {
00065         GetGlobalData().m_seed = 0;
00066         return;
00067     }
00068     if (seed == 0)
00069         GetGlobalData().m_seed = time(0);
00070     else
00071         GetGlobalData().m_seed = seed;
00072     SgDebug() << "SgRandom::SetSeed: " << GetGlobalData().m_seed << '\n';
00073     for_each(GetGlobalData().m_allGenerators.begin(),
00074              GetGlobalData().m_allGenerators.end(),
00075              mem_fun(&SgRandom::SetSeed));
00076     srand(GetGlobalData().m_seed);
00077 }
00078 
00079 //----------------------------------------------------------------------------
00080 
00081 float SgRandomFloat(float min, float max)
00082 {
00083     return (max - min) * static_cast<float>(std::rand())
00084         / static_cast<float>(RAND_MAX) + min;
00085 }
00086 
00087 //----------------------------------------------------------------------------


17 Jun 2010 Doxygen 1.4.7