medfall

A super great game engine
Log | Files | Refs

pcg.cc (1683B)


      1 /*
      2  * PCG Random Number Generation for C.
      3  *
      4  * Copyright 2014 Melissa O'Neill <oneill@pcg-random.org>
      5  *
      6  * Licensed under the Apache License, Version 2.0 (the "License");
      7  * you may not use this file except in compliance with the License.
      8  * You may obtain a copy of the License at
      9  *
     10  *     http://www.apache.org/licenses/LICENSE-2.0
     11  *
     12  * Unless required by applicable law or agreed to in writing, software
     13  * distributed under the License is distributed on an "AS IS" BASIS,
     14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15  * See the License for the specific language governing permissions and
     16  * limitations under the License.
     17  *
     18  * For additional information about the PCG random number generation scheme,
     19  * including its license and other licensing options, visit
     20  *
     21  *       http://www.pcg-random.org
     22  */
     23 
     24 /*
     25  * This code is derived from the full C implementation, which is in turn
     26  * derived from the canonical C++ PCG implementation. The C++ version
     27  * has many additional features and is preferable if you can use C++ in
     28  * your project.
     29  */
     30 
     31 #include "rng/pcg.h"
     32 
     33 PCG new_pcg() {
     34 	PCG pcg;
     35 	pcg.state = U64( 0x853c49e6748fea9b );
     36 	pcg.inc = U64( 0xda3e39cb94b95bdb );
     37 	return pcg;
     38 }
     39 
     40 PCG new_pcg( u64 state, u64 seq ) {
     41 	PCG pcg;
     42 	pcg.state = 0;
     43 	pcg.inc = ( seq << 1 ) | 1;
     44 	rng_next( &pcg );
     45 	pcg.state += state;
     46 	rng_next( &pcg );
     47 	return pcg;
     48 }
     49 
     50 u32 rng_next( PCG * pcg ) {
     51 	u64 oldstate = pcg->state;
     52 	pcg->state = oldstate * U64( 6364136223846793005 ) + pcg->inc;
     53 	u32 xorshifted = u32( ( ( oldstate >> 18 ) ^ oldstate ) >> 27 );
     54 	u32 rot = u32( oldstate >> 59 );
     55 	return ( xorshifted >> rot ) | ( xorshifted << ( ( -rot ) & 31 ) );
     56 }