[dali_1.9.30] Merge branch 'devel/master'
[platform/core/uifw/dali-core.git] / dali / public-api / math / random.h
1 #ifndef DALI_RANDOM_H
2 #define DALI_RANDOM_H
3
4 /*
5  * Copyright (c) 2020 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // INTERNAL INCLUDES
22 #include <dali/public-api/math/vector4.h>
23
24 namespace Dali
25 {
26 /**
27  * @addtogroup dali_core_math
28  * @{
29  */
30
31 /**
32  * @brief Provides methods to generate and use random values.
33  * @SINCE_1_0.0
34  */
35 namespace Random
36 {
37 /**
38  * @brief Returns a random number between f0 and f1.
39  *
40  * Note, uses a limited number of values.
41  * @SINCE_1_0.0
42  * @param[in] f0 The lower bound
43  * @param[in] f1 The upper bound
44  * @return A random value between the lower and upper bound
45  */
46 inline float Range(float f0, float f1)
47 {
48   float min = std::min(f0, f1);
49   float max = std::max(f0, f1);
50
51   // Ensure we initialize only once. As it's inlined, this static variable will exist in the code-block using it, thus,
52   // will be created and then initialized again when another code-block uses this.
53   static bool initialized(false);
54   if(!initialized)
55   {
56     uint32_t seed = static_cast<uint32_t>(time(nullptr));
57     srand(seed);
58     initialized = true;
59   }
60
61   int32_t randValue = rand();
62   return static_cast<float>(randValue & 0xfff) * (1.0f / 4095.0f) * (max - min) + min;
63 }
64
65 /**
66  * @brief Function to return a normalized axis in a random direction.
67  *
68  * @SINCE_1_0.0
69  * @return The axis
70  */
71 inline Vector4 Axis()
72 {
73   Vector4 axis;
74   // This function needs to return a vector with direction, that is to say a non-zero vector
75   // There is a possibility that a random vector will be a zero vector, so a loop is needed to ensure that a non-zero vector is returned
76   do
77   {
78     axis.x = Range(-1.0f, 1.0f);
79     axis.y = Range(0.0f, 1.0f);
80     axis.z = Range(0.0f, 1.0f);
81     axis.w = 0.0f;
82   } while(axis == Vector4::ZERO);
83   axis.Normalize();
84   return axis;
85 }
86
87 } // namespace Random
88
89 /**
90  * @}
91  */
92 } // namespace Dali
93
94 #endif // DALI_RANDOM_H