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


Sun Mar 13 2011 Doxygen 1.7.1