[Tizen] Add codes for Dali Windows Backend
[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) 2017 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 // EXTERNAL INCLUDES
21 #include <ctime>
22
23 // INTERNAL INCLUDES
24 #include <dali/public-api/math/vector4.h>
25
26 namespace Dali
27 {
28 /**
29  * @addtogroup dali_core_math
30  * @{
31  */
32
33 /**
34  * @brief Provides methods to generate and use random values.
35  * @SINCE_1_0.0
36  */
37 namespace Random
38 {
39
40 /**
41  * @brief Returns a random number between f0 and f1.
42  *
43  * Note, uses a limited number of values.
44  * @SINCE_1_0.0
45  * @param[in] f0 The lower bound
46  * @param[in] f1 The upper bound
47  * @return A random value between the lower and upper bound
48  */
49 inline float Range(float f0, float f1)
50 {
51   float min = std::min(f0, f1);
52   float max = std::max(f0, f1);
53
54   // Ensure we initialize only once. As it's inlined, this static variable will exist in the code-block using it, thus,
55   // will be created and then initialized again when another code-block uses this.
56   static bool initialized( false );
57   if( !initialized )
58   {
59     auto seed = time( NULL );
60     srand( seed );
61     initialized = true;
62   }
63
64   auto randValue = rand();
65   return (randValue & 0xfff) * (1.0f/4095.0f) * (max-min) + min;
66 }
67
68 /**
69  * @brief Function to return a normalized axis in a random direction.
70  *
71  * @SINCE_1_0.0
72  * @return The axis
73  */
74 inline Vector4 Axis()
75 {
76   Vector4 axis;
77   // This function needs to return a vector with direction, that is to say a non-zero vector
78   // 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
79   do
80   {
81     axis.x = Range(-1.0f, 1.0f);
82     axis.y = Range( 0.0f, 1.0f);
83     axis.z = Range( 0.0f, 1.0f);
84     axis.w = 0.0f;
85   } while (axis == Vector4::ZERO);
86   axis.Normalize();
87   return axis;
88 }
89
90 } // namespace Random
91
92 /**
93  * @}
94  */
95 } // namespace Dali
96
97 #endif // __DALI_RANDOM_H__