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