random_func.cpp

Go to the documentation of this file.
00001 /* $Id: random_func.cpp 25893 2013-10-20 14:48:08Z fonsinchen $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "../stdafx.h"
00013 #include "random_func.hpp"
00014 #include "bitmath_func.hpp"
00015 
00016 Randomizer _random, _interactive_random;
00017 
00022 uint32 Randomizer::Next()
00023 {
00024   const uint32 s = this->state[0];
00025   const uint32 t = this->state[1];
00026 
00027   this->state[0] = s + ROR(t ^ 0x1234567F, 7) + 1;
00028   return this->state[1] = ROR(s, 3) - 1;
00029 }
00030 
00037 uint32 Randomizer::Next(uint32 limit)
00038 {
00039   return ((uint64)this->Next() * (uint64)limit) >> 32;
00040 }
00041 
00046 void Randomizer::SetSeed(uint32 seed)
00047 {
00048   this->state[0] = seed;
00049   this->state[1] = seed;
00050 }
00051 
00056 void SetRandomSeed(uint32 seed)
00057 {
00058   _random.SetSeed(seed);
00059   _interactive_random.SetSeed(seed * 0x1234567);
00060 }
00061 
00062 #ifdef RANDOM_DEBUG
00063 #include "../network/network.h"
00064 #include "../network/network_server.h"
00065 #include "../network/network_internal.h"
00066 #include "../company_func.h"
00067 #include "../fileio_func.h"
00068 #include "../date_func.h"
00069 
00070 uint32 DoRandom(int line, const char *file)
00071 {
00072   if (_networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != NetworkClientSocket::STATUS_INACTIVE))) {
00073     DEBUG(random, 0, "%08x; %02x; %04x; %02x; %s:%d", _date, _date_fract, _frame_counter, (byte)_current_company, file, line);
00074   }
00075 
00076   return _random.Next();
00077 }
00078 
00079 uint32 DoRandomRange(uint32 limit, int line, const char *file)
00080 {
00081   return ((uint64)DoRandom(line, file) * (uint64)limit) >> 32;
00082 }
00083 #endif /* RANDOM_DEBUG */