Home | History | Annotate | Download | only in include
      1 /*
      2     Copyright 2010 Google Inc.
      3 
      4     Licensed under the Apache License, Version 2.0 (the "License");
      5     you may not use this file except in compliance with the License.
      6     You may obtain a copy of the License at
      7 
      8          http://www.apache.org/licenses/LICENSE-2.0
      9 
     10     Unless required by applicable law or agreed to in writing, software
     11     distributed under the License is distributed on an "AS IS" BASIS,
     12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13     See the License for the specific language governing permissions and
     14     limitations under the License.
     15  */
     16 
     17 
     18 #ifndef GrRandom_DEFINED
     19 #define GrRandom_DEFINED
     20 
     21 class GrRandom {
     22 public:
     23     GrRandom() : fSeed(0) {}
     24     GrRandom(uint32_t seed) : fSeed(seed) {}
     25 
     26     uint32_t seed() const { return fSeed; }
     27 
     28     uint32_t nextU() {
     29         fSeed = fSeed * kMUL + kADD;
     30         return fSeed;
     31     }
     32 
     33     int32_t nextS() { return (int32_t)this->nextU(); }
     34 
     35     /**
     36      *  Returns value [0...1) as a float
     37      */
     38     float nextF() {
     39         // const is 1 / (2^32 - 1)
     40         return (float)(this->nextU() * 2.32830644e-10);
     41     }
     42 
     43     /**
     44      *  Returns value [min...max) as a float
     45      */
     46     float nextF(float min, float max) {
     47         return min + this->nextF() * (max - min);
     48     }
     49 
     50 private:
     51     /*
     52      *  These constants taken from "Numerical Recipes in C", reprinted 1999
     53      */
     54     enum {
     55         kMUL = 1664525,
     56         kADD = 1013904223
     57     };
     58     uint32_t    fSeed;
     59 };
     60 
     61 #endif
     62 
     63