osgEarth 2.1.1

/home/cube/sources/osgearth/src/osgEarth/Random.cpp

Go to the documentation of this file.
00001 /* -*-c++-*- */
00002 /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
00003  * Copyright 2008-2010 Pelican Mapping
00004  * http://osgearth.org
00005  *
00006  * osgEarth is free software; you can redistribute it and/or modify
00007  * it under the terms of the GNU Lesser General Public License as published by
00008  * the Free Software Foundation; either version 2 of the License, or
00009  * (at your option) any later version.
00010  *
00011  * This program is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014  * GNU Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public License
00017  * along with this program.  If not, see <http://www.gnu.org/licenses/>
00018  */
00019 #include <osgEarth/Random>
00020 #include <time.h>
00021 #include <limits.h>
00022 
00023 #define LC "[Random] "
00024 
00025 using namespace osgEarth;
00026 
00027 //------------------------------------------------------------------------
00028 
00029 namespace
00030 {
00031     void fast_rand( unsigned& next )
00032     {
00033         // note: this is not a "good" PRNG, but it is good enough for some applications
00034         // and it is wicked fast.
00035         next = next * 1103515245 + 12345;
00036     }
00037 }
00038 
00039 //------------------------------------------------------------------------
00040 
00041 Random::Random( Random::Method method ) :
00042 _method( method ),
00043 _seed  ( (unsigned)::time(0L) )
00044 {
00045     _next = _seed;
00046 }
00047 
00048 Random::Random( unsigned seed, Random::Method method ) :
00049 _method( method ),
00050 _seed  ( seed == 0 ? (unsigned)::time(0L) : seed ) // seed=0 => time-based
00051 {
00052     _next = _seed;
00053 }
00054 
00055 Random::Random( const Random& rhs ) :
00056 _method( rhs._method ),
00057 _seed  ( rhs._seed ),
00058 _next  ( rhs._next )
00059 {
00060     //nop
00061 }
00062 
00063 void
00064 Random::reset()
00065 {
00066     _next = _seed;
00067 }
00068 
00069 unsigned
00070 Random::next( unsigned mod )
00071 {
00072     if ( _method == METHOD_FAST )
00073     {
00074         fast_rand( _next );
00075     }    
00076     return mod == UINT_MAX ? _next : _next % mod;
00077 }
00078 
00079 double
00080 Random::next()
00081 {
00082     return (double)next(UINT_MAX) / (double)UINT_MAX;
00083 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines