]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/util.qc
Merge remote branch 'origin/mand1nga/bots/weapons-fixes'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / util.qc
1 string wordwrap_buffer;
2
3 void wordwrap_buffer_put(string s)
4 {
5         wordwrap_buffer = strcat(wordwrap_buffer, s);
6 }
7
8 string wordwrap(string s, float l)
9 {
10         string r;
11         wordwrap_buffer = "";
12         wordwrap_cb(s, l, wordwrap_buffer_put);
13         r = wordwrap_buffer;
14         wordwrap_buffer = "";
15         return r;
16 }
17
18 #ifndef MENUQC
19 #ifndef CSQC
20 void wordwrap_buffer_sprint(string s)
21 {
22         wordwrap_buffer = strcat(wordwrap_buffer, s);
23         if(s == "\n")
24         {
25                 sprint(self, wordwrap_buffer);
26                 wordwrap_buffer = "";
27         }
28 }
29
30 void wordwrap_sprint(string s, float l)
31 {
32         wordwrap_buffer = "";
33         wordwrap_cb(s, l, wordwrap_buffer_sprint);
34         if(wordwrap_buffer != "")
35                 sprint(self, strcat(wordwrap_buffer, "\n"));
36         wordwrap_buffer = "";
37         return;
38 }
39 #endif
40 #endif
41
42 string unescape(string in)
43 {
44         local float i, len;
45         local string str, s;
46
47         // but it doesn't seem to be necessary in my tests at least
48         in = strzone(in);
49
50         len = strlen(in);
51         str = "";
52         for(i = 0; i < len; ++i)
53         {
54                 s = substring(in, i, 1);
55                 if(s == "\\")
56                 {
57                         s = substring(in, i+1, 1);
58                         if(s == "n")
59                                 str = strcat(str, "\n");
60                         else if(s == "\\")
61                                 str = strcat(str, "\\");
62                         else
63                                 str = strcat(str, substring(in, i, 2));
64                         ++i;
65                 } else
66                         str = strcat(str, s);
67         }
68
69         strunzone(in);
70         return str;
71 }
72
73 void wordwrap_cb(string s, float l, void(string) callback)
74 {
75         local string c;
76         local float lleft, i, j, wlen;
77
78         s = strzone(s);
79         lleft = l;
80         for (i = 0;i < strlen(s);++i)
81         {
82                 if (substring(s, i, 2) == "\\n")
83                 {
84                         callback("\n");
85                         lleft = l;
86                         ++i;
87                 }
88                 else if (substring(s, i, 1) == "\n")
89                 {
90                         callback("\n");
91                         lleft = l;
92                 }
93                 else if (substring(s, i, 1) == " ")
94                 {
95                         if (lleft > 0)
96                         {
97                                 callback(" ");
98                                 lleft = lleft - 1;
99                         }
100                 }
101                 else
102                 {
103                         for (j = i+1;j < strlen(s);++j)
104                                 //    ^^ this skips over the first character of a word, which
105                                 //       is ALWAYS part of the word
106                                 //       this is safe since if i+1 == strlen(s), i will become
107                                 //       strlen(s)-1 at the end of this block and the function
108                                 //       will terminate. A space can't be the first character we
109                                 //       read here, and neither can a \n be the start, since these
110                                 //       two cases have been handled above.
111                         {
112                                 c = substring(s, j, 1);
113                                 if (c == " ")
114                                         break;
115                                 if (c == "\\")
116                                         break;
117                                 if (c == "\n")
118                                         break;
119                                 // we need to keep this tempstring alive even if substring is
120                                 // called repeatedly, so call strcat even though we're not
121                                 // doing anything
122                                 callback("");
123                         }
124                         wlen = j - i;
125                         if (lleft < wlen)
126                         {
127                                 callback("\n");
128                                 lleft = l;
129                         }
130                         callback(substring(s, i, wlen));
131                         lleft = lleft - wlen;
132                         i = j - 1;
133                 }
134         }
135         strunzone(s);
136 }
137
138 float dist_point_line(vector p, vector l0, vector ldir)
139 {
140         ldir = normalize(ldir);
141         
142         // remove the component in line direction
143         p = p - (p * ldir) * ldir;
144
145         // vlen of the remaining vector
146         return vlen(p);
147 }
148
149 void depthfirst(entity start, .entity up, .entity downleft, .entity right, void(entity, entity) funcPre, void(entity, entity) funcPost, entity pass)
150 {
151         entity e;
152         e = start;
153         funcPre(pass, e);
154         while(e.downleft)
155         {
156                 e = e.downleft;
157                 funcPre(pass, e);
158         }
159         funcPost(pass, e);
160         while(e != start)
161         {
162                 if(e.right)
163                 {
164                         e = e.right;
165                         funcPre(pass, e);
166                         while(e.downleft)
167                         {
168                                 e = e.downleft;
169                                 funcPre(pass, e);
170                         }
171                 }
172                 else
173                         e = e.up;
174                 funcPost(pass, e);
175         }
176 }
177
178 float median(float a, float b, float c)
179 {
180         if(a < c)
181                 return bound(a, b, c);
182         return bound(c, b, a);
183 }
184
185 // converts a number to a string with the indicated number of decimals
186 // works for up to 10 decimals!
187 string ftos_decimals(float number, float decimals)
188 {
189         // we have sprintf...
190         return sprintf("%.*f", decimals, number);
191 }
192
193 float time;
194 vector colormapPaletteColor(float c, float isPants)
195 {
196         switch(c)
197         {
198                 case  0: return '0.800000 0.800000 0.800000';
199                 case  1: return '0.600000 0.400000 0.000000';
200                 case  2: return '0.000000 1.000000 0.501961';
201                 case  3: return '0.000000 1.000000 0.000000';
202                 case  4: return '1.000000 0.000000 0.000000';
203                 case  5: return '0.000000 0.658824 1.000000';
204                 case  6: return '0.000000 1.000000 1.000000';
205                 case  7: return '0.501961 1.000000 0.000000';
206                 case  8: return '0.501961 0.000000 1.000000';
207                 case  9: return '1.000000 0.000000 1.000000';
208                 case 10: return '1.000000 0.000000 0.501961';
209                 case 11: return '0.600000 0.600000 0.600000';
210                 case 12: return '1.000000 1.000000 0.000000';
211                 case 13: return '0.000000 0.313725 1.000000';
212                 case 14: return '1.000000 0.501961 0.000000';
213                 case 15:
214                         if(isPants)
215                                 return
216                                           '1 0 0' * (0.502 + 0.498 * sin(time / 2.7182818285 + 0.0000000000))
217                                         + '0 1 0' * (0.502 + 0.498 * sin(time / 2.7182818285 + 2.0943951024))
218                                         + '0 0 1' * (0.502 + 0.498 * sin(time / 2.7182818285 + 4.1887902048));
219                         else
220                                 return
221                                           '1 0 0' * (0.502 + 0.498 * sin(time / 3.1415926536 + 5.2359877560))
222                                         + '0 1 0' * (0.502 + 0.498 * sin(time / 3.1415926536 + 3.1415926536))
223                                         + '0 0 1' * (0.502 + 0.498 * sin(time / 3.1415926536 + 1.0471975512));
224                 default: return '0.000 0.000 0.000';
225         }
226 }
227
228 // unzone the string, and return it as tempstring. Safe to be called on string_null
229 string fstrunzone(string s)
230 {
231         string sc;
232         if not(s)
233                 return s;
234         sc = strcat(s, "");
235         strunzone(s);
236         return sc;
237 }
238
239 // Databases (hash tables)
240 #define DB_BUCKETS 8192
241 void db_save(float db, string pFilename)
242 {
243         float fh, i, n;
244         fh = fopen(pFilename, FILE_WRITE);
245         if(fh < 0) 
246         {
247                 print(strcat("^1Can't write DB to ", pFilename));
248                 return;
249         }
250         n = buf_getsize(db);
251         fputs(fh, strcat(ftos(DB_BUCKETS), "\n"));
252         for(i = 0; i < n; ++i)
253                 fputs(fh, strcat(bufstr_get(db, i), "\n"));
254         fclose(fh);
255 }
256
257 float db_create()
258 {
259         return buf_create();
260 }
261
262 float db_load(string pFilename)
263 {
264         float db, fh, i, j, n;
265         string l;
266         db = buf_create();
267         if(db < 0)
268                 return -1;
269         fh = fopen(pFilename, FILE_READ);
270         if(fh < 0)
271                 return db;
272         l = fgets(fh);
273         if(stof(l) == DB_BUCKETS)
274         {
275                 i = 0;
276                 while((l = fgets(fh)))
277                 {
278                         if(l != "")
279                                 bufstr_set(db, i, l);
280                         ++i;
281                 }
282         }
283         else
284         {
285                 // different count of buckets, or a dump?
286                 // need to reorganize the database then (SLOW)
287                 //
288                 // note: we also parse the first line (l) in case the DB file is
289                 // missing the bucket count
290                 do
291                 {
292                         n = tokenizebyseparator(l, "\\");
293                         for(j = 2; j < n; j += 2)
294                                 db_put(db, argv(j-1), uri_unescape(argv(j)));
295                 }
296                 while((l = fgets(fh)));
297         }
298         fclose(fh);
299         return db;
300 }
301
302 void db_dump(float db, string pFilename)
303 {
304         float fh, i, j, n, m;
305         fh = fopen(pFilename, FILE_WRITE);
306         if(fh < 0)
307                 error(strcat("Can't dump DB to ", pFilename));
308         n = buf_getsize(db);
309         fputs(fh, "0\n");
310         for(i = 0; i < n; ++i)
311         {
312                 m = tokenizebyseparator(bufstr_get(db, i), "\\");
313                 for(j = 2; j < m; j += 2)
314                         fputs(fh, strcat("\\", argv(j-1), "\\", argv(j), "\n"));
315         }
316         fclose(fh);
317 }
318
319 void db_close(float db)
320 {
321         buf_del(db);
322 }
323
324 string db_get(float db, string pKey)
325 {
326         float h;
327         h = mod(crc16(FALSE, pKey), DB_BUCKETS);
328         return uri_unescape(infoget(bufstr_get(db, h), pKey));
329 }
330
331 void db_put(float db, string pKey, string pValue)
332 {
333         float h;
334         h = mod(crc16(FALSE, pKey), DB_BUCKETS);
335         bufstr_set(db, h, infoadd(bufstr_get(db, h), pKey, uri_escape(pValue)));
336 }
337
338 void db_test()
339 {
340         float db, i;
341         print("LOAD...\n");
342         db = db_load("foo.db");
343         print("LOADED. FILL...\n");
344         for(i = 0; i < DB_BUCKETS; ++i)
345                 db_put(db, ftos(random()), "X");
346         print("FILLED. SAVE...\n");
347         db_save(db, "foo.db");
348         print("SAVED. CLOSE...\n");
349         db_close(db);
350         print("CLOSED.\n");
351 }
352
353 // Multiline text file buffers
354 float buf_load(string pFilename)
355 {
356         float buf, fh, i;
357         string l;
358         buf = buf_create();
359         if(buf < 0)
360                 return -1;
361         fh = fopen(pFilename, FILE_READ);
362         if(fh < 0)
363                 return buf;
364         i = 0;
365         while((l = fgets(fh)))
366         {
367                 bufstr_set(buf, i, l);
368                 ++i;
369         }
370         fclose(fh);
371         return buf;
372 }
373
374 void buf_save(float buf, string pFilename)
375 {
376         float fh, i, n;
377         fh = fopen(pFilename, FILE_WRITE);
378         if(fh < 0)
379                 error(strcat("Can't write buf to ", pFilename));
380         n = buf_getsize(buf);
381         for(i = 0; i < n; ++i)
382                 fputs(fh, strcat(bufstr_get(buf, i), "\n"));
383         fclose(fh);
384 }
385
386 string GametypeNameFromType(float g)
387 {
388         if      (g == GAME_DEATHMATCH) return "dm";
389         else if (g == GAME_TEAM_DEATHMATCH) return "tdm";
390         else if (g == GAME_DOMINATION) return "dom";
391         else if (g == GAME_CTF) return "ctf";
392         else if (g == GAME_RUNEMATCH) return "rune";
393         else if (g == GAME_LMS) return "lms";
394         else if (g == GAME_ARENA) return "arena";
395         else if (g == GAME_CA) return "ca";
396         else if (g == GAME_KEYHUNT) return "kh";
397         else if (g == GAME_ONSLAUGHT) return "ons";
398         else if (g == GAME_ASSAULT) return "as";
399         else if (g == GAME_RACE) return "rc";
400         else if (g == GAME_NEXBALL) return "nexball";
401         else if (g == GAME_CTS) return "cts";
402         else if (g == GAME_FREEZETAG) return "freezetag";
403         else if (g == GAME_KEEPAWAY) return "ka";
404         return "dm";
405 }
406
407 string mmsss(float tenths)
408 {
409         float minutes;
410         string s;
411         tenths = floor(tenths + 0.5);
412         minutes = floor(tenths / 600);
413         tenths -= minutes * 600;
414         s = ftos(1000 + tenths);
415         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 1));
416 }
417
418 string mmssss(float hundredths)
419 {
420         float minutes;
421         string s;
422         hundredths = floor(hundredths + 0.5);
423         minutes = floor(hundredths / 6000);
424         hundredths -= minutes * 6000;
425         s = ftos(10000 + hundredths);
426         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 2));
427 }
428
429 string ScoreString(float pFlags, float pValue)
430 {
431         string valstr;
432         float l;
433
434         pValue = floor(pValue + 0.5); // round
435
436         if((pValue == 0) && (pFlags & (SFL_HIDE_ZERO | SFL_RANK | SFL_TIME)))
437                 valstr = "";
438         else if(pFlags & SFL_RANK)
439         {
440                 valstr = ftos(pValue);
441                 l = strlen(valstr);
442                 if((l >= 2) && (substring(valstr, l - 2, 1) == "1"))
443                         valstr = strcat(valstr, "th");
444                 else if(substring(valstr, l - 1, 1) == "1")
445                         valstr = strcat(valstr, "st");
446                 else if(substring(valstr, l - 1, 1) == "2")
447                         valstr = strcat(valstr, "nd");
448                 else if(substring(valstr, l - 1, 1) == "3")
449                         valstr = strcat(valstr, "rd");
450                 else
451                         valstr = strcat(valstr, "th");
452         }
453         else if(pFlags & SFL_TIME)
454                 valstr = TIME_ENCODED_TOSTRING(pValue);
455         else
456                 valstr = ftos(pValue);
457         
458         return valstr;
459 }
460
461 vector cross(vector a, vector b)
462 {
463         return
464                 '1 0 0' * (a_y * b_z - a_z * b_y)
465         +       '0 1 0' * (a_z * b_x - a_x * b_z)
466         +       '0 0 1' * (a_x * b_y - a_y * b_x);
467 }
468
469 // compressed vector format:
470 // like MD3, just even shorter
471 //   4 bit pitch (16 angles), 0 is -90, 8 is 0, 16 would be 90
472 //   5 bit yaw (32 angles), 0=0, 8=90, 16=180, 24=270
473 //   7 bit length (logarithmic encoding), 1/8 .. about 7844
474 //     length = 2^(length_encoded/8) / 8
475 // if pitch is 90, yaw does nothing and therefore indicates the sign (yaw is then either 11111 or 11110); 11111 is pointing DOWN
476 // thus, valid values are from 0000.11110.0000000 to 1111.11111.1111111
477 // the special value 0 indicates the zero vector
478
479 float lengthLogTable[128];
480
481 float invertLengthLog(float x)
482 {
483         float l, r, m, lerr, rerr;
484
485         if(x >= lengthLogTable[127])
486                 return 127;
487         if(x <= lengthLogTable[0])
488                 return 0;
489
490         l = 0;
491         r = 127;
492
493         while(r - l > 1)
494         {
495                 m = floor((l + r) / 2);
496                 if(lengthLogTable[m] < x)
497                         l = m;
498                 else
499                         r = m;
500         }
501
502         // now: r is >=, l is <
503         lerr = (x - lengthLogTable[l]);
504         rerr = (lengthLogTable[r] - x);
505         if(lerr < rerr)
506                 return l;
507         return r;
508 }
509
510 vector decompressShortVector(float data)
511 {
512         vector out;
513         float pitch, yaw, len;
514         if(data == 0)
515                 return '0 0 0';
516         pitch = (data & 0xF000) / 0x1000;
517         yaw =   (data & 0x0F80) / 0x80;
518         len =   (data & 0x007F);
519
520         //print("\ndecompress: pitch ", ftos(pitch)); print("yaw ", ftos(yaw)); print("len ", ftos(len), "\n");
521
522         if(pitch == 0)
523         {
524                 out_x = 0;
525                 out_y = 0;
526                 if(yaw == 31)
527                         out_z = -1;
528                 else
529                         out_z = +1;
530         }
531         else
532         {
533                 yaw   = .19634954084936207740 * yaw;
534                 pitch = .19634954084936207740 * pitch - 1.57079632679489661922;
535                 out_x = cos(yaw) *  cos(pitch);
536                 out_y = sin(yaw) *  cos(pitch);
537                 out_z =            -sin(pitch);
538         }
539
540         //print("decompressed: ", vtos(out), "\n");
541
542         return out * lengthLogTable[len];
543 }
544
545 float compressShortVector(vector vec)
546 {
547         vector ang;
548         float pitch, yaw, len;
549         if(vlen(vec) == 0)
550                 return 0;
551         //print("compress: ", vtos(vec), "\n");
552         ang = vectoangles(vec);
553         ang_x = -ang_x;
554         if(ang_x < -90)
555                 ang_x += 360;
556         if(ang_x < -90 && ang_x > +90)
557                 error("BOGUS vectoangles");
558         //print("angles: ", vtos(ang), "\n");
559
560         pitch = floor(0.5 + (ang_x + 90) * 16 / 180) & 15; // -90..90 to 0..14
561         if(pitch == 0)
562         {
563                 if(vec_z < 0)
564                         yaw = 31;
565                 else
566                         yaw = 30;
567         }
568         else
569                 yaw = floor(0.5 + ang_y * 32 / 360)          & 31; // 0..360 to 0..32
570         len = invertLengthLog(vlen(vec));
571
572         //print("compressed: pitch ", ftos(pitch)); print("yaw ", ftos(yaw)); print("len ", ftos(len), "\n");
573
574         return (pitch * 0x1000) + (yaw * 0x80) + len;
575 }
576
577 void compressShortVector_init()
578 {
579         float l, f, i;
580         l = 1;
581         f = pow(2, 1/8);
582         for(i = 0; i < 128; ++i)
583         {
584                 lengthLogTable[i] = l;
585                 l *= f;
586         }
587
588         if(cvar("developer"))
589         {
590                 print("Verifying vector compression table...\n");
591                 for(i = 0x0F00; i < 0xFFFF; ++i)
592                         if(i != compressShortVector(decompressShortVector(i)))
593                         {
594                                 print("BROKEN vector compression: ", ftos(i));
595                                 print(" -> ", vtos(decompressShortVector(i)));
596                                 print(" -> ", ftos(compressShortVector(decompressShortVector(i))));
597                                 print("\n");
598                                 error("b0rk");
599                         }
600                 print("Done.\n");
601         }
602 }
603
604 #ifndef MENUQC
605 float CheckWireframeBox(entity forent, vector v0, vector dvx, vector dvy, vector dvz)
606 {
607         traceline(v0, v0 + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
608         traceline(v0, v0 + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
609         traceline(v0, v0 + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
610         traceline(v0 + dvx, v0 + dvx + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
611         traceline(v0 + dvx, v0 + dvx + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
612         traceline(v0 + dvy, v0 + dvy + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
613         traceline(v0 + dvy, v0 + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
614         traceline(v0 + dvz, v0 + dvz + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
615         traceline(v0 + dvz, v0 + dvz + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
616         traceline(v0 + dvx + dvy, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
617         traceline(v0 + dvx + dvz, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
618         traceline(v0 + dvy + dvz, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
619         return 1;
620 }
621 #endif
622
623 string fixPriorityList(string order, float from, float to, float subtract, float complete)
624 {
625         string neworder;
626         float i, n, w;
627
628         n = tokenize_console(order);
629         neworder = "";
630         for(i = 0; i < n; ++i)
631         {
632                 w = stof(argv(i));
633                 if(w == floor(w))
634                 {
635                         if(w >= from && w <= to)
636                                 neworder = strcat(neworder, ftos(w), " ");
637                         else
638                         {
639                                 w -= subtract;
640                                 if(w >= from && w <= to)
641                                         neworder = strcat(neworder, ftos(w), " ");
642                         }
643                 }
644         }
645
646         if(complete)
647         {
648                 n = tokenize_console(neworder);
649                 for(w = to; w >= from; --w)
650                 {
651                         for(i = 0; i < n; ++i)
652                                 if(stof(argv(i)) == w)
653                                         break;
654                         if(i == n) // not found
655                                 neworder = strcat(neworder, ftos(w), " ");
656                 }
657         }
658         
659         return substring(neworder, 0, strlen(neworder) - 1);
660 }
661
662 string mapPriorityList(string order, string(string) mapfunc)
663 {
664         string neworder;
665         float i, n;
666
667         n = tokenize_console(order);
668         neworder = "";
669         for(i = 0; i < n; ++i)
670                 neworder = strcat(neworder, mapfunc(argv(i)), " ");
671         
672         return substring(neworder, 0, strlen(neworder) - 1);
673 }
674
675 string swapInPriorityList(string order, float i, float j)
676 {
677         string s;
678         float w, n;
679
680         n = tokenize_console(order);
681
682         if(i >= 0 && i < n && j >= 0 && j < n && i != j)
683         {
684                 s = "";
685                 for(w = 0; w < n; ++w)
686                 {
687                         if(w == i)
688                                 s = strcat(s, argv(j), " ");
689                         else if(w == j)
690                                 s = strcat(s, argv(i), " ");
691                         else
692                                 s = strcat(s, argv(w), " ");
693                 }
694                 return substring(s, 0, strlen(s) - 1);
695         }
696         
697         return order;
698 }
699
700 float cvar_value_issafe(string s)
701 {
702         if(strstrofs(s, "\"", 0) >= 0)
703                 return 0;
704         if(strstrofs(s, "\\", 0) >= 0)
705                 return 0;
706         if(strstrofs(s, ";", 0) >= 0)
707                 return 0;
708         if(strstrofs(s, "$", 0) >= 0)
709                 return 0;
710         if(strstrofs(s, "\r", 0) >= 0)
711                 return 0;
712         if(strstrofs(s, "\n", 0) >= 0)
713                 return 0;
714         return 1;
715 }
716
717 #ifndef MENUQC
718 void get_mi_min_max(float mode)
719 {
720         vector mi, ma;
721
722         if(mi_shortname)
723                 strunzone(mi_shortname);
724         mi_shortname = mapname;
725         if(!strcasecmp(substring(mi_shortname, 0, 5), "maps/"))
726                 mi_shortname = substring(mi_shortname, 5, strlen(mi_shortname) - 5);
727         if(!strcasecmp(substring(mi_shortname, strlen(mi_shortname) - 4, 4), ".bsp"))
728                 mi_shortname = substring(mi_shortname, 0, strlen(mi_shortname) - 4);
729         mi_shortname = strzone(mi_shortname);
730
731 #ifdef CSQC
732         mi = world.mins;
733         ma = world.maxs;
734 #else
735         mi = world.absmin;
736         ma = world.absmax;
737 #endif
738
739         mi_min = mi;
740         mi_max = ma;
741         MapInfo_Get_ByName(mi_shortname, 0, 0);
742         if(MapInfo_Map_mins_x < MapInfo_Map_maxs_x)
743         {
744                 mi_min = MapInfo_Map_mins;
745                 mi_max = MapInfo_Map_maxs;
746         }
747         else
748         {
749                 // not specified
750                 if(mode)
751                 {
752                         // be clever
753                         tracebox('1 0 0' * mi_x,
754                                          '0 1 0' * mi_y + '0 0 1' * mi_z,
755                                          '0 1 0' * ma_y + '0 0 1' * ma_z,
756                                          '1 0 0' * ma_x,
757                                          MOVE_WORLDONLY,
758                                          world);
759                         if(!trace_startsolid)
760                                 mi_min_x = trace_endpos_x;
761
762                         tracebox('0 1 0' * mi_y,
763                                          '1 0 0' * mi_x + '0 0 1' * mi_z,
764                                          '1 0 0' * ma_x + '0 0 1' * ma_z,
765                                          '0 1 0' * ma_y,
766                                          MOVE_WORLDONLY,
767                                          world);
768                         if(!trace_startsolid)
769                                 mi_min_y = trace_endpos_y;
770
771                         tracebox('0 0 1' * mi_z,
772                                          '1 0 0' * mi_x + '0 1 0' * mi_y,
773                                          '1 0 0' * ma_x + '0 1 0' * ma_y,
774                                          '0 0 1' * ma_z,
775                                          MOVE_WORLDONLY,
776                                          world);
777                         if(!trace_startsolid)
778                                 mi_min_z = trace_endpos_z;
779
780                         tracebox('1 0 0' * ma_x,
781                                          '0 1 0' * mi_y + '0 0 1' * mi_z,
782                                          '0 1 0' * ma_y + '0 0 1' * ma_z,
783                                          '1 0 0' * mi_x,
784                                          MOVE_WORLDONLY,
785                                          world);
786                         if(!trace_startsolid)
787                                 mi_max_x = trace_endpos_x;
788
789                         tracebox('0 1 0' * ma_y,
790                                          '1 0 0' * mi_x + '0 0 1' * mi_z,
791                                          '1 0 0' * ma_x + '0 0 1' * ma_z,
792                                          '0 1 0' * mi_y,
793                                          MOVE_WORLDONLY,
794                                          world);
795                         if(!trace_startsolid)
796                                 mi_max_y = trace_endpos_y;
797
798                         tracebox('0 0 1' * ma_z,
799                                          '1 0 0' * mi_x + '0 1 0' * mi_y,
800                                          '1 0 0' * ma_x + '0 1 0' * ma_y,
801                                          '0 0 1' * mi_z,
802                                          MOVE_WORLDONLY,
803                                          world);
804                         if(!trace_startsolid)
805                                 mi_max_z = trace_endpos_z;
806                 }
807         }
808 }
809
810 void get_mi_min_max_texcoords(float mode)
811 {
812         vector extend;
813
814         get_mi_min_max(mode);
815
816         mi_picmin = mi_min;
817         mi_picmax = mi_max;
818
819         // extend mi_picmax to get a square aspect ratio
820         // center the map in that area
821         extend = mi_picmax - mi_picmin;
822         if(extend_y > extend_x)
823         {
824                 mi_picmin_x -= (extend_y - extend_x) * 0.5;
825                 mi_picmax_x += (extend_y - extend_x) * 0.5;
826         }
827         else
828         {
829                 mi_picmin_y -= (extend_x - extend_y) * 0.5;
830                 mi_picmax_y += (extend_x - extend_y) * 0.5;
831         }
832
833         // add another some percent
834         extend = (mi_picmax - mi_picmin) * (1 / 64.0);
835         mi_picmin -= extend;
836         mi_picmax += extend;
837
838         // calculate the texcoords
839         mi_pictexcoord0 = mi_pictexcoord1 = mi_pictexcoord2 = mi_pictexcoord3 = '0 0 0';
840         // first the two corners of the origin
841         mi_pictexcoord0_x = (mi_min_x - mi_picmin_x) / (mi_picmax_x - mi_picmin_x);
842         mi_pictexcoord0_y = (mi_min_y - mi_picmin_y) / (mi_picmax_y - mi_picmin_y);
843         mi_pictexcoord2_x = (mi_max_x - mi_picmin_x) / (mi_picmax_x - mi_picmin_x);
844         mi_pictexcoord2_y = (mi_max_y - mi_picmin_y) / (mi_picmax_y - mi_picmin_y);
845         // then the other corners
846         mi_pictexcoord1_x = mi_pictexcoord0_x;
847         mi_pictexcoord1_y = mi_pictexcoord2_y;
848         mi_pictexcoord3_x = mi_pictexcoord2_x;
849         mi_pictexcoord3_y = mi_pictexcoord0_y;
850 }
851 #endif
852
853 #ifdef CSQC
854 void cvar_settemp(string pKey, string pValue)
855 {
856         error("cvar_settemp called from CSQC - use cvar_clientsettemp instead!");
857 }
858 void cvar_settemp_restore()
859 {
860         error("cvar_settemp_restore called from CSQC - use cvar_clientsettemp instead!");
861 }
862 #else
863 void cvar_settemp(string pKey, string pValue)
864 {
865         float i;
866         string settemp_var;
867         if(cvar_string(pKey) == pValue)
868                 return;
869         i = cvar("settemp_idx");
870         cvar_set("settemp_idx", ftos(i+1));
871         settemp_var = strcat("_settemp_x", ftos(i));
872 #ifdef MENUQC
873         registercvar(settemp_var, "", 0);
874 #else
875         registercvar(settemp_var, "");
876 #endif
877         cvar_set("settemp_list", strcat("1 ", pKey, " ", settemp_var, " ", cvar_string("settemp_list")));
878         cvar_set(settemp_var, cvar_string(pKey));
879         cvar_set(pKey, pValue);
880 }
881
882 void cvar_settemp_restore()
883 {
884         // undo what cvar_settemp did
885         float n, i;
886         n = tokenize_console(cvar_string("settemp_list"));
887         for(i = 0; i < n - 3; i += 3)
888                 cvar_set(argv(i + 1), cvar_string(argv(i + 2)));
889         cvar_set("settemp_list", "0");
890 }
891 #endif
892
893 float almost_equals(float a, float b)
894 {
895         float eps;
896         eps = (max(a, -a) + max(b, -b)) * 0.001;
897         if(a - b < eps && b - a < eps)
898                 return TRUE;
899         return FALSE;
900 }
901
902 float almost_in_bounds(float a, float b, float c)
903 {
904         float eps;
905         eps = (max(a, -a) + max(c, -c)) * 0.001;
906         return b == median(a - eps, b, c + eps);
907 }
908
909 float power2of(float e)
910 {
911         return pow(2, e);
912 }
913 float log2of(float x)
914 {
915         // NOTE: generated code
916         if(x > 2048)
917                 if(x > 131072)
918                         if(x > 1048576)
919                                 if(x > 4194304)
920                                         return 23;
921                                 else
922                                         if(x > 2097152)
923                                                 return 22;
924                                         else
925                                                 return 21;
926                         else
927                                 if(x > 524288)
928                                         return 20;
929                                 else
930                                         if(x > 262144)
931                                                 return 19;
932                                         else
933                                                 return 18;
934                 else
935                         if(x > 16384)
936                                 if(x > 65536)
937                                         return 17;
938                                 else
939                                         if(x > 32768)
940                                                 return 16;
941                                         else
942                                                 return 15;
943                         else
944                                 if(x > 8192)
945                                         return 14;
946                                 else
947                                         if(x > 4096)
948                                                 return 13;
949                                         else
950                                                 return 12;
951         else
952                 if(x > 32)
953                         if(x > 256)
954                                 if(x > 1024)
955                                         return 11;
956                                 else
957                                         if(x > 512)
958                                                 return 10;
959                                         else
960                                                 return 9;
961                         else
962                                 if(x > 128)
963                                         return 8;
964                                 else
965                                         if(x > 64)
966                                                 return 7;
967                                         else
968                                                 return 6;
969                 else
970                         if(x > 4)
971                                 if(x > 16)
972                                         return 5;
973                                 else
974                                         if(x > 8)
975                                                 return 4;
976                                         else
977                                                 return 3;
978                         else
979                                 if(x > 2)
980                                         return 2;
981                                 else
982                                         if(x > 1)
983                                                 return 1;
984                                         else
985                                                 return 0;
986 }
987
988 float rgb_mi_ma_to_hue(vector rgb, float mi, float ma)
989 {
990         if(mi == ma)
991                 return 0;
992         else if(ma == rgb_x)
993         {
994                 if(rgb_y >= rgb_z)
995                         return (rgb_y - rgb_z) / (ma - mi);
996                 else
997                         return (rgb_y - rgb_z) / (ma - mi) + 6;
998         }
999         else if(ma == rgb_y)
1000                 return (rgb_z - rgb_x) / (ma - mi) + 2;
1001         else // if(ma == rgb_z)
1002                 return (rgb_x - rgb_y) / (ma - mi) + 4;
1003 }
1004
1005 vector hue_mi_ma_to_rgb(float hue, float mi, float ma)
1006 {
1007         vector rgb;
1008
1009         hue -= 6 * floor(hue / 6);
1010
1011         //else if(ma == rgb_x)
1012         //      hue = 60 * (rgb_y - rgb_z) / (ma - mi);
1013         if(hue <= 1)
1014         {
1015                 rgb_x = ma;
1016                 rgb_y = hue * (ma - mi) + mi;
1017                 rgb_z = mi;
1018         }
1019         //else if(ma == rgb_y)
1020         //      hue = 60 * (rgb_z - rgb_x) / (ma - mi) + 120;
1021         else if(hue <= 2)
1022         {
1023                 rgb_x = (2 - hue) * (ma - mi) + mi;
1024                 rgb_y = ma;
1025                 rgb_z = mi;
1026         }
1027         else if(hue <= 3)
1028         {
1029                 rgb_x = mi;
1030                 rgb_y = ma;
1031                 rgb_z = (hue - 2) * (ma - mi) + mi;
1032         }
1033         //else // if(ma == rgb_z)
1034         //      hue = 60 * (rgb_x - rgb_y) / (ma - mi) + 240;
1035         else if(hue <= 4)
1036         {
1037                 rgb_x = mi;
1038                 rgb_y = (4 - hue) * (ma - mi) + mi;
1039                 rgb_z = ma;
1040         }
1041         else if(hue <= 5)
1042         {
1043                 rgb_x = (hue - 4) * (ma - mi) + mi;
1044                 rgb_y = mi;
1045                 rgb_z = ma;
1046         }
1047         //else if(ma == rgb_x)
1048         //      hue = 60 * (rgb_y - rgb_z) / (ma - mi);
1049         else // if(hue <= 6)
1050         {
1051                 rgb_x = ma;
1052                 rgb_y = mi;
1053                 rgb_z = (6 - hue) * (ma - mi) + mi;
1054         }
1055
1056         return rgb;
1057 }
1058
1059 vector rgb_to_hsv(vector rgb)
1060 {
1061         float mi, ma;
1062         vector hsv;
1063
1064         mi = min3(rgb_x, rgb_y, rgb_z);
1065         ma = max3(rgb_x, rgb_y, rgb_z);
1066
1067         hsv_x = rgb_mi_ma_to_hue(rgb, mi, ma);
1068         hsv_z = ma;
1069
1070         if(ma == 0)
1071                 hsv_y = 0;
1072         else
1073                 hsv_y = 1 - mi/ma;
1074         
1075         return hsv;
1076 }
1077
1078 vector hsv_to_rgb(vector hsv)
1079 {
1080         return hue_mi_ma_to_rgb(hsv_x, hsv_z * (1 - hsv_y), hsv_z);
1081 }
1082
1083 vector rgb_to_hsl(vector rgb)
1084 {
1085         float mi, ma;
1086         vector hsl;
1087
1088         mi = min3(rgb_x, rgb_y, rgb_z);
1089         ma = max3(rgb_x, rgb_y, rgb_z);
1090
1091         hsl_x = rgb_mi_ma_to_hue(rgb, mi, ma);
1092         
1093         hsl_z = 0.5 * (mi + ma);
1094         if(mi == ma)
1095                 hsl_y = 0;
1096         else if(hsl_z <= 0.5)
1097                 hsl_y = (ma - mi) / (2*hsl_z);
1098         else // if(hsl_z > 0.5)
1099                 hsl_y = (ma - mi) / (2 - 2*hsl_z);
1100         
1101         return hsl;
1102 }
1103
1104 vector hsl_to_rgb(vector hsl)
1105 {
1106         float mi, ma, maminusmi;
1107
1108         if(hsl_z <= 0.5)
1109                 maminusmi = hsl_y * 2 * hsl_z;
1110         else
1111                 maminusmi = hsl_y * (2 - 2 * hsl_z);
1112         
1113         // hsl_z     = 0.5 * mi + 0.5 * ma
1114         // maminusmi =     - mi +       ma
1115         mi = hsl_z - 0.5 * maminusmi;
1116         ma = hsl_z + 0.5 * maminusmi;
1117
1118         return hue_mi_ma_to_rgb(hsl_x, mi, ma);
1119 }
1120
1121 string rgb_to_hexcolor(vector rgb)
1122 {
1123         return
1124                 strcat(
1125                         "^x",
1126                         DEC_TO_HEXDIGIT(floor(rgb_x * 15 + 0.5)),
1127                         DEC_TO_HEXDIGIT(floor(rgb_y * 15 + 0.5)),
1128                         DEC_TO_HEXDIGIT(floor(rgb_z * 15 + 0.5))
1129                 );
1130 }
1131
1132 // requires that m2>m1 in all coordinates, and that m4>m3
1133 float boxesoverlap(vector m1, vector m2, vector m3, vector m4) {return m2_x >= m3_x && m1_x <= m4_x && m2_y >= m3_y && m1_y <= m4_y && m2_z >= m3_z && m1_z <= m4_z;};
1134
1135 // requires the same, but is a stronger condition
1136 float boxinsidebox(vector smins, vector smaxs, vector bmins, vector bmaxs) {return smins_x >= bmins_x && smaxs_x <= bmaxs_x && smins_y >= bmins_y && smaxs_y <= bmaxs_y && smins_z >= bmins_z && smaxs_z <= bmaxs_z;};
1137
1138 #ifndef MENUQC
1139 #endif
1140
1141 float textLengthUpToWidth(string theText, float maxWidth, vector theSize, textLengthUpToWidth_widthFunction_t w)
1142 {
1143         float ICanHasKallerz;
1144
1145         // detect color codes support in the width function
1146         ICanHasKallerz = (w("^7", theSize) == 0);
1147
1148         // STOP.
1149         // The following function is SLOW.
1150         // For your safety and for the protection of those around you...
1151         // DO NOT CALL THIS AT HOME.
1152         // No really, don't.
1153         if(w(theText, theSize) <= maxWidth)
1154                 return strlen(theText); // yeah!
1155
1156         // binary search for right place to cut string
1157         float ch;
1158         float left, right, middle; // this always works
1159         left = 0;
1160         right = strlen(theText); // this always fails
1161         do
1162         {
1163                 middle = floor((left + right) / 2);
1164                 if(w(substring(theText, 0, middle), theSize) <= maxWidth)
1165                         left = middle;
1166                 else
1167                         right = middle;
1168         }
1169         while(left < right - 1);
1170
1171         if(ICanHasKallerz)
1172         {
1173                 // NOTE: when color codes are involved, this binary search is,
1174                 // mathematically, BROKEN. However, it is obviously guaranteed to
1175                 // terminate, as the range still halves each time - but nevertheless, it is
1176                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
1177                 // range, and "right" is outside).
1178                 
1179                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
1180                 // and decrease left on the basis of the chars detected of the truncated tag
1181                 // Even if the ^xrgb tag is not complete/correct, left is decreased
1182                 // (sometimes too much but with a correct result)
1183                 // it fixes also ^[0-9]
1184                 while(left >= 1 && substring(theText, left-1, 1) == "^")
1185                         left-=1;
1186
1187                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
1188                         left-=2;
1189                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
1190                         {
1191                                 ch = str2chr(theText, left-1);
1192                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
1193                                         left-=3;
1194                         }
1195                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
1196                         {
1197                                 ch = str2chr(theText, left-2);
1198                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
1199                                 {
1200                                         ch = str2chr(theText, left-1);
1201                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
1202                                                 left-=4;
1203                                 }
1204                         }
1205         }
1206         
1207         return left;
1208 }
1209
1210 float textLengthUpToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t w)
1211 {
1212         float ICanHasKallerz;
1213
1214         // detect color codes support in the width function
1215         ICanHasKallerz = (w("^7") == 0);
1216
1217         // STOP.
1218         // The following function is SLOW.
1219         // For your safety and for the protection of those around you...
1220         // DO NOT CALL THIS AT HOME.
1221         // No really, don't.
1222         if(w(theText) <= maxWidth)
1223                 return strlen(theText); // yeah!
1224
1225         // binary search for right place to cut string
1226         float ch;
1227         float left, right, middle; // this always works
1228         left = 0;
1229         right = strlen(theText); // this always fails
1230         do
1231         {
1232                 middle = floor((left + right) / 2);
1233                 if(w(substring(theText, 0, middle)) <= maxWidth)
1234                         left = middle;
1235                 else
1236                         right = middle;
1237         }
1238         while(left < right - 1);
1239
1240         if(ICanHasKallerz)
1241         {
1242                 // NOTE: when color codes are involved, this binary search is,
1243                 // mathematically, BROKEN. However, it is obviously guaranteed to
1244                 // terminate, as the range still halves each time - but nevertheless, it is
1245                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
1246                 // range, and "right" is outside).
1247                 
1248                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
1249                 // and decrease left on the basis of the chars detected of the truncated tag
1250                 // Even if the ^xrgb tag is not complete/correct, left is decreased
1251                 // (sometimes too much but with a correct result)
1252                 // it fixes also ^[0-9]
1253                 while(left >= 1 && substring(theText, left-1, 1) == "^")
1254                         left-=1;
1255
1256                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
1257                         left-=2;
1258                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
1259                         {
1260                                 ch = str2chr(theText, left-1);
1261                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
1262                                         left-=3;
1263                         }
1264                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
1265                         {
1266                                 ch = str2chr(theText, left-2);
1267                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
1268                                 {
1269                                         ch = str2chr(theText, left-1);
1270                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
1271                                                 left-=4;
1272                                 }
1273                         }
1274         }
1275         
1276         return left;
1277 }
1278
1279 string getWrappedLine(float w, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1280 {
1281         float cantake;
1282         float take;
1283         string s;
1284
1285         s = getWrappedLine_remaining;
1286
1287         cantake = textLengthUpToWidth(s, w, theFontSize, tw);
1288         if(cantake > 0 && cantake < strlen(s))
1289         {
1290                 take = cantake - 1;
1291                 while(take > 0 && substring(s, take, 1) != " ")
1292                         --take;
1293                 if(take == 0)
1294                 {
1295                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
1296                         if(getWrappedLine_remaining == "")
1297                                 getWrappedLine_remaining = string_null;
1298                         return substring(s, 0, cantake);
1299                 }
1300                 else
1301                 {
1302                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1303                         if(getWrappedLine_remaining == "")
1304                                 getWrappedLine_remaining = string_null;
1305                         return substring(s, 0, take);
1306                 }
1307         }
1308         else
1309         {
1310                 getWrappedLine_remaining = string_null;
1311                 return s;
1312         }
1313 }
1314
1315 string getWrappedLineLen(float w, textLengthUpToLength_lenFunction_t tw)
1316 {
1317         float cantake;
1318         float take;
1319         string s;
1320
1321         s = getWrappedLine_remaining;
1322
1323         cantake = textLengthUpToLength(s, w, tw);
1324         if(cantake > 0 && cantake < strlen(s))
1325         {
1326                 take = cantake - 1;
1327                 while(take > 0 && substring(s, take, 1) != " ")
1328                         --take;
1329                 if(take == 0)
1330                 {
1331                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
1332                         if(getWrappedLine_remaining == "")
1333                                 getWrappedLine_remaining = string_null;
1334                         return substring(s, 0, cantake);
1335                 }
1336                 else
1337                 {
1338                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1339                         if(getWrappedLine_remaining == "")
1340                                 getWrappedLine_remaining = string_null;
1341                         return substring(s, 0, take);
1342                 }
1343         }
1344         else
1345         {
1346                 getWrappedLine_remaining = string_null;
1347                 return s;
1348         }
1349 }
1350
1351 string textShortenToWidth(string theText, float maxWidth, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1352 {
1353         if(tw(theText, theFontSize) <= maxWidth)
1354                 return theText;
1355         else
1356                 return strcat(substring(theText, 0, textLengthUpToWidth(theText, maxWidth - tw("...", theFontSize), theFontSize, tw)), "...");
1357 }
1358
1359 string textShortenToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t tw)
1360 {
1361         if(tw(theText) <= maxWidth)
1362                 return theText;
1363         else
1364                 return strcat(substring(theText, 0, textLengthUpToLength(theText, maxWidth - tw("..."), tw)), "...");
1365 }
1366
1367 float isGametypeInFilter(float gt, float tp, string pattern)
1368 {
1369         string subpattern, subpattern2, subpattern3;
1370         subpattern = strcat(",", GametypeNameFromType(gt), ",");
1371         if(tp)
1372                 subpattern2 = ",teams,";
1373         else
1374                 subpattern2 = ",noteams,";
1375         if(gt == GAME_RACE || gt == GAME_CTS)
1376                 subpattern3 = ",race,";
1377         else
1378                 subpattern3 = string_null;
1379
1380         if(substring(pattern, 0, 1) == "-")
1381         {
1382                 pattern = substring(pattern, 1, strlen(pattern) - 1);
1383                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) >= 0)
1384                         return 0;
1385                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) >= 0)
1386                         return 0;
1387                 if(subpattern3 && strstrofs(strcat(",", pattern, ","), subpattern3, 0) >= 0)
1388                         return 0;
1389         }
1390         else
1391         {
1392                 if(substring(pattern, 0, 1) == "+")
1393                         pattern = substring(pattern, 1, strlen(pattern) - 1);
1394                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) < 0)
1395                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) < 0)
1396                 if((!subpattern3) || strstrofs(strcat(",", pattern, ","), subpattern3, 0) < 0)
1397                         return 0;
1398         }
1399         return 1;
1400 }
1401
1402 void shuffle(float n, swapfunc_t swap, entity pass)
1403 {
1404         float i, j;
1405         for(i = 1; i < n; ++i)
1406         {
1407                 // swap i-th item at a random position from 0 to i
1408                 // proof for even distribution:
1409                 //   n = 1: obvious
1410                 //   n -> n+1:
1411                 //     item n+1 gets at any position with chance 1/(n+1)
1412                 //     all others will get their 1/n chance reduced by factor n/(n+1)
1413                 //     to be on place n+1, their chance will be 1/(n+1)
1414                 //     1/n * n/(n+1) = 1/(n+1)
1415                 //     q.e.d.
1416                 j = floor(random() * (i + 1));
1417                 if(j != i)
1418                         swap(j, i, pass);
1419         }
1420 }
1421
1422 string substring_range(string s, float b, float e)
1423 {
1424         return substring(s, b, e - b);
1425 }
1426
1427 string swapwords(string str, float i, float j)
1428 {
1429         float n;
1430         string s1, s2, s3, s4, s5;
1431         float si, ei, sj, ej, s0, en;
1432         n = tokenizebyseparator(str, " "); // must match g_maplist processing in ShuffleMaplist and "shuffle"
1433         si = argv_start_index(i);
1434         sj = argv_start_index(j);
1435         ei = argv_end_index(i);
1436         ej = argv_end_index(j);
1437         s0 = argv_start_index(0);
1438         en = argv_end_index(n-1);
1439         s1 = substring_range(str, s0, si);
1440         s2 = substring_range(str, si, ei);
1441         s3 = substring_range(str, ei, sj);
1442         s4 = substring_range(str, sj, ej);
1443         s5 = substring_range(str, ej, en);
1444         return strcat(s1, s4, s3, s2, s5);
1445 }
1446
1447 string _shufflewords_str;
1448 void _shufflewords_swapfunc(float i, float j, entity pass)
1449 {
1450         _shufflewords_str = swapwords(_shufflewords_str, i, j);
1451 }
1452 string shufflewords(string str)
1453 {
1454         float n;
1455         _shufflewords_str = str;
1456         n = tokenizebyseparator(str, " ");
1457         shuffle(n, _shufflewords_swapfunc, world);
1458         str = _shufflewords_str;
1459         _shufflewords_str = string_null;
1460         return str;
1461 }
1462
1463 vector solve_quadratic(float a, float b, float c) // ax^2 + bx + c = 0
1464 {
1465         vector v;
1466         float D;
1467         v = '0 0 0';
1468         if(a == 0)
1469         {
1470                 if(b != 0)
1471                 {
1472                         v_x = v_y = -c / b;
1473                         v_z = 1;
1474                 }
1475                 else
1476                 {
1477                         if(c == 0)
1478                         {
1479                                 // actually, every number solves the equation!
1480                                 v_z = 1;
1481                         }
1482                 }
1483         }
1484         else
1485         {
1486                 D = b*b - 4*a*c;
1487                 if(D >= 0)
1488                 {
1489                         D = sqrt(D);
1490                         if(a > 0) // put the smaller solution first
1491                         {
1492                                 v_x = ((-b)-D) / (2*a);
1493                                 v_y = ((-b)+D) / (2*a);
1494                         }
1495                         else
1496                         {
1497                                 v_x = (-b+D) / (2*a);
1498                                 v_y = (-b-D) / (2*a);
1499                         }
1500                         v_z = 1;
1501                 }
1502                 else
1503                 {
1504                         // complex solutions!
1505                         D = sqrt(-D);
1506                         v_x = -b / (2*a);
1507                         if(a > 0)
1508                                 v_y =  D / (2*a);
1509                         else
1510                                 v_y = -D / (2*a);
1511                         v_z = 0;
1512                 }
1513         }
1514         return v;
1515 }
1516
1517
1518 float _unacceptable_compiler_bug_1_a(float b, float c) { return b == c; }
1519 float _unacceptable_compiler_bug_1_b() { return 1; }
1520 float _unacceptable_compiler_bug_1_c(float d) { return 2 * d; }
1521 float _unacceptable_compiler_bug_1_d() { return 1; }
1522
1523 void check_unacceptable_compiler_bugs()
1524 {
1525         if(cvar("_allow_unacceptable_compiler_bugs"))
1526                 return;
1527         tokenize_console("foo bar");
1528         if(strcat(argv(0), substring("foo bar", 4, 7 - argv_start_index(1))) == "barbar")
1529                 error("fteqcc bug introduced with revision 3178 detected. Please upgrade fteqcc to a later revision, downgrade fteqcc to revision 3177, or pester Spike until he fixes it. You can set _allow_unacceptable_compiler_bugs 1 to skip this check, but expect stuff to be horribly broken then.");
1530 }
1531
1532 float compressShotOrigin(vector v)
1533 {
1534         float x, y, z;
1535         x = rint(v_x * 2);
1536         y = rint(v_y * 4) + 128;
1537         z = rint(v_z * 4) + 128;
1538         if(x > 255 || x < 0)
1539         {
1540                 print("shot origin ", vtos(v), " x out of bounds\n");
1541                 x = bound(0, x, 255);
1542         }
1543         if(y > 255 || y < 0)
1544         {
1545                 print("shot origin ", vtos(v), " y out of bounds\n");
1546                 y = bound(0, y, 255);
1547         }
1548         if(z > 255 || z < 0)
1549         {
1550                 print("shot origin ", vtos(v), " z out of bounds\n");
1551                 z = bound(0, z, 255);
1552         }
1553         return x * 0x10000 + y * 0x100 + z;
1554 }
1555 vector decompressShotOrigin(float f)
1556 {
1557         vector v;
1558         v_x = ((f & 0xFF0000) / 0x10000) / 2;
1559         v_y = ((f & 0xFF00) / 0x100 - 128) / 4;
1560         v_z = ((f & 0xFF) - 128) / 4;
1561         return v;
1562 }
1563
1564 void heapsort(float n, swapfunc_t swap, comparefunc_t cmp, entity pass)
1565 {
1566         float start, end, root, child;
1567
1568         // heapify
1569         start = floor((n - 2) / 2);
1570         while(start >= 0)
1571         {
1572                 // siftdown(start, count-1);
1573                 root = start;
1574                 while(root * 2 + 1 <= n-1)
1575                 {
1576                         child = root * 2 + 1;
1577                         if(child < n-1)
1578                                 if(cmp(child, child+1, pass) < 0)
1579                                         ++child;
1580                         if(cmp(root, child, pass) < 0)
1581                         {
1582                                 swap(root, child, pass);
1583                                 root = child;
1584                         }
1585                         else
1586                                 break;
1587                 }
1588                 // end of siftdown
1589                 --start;
1590         }
1591
1592         // extract
1593         end = n - 1;
1594         while(end > 0)
1595         {
1596                 swap(0, end, pass);
1597                 --end;
1598                 // siftdown(0, end);
1599                 root = 0;
1600                 while(root * 2 + 1 <= end)
1601                 {
1602                         child = root * 2 + 1;
1603                         if(child < end && cmp(child, child+1, pass) < 0)
1604                                 ++child;
1605                         if(cmp(root, child, pass) < 0)
1606                         {
1607                                 swap(root, child, pass);
1608                                 root = child;
1609                         }
1610                         else
1611                                 break;
1612                 }
1613                 // end of siftdown
1614         }
1615 }
1616
1617 void RandomSelection_Init()
1618 {
1619         RandomSelection_totalweight = 0;
1620         RandomSelection_chosen_ent = world;
1621         RandomSelection_chosen_float = 0;
1622         RandomSelection_chosen_string = string_null;
1623         RandomSelection_best_priority = -1;
1624 }
1625 void RandomSelection_Add(entity e, float f, string s, float weight, float priority)
1626 {
1627         if(priority > RandomSelection_best_priority)
1628         {
1629                 RandomSelection_best_priority = priority;
1630                 RandomSelection_chosen_ent = e;
1631                 RandomSelection_chosen_float = f;
1632                 RandomSelection_chosen_string = s;
1633                 RandomSelection_totalweight = weight;
1634         }
1635         else if(priority == RandomSelection_best_priority)
1636         {
1637                 RandomSelection_totalweight += weight;
1638                 if(random() * RandomSelection_totalweight <= weight)
1639                 {
1640                         RandomSelection_chosen_ent = e;
1641                         RandomSelection_chosen_float = f;
1642                         RandomSelection_chosen_string = s;
1643                 }
1644         }
1645 }
1646
1647 vector healtharmor_maxdamage(float h, float a, float armorblock)
1648 {
1649         // NOTE: we'll always choose the SMALLER value...
1650         float healthdamage, armordamage, armorideal;
1651         vector v;
1652         healthdamage = (h - 1) / (1 - armorblock); // damage we can take if we could use more health
1653         armordamage = a + (h - 1); // damage we can take if we could use more armor
1654         armorideal = healthdamage * armorblock;
1655         v_y = armorideal;
1656         if(armordamage < healthdamage)
1657         {
1658                 v_x = armordamage;
1659                 v_z = 1;
1660         }
1661         else
1662         {
1663                 v_x = healthdamage;
1664                 v_z = 0;
1665         }
1666         return v;
1667 }
1668
1669 vector healtharmor_applydamage(float a, float armorblock, float damage)
1670 {
1671         vector v;
1672         v_y = bound(0, damage * armorblock, a); // save
1673         v_x = bound(0, damage - v_y, damage); // take
1674         v_z = 0;
1675         return v;
1676 }
1677
1678 string getcurrentmod()
1679 {
1680         float n;
1681         string m;
1682         m = cvar_string("fs_gamedir");
1683         n = tokenize_console(m);
1684         if(n == 0)
1685                 return "data";
1686         else
1687                 return argv(n - 1);
1688 }
1689
1690 #ifndef MENUQC
1691 #ifdef CSQC
1692 float ReadInt24_t()
1693 {
1694         float v;
1695         v = ReadShort() * 256; // note: this is signed
1696         v += ReadByte(); // note: this is unsigned
1697         return v;
1698 }
1699 #else
1700 void WriteInt24_t(float dest, float val)
1701 {
1702         float v;
1703         WriteShort(dest, (v = floor(val / 256)));
1704         WriteByte(dest, val - v * 256); // 0..255
1705 }
1706 #endif
1707 #endif
1708
1709 float float2range11(float f)
1710 {
1711         // continuous function mapping all reals into -1..1
1712         return f / (fabs(f) + 1);
1713 }
1714
1715 float float2range01(float f)
1716 {
1717         // continuous function mapping all reals into 0..1
1718         return 0.5 + 0.5 * float2range11(f);
1719 }
1720
1721 // from the GNU Scientific Library
1722 float gsl_ran_gaussian_lastvalue;
1723 float gsl_ran_gaussian_lastvalue_set;
1724 float gsl_ran_gaussian(float sigma)
1725 {
1726         float a, b;
1727         if(gsl_ran_gaussian_lastvalue_set)
1728         {
1729                 gsl_ran_gaussian_lastvalue_set = 0;
1730                 return sigma * gsl_ran_gaussian_lastvalue;
1731         }
1732         else
1733         {
1734                 a = random() * 2 * M_PI;
1735                 b = sqrt(-2 * log(random()));
1736                 gsl_ran_gaussian_lastvalue = cos(a) * b;
1737                 gsl_ran_gaussian_lastvalue_set = 1;
1738                 return sigma * sin(a) * b;
1739         }
1740 }
1741
1742 string car(string s)
1743 {
1744         float o;
1745         o = strstrofs(s, " ", 0);
1746         if(o < 0)
1747                 return s;
1748         return substring(s, 0, o);
1749 }
1750 string cdr(string s)
1751 {
1752         float o;
1753         o = strstrofs(s, " ", 0);
1754         if(o < 0)
1755                 return string_null;
1756         return substring(s, o + 1, strlen(s) - (o + 1));
1757 }
1758 float matchacl(string acl, string str)
1759 {
1760         string t, s;
1761         float r, d;
1762         r = 0;
1763         while(acl)
1764         {
1765                 t = car(acl); acl = cdr(acl);
1766                 d = 1;
1767                 if(substring(t, 0, 1) == "-")
1768                 {
1769                         d = -1;
1770                         t = substring(t, 1, strlen(t) - 1);
1771                 }
1772                 else if(substring(t, 0, 1) == "+")
1773                         t = substring(t, 1, strlen(t) - 1);
1774                 if(substring(t, -1, 1) == "*")
1775                 {
1776                         t = substring(t, 0, strlen(t) - 1);
1777                         s = substring(s, 0, strlen(t));
1778                 }
1779                 else
1780                         s = str;
1781
1782                 if(s == t)
1783                 {
1784                         r = d;
1785                 }
1786         }
1787         return r;
1788 }
1789 float startsWith(string haystack, string needle)
1790 {
1791         return substring(haystack, 0, strlen(needle)) == needle;
1792 }
1793 float startsWithNocase(string haystack, string needle)
1794 {
1795         return strcasecmp(substring(haystack, 0, strlen(needle)), needle) == 0;
1796 }
1797
1798 string get_model_datafilename(string m, float sk, string fil)
1799 {
1800         if(m)
1801                 m = strcat(m, "_");
1802         else
1803                 m = "models/player/*_";
1804         if(sk >= 0)
1805                 m = strcat(m, ftos(sk));
1806         else
1807                 m = strcat(m, "*");
1808         return strcat(m, ".", fil);
1809 }
1810
1811 float get_model_parameters(string m, float sk)
1812 {
1813         string fn, s, c;
1814         float fh;
1815
1816         get_model_parameters_modelname = string_null;
1817         get_model_parameters_modelskin = -1;
1818         get_model_parameters_name = string_null;
1819         get_model_parameters_species = -1;
1820         get_model_parameters_sex = string_null;
1821         get_model_parameters_weight = -1;
1822         get_model_parameters_age = -1;
1823         get_model_parameters_desc = string_null;
1824
1825         if not(m)
1826                 return 1;
1827         if(sk < 0)
1828         {
1829                 if(substring(m, -4, -1) != ".txt")
1830                         return 0;
1831                 if(substring(m, -6, 1) != "_")
1832                         return 0;
1833                 sk = stof(substring(m, -5, 1));
1834                 m = substring(m, 0, -7);
1835         }
1836
1837         fn = get_model_datafilename(m, sk, "txt");
1838         fh = fopen(fn, FILE_READ);
1839         if(fh < 0)
1840                 return 0;
1841
1842         get_model_parameters_modelname = m;
1843         get_model_parameters_modelskin = sk;
1844         while((s = fgets(fh)))
1845         {
1846                 if(s == "")
1847                         break; // next lines will be description
1848                 c = car(s);
1849                 s = cdr(s);
1850                 if(c == "name")
1851                         get_model_parameters_name = s;
1852                 if(c == "species")
1853                         switch(s)
1854                         {
1855                                 case "human":       get_model_parameters_species = SPECIES_HUMAN;       break;
1856                                 case "alien":       get_model_parameters_species = SPECIES_ALIEN;       break;
1857                                 case "robot_shiny": get_model_parameters_species = SPECIES_ROBOT_SHINY; break;
1858                                 case "robot_rusty": get_model_parameters_species = SPECIES_ROBOT_RUSTY; break;
1859                                 case "robot_solid": get_model_parameters_species = SPECIES_ROBOT_SOLID; break;
1860                                 case "animal":      get_model_parameters_species = SPECIES_ANIMAL;      break;
1861                                 case "reserved":    get_model_parameters_species = SPECIES_RESERVED;    break;
1862                         }
1863                 if(c == "sex")
1864                         get_model_parameters_sex = s;
1865                 if(c == "weight")
1866                         get_model_parameters_weight = stof(s);
1867                 if(c == "age")
1868                         get_model_parameters_age = stof(s);
1869         }
1870
1871         while((s = fgets(fh)))
1872         {
1873                 if(get_model_parameters_desc)
1874                         get_model_parameters_desc = strcat(get_model_parameters_desc, "\n");
1875                 if(s != "")
1876                         get_model_parameters_desc = strcat(get_model_parameters_desc, s);
1877         }
1878
1879         fclose(fh);
1880
1881         return 1;
1882 }
1883
1884 vector vec2(vector v)
1885 {
1886         v_z = 0;
1887         return v;
1888 }
1889
1890 #ifndef MENUQC
1891 vector NearestPointOnBox(entity box, vector org)
1892 {
1893         vector m1, m2, nearest;
1894
1895         m1 = box.mins + box.origin;
1896         m2 = box.maxs + box.origin;
1897
1898         nearest_x = bound(m1_x, org_x, m2_x);
1899         nearest_y = bound(m1_y, org_y, m2_y);
1900         nearest_z = bound(m1_z, org_z, m2_z);
1901
1902         return nearest;
1903 }
1904 #endif
1905
1906 float vercmp_recursive(string v1, string v2)
1907 {
1908         float dot1, dot2;
1909         string s1, s2;
1910         float r;
1911
1912         dot1 = strstrofs(v1, ".", 0);
1913         dot2 = strstrofs(v2, ".", 0);
1914         if(dot1 == -1)
1915                 s1 = v1;
1916         else
1917                 s1 = substring(v1, 0, dot1);
1918         if(dot2 == -1)
1919                 s2 = v2;
1920         else
1921                 s2 = substring(v2, 0, dot2);
1922
1923         r = stof(s1) - stof(s2);
1924         if(r != 0)
1925                 return r;
1926
1927         r = strcasecmp(s1, s2);
1928         if(r != 0)
1929                 return r;
1930
1931         if(dot1 == -1)
1932                 if(dot2 == -1)
1933                         return 0;
1934                 else
1935                         return -1;
1936         else
1937                 if(dot2 == -1)
1938                         return 1;
1939                 else
1940                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
1941 }
1942
1943 float vercmp(string v1, string v2)
1944 {
1945         if(strcasecmp(v1, v2) == 0) // early out check
1946                 return 0;
1947
1948         // "git" beats all
1949         if(v1 == "git")
1950                 return 1;
1951         if(v2 == "git")
1952                 return -1;
1953
1954         return vercmp_recursive(v1, v2);
1955 }
1956
1957 float u8_strsize(string s)
1958 {
1959         float l, i, c;
1960         l = 0;
1961         for(i = 0; ; ++i)
1962         {
1963                 c = str2chr(s, i);
1964                 if(c <= 0)
1965                         break;
1966                 ++l;
1967                 if(c >= 0x80)
1968                         ++l;
1969                 if(c >= 0x800)
1970                         ++l;
1971                 if(c >= 0x10000)
1972                         ++l;
1973         }
1974         return l;
1975 }