1 /*
2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
3 *
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on the
6 * source.
7 *
8 */
9
10 #include <stdlib.h>
11 #include <math.h>
12
13 #include "globalincs/pstypes.h"
14 #include "math/floating.h"
15 #include "io/timer.h"
16
17
18 /**
19 * @brief Rounds off a floating point number to a multiple of some number
20 * @param x Input floating point number
21 * @param multiple Multiple to round to
22 */
fl_roundoff(float x,int multiple)23 float fl_roundoff(float x, int multiple)
24 {
25 float half = (float) multiple / 2.0f;
26
27 if (x < 0)
28 half = -half;
29
30 x += half;
31 return (float) (((int) x / multiple) * multiple);
32 }
33
34 /**
35 * @brief Return random value in range 0.0..1.0- (1.0- means the closest number less than 1.0)
36 */
frand()37 float frand()
38 {
39 int i_rval;
40 do {
41 i_rval = myrand();
42 } while (i_rval == RAND_MAX);
43 float rval = ((float) i_rval) / RAND_MAX;
44 return rval;
45 }
46
47 /**
48 * @brief Return a floating point number in the range min..max.
49 * @param min Minimum (inclusive)
50 * @param max Maxiumum (inclusive)
51 */
frand_range(float min,float max)52 float frand_range(float min, float max)
53 {
54 float rval;
55
56 rval = frand();
57 rval = rval * (max - min) + min;
58
59 return rval;
60 }
61
62 /**
63 * @brief Call this in the frame interval to get TRUE chance times per second.
64 * @details If you want it to return TRUE 3 times per second, call it in the frame interval like so: rand_chance(flFrametime, 3.0f);
65 * @param frametime
66 * @param chance
67 */
rand_chance(float frametime,float chance)68 int rand_chance(float frametime, float chance)
69 {
70 while (--chance > 0.0f)
71 if (frand() < frametime)
72 return 1;
73
74 return frand() < (frametime * (chance + 1.0f));
75 }
76