1 #ifndef INCLUDED_FREI0R_MATH_H
2 #define INCLUDED_FREI0R_MATH_H
3 
4 /*
5 
6   Code stripped from The Gimp:
7   INT_MULT(a,b,t)
8   INT_MULT3(a,b,c,t)
9   INT_BLEND(a,b,alpha,tmp)
10   CLAMP
11   ROUND
12   MAX255
13 
14   Code stripped from Drone:
15   CLAMP0255
16   SQR
17 */
18 
19 /* Clamps a int32-range int between 0 and 255 inclusive. */
20 #ifndef CLAMP0255
CLAMP0255(int32_t a)21 static inline unsigned char CLAMP0255(int32_t a)
22 {
23   return (unsigned char)
24     ( (((-a) >> 31) & a)  // 0 if the number was negative
25       | (255 - a) >> 31); // -1 if the number was greater than 255
26 }
27 #endif
28 
29 /* Provided temporary int t, returns a * b / 255 */
30 #ifndef INT_MULT
31 #define INT_MULT(a,b,t)  ((t) = (a) * (b) + 0x80, ((((t) >> 8) + (t)) >> 8))
32 #endif
33 
34 /* This version of INT_MULT3 is very fast, but suffers from some
35    slight roundoff errors.  It returns the correct result 99.987
36    percent of the time */
37 #ifndef INT_MULT3
38 #define INT_MULT3(a,b,c,t)  ((t) = (a) * (b) * (c) + 0x7F5B, \
39                             ((((t) >> 7) + (t)) >> 16))
40 #endif
41 
42 #ifndef INT_BLEND
43 #define INT_BLEND(a,b,alpha,tmp)  (INT_MULT((a) - (b), alpha, tmp) + (b))
44 #endif
45 
46 #ifndef CLAMP
47 //! Clamp x at min and max
48 #define CLAMP(x,min,max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x)))
49 #endif
50 
51 #ifndef ROUND
52 //! Round.
53 #define ROUND(x) ((int32_t)((x)+0.5))
54 #endif
55 
56 #ifndef SQR
57 //! Square.
58 #define SQR(x) ((x) * (x))
59 #endif
60 
61 #ifndef MAX255
62 //! Limit a (0->511) int to 255.
MAX255(uint32_t a)63 uint8_t MAX255(uint32_t a) { return (uint8_t) (a | ((a & 256) - ((a & 256) >> 8))); }
64 #endif
65 
66 #ifndef MIN
67 #define MIN(x, y)  ((x) < (y) ? (x) : (y))
68 #endif
69 
70 #ifndef MAX
71 #define MAX(x, y)  ((x) > (y) ? (x) : (y))
72 #endif
73 
74 #endif
75