00001 /* 00002 * Copyright (C) 2006 The Android Open Source Project 00003 * 00004 * Licensed under the Apache License, Version 2.0 (the "License"); 00005 * you may not use this file except in compliance with the License. 00006 * You may obtain a copy of the License at 00007 * 00008 * http://www.apache.org/licenses/LICENSE-2.0 00009 * 00010 * Unless required by applicable law or agreed to in writing, software 00011 * distributed under the License is distributed on an "AS IS" BASIS, 00012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00013 * See the License for the specific language governing permissions and 00014 * limitations under the License. 00015 */ 00016 00017 #ifndef SkRandom_DEFINED 00018 #define SkRandom_DEFINED 00019 00020 #include "Sk64.h" 00021 #include "SkScalar.h" 00022 00029 class SkRandom { 00030 public: 00031 SkRandom() : fSeed(0) {} 00032 SkRandom(uint32_t seed) : fSeed(seed) {} 00033 00036 uint32_t nextU() { uint32_t r = fSeed * kMul + kAdd; fSeed = r; return r; } 00037 00040 int32_t nextS() { return (int32_t)this->nextU(); } 00041 00044 U16CPU nextU16() { return this->nextU() >> 16; } 00045 00048 S16CPU nextS16() { return this->nextS() >> 16; } 00049 00054 uint32_t nextBits(unsigned bitCount) { 00055 SkASSERT(bitCount > 0 && bitCount <= 32); 00056 return this->nextU() >> (32 - bitCount); 00057 } 00058 00062 uint32_t nextRangeU(uint32_t min, uint32_t max) { 00063 SkASSERT(min <= max); 00064 return min + this->nextU() % (max - min + 1); 00065 } 00066 00070 SkFixed nextUFixed1() { return this->nextU() >> 16; } 00071 00075 SkFixed nextSFixed1() { return this->nextS() >> 15; } 00076 00080 SkScalar nextUScalar1() { return SkFixedToScalar(this->nextUFixed1()); } 00081 00085 SkScalar nextSScalar1() { return SkFixedToScalar(this->nextSFixed1()); } 00086 00089 void next64(Sk64* a) { 00090 SkASSERT(a); 00091 a->set(this->nextS(), this->nextU()); 00092 } 00093 00098 void setSeed(int32_t seed) { fSeed = (uint32_t)seed; } 00099 00100 private: 00101 // See "Numerical Recipes in C", 1992 page 284 for these constants 00102 enum { 00103 kMul = 1664525, 00104 kAdd = 1013904223 00105 }; 00106 uint32_t fSeed; 00107 }; 00108 00109 #endif 00110