Lunchbox  1.8.0
rng.h
1 
2 /* Copyright (c) 2007-2012, Stefan Eilemann <eile@equalizergraphics.com>
3  *
4  * This library is free software; you can redistribute it and/or modify it under
5  * the terms of the GNU Lesser General Public License version 2.1 as published
6  * by the Free Software Foundation.
7  *
8  * This library is distributed in the hope that it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
11  * details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this library; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16  */
17 
18 #ifndef LUNCHBOX_RNG_H
19 #define LUNCHBOX_RNG_H
20 
21 #include <lunchbox/debug.h> // for LBASSERT
22 #include <lunchbox/init.h> // friend function
23 #include <lunchbox/nonCopyable.h>
24 #include <lunchbox/types.h>
25 
26 #include <limits>
27 
28 namespace lunchbox
29 {
30 namespace detail { class RNG; }
31 
38  class RNG : public NonCopyable
39  {
40  public:
42  LUNCHBOX_API RNG();
43 
45  LUNCHBOX_API ~RNG();
46 
48  LUNCHBOX_API void reseed();
49 
58  template< typename T > T get()
59  {
60  T value;
61  if( !_get( &value, sizeof( T )))
62  return 0;
63  return value;
64  }
65 
66  private:
67  detail::RNG* const _impl;
68 
69  static LUNCHBOX_API bool _init();
70  static void _exit();
71  friend LUNCHBOX_API bool init( const int argc, char** argv );
72  LUNCHBOX_API bool _get( void* data, size_t size );
73  };
74 
75  template<> inline float RNG::get()
76  {
77  const float max_limits =
78  static_cast< float >( std::numeric_limits< uint32_t >::max( ));
79  return ( get< uint32_t >() / max_limits);
80  }
81 
82  template<> inline double RNG::get()
83  {
84  const double max_limits =
85  static_cast< double >( std::numeric_limits< uint64_t >::max( ));
86  return ( get< uint64_t >() / max_limits);
87  }
88 
89  template<> inline bool RNG::get()
90  {
91  return ( get< uint32_t >() & 1 );
92  }
93 }
94 #endif // LUNCHBOX_RNG_H