ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/common/utils.C
(Generate patch)

Comparing deliantra/server/common/utils.C (file contents):
Revision 1.78 by root, Fri May 16 17:09:38 2008 UTC vs.
Revision 1.96 by root, Mon Apr 5 20:33:13 2010 UTC

1/* 1/*
2 * This file is part of Deliantra, the Roguelike Realtime MMORPG. 2 * This file is part of Deliantra, the Roguelike Realtime MMORPG.
3 * 3 *
4 * Copyright (©) 2005,2006,2007,2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team 4 * Copyright (©) 2005,2006,2007,2008,2009,2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5 * Copyright (©) 2002,2007 Mark Wedel & Crossfire Development Team
6 * Copyright (©) 1992,2007 Frank Tore Johansen
7 * 5 *
8 * Deliantra is free software: you can redistribute it and/or modify 6 * Deliantra is free software: you can redistribute it and/or modify it under
9 * it under the terms of the GNU General Public License as published by 7 * the terms of the Affero GNU General Public License as published by the
10 * the Free Software Foundation, either version 3 of the License, or 8 * Free Software Foundation, either version 3 of the License, or (at your
11 * (at your option) any later version. 9 * option) any later version.
12 * 10 *
13 * This program is distributed in the hope that it will be useful, 11 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details. 14 * GNU General Public License for more details.
17 * 15 *
18 * You should have received a copy of the GNU General Public License 16 * You should have received a copy of the Affero GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * and the GNU General Public License along with this program. If not, see
18 * <http://www.gnu.org/licenses/>.
20 * 19 *
21 * The authors can be reached via e-mail to <support@deliantra.net> 20 * The authors can be reached via e-mail to <support@deliantra.net>
22 */ 21 */
23 22
24/* 23/*
25 * General convenience functions for crossfire. 24 * General convenience functions for deliantra.
26 */ 25 */
27 26
28#include <cstdlib> 27#include <cstdlib>
29#include <sys/types.h> 28#include <sys/types.h>
30#include <unistd.h> 29#include <unistd.h>
32#include <time.h> 31#include <time.h>
33#include <signal.h> 32#include <signal.h>
34 33
35#include <global.h> 34#include <global.h>
36#include <material.h> 35#include <material.h>
36#include <object.h>
37
38#include <sys/time.h>
39#include <sys/resource.h>
37 40
38#include <glib.h> 41#include <glib.h>
39 42
40refcnt_base::refcnt_t refcnt_dummy; 43refcnt_base::refcnt_t refcnt_dummy;
41ssize_t slice_alloc; 44ssize_t slice_alloc;
42rand_gen rndm, rmg_rndm; 45rand_gen rndm, rmg_rndm;
46
47#if !GCC_VERSION(3,4)
48int least_significant_bit (uint32_t x)
49{
50 x &= -x; // this isolates the lowest bit
51
52 int r = 0;
53
54 if (x & 0xaaaaaaaa) r += 1;
55 if (x & 0xcccccccc) r += 2;
56 if (x & 0xf0f0f0f0) r += 4;
57 if (x & 0xff00ff00) r += 8;
58 if (x & 0xffff0000) r += 16;
59
60 return r;
61}
62#endif
43 63
44void 64void
45tausworthe_random_generator::seed (uint32_t seed) 65tausworthe_random_generator::seed (uint32_t seed)
46{ 66{
47 state [0] = seed * 69069U; if (state [0] < 2U) state [0] += 2U; 67 state [0] = seed * 69069U; if (state [0] < 2U) state [0] += 2U;
48 state [1] = state [0] * 69069U; if (state [0] < 8U) state [0] += 8U; 68 state [1] = state [0] * 69069U; if (state [0] < 8U) state [0] += 8U;
49 state [2] = state [1] * 69069U; if (state [0] < 16U) state [0] += 16U; 69 state [2] = state [1] * 69069U; if (state [0] < 16U) state [0] += 16U;
50 state [3] = state [2] * 69069U; if (state [0] < 128U) state [0] += 128U; 70 state [3] = state [2] * 69069U; if (state [0] < 128U) state [0] += 128U;
51 71
52 for (int i = 11; --i; ) 72 for (int i = 11; --i; )
53 operator ()(); 73 next ();
54} 74}
55 75
56uint32_t 76uint32_t
57tausworthe_random_generator::next () 77tausworthe_random_generator::next ()
58{ 78{
62 state [3] = ((state [3] & 0xFFFFFF80U) << 13U) ^ (((state [3] << 3U) ^ state [3]) >> 12U); 82 state [3] = ((state [3] & 0xFFFFFF80U) << 13U) ^ (((state [3] << 3U) ^ state [3]) >> 12U);
63 83
64 return state [0] ^ state [1] ^ state [2] ^ state [3]; 84 return state [0] ^ state [1] ^ state [2] ^ state [3];
65} 85}
66 86
87template<class generator>
67uint32_t 88uint32_t
68tausworthe_random_generator::get_range (uint32_t num) 89random_number_generator<generator>::get_range (uint32_t num)
69{ 90{
70 return (next () * (uint64_t)num) >> 32U; 91 return (this->next () * (uint64_t)num) >> 32U;
71} 92}
72 93
73// return a number within (min .. max) 94// return a number within (min .. max)
95template<class generator>
74int 96int
75tausworthe_random_generator::get_range (int r_min, int r_max) 97random_number_generator<generator>::get_range (int r_min, int r_max)
76{ 98{
77 return r_min + get_range (max (r_max - r_min + 1, 0)); 99 return r_min + get_range (max (r_max - r_min + 1, 0));
78} 100}
79 101
80/* 102template struct random_number_generator<tausworthe_random_generator>;
81 * The random functions here take luck into account when rolling random 103template struct random_number_generator<xorshift_random_generator>;
82 * dice or numbers. This function has less of an impact the larger the 104
83 * difference becomes in the random numbers. IE, the effect is lessened 105/******************************************************************************/
84 * on a 1-1000 roll, vs a 1-6 roll. This can be used by crafty programmers, 106
85 * to specifically disable luck in certain rolls, simply by making the 107/* Checks a player-provided string which will become the msg property of
86 * numbers larger (ie, 1d1000 > 500 vs 1d6 > 3) 108 * an object for dangerous input.
87 */ 109 */
88 110bool
89/* 111msg_is_safe (const char *msg)
90 * Roll a random number between min and max. Uses op to determine luck,
91 * and if goodbad is non-zero, luck increases the roll, if zero, it decreases.
92 * Generally, op should be the player/caster/hitter requesting the roll,
93 * not the recipient (ie, the poor slob getting hit). [garbled 20010916]
94 */
95int
96random_roll (int r_min, int r_max, const object *op, int goodbad)
97{ 112{
98 r_max = max (r_min, r_max); 113 bool safe = true;
99 114
100 int base = r_max - r_min > 1 ? 20 : 50; /* d2 and d3 are corner cases */ 115 /* Trying to cheat by getting data into the object */
116 if (!strncmp (msg, "endmsg", sizeof ("endmsg") - 1)
117 || strstr (msg, "\nendmsg"))
118 safe = false;
101 119
102 if (op->type == PLAYER) 120 /* Trying to make the object talk, and potentially access arbitrary code */
103 { 121 if (object::msg_has_dialogue (msg))
104 int luck = op->stats.luck; 122 safe = false;
105 123
106 if (rndm (base) < min (10, abs (luck)))
107 {
108 //TODO: take luck into account
109 }
110 }
111
112 return rndm (r_min, r_max);
113}
114
115/*
116 * This is a 64 bit version of random_roll above. This is needed
117 * for exp loss calculations for players changing religions.
118 */
119sint64
120random_roll64 (sint64 r_min, sint64 r_max, const object *op, int goodbad)
121{
122 sint64 omin = r_min;
123 sint64 range = max (0, r_max - r_min + 1);
124 int base = range > 2 ? 20 : 50; /* d2 and d3 are corner cases */
125
126 /*
127 * Make a call to get two 32 bit unsigned random numbers, and just to
128 * a little bitshifting.
129 */
130 sint64 ran = (sint64) rndm.next () ^ ((sint64) rndm.next () << 31);
131
132 if (op->type != PLAYER)
133 return ((ran % range) + r_min);
134
135 int luck = op->stats.luck;
136
137 if (rndm (base) < min (10, abs (luck)))
138 {
139 /* we have a winner */
140 ((luck > 0) ? (luck = 1) : (luck = -1));
141 range -= luck;
142 if (range < 1)
143 return (omin); /*check again */
144
145 ((goodbad) ? (r_min += luck) : (range));
146
147 return (max (omin, min (r_max, (ran % range) + r_min)));
148 }
149
150 return ran % range + r_min;
151}
152
153/*
154 * Roll a number of dice (2d3, 4d6). Uses op to determine luck,
155 * If goodbad is non-zero, luck increases the roll, if zero, it decreases.
156 * Generally, op should be the player/caster/hitter requesting the roll,
157 * not the recipient (ie, the poor slob getting hit).
158 * The args are num D size (ie 4d6) [garbled 20010916]
159 */
160int
161die_roll (int num, int size, const object *op, int goodbad)
162{
163 int min, luck, total, i, gotlucky;
164
165 int diff = size;
166 min = 1;
167 luck = total = gotlucky = 0;
168 int base = diff > 2 ? 20 : 50; /* d2 and d3 are corner cases */
169
170 if (size < 2 || diff < 1)
171 {
172 LOG (llevError, "Calling die_roll with num=%d size=%d\n", num, size);
173 return num; /* avoids a float exception */
174 }
175
176 if (op->type == PLAYER)
177 luck = op->stats.luck;
178
179 for (i = 0; i < num; i++)
180 {
181 if (rndm (base) < MIN (10, abs (luck)) && !gotlucky)
182 {
183 /* we have a winner */
184 gotlucky++;
185 ((luck > 0) ? (luck = 1) : (luck = -1));
186 diff -= luck;
187 if (diff < 1)
188 return (num); /*check again */
189 ((goodbad) ? (min += luck) : (diff));
190 total += MAX (1, MIN (size, rndm (diff) + min));
191 }
192 else
193 total += rndm (size) + 1;
194 }
195
196 return total;
197}
198
199/* convert materialname to materialtype_t */
200
201materialtype_t *
202name_to_material (const shstr &name)
203{
204 for (materialtype_t *mt = materialt; mt && mt->next; mt = mt->next)
205 if (name == mt->name)
206 return mt;
207
208 return 0; 124 return safe;
209}
210
211/* when doing transmutation of objects, we have to recheck the resistances,
212 * as some that did not apply previously, may apply now.
213 */
214void
215transmute_materialname (object *op, const object *change)
216{
217 materialtype_t *mt;
218 int j;
219
220 if (op->materialname == NULL)
221 return;
222
223 if (change->materialname != NULL && strcmp (op->materialname, change->materialname))
224 return;
225
226 if (!op->is_armor ())
227 return;
228
229 mt = name_to_material (op->materialname);
230 if (!mt)
231 {
232 LOG (llevError, "archetype '%s>%s' uses nonexistent material '%s'\n", &op->arch->archname, &op->name, &op->materialname);
233 return;
234 }
235
236 for (j = 0; j < NROFATTACKS; j++)
237 if (op->resist[j] == 0 && change->resist[j] != 0)
238 {
239 op->resist[j] += mt->mod[j];
240 if (op->resist[j] > 100)
241 op->resist[j] = 100;
242 if (op->resist[j] < -100)
243 op->resist[j] = -100;
244 }
245}
246
247/* set the materialname and type for an item */
248void
249set_materialname (object *op, int difficulty, materialtype_t *nmt)
250{
251 materialtype_t *mt, *lmt;
252
253 if (op->materialname != NULL)
254 return;
255
256 if (nmt == NULL)
257 {
258 lmt = NULL;
259
260 for (mt = materialt; mt && mt->next; mt = mt->next)
261 if (op->materials & mt->material && rndm (1, 100) <= mt->chance &&
262 difficulty >= mt->difficulty && (op->magic >= mt->magic || mt->magic == 0))
263 {
264 lmt = mt;
265 if (!(op->is_weapon () || op->is_armor ()))
266 break;
267 }
268 }
269 else
270 lmt = nmt;
271
272 if (lmt != NULL)
273 {
274 if (op->stats.dam && op->is_weapon ())
275 {
276 op->stats.dam += lmt->damage;
277 if (op->stats.dam < 1)
278 op->stats.dam = 1;
279 }
280
281 if (op->stats.sp && op->type == BOW)
282 op->stats.sp += lmt->sp;
283 if (op->stats.wc && op->is_weapon ())
284 op->stats.wc += lmt->wc;
285 if (op->is_armor ())
286 {
287 if (op->stats.ac)
288 op->stats.ac += lmt->ac;
289
290 for (int j = 0; j < NROFATTACKS; j++)
291 if (op->resist[j] != 0)
292 {
293 op->resist[j] += lmt->mod[j];
294 if (op->resist[j] > 100)
295 op->resist[j] = 100;
296 if (op->resist[j] < -100)
297 op->resist[j] = -100;
298 }
299 }
300
301 op->materialname = lmt->name;
302 /* dont make it unstackable if it doesn't need to be */
303 if (op->is_weapon () || op->is_armor ())
304 {
305 op->weight = (op->weight * lmt->weight) / 100;
306 op->value = (op->value * lmt->value) / 100;
307 }
308 }
309}
310
311/*
312 * Strip out the media tags from a String.
313 * Warning the input string will contain the result string
314 */
315void
316strip_media_tag (char *message)
317{
318 int in_tag = 0;
319 char *dest;
320 char *src;
321
322 src = dest = message;
323 while (*src != '\0')
324 {
325 if (*src == '[')
326 {
327 in_tag = 1;
328 }
329 else if (in_tag && (*src == ']'))
330 in_tag = 0;
331 else if (!in_tag)
332 {
333 *dest = *src;
334 dest++;
335 }
336 src++;
337 }
338 *dest = '\0';
339}
340
341const char *
342strrstr (const char *haystack, const char *needle)
343{
344 const char *lastneedle;
345
346 lastneedle = NULL;
347 while ((haystack = strstr (haystack, needle)) != NULL)
348 {
349 lastneedle = haystack;
350 haystack++;
351 }
352 return lastneedle;
353
354}
355
356#define EOL_SIZE (sizeof("\n")-1)
357void
358strip_endline (char *buf)
359{
360 if (strlen (buf) < sizeof ("\n"))
361 {
362 return;
363 }
364 if (!strcmp (buf + strlen (buf) - EOL_SIZE, "\n"))
365 buf[strlen (buf) - EOL_SIZE] = '\0';
366}
367
368/**
369 * Replace in string src all occurrences of key by replacement. The resulting
370 * string is put into result; at most resultsize characters (including the
371 * terminating null character) will be written to result.
372 */
373void
374replace (const char *src, const char *key, const char *replacement, char *result, size_t resultsize)
375{
376 size_t resultlen;
377 size_t keylen;
378
379 /* special case to prevent infinite loop if key==replacement=="" */
380 if (strcmp (key, replacement) == 0)
381 {
382 snprintf (result, resultsize, "%s", src);
383 return;
384 }
385
386 keylen = strlen (key);
387
388 resultlen = 0;
389 while (*src != '\0' && resultlen + 1 < resultsize)
390 {
391 if (strncmp (src, key, keylen) == 0)
392 {
393 snprintf (result + resultlen, resultsize - resultlen, "%s", replacement);
394 resultlen += strlen (result + resultlen);
395 src += keylen;
396 }
397 else
398 {
399 result[resultlen++] = *src++;
400 }
401 }
402 result[resultlen] = '\0';
403}
404
405/**
406 * Taking a string as an argument, mutate it into a string that looks like a list.
407 * a 'list' for the purposes here, is a string of items, seperated by commas, except
408 * for the last entry, which has an 'and' before it, and a full stop (period) after it.
409 * This function will also strip all trailing non alphanumeric characters.
410 * It does not insert an oxford comma.
411 */
412void
413make_list_like (char *input)
414{
415 char *p, tmp[MAX_BUF];
416 int i;
417
418 if (!input || strlen (input) > MAX_BUF - 5)
419 return;
420 /* bad stuff would happen if we continued here, the -5 is to make space for ' and ' */
421
422 strncpy (tmp, input, MAX_BUF - 5);
423 /*trim all trailing commas, spaces etc. */
424 for (i = strlen (tmp); !isalnum (tmp[i]) && i >= 0; i--)
425 tmp[i] = '\0';
426
427 strcat (tmp, ".");
428
429 p = strrchr (tmp, ',');
430 if (p)
431 {
432 *p = '\0';
433 strcpy (input, tmp);
434 p++;
435 strcat (input, " and");
436 strcat (input, p);
437 }
438 else
439 strcpy (input, tmp);
440
441 return;
442} 125}
443 126
444///////////////////////////////////////////////////////////////////////////// 127/////////////////////////////////////////////////////////////////////////////
445 128
446void 129void
447fork_abort (const char *msg) 130fork_abort (const char *msg)
448{ 131{
449 if (!fork ()) 132 if (!fork ())
450 { 133 {
134 signal (SIGINT , SIG_IGN);
135 signal (SIGTERM, SIG_IGN);
451 signal (SIGABRT, SIG_DFL); 136 signal (SIGABRT, SIG_IGN);
137
138 signal (SIGSEGV, SIG_DFL);
139 signal (SIGBUS , SIG_DFL);
140 signal (SIGILL , SIG_DFL);
141 signal (SIGTRAP, SIG_DFL);
142
452 // try to put corefiles into a subdirectory, if existing, to allow 143 // try to put corefiles into a subdirectory, if existing, to allow
453 // an administrator to reduce the I/O load. 144 // an administrator to reduce the I/O load.
454 chdir ("cores"); 145 chdir ("cores");
146
147 // try to detach us from as many external dependencies as possible
148 // as coredumping can take time by closing all fd's.
149 {
150 struct rlimit lim;
151
152 if (getrlimit (RLIMIT_NOFILE, &lim))
153 lim.rlim_cur = 1024;
154
155 for (int i = 0; i < lim.rlim_cur; ++i)
156 close (i);
157 }
158
159 {
160 sigset_t empty;
161 sigemptyset (&empty);
162 sigprocmask (SIG_SETMASK, &empty, 0);
163 }
164
165 // try to coredump with SIGTRAP
166 kill (getpid (), SIGTRAP);
455 abort (); 167 abort ();
456 } 168 }
457 169
458 LOG (llevError, "fork abort: %s\n", msg); 170 LOG (llevError, "fork abort: %s\n", msg);
459} 171}
522 234
523#endif 235#endif
524 236
525/******************************************************************************/ 237/******************************************************************************/
526 238
239int
527void assign (char *dst, const char *src, int maxlen) 240assign (char *dst, const char *src, int maxsize)
528{ 241{
529 if (!src) 242 if (!src)
530 src = ""; 243 src = "";
531 244
532 int len = strlen (src); 245 int len = strlen (src);
533 246
534 if (len >= maxlen - 1) 247 if (len >= maxsize)
535 { 248 {
536 if (maxlen <= 4) 249 if (maxsize <= 4)
537 { 250 {
538 memset (dst, '.', maxlen - 1); 251 memset (dst, '.', maxsize - 2);
539 dst [maxlen - 1] = 0; 252 dst [maxsize - 1] = 0;
540 } 253 }
541 else 254 else
542 { 255 {
543 memcpy (dst, src, maxlen - 4); 256 memcpy (dst, src, maxsize - 4);
544 memcpy (dst + maxlen - 4, "...", 4); 257 memcpy (dst + maxsize - 4, "...", 4);
545 } 258 }
259
260 len = maxsize;
546 } 261 }
547 else 262 else
548 memcpy (dst, src, len + 1); 263 memcpy (dst, src, ++len);
549}
550 264
551const char * 265 return len;
266}
267
268char *
269vformat (const char *format, va_list ap)
270{
271 static dynbuf_text bufs[8];
272 static int bufidx;
273
274 dynbuf_text &buf = bufs [++bufidx & 7];
275
276 buf.clear ();
277 buf.vprintf (format, ap);
278 return buf;
279}
280
281char *
552format (const char *format, ...) 282format (const char *format, ...)
553{ 283{
554 static dynbuf_text buf;
555
556 buf.clear ();
557
558 va_list ap; 284 va_list ap;
559 va_start (ap, format); 285 va_start (ap, format);
560 buf.vprintf (format, ap); 286 char *buf = vformat (format, ap);
561 va_end (ap); 287 va_end (ap);
562 288
563 return buf; 289 return buf;
564} 290}
565 291

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines