BRL-CAD
fixpt.h
Go to the documentation of this file.
1 /* F I X P T . H
2  * BRL-CAD
3  *
4  * Copyright (c) 2004-2014 United States Government as represented by
5  * the U.S. Army Research Laboratory.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License
9  * version 2.1 as published by the Free Software Foundation.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this file; see the file named COPYING for more
18  * information.
19  */
20 /** @addtogroup librt */
21 /** @{ */
22 /** @file fixpt.h
23  *
24  * Data structures and macros for dealing with integer-based fixed
25  * point math.
26  *
27  * These macros use integer instructions for a special "fixed point"
28  * format. The fractional part is stored in 28-bit integer form, to
29  * prevent roundoff errors.
30  *
31  */
32 /** @} */
33 
34 #ifndef LIBRT_PRIMITIVES_FIXPT_H
35 #define LIBRT_PRIMITIVES_FIXPT_H seen
36 
37 #define FIXPT_SCALE ((1<<28)-1)
38 struct fixpt {
39  int i;
40  int f; /* Ranges 0 to FIXPT_SCALE-1 */
41 };
42 
43 
44 #define FIXPT_FLOAT(fp, fl) { \
45  register double d = fl; \
46  fp.f = (d - (fp.i = (int)d)) * FIXPT_SCALE; \
47  FIXPT_NORMALIZE(fp); }
48 
49 #define FLOAT_FIXPT(fp) (fp.i + ((double)fp.f)/FIXPT_SCALE)
50 
51 #define FIXPT_NORMALIZE(fp) { \
52  if (fp.f < 0) { \
53  do { \
54  fp.i--; \
55  fp.f += FIXPT_SCALE; \
56  } while (fp.f < 0); \
57  } else if (fp.f >= FIXPT_SCALE) { \
58  do { \
59  fp.i++; \
60  fp.f -= FIXPT_SCALE; \
61  } while (fp.f >= FIXPT_SCALE); \
62  } }
63 
64 #define FIXPT_ROUND(fp) { \
65  if (fp.f > FIXPT_SCALE/2) { \
66  if (fp.i >= 0) fp.i++; \
67  else fp.i--; \
68  } fp.f = 0; }
69 
70 #define FIXPT_ADD2(o, a, b) {\
71  o.i = a.i + b.i; \
72  o.f = a.f + b.f; \
73  FIXPT_NORMALIZE(o); }
74 
75 #define PR_FIX(str, fp) bu_log("%s = %2d+x%8.8x\n", str, fp.i, fp.f)
76 
77 #define PR_FIX2(str, fp) bu_log("%s = (%2d+x%8.8x, %2d+x%8.8x)\n", \
78  str, fp[0].i, fp[0].f, fp[1].i, fp[1].f)
79 
80 #endif /* LIBRT_PRIMITIVES_FIXPT_H */
81 
82 /*
83  * Local Variables:
84  * mode: C
85  * tab-width: 8
86  * indent-tabs-mode: t
87  * c-file-style: "stroustrup"
88  * End:
89  * ex: shiftwidth=4 tabstop=8
90  */
int i
Definition: fixpt.h:39
int f
Definition: fixpt.h:40
Definition: fixpt.h:38