ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/include/util.h
(Generate patch)

Comparing deliantra/server/include/util.h (file contents):
Revision 1.30 by root, Mon Jan 15 01:50:33 2007 UTC vs.
Revision 1.61 by root, Fri Jan 25 18:09:23 2008 UTC

1/*
2 * This file is part of Deliantra, the Roguelike Realtime MMORPG.
3 *
4 * Copyright (©) 2005,2006,2007 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5 *
6 * Deliantra is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * The authors can be reached via e-mail to <support@deliantra.net>
20 */
21
1#ifndef UTIL_H__ 22#ifndef UTIL_H__
2#define UTIL_H__ 23#define UTIL_H__
3 24
25//#define PREFER_MALLOC
26//#define DEBUG_SALLOC
27
4#if __GNUC__ >= 3 28#if __GNUC__ >= 3
5# define is_constant(c) __builtin_constant_p (c) 29# define is_constant(c) __builtin_constant_p (c)
30# define expect(expr,value) __builtin_expect ((expr),(value))
31# define prefetch(addr,rw,locality) __builtin_prefetch (addr, rw, locality)
6#else 32#else
7# define is_constant(c) 0 33# define is_constant(c) 0
34# define expect(expr,value) (expr)
35# define prefetch(addr,rw,locality)
8#endif 36#endif
37
38#if __GNUC__ < 4 || (__GNUC__ == 4 || __GNUC_MINOR__ < 4)
39# define decltype(x) typeof(x)
40#endif
41
42// put into ifs if you are very sure that the expression
43// is mostly true or mosty false. note that these return
44// booleans, not the expression.
45#define expect_false(expr) expect ((expr) != 0, 0)
46#define expect_true(expr) expect ((expr) != 0, 1)
9 47
10#include <cstddef> 48#include <cstddef>
11#include <cmath> 49#include <cmath>
12#include <new> 50#include <new>
13#include <vector> 51#include <vector>
15#include <glib.h> 53#include <glib.h>
16 54
17#include <shstr.h> 55#include <shstr.h>
18#include <traits.h> 56#include <traits.h>
19 57
58#ifdef DEBUG_SALLOC
59# define g_slice_alloc0(s) debug_slice_alloc0(s)
60# define g_slice_alloc(s) debug_slice_alloc(s)
61# define g_slice_free1(s,p) debug_slice_free1(s,p)
62void *g_slice_alloc (unsigned long size);
63void *g_slice_alloc0 (unsigned long size);
64void g_slice_free1 (unsigned long size, void *ptr);
65#endif
66
20// use a gcc extension for auto declarations until ISO C++ sanctifies them 67// use C0X decltype for auto declarations until ISO C++ sanctifies them (if ever)
21#define AUTODECL(var,expr) typeof(expr) var = (expr) 68#define auto(var,expr) decltype(expr) var = (expr)
22 69
23// very ugly macro that basicaly declares and initialises a variable 70// very ugly macro that basicaly declares and initialises a variable
24// that is in scope for the next statement only 71// that is in scope for the next statement only
25// works only for stuff that can be assigned 0 and converts to false 72// works only for stuff that can be assigned 0 and converts to false
26// (note: works great for pointers) 73// (note: works great for pointers)
27// most ugly macro I ever wrote 74// most ugly macro I ever wrote
28#define declvar(type, name, value) if (type name = 0) { } else if (((name) = (value)), 1) 75#define statementvar(type, name, value) if (type name = 0) { } else if (((name) = (value)), 1)
29 76
30// in range including end 77// in range including end
31#define IN_RANGE_INC(val,beg,end) \ 78#define IN_RANGE_INC(val,beg,end) \
32 ((unsigned int)(val) - (unsigned int)(beg) <= (unsigned int)(end) - (unsigned int)(beg)) 79 ((unsigned int)(val) - (unsigned int)(beg) <= (unsigned int)(end) - (unsigned int)(beg))
33 80
34// in range excluding end 81// in range excluding end
35#define IN_RANGE_EXC(val,beg,end) \ 82#define IN_RANGE_EXC(val,beg,end) \
36 ((unsigned int)(val) - (unsigned int)(beg) < (unsigned int)(end) - (unsigned int)(beg)) 83 ((unsigned int)(val) - (unsigned int)(beg) < (unsigned int)(end) - (unsigned int)(beg))
84
85void fork_abort (const char *msg);
86
87// rationale for using (U) not (T) is to reduce signed/unsigned issues,
88// as a is often a constant while b is the variable. it is still a bug, though.
89template<typename T, typename U> static inline T min (T a, U b) { return (U)a < b ? (U)a : b; }
90template<typename T, typename U> static inline T max (T a, U b) { return (U)a > b ? (U)a : b; }
91template<typename T, typename U, typename V> static inline T clamp (T v, U a, V b) { return v < (T)a ? (T)a : v >(T)b ? (T)b : v; }
92
93template<typename T, typename U> static inline void swap (T& a, U& b) { T t=a; a=(T)b; b=(U)t; }
94
95template<typename T>
96static inline T
97lerp (T val, T min_in, T max_in, T min_out, T max_out)
98{
99 return (val - min_in) * (max_out - min_out) / (max_in - min_in) + min_out;
100}
101
102// lots of stuff taken from FXT
103
104/* Rotate right. This is used in various places for checksumming */
105//TODO: that sucks, use a better checksum algo
106static inline uint32_t
107rotate_right (uint32_t c, uint32_t count = 1)
108{
109 return (c << (32 - count)) | (c >> count);
110}
111
112static inline uint32_t
113rotate_left (uint32_t c, uint32_t count = 1)
114{
115 return (c >> (32 - count)) | (c << count);
116}
117
118// Return abs(a-b)
119// Both a and b must not have the most significant bit set
120static inline uint32_t
121upos_abs_diff (uint32_t a, uint32_t b)
122{
123 long d1 = b - a;
124 long d2 = (d1 & (d1 >> 31)) << 1;
125
126 return d1 - d2; // == (b - d) - (a + d);
127}
128
129// Both a and b must not have the most significant bit set
130static inline uint32_t
131upos_min (uint32_t a, uint32_t b)
132{
133 int32_t d = b - a;
134 d &= d >> 31;
135 return a + d;
136}
137
138// Both a and b must not have the most significant bit set
139static inline uint32_t
140upos_max (uint32_t a, uint32_t b)
141{
142 int32_t d = b - a;
143 d &= d >> 31;
144 return b - d;
145}
37 146
38// this is much faster than crossfires original algorithm 147// this is much faster than crossfires original algorithm
39// on modern cpus 148// on modern cpus
40inline int 149inline int
41isqrt (int n) 150isqrt (int n)
73absdir (int d) 182absdir (int d)
74{ 183{
75 return ((d - 1) & 7) + 1; 184 return ((d - 1) & 7) + 1;
76} 185}
77 186
187extern size_t slice_alloc; // statistics
188
78// makes dynamically allocated objects zero-initialised 189// makes dynamically allocated objects zero-initialised
79struct zero_initialised 190struct zero_initialised
80{ 191{
81 void *operator new (size_t s, void *p) 192 void *operator new (size_t s, void *p)
82 { 193 {
84 return p; 195 return p;
85 } 196 }
86 197
87 void *operator new (size_t s) 198 void *operator new (size_t s)
88 { 199 {
200 slice_alloc += s;
89 return g_slice_alloc0 (s); 201 return g_slice_alloc0 (s);
90 } 202 }
91 203
92 void *operator new[] (size_t s) 204 void *operator new[] (size_t s)
93 { 205 {
206 slice_alloc += s;
94 return g_slice_alloc0 (s); 207 return g_slice_alloc0 (s);
95 } 208 }
96 209
97 void operator delete (void *p, size_t s) 210 void operator delete (void *p, size_t s)
98 { 211 {
212 slice_alloc -= s;
99 g_slice_free1 (s, p); 213 g_slice_free1 (s, p);
100 } 214 }
101 215
102 void operator delete[] (void *p, size_t s) 216 void operator delete[] (void *p, size_t s)
103 { 217 {
218 slice_alloc -= s;
104 g_slice_free1 (s, p); 219 g_slice_free1 (s, p);
105 } 220 }
106}; 221};
107 222
108void *salloc_ (int n) throw (std::bad_alloc); 223void *salloc_ (int n) throw (std::bad_alloc);
123 238
124// for symmetry 239// for symmetry
125template<typename T> 240template<typename T>
126inline void sfree (T *ptr, int n = 1) throw () 241inline void sfree (T *ptr, int n = 1) throw ()
127{ 242{
243#ifdef PREFER_MALLOC
244 free (ptr);
245#else
246 slice_alloc -= n * sizeof (T);
128 g_slice_free1 (n * sizeof (T), (void *)ptr); 247 g_slice_free1 (n * sizeof (T), (void *)ptr);
248#endif
129} 249}
130 250
131// a STL-compatible allocator that uses g_slice 251// a STL-compatible allocator that uses g_slice
132// boy, this is verbose 252// boy, this is verbose
133template<typename Tp> 253template<typename Tp>
181 { 301 {
182 p->~Tp (); 302 p->~Tp ();
183 } 303 }
184}; 304};
185 305
306// P. L'Ecuyer, “Maximally Equidistributed Combined Tausworthe Generators”, Mathematics of Computation, 65, 213 (1996), 203–213.
307// http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps
308// http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps
309struct tausworthe_random_generator
310{
311 // generator
312 uint32_t state [4];
313
314 void operator =(const tausworthe_random_generator &src)
315 {
316 state [0] = src.state [0];
317 state [1] = src.state [1];
318 state [2] = src.state [2];
319 state [3] = src.state [3];
320 }
321
322 void seed (uint32_t seed);
323 uint32_t next ();
324
325 // uniform distribution
326 uint32_t operator ()(uint32_t num)
327 {
328 return is_constant (num)
329 ? (next () * (uint64_t)num) >> 32U
330 : get_range (num);
331 }
332
333 // return a number within (min .. max)
334 int operator () (int r_min, int r_max)
335 {
336 return is_constant (r_min) && is_constant (r_max) && r_min <= r_max
337 ? r_min + operator ()(r_max - r_min + 1)
338 : get_range (r_min, r_max);
339 }
340
341 double operator ()()
342 {
343 return this->next () / (double)0xFFFFFFFFU;
344 }
345
346protected:
347 uint32_t get_range (uint32_t r_max);
348 int get_range (int r_min, int r_max);
349};
350
351typedef tausworthe_random_generator rand_gen;
352
353extern rand_gen rndm;
354
355INTERFACE_CLASS (attachable)
356struct refcnt_base
357{
358 typedef int refcnt_t;
359 mutable refcnt_t ACC (RW, refcnt);
360
361 MTH void refcnt_inc () const { ++refcnt; }
362 MTH void refcnt_dec () const { --refcnt; }
363
364 refcnt_base () : refcnt (0) { }
365};
366
367// to avoid branches with more advanced compilers
368extern refcnt_base::refcnt_t refcnt_dummy;
369
186template<class T> 370template<class T>
187struct refptr 371struct refptr
188{ 372{
373 // p if not null
374 refcnt_base::refcnt_t *refcnt_ref () { return p ? &p->refcnt : &refcnt_dummy; }
375
376 void refcnt_dec ()
377 {
378 if (!is_constant (p))
379 --*refcnt_ref ();
380 else if (p)
381 --p->refcnt;
382 }
383
384 void refcnt_inc ()
385 {
386 if (!is_constant (p))
387 ++*refcnt_ref ();
388 else if (p)
389 ++p->refcnt;
390 }
391
189 T *p; 392 T *p;
190 393
191 refptr () : p(0) { } 394 refptr () : p(0) { }
192 refptr (const refptr<T> &p) : p(p.p) { if (p) p->refcnt_inc (); } 395 refptr (const refptr<T> &p) : p(p.p) { refcnt_inc (); }
193 refptr (T *p) : p(p) { if (p) p->refcnt_inc (); } 396 refptr (T *p) : p(p) { refcnt_inc (); }
194 ~refptr () { if (p) p->refcnt_dec (); } 397 ~refptr () { refcnt_dec (); }
195 398
196 const refptr<T> &operator =(T *o) 399 const refptr<T> &operator =(T *o)
197 { 400 {
401 // if decrementing ever destroys we need to reverse the order here
198 if (p) p->refcnt_dec (); 402 refcnt_dec ();
199 p = o; 403 p = o;
200 if (p) p->refcnt_inc (); 404 refcnt_inc ();
201
202 return *this; 405 return *this;
203 } 406 }
204 407
205 const refptr<T> &operator =(const refptr<T> o) 408 const refptr<T> &operator =(const refptr<T> &o)
206 { 409 {
207 *this = o.p; 410 *this = o.p;
208 return *this; 411 return *this;
209 } 412 }
210 413
211 T &operator * () const { return *p; } 414 T &operator * () const { return *p; }
212 T *operator ->() const { return p; } 415 T *operator ->() const { return p; }
213 416
214 operator T *() const { return p; } 417 operator T *() const { return p; }
215}; 418};
216 419
217typedef refptr<maptile> maptile_ptr; 420typedef refptr<maptile> maptile_ptr;
252 { 455 {
253 return !strcmp (a, b); 456 return !strcmp (a, b);
254 } 457 }
255}; 458};
256 459
460// Mostly the same as std::vector, but insert/erase can reorder
461// the elements, making append(=insert)/remove O(1) instead of O(n).
462//
463// NOTE: only some forms of erase are available
257template<class T> 464template<class T>
258struct unordered_vector : std::vector<T, slice_allocator<T> > 465struct unordered_vector : std::vector<T, slice_allocator<T> >
259{ 466{
260 typedef typename unordered_vector::iterator iterator; 467 typedef typename unordered_vector::iterator iterator;
261 468
271 { 478 {
272 erase ((unsigned int )(i - this->begin ())); 479 erase ((unsigned int )(i - this->begin ()));
273 } 480 }
274}; 481};
275 482
276template<class T, int T::* index> 483// This container blends advantages of linked lists
484// (efficiency) with vectors (random access) by
485// by using an unordered vector and storing the vector
486// index inside the object.
487//
488// + memory-efficient on most 64 bit archs
489// + O(1) insert/remove
490// + free unique (but varying) id for inserted objects
491// + cache-friendly iteration
492// - only works for pointers to structs
493//
494// NOTE: only some forms of erase/insert are available
495typedef int object_vector_index;
496
497template<class T, object_vector_index T::*indexmember>
277struct object_vector : std::vector<T *, slice_allocator<T *> > 498struct object_vector : std::vector<T *, slice_allocator<T *> >
278{ 499{
500 typedef typename object_vector::iterator iterator;
501
502 bool contains (const T *obj) const
503 {
504 return obj->*indexmember;
505 }
506
507 iterator find (const T *obj)
508 {
509 return obj->*indexmember
510 ? this->begin () + obj->*indexmember - 1
511 : this->end ();
512 }
513
514 void push_back (T *obj)
515 {
516 std::vector<T *, slice_allocator<T *> >::push_back (obj);
517 obj->*indexmember = this->size ();
518 }
519
279 void insert (T *obj) 520 void insert (T *obj)
280 { 521 {
281 assert (!(obj->*index));
282 push_back (obj); 522 push_back (obj);
283 obj->*index = this->size ();
284 } 523 }
285 524
286 void insert (T &obj) 525 void insert (T &obj)
287 { 526 {
288 insert (&obj); 527 insert (&obj);
289 } 528 }
290 529
291 void erase (T *obj) 530 void erase (T *obj)
292 { 531 {
293 assert (obj->*index);
294 int pos = obj->*index; 532 unsigned int pos = obj->*indexmember;
295 obj->*index = 0; 533 obj->*indexmember = 0;
296 534
297 if (pos < this->size ()) 535 if (pos < this->size ())
298 { 536 {
299 (*this)[pos - 1] = (*this)[this->size () - 1]; 537 (*this)[pos - 1] = (*this)[this->size () - 1];
300 (*this)[pos - 1]->*index = pos; 538 (*this)[pos - 1]->*indexmember = pos;
301 } 539 }
302 540
303 this->pop_back (); 541 this->pop_back ();
304 } 542 }
305 543
306 void erase (T &obj) 544 void erase (T &obj)
307 { 545 {
308 errase (&obj); 546 erase (&obj);
309 } 547 }
310}; 548};
311
312template<typename T, typename U> static inline T min (T a, U b) { return a < (T)b ? a : (T)b; }
313template<typename T, typename U> static inline T max (T a, U b) { return a > (T)b ? a : (T)b; }
314template<typename T, typename U, typename V> static inline T clamp (T v, U a, V b) { return v < (T)a ? a : v >(T)b ? b : v; }
315
316template<typename T, typename U> static inline void swap (T& a, U& b) { T t=a; a=(T)b; b=(U)t; }
317 549
318// basically does what strncpy should do, but appends "..." to strings exceeding length 550// basically does what strncpy should do, but appends "..." to strings exceeding length
319void assign (char *dst, const char *src, int maxlen); 551void assign (char *dst, const char *src, int maxlen);
320 552
321// type-safe version of assign 553// type-safe version of assign
325 assign ((char *)&dst, src, N); 557 assign ((char *)&dst, src, N);
326} 558}
327 559
328typedef double tstamp; 560typedef double tstamp;
329 561
330// return current time as timestampe 562// return current time as timestamp
331tstamp now (); 563tstamp now ();
332 564
333int similar_direction (int a, int b); 565int similar_direction (int a, int b);
334 566
335#endif 567// like sprintf, but returns a "static" buffer
568const char *format (const char *format, ...);
336 569
570#endif
571

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines