File: rng.cpp

package info (click to toggle)
openmw 0.50.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 37,076 kB
  • sloc: cpp: 380,958; xml: 2,192; sh: 1,449; python: 911; makefile: 26; javascript: 5
file content (84 lines) | stat: -rw-r--r-- 1,953 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "rng.hpp"

#include <chrono>
#include <random>
#include <sstream>

namespace Misc::Rng
{
    static Generator sGenerator;

    Generator& getGenerator()
    {
        return sGenerator;
    }

    std::string serialize(const Generator& prng)
    {
        std::stringstream ss;
        ss << prng;

        return ss.str();
    }

    void deserialize(std::string_view data, Generator& prng)
    {
        std::stringstream ss;
        ss << data;

        ss.seekg(0);
        ss >> prng;
    }

    unsigned int generateDefaultSeed()
    {
        auto res = static_cast<unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count());
        return res;
    }

    void init(unsigned int seed)
    {
        sGenerator.seed(seed);
    }

    float rollProbability()
    {
        return std::uniform_real_distribution<float>(0, 1 - std::numeric_limits<float>::epsilon())(getGenerator());
    }

    float rollProbability(Generator& prng)
    {
        return std::uniform_real_distribution<float>(0, 1 - std::numeric_limits<float>::epsilon())(prng);
    }

    float rollClosedProbability()
    {
        return std::uniform_real_distribution<float>(0, 1)(getGenerator());
    }

    float rollClosedProbability(Generator& prng)
    {
        return std::uniform_real_distribution<float>(0, 1)(prng);
    }

    int rollDice(int max)
    {
        return max > 0 ? std::uniform_int_distribution<int>(0, max - 1)(getGenerator()) : 0;
    }

    int rollDice(int max, Generator& prng)
    {
        return max > 0 ? std::uniform_int_distribution<int>(0, max - 1)(prng) : 0;
    }

    float deviate(float mean, float deviation)
    {
        return std::uniform_real_distribution<float>(mean - deviation, mean + deviation)(getGenerator());
    }

    float deviate(float mean, float deviation, Generator& prng)
    {
        return std::uniform_real_distribution<float>(mean - deviation, mean + deviation)(prng);
    }

}