]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/util.qc
f99312b5b2eae92a96b025d1e9d8ecc15a8dbcd5
[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         // inhibit stupid negative zero
200         if(number == 0)
201                 number = 0;
202         // we have sprintf...
203         return sprintf("%.*f", decimals, number);
204 }
205
206 float time;
207 vector colormapPaletteColor(float c, float isPants)
208 {
209         switch(c)
210         {
211                 case  0: return '1.000000 1.000000 1.000000';
212                 case  1: return '1.000000 0.333333 0.000000';
213                 case  2: return '0.000000 1.000000 0.501961';
214                 case  3: return '0.000000 1.000000 0.000000';
215                 case  4: return '1.000000 0.000000 0.000000';
216                 case  5: return '0.000000 0.666667 1.000000';
217                 case  6: return '0.000000 1.000000 1.000000';
218                 case  7: return '0.501961 1.000000 0.000000';
219                 case  8: return '0.501961 0.000000 1.000000';
220                 case  9: return '1.000000 0.000000 1.000000';
221                 case 10: return '1.000000 0.000000 0.501961';
222                 case 11: return '0.000000 0.000000 1.000000';
223                 case 12: return '1.000000 1.000000 0.000000';
224                 case 13: return '0.000000 0.333333 1.000000';
225                 case 14: return '1.000000 0.666667 0.000000';
226                 case 15:
227                         if(isPants)
228                                 return
229                                           '1 0 0' * (0.502 + 0.498 * sin(time / 2.7182818285 + 0.0000000000))
230                                         + '0 1 0' * (0.502 + 0.498 * sin(time / 2.7182818285 + 2.0943951024))
231                                         + '0 0 1' * (0.502 + 0.498 * sin(time / 2.7182818285 + 4.1887902048));
232                         else
233                                 return
234                                           '1 0 0' * (0.502 + 0.498 * sin(time / 3.1415926536 + 5.2359877560))
235                                         + '0 1 0' * (0.502 + 0.498 * sin(time / 3.1415926536 + 3.1415926536))
236                                         + '0 0 1' * (0.502 + 0.498 * sin(time / 3.1415926536 + 1.0471975512));
237                 default: return '0.000 0.000 0.000';
238         }
239 }
240
241 // unzone the string, and return it as tempstring. Safe to be called on string_null
242 string fstrunzone(string s)
243 {
244         string sc;
245         if not(s)
246                 return s;
247         sc = strcat(s, "");
248         strunzone(s);
249         return sc;
250 }
251
252 float fexists(string f)
253 {
254     float fh;
255     fh = fopen(f, FILE_READ);
256     if (fh < 0)
257         return FALSE;
258     fclose(fh);
259     return TRUE;
260 }
261
262 // Databases (hash tables)
263 #define DB_BUCKETS 8192
264 void db_save(float db, string pFilename)
265 {
266         float fh, i, n;
267         fh = fopen(pFilename, FILE_WRITE);
268         if(fh < 0) 
269         {
270                 print(strcat("^1Can't write DB to ", pFilename));
271                 return;
272         }
273         n = buf_getsize(db);
274         fputs(fh, strcat(ftos(DB_BUCKETS), "\n"));
275         for(i = 0; i < n; ++i)
276                 fputs(fh, strcat(bufstr_get(db, i), "\n"));
277         fclose(fh);
278 }
279
280 float db_create()
281 {
282         return buf_create();
283 }
284
285 float db_load(string pFilename)
286 {
287         float db, fh, i, j, n;
288         string l;
289         db = buf_create();
290         if(db < 0)
291                 return -1;
292         fh = fopen(pFilename, FILE_READ);
293         if(fh < 0)
294                 return db;
295         l = fgets(fh);
296         if(stof(l) == DB_BUCKETS)
297         {
298                 i = 0;
299                 while((l = fgets(fh)))
300                 {
301                         if(l != "")
302                                 bufstr_set(db, i, l);
303                         ++i;
304                 }
305         }
306         else
307         {
308                 // different count of buckets, or a dump?
309                 // need to reorganize the database then (SLOW)
310                 //
311                 // note: we also parse the first line (l) in case the DB file is
312                 // missing the bucket count
313                 do
314                 {
315                         n = tokenizebyseparator(l, "\\");
316                         for(j = 2; j < n; j += 2)
317                                 db_put(db, argv(j-1), uri_unescape(argv(j)));
318                 }
319                 while((l = fgets(fh)));
320         }
321         fclose(fh);
322         return db;
323 }
324
325 void db_dump(float db, string pFilename)
326 {
327         float fh, i, j, n, m;
328         fh = fopen(pFilename, FILE_WRITE);
329         if(fh < 0)
330                 error(strcat("Can't dump DB to ", pFilename));
331         n = buf_getsize(db);
332         fputs(fh, "0\n");
333         for(i = 0; i < n; ++i)
334         {
335                 m = tokenizebyseparator(bufstr_get(db, i), "\\");
336                 for(j = 2; j < m; j += 2)
337                         fputs(fh, strcat("\\", argv(j-1), "\\", argv(j), "\n"));
338         }
339         fclose(fh);
340 }
341
342 void db_close(float db)
343 {
344         buf_del(db);
345 }
346
347 string db_get(float db, string pKey)
348 {
349         float h;
350         h = mod(crc16(FALSE, pKey), DB_BUCKETS);
351         return uri_unescape(infoget(bufstr_get(db, h), pKey));
352 }
353
354 void db_put(float db, string pKey, string pValue)
355 {
356         float h;
357         h = mod(crc16(FALSE, pKey), DB_BUCKETS);
358         bufstr_set(db, h, infoadd(bufstr_get(db, h), pKey, uri_escape(pValue)));
359 }
360
361 void db_test()
362 {
363         float db, i;
364         print("LOAD...\n");
365         db = db_load("foo.db");
366         print("LOADED. FILL...\n");
367         for(i = 0; i < DB_BUCKETS; ++i)
368                 db_put(db, ftos(random()), "X");
369         print("FILLED. SAVE...\n");
370         db_save(db, "foo.db");
371         print("SAVED. CLOSE...\n");
372         db_close(db);
373         print("CLOSED.\n");
374 }
375
376 // Multiline text file buffers
377 float buf_load(string pFilename)
378 {
379         float buf, fh, i;
380         string l;
381         buf = buf_create();
382         if(buf < 0)
383                 return -1;
384         fh = fopen(pFilename, FILE_READ);
385         if(fh < 0)
386         {
387                 buf_del(buf);
388                 return -1;
389         }
390         i = 0;
391         while((l = fgets(fh)))
392         {
393                 bufstr_set(buf, i, l);
394                 ++i;
395         }
396         fclose(fh);
397         return buf;
398 }
399
400 void buf_save(float buf, string pFilename)
401 {
402         float fh, i, n;
403         fh = fopen(pFilename, FILE_WRITE);
404         if(fh < 0)
405                 error(strcat("Can't write buf to ", pFilename));
406         n = buf_getsize(buf);
407         for(i = 0; i < n; ++i)
408                 fputs(fh, strcat(bufstr_get(buf, i), "\n"));
409         fclose(fh);
410 }
411
412 string mmsss(float tenths)
413 {
414         float minutes;
415         string s;
416         tenths = floor(tenths + 0.5);
417         minutes = floor(tenths / 600);
418         tenths -= minutes * 600;
419         s = ftos(1000 + tenths);
420         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 1));
421 }
422
423 string mmssss(float hundredths)
424 {
425         float minutes;
426         string s;
427         hundredths = floor(hundredths + 0.5);
428         minutes = floor(hundredths / 6000);
429         hundredths -= minutes * 6000;
430         s = ftos(10000 + hundredths);
431         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 2));
432 }
433
434 string ScoreString(float pFlags, float pValue)
435 {
436         string valstr;
437         float l;
438
439         pValue = floor(pValue + 0.5); // round
440
441         if((pValue == 0) && (pFlags & (SFL_HIDE_ZERO | SFL_RANK | SFL_TIME)))
442                 valstr = "";
443         else if(pFlags & SFL_RANK)
444         {
445                 valstr = ftos(pValue);
446                 l = strlen(valstr);
447                 if((l >= 2) && (substring(valstr, l - 2, 1) == "1"))
448                         valstr = strcat(valstr, "th");
449                 else if(substring(valstr, l - 1, 1) == "1")
450                         valstr = strcat(valstr, "st");
451                 else if(substring(valstr, l - 1, 1) == "2")
452                         valstr = strcat(valstr, "nd");
453                 else if(substring(valstr, l - 1, 1) == "3")
454                         valstr = strcat(valstr, "rd");
455                 else
456                         valstr = strcat(valstr, "th");
457         }
458         else if(pFlags & SFL_TIME)
459                 valstr = TIME_ENCODED_TOSTRING(pValue);
460         else
461                 valstr = ftos(pValue);
462         
463         return valstr;
464 }
465
466 float dotproduct(vector a, vector b)
467 {
468         return a_x * b_x + a_y * b_y + a_z * b_z;
469 }
470
471 vector cross(vector a, vector b)
472 {
473         return
474                 '1 0 0' * (a_y * b_z - a_z * b_y)
475         +       '0 1 0' * (a_z * b_x - a_x * b_z)
476         +       '0 0 1' * (a_x * b_y - a_y * b_x);
477 }
478
479 // compressed vector format:
480 // like MD3, just even shorter
481 //   4 bit pitch (16 angles), 0 is -90, 8 is 0, 16 would be 90
482 //   5 bit yaw (32 angles), 0=0, 8=90, 16=180, 24=270
483 //   7 bit length (logarithmic encoding), 1/8 .. about 7844
484 //     length = 2^(length_encoded/8) / 8
485 // if pitch is 90, yaw does nothing and therefore indicates the sign (yaw is then either 11111 or 11110); 11111 is pointing DOWN
486 // thus, valid values are from 0000.11110.0000000 to 1111.11111.1111111
487 // the special value 0 indicates the zero vector
488
489 float lengthLogTable[128];
490
491 float invertLengthLog(float x)
492 {
493         float l, r, m, lerr, rerr;
494
495         if(x >= lengthLogTable[127])
496                 return 127;
497         if(x <= lengthLogTable[0])
498                 return 0;
499
500         l = 0;
501         r = 127;
502
503         while(r - l > 1)
504         {
505                 m = floor((l + r) / 2);
506                 if(lengthLogTable[m] < x)
507                         l = m;
508                 else
509                         r = m;
510         }
511
512         // now: r is >=, l is <
513         lerr = (x - lengthLogTable[l]);
514         rerr = (lengthLogTable[r] - x);
515         if(lerr < rerr)
516                 return l;
517         return r;
518 }
519
520 vector decompressShortVector(float data)
521 {
522         vector out;
523         float p, y, len;
524         if(data == 0)
525                 return '0 0 0';
526         p   = (data & 0xF000) / 0x1000;
527         y   = (data & 0x0F80) / 0x80;
528         len = (data & 0x007F);
529
530         //print("\ndecompress: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
531
532         if(p == 0)
533         {
534                 out_x = 0;
535                 out_y = 0;
536                 if(y == 31)
537                         out_z = -1;
538                 else
539                         out_z = +1;
540         }
541         else
542         {
543                 y   = .19634954084936207740 * y;
544                 p = .19634954084936207740 * p - 1.57079632679489661922;
545                 out_x = cos(y) *  cos(p);
546                 out_y = sin(y) *  cos(p);
547                 out_z =          -sin(p);
548         }
549
550         //print("decompressed: ", vtos(out), "\n");
551
552         return out * lengthLogTable[len];
553 }
554
555 float compressShortVector(vector vec)
556 {
557         vector ang;
558         float p, y, len;
559         if(vlen(vec) == 0)
560                 return 0;
561         //print("compress: ", vtos(vec), "\n");
562         ang = vectoangles(vec);
563         ang_x = -ang_x;
564         if(ang_x < -90)
565                 ang_x += 360;
566         if(ang_x < -90 && ang_x > +90)
567                 error("BOGUS vectoangles");
568         //print("angles: ", vtos(ang), "\n");
569
570         p = floor(0.5 + (ang_x + 90) * 16 / 180) & 15; // -90..90 to 0..14
571         if(p == 0)
572         {
573                 if(vec_z < 0)
574                         y = 31;
575                 else
576                         y = 30;
577         }
578         else
579                 y = floor(0.5 + ang_y * 32 / 360)          & 31; // 0..360 to 0..32
580         len = invertLengthLog(vlen(vec));
581
582         //print("compressed: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
583
584         return (p * 0x1000) + (y * 0x80) + len;
585 }
586
587 void compressShortVector_init()
588 {
589         float l, f, i;
590         l = 1;
591         f = pow(2, 1/8);
592         for(i = 0; i < 128; ++i)
593         {
594                 lengthLogTable[i] = l;
595                 l *= f;
596         }
597
598         if(cvar("developer"))
599         {
600                 print("Verifying vector compression table...\n");
601                 for(i = 0x0F00; i < 0xFFFF; ++i)
602                         if(i != compressShortVector(decompressShortVector(i)))
603                         {
604                                 print("BROKEN vector compression: ", ftos(i));
605                                 print(" -> ", vtos(decompressShortVector(i)));
606                                 print(" -> ", ftos(compressShortVector(decompressShortVector(i))));
607                                 print("\n");
608                                 error("b0rk");
609                         }
610                 print("Done.\n");
611         }
612 }
613
614 #ifndef MENUQC
615 float CheckWireframeBox(entity forent, vector v0, vector dvx, vector dvy, vector dvz)
616 {
617         traceline(v0, v0 + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
618         traceline(v0, v0 + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
619         traceline(v0, v0 + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
620         traceline(v0 + dvx, v0 + dvx + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
621         traceline(v0 + dvx, v0 + dvx + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
622         traceline(v0 + dvy, v0 + dvy + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
623         traceline(v0 + dvy, v0 + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
624         traceline(v0 + dvz, v0 + dvz + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
625         traceline(v0 + dvz, v0 + dvz + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
626         traceline(v0 + dvx + dvy, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
627         traceline(v0 + dvx + dvz, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
628         traceline(v0 + dvy + dvz, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
629         return 1;
630 }
631 #endif
632
633 string fixPriorityList(string order, float from, float to, float subtract, float complete)
634 {
635         string neworder;
636         float i, n, w;
637
638         n = tokenize_console(order);
639         neworder = "";
640         for(i = 0; i < n; ++i)
641         {
642                 w = stof(argv(i));
643                 if(w == floor(w))
644                 {
645                         if(w >= from && w <= to)
646                                 neworder = strcat(neworder, ftos(w), " ");
647                         else
648                         {
649                                 w -= subtract;
650                                 if(w >= from && w <= to)
651                                         neworder = strcat(neworder, ftos(w), " ");
652                         }
653                 }
654         }
655
656         if(complete)
657         {
658                 n = tokenize_console(neworder);
659                 for(w = to; w >= from; --w)
660                 {
661                         for(i = 0; i < n; ++i)
662                                 if(stof(argv(i)) == w)
663                                         break;
664                         if(i == n) // not found
665                                 neworder = strcat(neworder, ftos(w), " ");
666                 }
667         }
668         
669         return substring(neworder, 0, strlen(neworder) - 1);
670 }
671
672 string mapPriorityList(string order, string(string) mapfunc)
673 {
674         string neworder;
675         float i, n;
676
677         n = tokenize_console(order);
678         neworder = "";
679         for(i = 0; i < n; ++i)
680                 neworder = strcat(neworder, mapfunc(argv(i)), " ");
681         
682         return substring(neworder, 0, strlen(neworder) - 1);
683 }
684
685 string swapInPriorityList(string order, float i, float j)
686 {
687         string s;
688         float w, n;
689
690         n = tokenize_console(order);
691
692         if(i >= 0 && i < n && j >= 0 && j < n && i != j)
693         {
694                 s = "";
695                 for(w = 0; w < n; ++w)
696                 {
697                         if(w == i)
698                                 s = strcat(s, argv(j), " ");
699                         else if(w == j)
700                                 s = strcat(s, argv(i), " ");
701                         else
702                                 s = strcat(s, argv(w), " ");
703                 }
704                 return substring(s, 0, strlen(s) - 1);
705         }
706         
707         return order;
708 }
709
710 float cvar_value_issafe(string s)
711 {
712         if(strstrofs(s, "\"", 0) >= 0)
713                 return 0;
714         if(strstrofs(s, "\\", 0) >= 0)
715                 return 0;
716         if(strstrofs(s, ";", 0) >= 0)
717                 return 0;
718         if(strstrofs(s, "$", 0) >= 0)
719                 return 0;
720         if(strstrofs(s, "\r", 0) >= 0)
721                 return 0;
722         if(strstrofs(s, "\n", 0) >= 0)
723                 return 0;
724         return 1;
725 }
726
727 #ifndef MENUQC
728 void get_mi_min_max(float mode)
729 {
730         vector mi, ma;
731
732         if(mi_shortname)
733                 strunzone(mi_shortname);
734         mi_shortname = mapname;
735         if(!strcasecmp(substring(mi_shortname, 0, 5), "maps/"))
736                 mi_shortname = substring(mi_shortname, 5, strlen(mi_shortname) - 5);
737         if(!strcasecmp(substring(mi_shortname, strlen(mi_shortname) - 4, 4), ".bsp"))
738                 mi_shortname = substring(mi_shortname, 0, strlen(mi_shortname) - 4);
739         mi_shortname = strzone(mi_shortname);
740
741 #ifdef CSQC
742         mi = world.mins;
743         ma = world.maxs;
744 #else
745         mi = world.absmin;
746         ma = world.absmax;
747 #endif
748
749         mi_min = mi;
750         mi_max = ma;
751         MapInfo_Get_ByName(mi_shortname, 0, 0);
752         if(MapInfo_Map_mins_x < MapInfo_Map_maxs_x)
753         {
754                 mi_min = MapInfo_Map_mins;
755                 mi_max = MapInfo_Map_maxs;
756         }
757         else
758         {
759                 // not specified
760                 if(mode)
761                 {
762                         // be clever
763                         tracebox('1 0 0' * mi_x,
764                                          '0 1 0' * mi_y + '0 0 1' * mi_z,
765                                          '0 1 0' * ma_y + '0 0 1' * ma_z,
766                                          '1 0 0' * ma_x,
767                                          MOVE_WORLDONLY,
768                                          world);
769                         if(!trace_startsolid)
770                                 mi_min_x = trace_endpos_x;
771
772                         tracebox('0 1 0' * mi_y,
773                                          '1 0 0' * mi_x + '0 0 1' * mi_z,
774                                          '1 0 0' * ma_x + '0 0 1' * ma_z,
775                                          '0 1 0' * ma_y,
776                                          MOVE_WORLDONLY,
777                                          world);
778                         if(!trace_startsolid)
779                                 mi_min_y = trace_endpos_y;
780
781                         tracebox('0 0 1' * mi_z,
782                                          '1 0 0' * mi_x + '0 1 0' * mi_y,
783                                          '1 0 0' * ma_x + '0 1 0' * ma_y,
784                                          '0 0 1' * ma_z,
785                                          MOVE_WORLDONLY,
786                                          world);
787                         if(!trace_startsolid)
788                                 mi_min_z = trace_endpos_z;
789
790                         tracebox('1 0 0' * ma_x,
791                                          '0 1 0' * mi_y + '0 0 1' * mi_z,
792                                          '0 1 0' * ma_y + '0 0 1' * ma_z,
793                                          '1 0 0' * mi_x,
794                                          MOVE_WORLDONLY,
795                                          world);
796                         if(!trace_startsolid)
797                                 mi_max_x = trace_endpos_x;
798
799                         tracebox('0 1 0' * ma_y,
800                                          '1 0 0' * mi_x + '0 0 1' * mi_z,
801                                          '1 0 0' * ma_x + '0 0 1' * ma_z,
802                                          '0 1 0' * mi_y,
803                                          MOVE_WORLDONLY,
804                                          world);
805                         if(!trace_startsolid)
806                                 mi_max_y = trace_endpos_y;
807
808                         tracebox('0 0 1' * ma_z,
809                                          '1 0 0' * mi_x + '0 1 0' * mi_y,
810                                          '1 0 0' * ma_x + '0 1 0' * ma_y,
811                                          '0 0 1' * mi_z,
812                                          MOVE_WORLDONLY,
813                                          world);
814                         if(!trace_startsolid)
815                                 mi_max_z = trace_endpos_z;
816                 }
817         }
818 }
819
820 void get_mi_min_max_texcoords(float mode)
821 {
822         vector extend;
823
824         get_mi_min_max(mode);
825
826         mi_picmin = mi_min;
827         mi_picmax = mi_max;
828
829         // extend mi_picmax to get a square aspect ratio
830         // center the map in that area
831         extend = mi_picmax - mi_picmin;
832         if(extend_y > extend_x)
833         {
834                 mi_picmin_x -= (extend_y - extend_x) * 0.5;
835                 mi_picmax_x += (extend_y - extend_x) * 0.5;
836         }
837         else
838         {
839                 mi_picmin_y -= (extend_x - extend_y) * 0.5;
840                 mi_picmax_y += (extend_x - extend_y) * 0.5;
841         }
842
843         // add another some percent
844         extend = (mi_picmax - mi_picmin) * (1 / 64.0);
845         mi_picmin -= extend;
846         mi_picmax += extend;
847
848         // calculate the texcoords
849         mi_pictexcoord0 = mi_pictexcoord1 = mi_pictexcoord2 = mi_pictexcoord3 = '0 0 0';
850         // first the two corners of the origin
851         mi_pictexcoord0_x = (mi_min_x - mi_picmin_x) / (mi_picmax_x - mi_picmin_x);
852         mi_pictexcoord0_y = (mi_min_y - mi_picmin_y) / (mi_picmax_y - mi_picmin_y);
853         mi_pictexcoord2_x = (mi_max_x - mi_picmin_x) / (mi_picmax_x - mi_picmin_x);
854         mi_pictexcoord2_y = (mi_max_y - mi_picmin_y) / (mi_picmax_y - mi_picmin_y);
855         // then the other corners
856         mi_pictexcoord1_x = mi_pictexcoord0_x;
857         mi_pictexcoord1_y = mi_pictexcoord2_y;
858         mi_pictexcoord3_x = mi_pictexcoord2_x;
859         mi_pictexcoord3_y = mi_pictexcoord0_y;
860 }
861 #endif
862
863 float cvar_settemp(string tmp_cvar, string tmp_value)
864 {
865         float created_saved_value;
866         entity e;
867
868         created_saved_value = FALSE;
869         
870         if not(tmp_cvar || tmp_value)
871         {
872                 dprint("Error: Invalid usage of cvar_settemp(string, string); !\n");
873                 return FALSE;
874         }
875         
876         for(e = world; (e = find(e, classname, "saved_cvar_value")); )
877                 if(e.netname == tmp_cvar)
878                         goto saved; // skip creation
879                         
880         // creating a new entity to keep track of this cvar
881         e = spawn();
882         e.classname = "saved_cvar_value";
883         e.netname = strzone(tmp_cvar);
884         e.message = strzone(cvar_string(tmp_cvar));
885         created_saved_value = TRUE;
886         
887         // an entity for this cvar already exists
888         :saved
889         
890         // update the cvar to the value given
891         cvar_set(tmp_cvar, tmp_value);
892         
893         return created_saved_value;
894 }
895
896 float cvar_settemp_restore()
897 {
898         float i;
899         entity e;
900         while((e = find(world, classname, "saved_cvar_value")))
901         {
902                 cvar_set(e.netname, e.message);
903                 remove(e);
904         }
905         
906         return i;
907 }
908
909 float almost_equals(float a, float b)
910 {
911         float eps;
912         eps = (max(a, -a) + max(b, -b)) * 0.001;
913         if(a - b < eps && b - a < eps)
914                 return TRUE;
915         return FALSE;
916 }
917
918 float almost_in_bounds(float a, float b, float c)
919 {
920         float eps;
921         eps = (max(a, -a) + max(c, -c)) * 0.001;
922         if(a > c)
923                 eps = -eps;
924         return b == median(a - eps, b, c + eps);
925 }
926
927 float power2of(float e)
928 {
929         return pow(2, e);
930 }
931 float log2of(float x)
932 {
933         // NOTE: generated code
934         if(x > 2048)
935                 if(x > 131072)
936                         if(x > 1048576)
937                                 if(x > 4194304)
938                                         return 23;
939                                 else
940                                         if(x > 2097152)
941                                                 return 22;
942                                         else
943                                                 return 21;
944                         else
945                                 if(x > 524288)
946                                         return 20;
947                                 else
948                                         if(x > 262144)
949                                                 return 19;
950                                         else
951                                                 return 18;
952                 else
953                         if(x > 16384)
954                                 if(x > 65536)
955                                         return 17;
956                                 else
957                                         if(x > 32768)
958                                                 return 16;
959                                         else
960                                                 return 15;
961                         else
962                                 if(x > 8192)
963                                         return 14;
964                                 else
965                                         if(x > 4096)
966                                                 return 13;
967                                         else
968                                                 return 12;
969         else
970                 if(x > 32)
971                         if(x > 256)
972                                 if(x > 1024)
973                                         return 11;
974                                 else
975                                         if(x > 512)
976                                                 return 10;
977                                         else
978                                                 return 9;
979                         else
980                                 if(x > 128)
981                                         return 8;
982                                 else
983                                         if(x > 64)
984                                                 return 7;
985                                         else
986                                                 return 6;
987                 else
988                         if(x > 4)
989                                 if(x > 16)
990                                         return 5;
991                                 else
992                                         if(x > 8)
993                                                 return 4;
994                                         else
995                                                 return 3;
996                         else
997                                 if(x > 2)
998                                         return 2;
999                                 else
1000                                         if(x > 1)
1001                                                 return 1;
1002                                         else
1003                                                 return 0;
1004 }
1005
1006 float rgb_mi_ma_to_hue(vector rgb, float mi, float ma)
1007 {
1008         if(mi == ma)
1009                 return 0;
1010         else if(ma == rgb_x)
1011         {
1012                 if(rgb_y >= rgb_z)
1013                         return (rgb_y - rgb_z) / (ma - mi);
1014                 else
1015                         return (rgb_y - rgb_z) / (ma - mi) + 6;
1016         }
1017         else if(ma == rgb_y)
1018                 return (rgb_z - rgb_x) / (ma - mi) + 2;
1019         else // if(ma == rgb_z)
1020                 return (rgb_x - rgb_y) / (ma - mi) + 4;
1021 }
1022
1023 vector hue_mi_ma_to_rgb(float hue, float mi, float ma)
1024 {
1025         vector rgb;
1026
1027         hue -= 6 * floor(hue / 6);
1028
1029         //else if(ma == rgb_x)
1030         //      hue = 60 * (rgb_y - rgb_z) / (ma - mi);
1031         if(hue <= 1)
1032         {
1033                 rgb_x = ma;
1034                 rgb_y = hue * (ma - mi) + mi;
1035                 rgb_z = mi;
1036         }
1037         //else if(ma == rgb_y)
1038         //      hue = 60 * (rgb_z - rgb_x) / (ma - mi) + 120;
1039         else if(hue <= 2)
1040         {
1041                 rgb_x = (2 - hue) * (ma - mi) + mi;
1042                 rgb_y = ma;
1043                 rgb_z = mi;
1044         }
1045         else if(hue <= 3)
1046         {
1047                 rgb_x = mi;
1048                 rgb_y = ma;
1049                 rgb_z = (hue - 2) * (ma - mi) + mi;
1050         }
1051         //else // if(ma == rgb_z)
1052         //      hue = 60 * (rgb_x - rgb_y) / (ma - mi) + 240;
1053         else if(hue <= 4)
1054         {
1055                 rgb_x = mi;
1056                 rgb_y = (4 - hue) * (ma - mi) + mi;
1057                 rgb_z = ma;
1058         }
1059         else if(hue <= 5)
1060         {
1061                 rgb_x = (hue - 4) * (ma - mi) + mi;
1062                 rgb_y = mi;
1063                 rgb_z = ma;
1064         }
1065         //else if(ma == rgb_x)
1066         //      hue = 60 * (rgb_y - rgb_z) / (ma - mi);
1067         else // if(hue <= 6)
1068         {
1069                 rgb_x = ma;
1070                 rgb_y = mi;
1071                 rgb_z = (6 - hue) * (ma - mi) + mi;
1072         }
1073
1074         return rgb;
1075 }
1076
1077 vector rgb_to_hsv(vector rgb)
1078 {
1079         float mi, ma;
1080         vector hsv;
1081
1082         mi = min(rgb_x, rgb_y, rgb_z);
1083         ma = max(rgb_x, rgb_y, rgb_z);
1084
1085         hsv_x = rgb_mi_ma_to_hue(rgb, mi, ma);
1086         hsv_z = ma;
1087
1088         if(ma == 0)
1089                 hsv_y = 0;
1090         else
1091                 hsv_y = 1 - mi/ma;
1092         
1093         return hsv;
1094 }
1095
1096 vector hsv_to_rgb(vector hsv)
1097 {
1098         return hue_mi_ma_to_rgb(hsv_x, hsv_z * (1 - hsv_y), hsv_z);
1099 }
1100
1101 vector rgb_to_hsl(vector rgb)
1102 {
1103         float mi, ma;
1104         vector hsl;
1105
1106         mi = min(rgb_x, rgb_y, rgb_z);
1107         ma = max(rgb_x, rgb_y, rgb_z);
1108
1109         hsl_x = rgb_mi_ma_to_hue(rgb, mi, ma);
1110         
1111         hsl_z = 0.5 * (mi + ma);
1112         if(mi == ma)
1113                 hsl_y = 0;
1114         else if(hsl_z <= 0.5)
1115                 hsl_y = (ma - mi) / (2*hsl_z);
1116         else // if(hsl_z > 0.5)
1117                 hsl_y = (ma - mi) / (2 - 2*hsl_z);
1118         
1119         return hsl;
1120 }
1121
1122 vector hsl_to_rgb(vector hsl)
1123 {
1124         float mi, ma, maminusmi;
1125
1126         if(hsl_z <= 0.5)
1127                 maminusmi = hsl_y * 2 * hsl_z;
1128         else
1129                 maminusmi = hsl_y * (2 - 2 * hsl_z);
1130         
1131         // hsl_z     = 0.5 * mi + 0.5 * ma
1132         // maminusmi =     - mi +       ma
1133         mi = hsl_z - 0.5 * maminusmi;
1134         ma = hsl_z + 0.5 * maminusmi;
1135
1136         return hue_mi_ma_to_rgb(hsl_x, mi, ma);
1137 }
1138
1139 string rgb_to_hexcolor(vector rgb)
1140 {
1141         return
1142                 strcat(
1143                         "^x",
1144                         DEC_TO_HEXDIGIT(floor(rgb_x * 15 + 0.5)),
1145                         DEC_TO_HEXDIGIT(floor(rgb_y * 15 + 0.5)),
1146                         DEC_TO_HEXDIGIT(floor(rgb_z * 15 + 0.5))
1147                 );
1148 }
1149
1150 // requires that m2>m1 in all coordinates, and that m4>m3
1151 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;}
1152
1153 // requires the same, but is a stronger condition
1154 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;}
1155
1156 #ifndef MENUQC
1157 #endif
1158
1159 float textLengthUpToWidth(string theText, float maxWidth, vector theSize, textLengthUpToWidth_widthFunction_t w)
1160 {
1161         // STOP.
1162         // The following function is SLOW.
1163         // For your safety and for the protection of those around you...
1164         // DO NOT CALL THIS AT HOME.
1165         // No really, don't.
1166         if(w(theText, theSize) <= maxWidth)
1167                 return strlen(theText); // yeah!
1168
1169         // binary search for right place to cut string
1170         float ch;
1171         float left, right, middle; // this always works
1172         left = 0;
1173         right = strlen(theText); // this always fails
1174         do
1175         {
1176                 middle = floor((left + right) / 2);
1177                 if(w(substring(theText, 0, middle), theSize) <= maxWidth)
1178                         left = middle;
1179                 else
1180                         right = middle;
1181         }
1182         while(left < right - 1);
1183
1184         if(w("^7", theSize) == 0) // detect color codes support in the width function
1185         {
1186                 // NOTE: when color codes are involved, this binary search is,
1187                 // mathematically, BROKEN. However, it is obviously guaranteed to
1188                 // terminate, as the range still halves each time - but nevertheless, it is
1189                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
1190                 // range, and "right" is outside).
1191                 
1192                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
1193                 // and decrease left on the basis of the chars detected of the truncated tag
1194                 // Even if the ^xrgb tag is not complete/correct, left is decreased
1195                 // (sometimes too much but with a correct result)
1196                 // it fixes also ^[0-9]
1197                 while(left >= 1 && substring(theText, left-1, 1) == "^")
1198                         left-=1;
1199
1200                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
1201                         left-=2;
1202                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
1203                         {
1204                                 ch = str2chr(theText, left-1);
1205                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
1206                                         left-=3;
1207                         }
1208                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
1209                         {
1210                                 ch = str2chr(theText, left-2);
1211                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
1212                                 {
1213                                         ch = str2chr(theText, left-1);
1214                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
1215                                                 left-=4;
1216                                 }
1217                         }
1218         }
1219         
1220         return left;
1221 }
1222
1223 float textLengthUpToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t w)
1224 {
1225         // STOP.
1226         // The following function is SLOW.
1227         // For your safety and for the protection of those around you...
1228         // DO NOT CALL THIS AT HOME.
1229         // No really, don't.
1230         if(w(theText) <= maxWidth)
1231                 return strlen(theText); // yeah!
1232
1233         // binary search for right place to cut string
1234         float ch;
1235         float left, right, middle; // this always works
1236         left = 0;
1237         right = strlen(theText); // this always fails
1238         do
1239         {
1240                 middle = floor((left + right) / 2);
1241                 if(w(substring(theText, 0, middle)) <= maxWidth)
1242                         left = middle;
1243                 else
1244                         right = middle;
1245         }
1246         while(left < right - 1);
1247
1248         if(w("^7") == 0) // detect color codes support in the width function
1249         {
1250                 // NOTE: when color codes are involved, this binary search is,
1251                 // mathematically, BROKEN. However, it is obviously guaranteed to
1252                 // terminate, as the range still halves each time - but nevertheless, it is
1253                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
1254                 // range, and "right" is outside).
1255                 
1256                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
1257                 // and decrease left on the basis of the chars detected of the truncated tag
1258                 // Even if the ^xrgb tag is not complete/correct, left is decreased
1259                 // (sometimes too much but with a correct result)
1260                 // it fixes also ^[0-9]
1261                 while(left >= 1 && substring(theText, left-1, 1) == "^")
1262                         left-=1;
1263
1264                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
1265                         left-=2;
1266                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
1267                         {
1268                                 ch = str2chr(theText, left-1);
1269                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
1270                                         left-=3;
1271                         }
1272                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
1273                         {
1274                                 ch = str2chr(theText, left-2);
1275                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
1276                                 {
1277                                         ch = str2chr(theText, left-1);
1278                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
1279                                                 left-=4;
1280                                 }
1281                         }
1282         }
1283         
1284         return left;
1285 }
1286
1287 string find_last_color_code(string s)
1288 {
1289         float start, len, i, carets;
1290         start = strstrofs(s, "^", 0);
1291         if (start == -1) // no caret found
1292                 return "";
1293         len = strlen(s)-1;
1294         for(i = len; i >= start; --i)
1295         {
1296                 if(substring(s, i, 1) != "^")
1297                         continue;
1298
1299                 carets = 1;
1300                 while (i-carets >= start && substring(s, i-carets, 1) == "^")
1301                         ++carets;
1302
1303                 // check if carets aren't all escaped
1304                 if (carets == 1 || mod(carets, 2) == 1) // first check is just an optimization
1305                 {
1306                         if(i+1 <= len)
1307                         if(strstrofs("0123456789", substring(s, i+1, 1), 0) >= 0)
1308                                 return substring(s, i, 2);
1309
1310                         if(i+4 <= len)
1311                         if(substring(s, i+1, 1) == "x")
1312                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+2, 1), 0) >= 0)
1313                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+3, 1), 0) >= 0)
1314                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+4, 1), 0) >= 0)
1315                                 return substring(s, i, 5);
1316                 }
1317                 i -= carets; // this also skips one char before the carets
1318         }
1319
1320         return "";
1321 }
1322
1323 string getWrappedLine(float w, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1324 {
1325         float cantake;
1326         float take;
1327         string s;
1328
1329         s = getWrappedLine_remaining;
1330         
1331         if(w <= 0)
1332         {
1333                 getWrappedLine_remaining = string_null;
1334                 return s; // the line has no size ANYWAY, nothing would be displayed.
1335         }
1336
1337         cantake = textLengthUpToWidth(s, w, theFontSize, tw);
1338         if(cantake > 0 && cantake < strlen(s))
1339         {
1340                 take = cantake - 1;
1341                 while(take > 0 && substring(s, take, 1) != " ")
1342                         --take;
1343                 if(take == 0)
1344                 {
1345                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
1346                         if(getWrappedLine_remaining == "")
1347                                 getWrappedLine_remaining = string_null;
1348                         else if (tw("^7", theFontSize) == 0)
1349                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
1350                         return substring(s, 0, cantake);
1351                 }
1352                 else
1353                 {
1354                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1355                         if(getWrappedLine_remaining == "")
1356                                 getWrappedLine_remaining = string_null;
1357                         else if (tw("^7", theFontSize) == 0)
1358                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
1359                         return substring(s, 0, take);
1360                 }
1361         }
1362         else
1363         {
1364                 getWrappedLine_remaining = string_null;
1365                 return s;
1366         }
1367 }
1368
1369 string getWrappedLineLen(float w, textLengthUpToLength_lenFunction_t tw)
1370 {
1371         float cantake;
1372         float take;
1373         string s;
1374
1375         s = getWrappedLine_remaining;
1376         
1377         if(w <= 0)
1378         {
1379                 getWrappedLine_remaining = string_null;
1380                 return s; // the line has no size ANYWAY, nothing would be displayed.
1381         }
1382
1383         cantake = textLengthUpToLength(s, w, tw);
1384         if(cantake > 0 && cantake < strlen(s))
1385         {
1386                 take = cantake - 1;
1387                 while(take > 0 && substring(s, take, 1) != " ")
1388                         --take;
1389                 if(take == 0)
1390                 {
1391                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
1392                         if(getWrappedLine_remaining == "")
1393                                 getWrappedLine_remaining = string_null;
1394                         else if (tw("^7") == 0)
1395                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
1396                         return substring(s, 0, cantake);
1397                 }
1398                 else
1399                 {
1400                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1401                         if(getWrappedLine_remaining == "")
1402                                 getWrappedLine_remaining = string_null;
1403                         else if (tw("^7") == 0)
1404                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
1405                         return substring(s, 0, take);
1406                 }
1407         }
1408         else
1409         {
1410                 getWrappedLine_remaining = string_null;
1411                 return s;
1412         }
1413 }
1414
1415 string textShortenToWidth(string theText, float maxWidth, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1416 {
1417         if(tw(theText, theFontSize) <= maxWidth)
1418                 return theText;
1419         else
1420                 return strcat(substring(theText, 0, textLengthUpToWidth(theText, maxWidth - tw("...", theFontSize), theFontSize, tw)), "...");
1421 }
1422
1423 string textShortenToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t tw)
1424 {
1425         if(tw(theText) <= maxWidth)
1426                 return theText;
1427         else
1428                 return strcat(substring(theText, 0, textLengthUpToLength(theText, maxWidth - tw("..."), tw)), "...");
1429 }
1430
1431 float isGametypeInFilter(float gt, float tp, float ts, string pattern)
1432 {
1433         string subpattern, subpattern2, subpattern3, subpattern4;
1434         subpattern = strcat(",", MapInfo_Type_ToString(gt), ",");
1435         if(tp)
1436                 subpattern2 = ",teams,";
1437         else
1438                 subpattern2 = ",noteams,";
1439         if(ts)
1440                 subpattern3 = ",teamspawns,";
1441         else
1442                 subpattern3 = ",noteamspawns,";
1443         if(gt == MAPINFO_TYPE_RACE || gt == MAPINFO_TYPE_CTS)
1444                 subpattern4 = ",race,";
1445         else
1446                 subpattern4 = string_null;
1447
1448         if(substring(pattern, 0, 1) == "-")
1449         {
1450                 pattern = substring(pattern, 1, strlen(pattern) - 1);
1451                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) >= 0)
1452                         return 0;
1453                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) >= 0)
1454                         return 0;
1455                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) >= 0)
1456                         return 0;
1457                 if(subpattern4 && strstrofs(strcat(",", pattern, ","), subpattern4, 0) >= 0)
1458                         return 0;
1459         }
1460         else
1461         {
1462                 if(substring(pattern, 0, 1) == "+")
1463                         pattern = substring(pattern, 1, strlen(pattern) - 1);
1464                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) < 0)
1465                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) < 0)
1466                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) < 0)
1467                 if((!subpattern4) || strstrofs(strcat(",", pattern, ","), subpattern4, 0) < 0)
1468                         return 0;
1469         }
1470         return 1;
1471 }
1472
1473 void shuffle(float n, swapfunc_t swap, entity pass)
1474 {
1475         float i, j;
1476         for(i = 1; i < n; ++i)
1477         {
1478                 // swap i-th item at a random position from 0 to i
1479                 // proof for even distribution:
1480                 //   n = 1: obvious
1481                 //   n -> n+1:
1482                 //     item n+1 gets at any position with chance 1/(n+1)
1483                 //     all others will get their 1/n chance reduced by factor n/(n+1)
1484                 //     to be on place n+1, their chance will be 1/(n+1)
1485                 //     1/n * n/(n+1) = 1/(n+1)
1486                 //     q.e.d.
1487                 j = floor(random() * (i + 1));
1488                 if(j != i)
1489                         swap(j, i, pass);
1490         }
1491 }
1492
1493 string substring_range(string s, float b, float e)
1494 {
1495         return substring(s, b, e - b);
1496 }
1497
1498 string swapwords(string str, float i, float j)
1499 {
1500         float n;
1501         string s1, s2, s3, s4, s5;
1502         float si, ei, sj, ej, s0, en;
1503         n = tokenizebyseparator(str, " "); // must match g_maplist processing in ShuffleMaplist and "shuffle"
1504         si = argv_start_index(i);
1505         sj = argv_start_index(j);
1506         ei = argv_end_index(i);
1507         ej = argv_end_index(j);
1508         s0 = argv_start_index(0);
1509         en = argv_end_index(n-1);
1510         s1 = substring_range(str, s0, si);
1511         s2 = substring_range(str, si, ei);
1512         s3 = substring_range(str, ei, sj);
1513         s4 = substring_range(str, sj, ej);
1514         s5 = substring_range(str, ej, en);
1515         return strcat(s1, s4, s3, s2, s5);
1516 }
1517
1518 string _shufflewords_str;
1519 void _shufflewords_swapfunc(float i, float j, entity pass)
1520 {
1521         _shufflewords_str = swapwords(_shufflewords_str, i, j);
1522 }
1523 string shufflewords(string str)
1524 {
1525         float n;
1526         _shufflewords_str = str;
1527         n = tokenizebyseparator(str, " ");
1528         shuffle(n, _shufflewords_swapfunc, world);
1529         str = _shufflewords_str;
1530         _shufflewords_str = string_null;
1531         return str;
1532 }
1533
1534 vector solve_quadratic(float a, float b, float c) // ax^2 + bx + c = 0
1535 {
1536         vector v;
1537         float D;
1538         v = '0 0 0';
1539         if(a == 0)
1540         {
1541                 if(b != 0)
1542                 {
1543                         v_x = v_y = -c / b;
1544                         v_z = 1;
1545                 }
1546                 else
1547                 {
1548                         if(c == 0)
1549                         {
1550                                 // actually, every number solves the equation!
1551                                 v_z = 1;
1552                         }
1553                 }
1554         }
1555         else
1556         {
1557                 D = b*b - 4*a*c;
1558                 if(D >= 0)
1559                 {
1560                         D = sqrt(D);
1561                         if(a > 0) // put the smaller solution first
1562                         {
1563                                 v_x = ((-b)-D) / (2*a);
1564                                 v_y = ((-b)+D) / (2*a);
1565                         }
1566                         else
1567                         {
1568                                 v_x = (-b+D) / (2*a);
1569                                 v_y = (-b-D) / (2*a);
1570                         }
1571                         v_z = 1;
1572                 }
1573                 else
1574                 {
1575                         // complex solutions!
1576                         D = sqrt(-D);
1577                         v_x = -b / (2*a);
1578                         if(a > 0)
1579                                 v_y =  D / (2*a);
1580                         else
1581                                 v_y = -D / (2*a);
1582                         v_z = 0;
1583                 }
1584         }
1585         return v;
1586 }
1587
1588 vector solve_shotdirection(vector myorg, vector myvel, vector eorg, vector evel, float spd, float newton_style)
1589 {
1590         vector ret;
1591
1592         // make origin and speed relative
1593         eorg -= myorg;
1594         if(newton_style)
1595                 evel -= myvel;
1596
1597         // now solve for ret, ret normalized:
1598         //   eorg + t * evel == t * ret * spd
1599         // or, rather, solve for t:
1600         //   |eorg + t * evel| == t * spd
1601         //   eorg^2 + t^2 * evel^2 + 2 * t * (eorg * evel) == t^2 * spd^2
1602         //   t^2 * (evel^2 - spd^2) + t * (2 * (eorg * evel)) + eorg^2 == 0
1603         vector solution = solve_quadratic(evel * evel - spd * spd, 2 * (eorg * evel), eorg * eorg);
1604         // p = 2 * (eorg * evel) / (evel * evel - spd * spd)
1605         // q = (eorg * eorg) / (evel * evel - spd * spd)
1606         if(!solution_z) // no real solution
1607         {
1608                 // happens if D < 0
1609                 // (eorg * evel)^2 < (evel^2 - spd^2) * eorg^2
1610                 // (eorg * evel)^2 / eorg^2 < evel^2 - spd^2
1611                 // spd^2 < ((evel^2 * eorg^2) - (eorg * evel)^2) / eorg^2
1612                 // spd^2 < evel^2 * (1 - cos^2 angle(evel, eorg))
1613                 // spd^2 < evel^2 * sin^2 angle(evel, eorg)
1614                 // spd < |evel| * sin angle(evel, eorg)
1615                 return '0 0 0';
1616         }
1617         else if(solution_x > 0)
1618         {
1619                 // both solutions > 0: take the smaller one
1620                 // happens if p < 0 and q > 0
1621                 ret = normalize(eorg + solution_x * evel);
1622         }
1623         else if(solution_y > 0)
1624         {
1625                 // one solution > 0: take the larger one
1626                 // happens if q < 0 or q == 0 and p < 0
1627                 ret = normalize(eorg + solution_y * evel);
1628         }
1629         else
1630         {
1631                 // no solution > 0: reject
1632                 // happens if p > 0 and q >= 0
1633                 // 2 * (eorg * evel) / (evel * evel - spd * spd) > 0
1634                 // (eorg * eorg) / (evel * evel - spd * spd) >= 0
1635                 //
1636                 // |evel| >= spd
1637                 // eorg * evel > 0
1638                 //
1639                 // "Enemy is moving away from me at more than spd"
1640                 return '0 0 0';
1641         }
1642
1643         // NOTE: we always got a solution if spd > |evel|
1644
1645         if(newton_style == 2)
1646                 ret = normalize(ret * spd + myvel);
1647
1648         return ret;
1649 }
1650
1651 vector get_shotvelocity(vector myvel, vector mydir, float spd, float newton_style, float mi, float ma)
1652 {
1653         if(!newton_style)
1654                 return spd * mydir;
1655
1656         if(newton_style == 2)
1657         {
1658                 // true Newtonian projectiles with automatic aim adjustment
1659                 //
1660                 // solve: |outspeed * mydir - myvel| = spd
1661                 // outspeed^2 - 2 * outspeed * (mydir * myvel) + myvel^2 - spd^2 = 0
1662                 // outspeed = (mydir * myvel) +- sqrt((mydir * myvel)^2 - myvel^2 + spd^2)
1663                 // PLUS SIGN!
1664                 // not defined?
1665                 // then...
1666                 // myvel^2 - (mydir * myvel)^2 > spd^2
1667                 // velocity without mydir component > spd
1668                 // fire at smallest possible spd that works?
1669                 // |(mydir * myvel) * myvel - myvel| = spd
1670
1671                 vector solution = solve_quadratic(1, -2 * (mydir * myvel), myvel * myvel - spd * spd);
1672
1673                 float outspeed;
1674                 if(solution_z)
1675                         outspeed = solution_y; // the larger one
1676                 else
1677                 {
1678                         //outspeed = 0; // slowest possible shot
1679                         outspeed = solution_x; // the real part (that is, the average!)
1680                         //dprint("impossible shot, adjusting\n");
1681                 }
1682
1683                 outspeed = bound(spd * mi, outspeed, spd * ma);
1684                 return mydir * outspeed;
1685         }
1686
1687         // real Newtonian
1688         return myvel + spd * mydir;
1689 }
1690
1691 void check_unacceptable_compiler_bugs()
1692 {
1693         if(cvar("_allow_unacceptable_compiler_bugs"))
1694                 return;
1695         tokenize_console("foo bar");
1696         if(strcat(argv(0), substring("foo bar", 4, 7 - argv_start_index(1))) == "barbar")
1697                 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.");
1698
1699         string s = "";
1700         if not(s)
1701                 error("The empty string counts as false. We do not want that!");
1702 }
1703
1704 float compressShotOrigin(vector v)
1705 {
1706         float x, y, z;
1707         x = rint(v_x * 2);
1708         y = rint(v_y * 4) + 128;
1709         z = rint(v_z * 4) + 128;
1710         if(x > 255 || x < 0)
1711         {
1712                 print("shot origin ", vtos(v), " x out of bounds\n");
1713                 x = bound(0, x, 255);
1714         }
1715         if(y > 255 || y < 0)
1716         {
1717                 print("shot origin ", vtos(v), " y out of bounds\n");
1718                 y = bound(0, y, 255);
1719         }
1720         if(z > 255 || z < 0)
1721         {
1722                 print("shot origin ", vtos(v), " z out of bounds\n");
1723                 z = bound(0, z, 255);
1724         }
1725         return x * 0x10000 + y * 0x100 + z;
1726 }
1727 vector decompressShotOrigin(float f)
1728 {
1729         vector v;
1730         v_x = ((f & 0xFF0000) / 0x10000) / 2;
1731         v_y = ((f & 0xFF00) / 0x100 - 128) / 4;
1732         v_z = ((f & 0xFF) - 128) / 4;
1733         return v;
1734 }
1735
1736 void heapsort(float n, swapfunc_t swap, comparefunc_t cmp, entity pass)
1737 {
1738         float start, end, root, child;
1739
1740         // heapify
1741         start = floor((n - 2) / 2);
1742         while(start >= 0)
1743         {
1744                 // siftdown(start, count-1);
1745                 root = start;
1746                 while(root * 2 + 1 <= n-1)
1747                 {
1748                         child = root * 2 + 1;
1749                         if(child < n-1)
1750                                 if(cmp(child, child+1, pass) < 0)
1751                                         ++child;
1752                         if(cmp(root, child, pass) < 0)
1753                         {
1754                                 swap(root, child, pass);
1755                                 root = child;
1756                         }
1757                         else
1758                                 break;
1759                 }
1760                 // end of siftdown
1761                 --start;
1762         }
1763
1764         // extract
1765         end = n - 1;
1766         while(end > 0)
1767         {
1768                 swap(0, end, pass);
1769                 --end;
1770                 // siftdown(0, end);
1771                 root = 0;
1772                 while(root * 2 + 1 <= end)
1773                 {
1774                         child = root * 2 + 1;
1775                         if(child < end && cmp(child, child+1, pass) < 0)
1776                                 ++child;
1777                         if(cmp(root, child, pass) < 0)
1778                         {
1779                                 swap(root, child, pass);
1780                                 root = child;
1781                         }
1782                         else
1783                                 break;
1784                 }
1785                 // end of siftdown
1786         }
1787 }
1788
1789 void RandomSelection_Init()
1790 {
1791         RandomSelection_totalweight = 0;
1792         RandomSelection_chosen_ent = world;
1793         RandomSelection_chosen_float = 0;
1794         RandomSelection_chosen_string = string_null;
1795         RandomSelection_best_priority = -1;
1796 }
1797 void RandomSelection_Add(entity e, float f, string s, float weight, float priority)
1798 {
1799         if(priority > RandomSelection_best_priority)
1800         {
1801                 RandomSelection_best_priority = priority;
1802                 RandomSelection_chosen_ent = e;
1803                 RandomSelection_chosen_float = f;
1804                 RandomSelection_chosen_string = s;
1805                 RandomSelection_totalweight = weight;
1806         }
1807         else if(priority == RandomSelection_best_priority)
1808         {
1809                 RandomSelection_totalweight += weight;
1810                 if(random() * RandomSelection_totalweight <= weight)
1811                 {
1812                         RandomSelection_chosen_ent = e;
1813                         RandomSelection_chosen_float = f;
1814                         RandomSelection_chosen_string = s;
1815                 }
1816         }
1817 }
1818
1819 vector healtharmor_maxdamage(float h, float a, float armorblock)
1820 {
1821         // NOTE: we'll always choose the SMALLER value...
1822         float healthdamage, armordamage, armorideal;
1823         vector v;
1824         healthdamage = (h - 1) / (1 - armorblock); // damage we can take if we could use more health
1825         armordamage = a + (h - 1); // damage we can take if we could use more armor
1826         armorideal = healthdamage * armorblock;
1827         v_y = armorideal;
1828         if(armordamage < healthdamage)
1829         {
1830                 v_x = armordamage;
1831                 v_z = 1;
1832         }
1833         else
1834         {
1835                 v_x = healthdamage;
1836                 v_z = 0;
1837         }
1838         return v;
1839 }
1840
1841 vector healtharmor_applydamage(float a, float armorblock, float damage)
1842 {
1843         vector v;
1844         v_y = bound(0, damage * armorblock, a); // save
1845         v_x = bound(0, damage - v_y, damage); // take
1846         v_z = 0;
1847         return v;
1848 }
1849
1850 string getcurrentmod()
1851 {
1852         float n;
1853         string m;
1854         m = cvar_string("fs_gamedir");
1855         n = tokenize_console(m);
1856         if(n == 0)
1857                 return "data";
1858         else
1859                 return argv(n - 1);
1860 }
1861
1862 #ifndef MENUQC
1863 #ifdef CSQC
1864 float ReadInt24_t()
1865 {
1866         float v;
1867         v = ReadShort() * 256; // note: this is signed
1868         v += ReadByte(); // note: this is unsigned
1869         return v;
1870 }
1871 #else
1872 void WriteInt24_t(float dst, float val)
1873 {
1874         float v;
1875         WriteShort(dst, (v = floor(val / 256)));
1876         WriteByte(dst, val - v * 256); // 0..255
1877 }
1878 #endif
1879 #endif
1880
1881 float float2range11(float f)
1882 {
1883         // continuous function mapping all reals into -1..1
1884         return f / (fabs(f) + 1);
1885 }
1886
1887 float float2range01(float f)
1888 {
1889         // continuous function mapping all reals into 0..1
1890         return 0.5 + 0.5 * float2range11(f);
1891 }
1892
1893 // from the GNU Scientific Library
1894 float gsl_ran_gaussian_lastvalue;
1895 float gsl_ran_gaussian_lastvalue_set;
1896 float gsl_ran_gaussian(float sigma)
1897 {
1898         float a, b;
1899         if(gsl_ran_gaussian_lastvalue_set)
1900         {
1901                 gsl_ran_gaussian_lastvalue_set = 0;
1902                 return sigma * gsl_ran_gaussian_lastvalue;
1903         }
1904         else
1905         {
1906                 a = random() * 2 * M_PI;
1907                 b = sqrt(-2 * log(random()));
1908                 gsl_ran_gaussian_lastvalue = cos(a) * b;
1909                 gsl_ran_gaussian_lastvalue_set = 1;
1910                 return sigma * sin(a) * b;
1911         }
1912 }
1913
1914 string car(string s)
1915 {
1916         float o;
1917         o = strstrofs(s, " ", 0);
1918         if(o < 0)
1919                 return s;
1920         return substring(s, 0, o);
1921 }
1922 string cdr(string s)
1923 {
1924         float o;
1925         o = strstrofs(s, " ", 0);
1926         if(o < 0)
1927                 return string_null;
1928         return substring(s, o + 1, strlen(s) - (o + 1));
1929 }
1930 float matchacl(string acl, string str)
1931 {
1932         string t, s;
1933         float r, d;
1934         r = 0;
1935         while(acl)
1936         {
1937                 t = car(acl); acl = cdr(acl);
1938
1939                 d = 1;
1940                 if(substring(t, 0, 1) == "-")
1941                 {
1942                         d = -1;
1943                         t = substring(t, 1, strlen(t) - 1);
1944                 }
1945                 else if(substring(t, 0, 1) == "+")
1946                         t = substring(t, 1, strlen(t) - 1);
1947
1948                 if(substring(t, -1, 1) == "*")
1949                 {
1950                         t = substring(t, 0, strlen(t) - 1);
1951                         s = substring(str, 0, strlen(t));
1952                 }
1953                 else
1954                         s = str;
1955
1956                 if(s == t)
1957                 {
1958                         r = d;
1959                 }
1960         }
1961         return r;
1962 }
1963 float startsWith(string haystack, string needle)
1964 {
1965         return substring(haystack, 0, strlen(needle)) == needle;
1966 }
1967 float startsWithNocase(string haystack, string needle)
1968 {
1969         return strcasecmp(substring(haystack, 0, strlen(needle)), needle) == 0;
1970 }
1971
1972 string get_model_datafilename(string m, float sk, string fil)
1973 {
1974         if(m)
1975                 m = strcat(m, "_");
1976         else
1977                 m = "models/player/*_";
1978         if(sk >= 0)
1979                 m = strcat(m, ftos(sk));
1980         else
1981                 m = strcat(m, "*");
1982         return strcat(m, ".", fil);
1983 }
1984
1985 float get_model_parameters(string m, float sk)
1986 {
1987         string fn, s, c;
1988         float fh;
1989
1990         get_model_parameters_modelname = string_null;
1991         get_model_parameters_modelskin = -1;
1992         get_model_parameters_name = string_null;
1993         get_model_parameters_species = -1;
1994         get_model_parameters_sex = string_null;
1995         get_model_parameters_weight = -1;
1996         get_model_parameters_age = -1;
1997         get_model_parameters_desc = string_null;
1998
1999         if not(m)
2000                 return 1;
2001         if(sk < 0)
2002         {
2003                 if(substring(m, -4, -1) != ".txt")
2004                         return 0;
2005                 if(substring(m, -6, 1) != "_")
2006                         return 0;
2007                 sk = stof(substring(m, -5, 1));
2008                 m = substring(m, 0, -7);
2009         }
2010
2011         fn = get_model_datafilename(m, sk, "txt");
2012         fh = fopen(fn, FILE_READ);
2013         if(fh < 0)
2014         {
2015                 sk = 0;
2016                 fn = get_model_datafilename(m, sk, "txt");
2017                 fh = fopen(fn, FILE_READ);
2018                 if(fh < 0)
2019                         return 0;
2020         }
2021
2022         get_model_parameters_modelname = m;
2023         get_model_parameters_modelskin = sk;
2024         while((s = fgets(fh)))
2025         {
2026                 if(s == "")
2027                         break; // next lines will be description
2028                 c = car(s);
2029                 s = cdr(s);
2030                 if(c == "name")
2031                         get_model_parameters_name = s;
2032                 if(c == "species")
2033                         switch(s)
2034                         {
2035                                 case "human":       get_model_parameters_species = SPECIES_HUMAN;       break;
2036                                 case "alien":       get_model_parameters_species = SPECIES_ALIEN;       break;
2037                                 case "robot_shiny": get_model_parameters_species = SPECIES_ROBOT_SHINY; break;
2038                                 case "robot_rusty": get_model_parameters_species = SPECIES_ROBOT_RUSTY; break;
2039                                 case "robot_solid": get_model_parameters_species = SPECIES_ROBOT_SOLID; break;
2040                                 case "animal":      get_model_parameters_species = SPECIES_ANIMAL;      break;
2041                                 case "reserved":    get_model_parameters_species = SPECIES_RESERVED;    break;
2042                         }
2043                 if(c == "sex")
2044                         get_model_parameters_sex = s;
2045                 if(c == "weight")
2046                         get_model_parameters_weight = stof(s);
2047                 if(c == "age")
2048                         get_model_parameters_age = stof(s);
2049         }
2050
2051         while((s = fgets(fh)))
2052         {
2053                 if(get_model_parameters_desc)
2054                         get_model_parameters_desc = strcat(get_model_parameters_desc, "\n");
2055                 if(s != "")
2056                         get_model_parameters_desc = strcat(get_model_parameters_desc, s);
2057         }
2058
2059         fclose(fh);
2060
2061         return 1;
2062 }
2063
2064 vector vec2(vector v)
2065 {
2066         v_z = 0;
2067         return v;
2068 }
2069
2070 #ifndef MENUQC
2071 vector NearestPointOnBox(entity box, vector org)
2072 {
2073         vector m1, m2, nearest;
2074
2075         m1 = box.mins + box.origin;
2076         m2 = box.maxs + box.origin;
2077
2078         nearest_x = bound(m1_x, org_x, m2_x);
2079         nearest_y = bound(m1_y, org_y, m2_y);
2080         nearest_z = bound(m1_z, org_z, m2_z);
2081
2082         return nearest;
2083 }
2084 #endif
2085
2086 float vercmp_recursive(string v1, string v2)
2087 {
2088         float dot1, dot2;
2089         string s1, s2;
2090         float r;
2091
2092         dot1 = strstrofs(v1, ".", 0);
2093         dot2 = strstrofs(v2, ".", 0);
2094         if(dot1 == -1)
2095                 s1 = v1;
2096         else
2097                 s1 = substring(v1, 0, dot1);
2098         if(dot2 == -1)
2099                 s2 = v2;
2100         else
2101                 s2 = substring(v2, 0, dot2);
2102
2103         r = stof(s1) - stof(s2);
2104         if(r != 0)
2105                 return r;
2106
2107         r = strcasecmp(s1, s2);
2108         if(r != 0)
2109                 return r;
2110
2111         if(dot1 == -1)
2112                 if(dot2 == -1)
2113                         return 0;
2114                 else
2115                         return -1;
2116         else
2117                 if(dot2 == -1)
2118                         return 1;
2119                 else
2120                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
2121 }
2122
2123 float vercmp(string v1, string v2)
2124 {
2125         if(strcasecmp(v1, v2) == 0) // early out check
2126                 return 0;
2127
2128         // "git" beats all
2129         if(v1 == "git")
2130                 return 1;
2131         if(v2 == "git")
2132                 return -1;
2133
2134         return vercmp_recursive(v1, v2);
2135 }
2136
2137 float u8_strsize(string s)
2138 {
2139         float l, i, c;
2140         l = 0;
2141         for(i = 0; ; ++i)
2142         {
2143                 c = str2chr(s, i);
2144                 if(c <= 0)
2145                         break;
2146                 ++l;
2147                 if(c >= 0x80)
2148                         ++l;
2149                 if(c >= 0x800)
2150                         ++l;
2151                 if(c >= 0x10000)
2152                         ++l;
2153         }
2154         return l;
2155 }
2156
2157 // translation helpers
2158 string language_filename(string s)
2159 {
2160         string fn;
2161         float fh;
2162         fn = prvm_language;
2163         if(fn == "" || fn == "dump")
2164                 return s;
2165         fn = strcat(s, ".", fn);
2166         if((fh = fopen(fn, FILE_READ)) >= 0)
2167         {
2168                 fclose(fh);
2169                 return fn;
2170         }
2171         return s;
2172 }
2173 string CTX(string s)
2174 {
2175         float p = strstrofs(s, "^", 0);
2176         if(p < 0)
2177                 return s;
2178         return substring(s, p+1, -1);
2179 }
2180
2181 // x-encoding (encoding as zero length invisible string)
2182 const string XENCODE_2  = "xX";
2183 const string XENCODE_22 = "0123456789abcdefABCDEF";
2184 string xencode(float f)
2185 {
2186         float a, b, c, d;
2187         d = mod(f, 22); f = floor(f / 22);
2188         c = mod(f, 22); f = floor(f / 22);
2189         b = mod(f, 22); f = floor(f / 22);
2190         a = mod(f,  2); // f = floor(f /  2);
2191         return strcat(
2192                 "^",
2193                 substring(XENCODE_2,  a, 1),
2194                 substring(XENCODE_22, b, 1),
2195                 substring(XENCODE_22, c, 1),
2196                 substring(XENCODE_22, d, 1)
2197         );
2198 }
2199 float xdecode(string s)
2200 {
2201         float a, b, c, d;
2202         if(substring(s, 0, 1) != "^")
2203                 return -1;
2204         if(strlen(s) < 5)
2205                 return -1;
2206         a = strstrofs(XENCODE_2,  substring(s, 1, 1), 0);
2207         b = strstrofs(XENCODE_22, substring(s, 2, 1), 0);
2208         c = strstrofs(XENCODE_22, substring(s, 3, 1), 0);
2209         d = strstrofs(XENCODE_22, substring(s, 4, 1), 0);
2210         if(a < 0 || b < 0 || c < 0 || d < 0)
2211                 return -1;
2212         return ((a * 22 + b) * 22 + c) * 22 + d;
2213 }
2214
2215 float lowestbit(float f)
2216 {
2217         f &~= f * 2;
2218         f &~= f * 4;
2219         f &~= f * 16;
2220         f &~= f * 256;
2221         f &~= f * 65536;
2222         return f;
2223 }
2224
2225 /*
2226 string strlimitedlen(string input, string truncation, float strip_colors, float limit)
2227 {
2228         if(strlen((strip_colors ? strdecolorize(input) : input)) <= limit)
2229                 return input;
2230         else
2231                 return strcat(substring(input, 0, (strlen(input) - strlen(truncation))), truncation);
2232 }*/
2233
2234 // escape the string to make it safe for consoles
2235 string MakeConsoleSafe(string input)
2236 {
2237         input = strreplace("\n", "", input);
2238         input = strreplace("\\", "\\\\", input);
2239         input = strreplace("$", "$$", input);
2240         input = strreplace("\"", "\\\"", input);
2241         return input;
2242 }
2243
2244 #ifndef MENUQC
2245 // get true/false value of a string with multiple different inputs
2246 float InterpretBoolean(string input)
2247 {
2248         switch(strtolower(input))
2249         {
2250                 case "yes":
2251                 case "true":
2252                 case "on":
2253                         return TRUE;
2254                 
2255                 case "no":
2256                 case "false":
2257                 case "off":
2258                         return FALSE;
2259                 
2260                 default: return stof(input);
2261         }
2262 }
2263 #endif
2264
2265 #ifdef CSQC
2266 entity ReadCSQCEntity()
2267 {
2268         float f;
2269         f = ReadShort();
2270         if(f == 0)
2271                 return world;
2272         return findfloat(world, entnum, f);
2273 }
2274 #endif
2275
2276 float shutdown_running;
2277 #ifdef SVQC
2278 void SV_Shutdown()
2279 #endif
2280 #ifdef CSQC
2281 void CSQC_Shutdown()
2282 #endif
2283 #ifdef MENUQC
2284 void m_shutdown()
2285 #endif
2286 {
2287         if(shutdown_running)
2288         {
2289                 print("Recursive shutdown detected! Only restoring cvars...\n");
2290         }
2291         else
2292         {
2293                 shutdown_running = 1;
2294                 Shutdown();
2295         }
2296         cvar_settemp_restore(); // this must be done LAST, but in any case
2297 }
2298
2299 #define APPROXPASTTIME_ACCURACY_REQUIREMENT 0.05
2300 #define APPROXPASTTIME_MAX (16384 * APPROXPASTTIME_ACCURACY_REQUIREMENT)
2301 #define APPROXPASTTIME_RANGE (64 * APPROXPASTTIME_ACCURACY_REQUIREMENT)
2302 // this will use the value:
2303 //   128
2304 // accuracy near zero is APPROXPASTTIME_MAX/(256*255)
2305 // accuracy at x is 1/derivative, i.e.
2306 //   APPROXPASTTIME_MAX * (1 + 256 * (dt / APPROXPASTTIME_MAX))^2 / 65536
2307 #ifdef SVQC
2308 void WriteApproxPastTime(float dst, float t)
2309 {
2310         float dt = time - t;
2311
2312         // warning: this is approximate; do not resend when you don't have to!
2313         // be careful with sendflags here!
2314         // we want: 0 -> 0.05, 1 -> 0.1, ..., 255 -> 12.75
2315
2316         // map to range...
2317         dt = 256 * (dt / ((APPROXPASTTIME_MAX / 256) + dt));
2318
2319         // round...
2320         dt = rint(bound(0, dt, 255));
2321
2322         WriteByte(dst, dt);
2323 }
2324 #endif
2325 #ifdef CSQC
2326 float ReadApproxPastTime()
2327 {
2328         float dt = ReadByte();
2329
2330         // map from range...PPROXPASTTIME_MAX / 256
2331         dt = (APPROXPASTTIME_MAX / 256) * (dt / (256 - dt));
2332
2333         return servertime - dt;
2334 }
2335 #endif
2336
2337 #ifndef MENUQC
2338 .float skeleton_bones_index;
2339 void Skeleton_SetBones(entity e)
2340 {
2341         // set skeleton_bones to the total number of bones on the model
2342         if(e.skeleton_bones_index == e.modelindex)
2343                 return; // same model, nothing to update
2344
2345         float skelindex;
2346         skelindex = skel_create(e.modelindex);
2347         e.skeleton_bones = skel_get_numbones(skelindex);
2348         skel_delete(skelindex);
2349         e.skeleton_bones_index = e.modelindex;
2350 }
2351 #endif
2352
2353 string to_execute_next_frame;
2354 void execute_next_frame()
2355 {
2356         if(to_execute_next_frame)
2357         {
2358                 localcmd("\n", to_execute_next_frame, "\n");
2359                 strunzone(to_execute_next_frame);
2360                 to_execute_next_frame = string_null;
2361         }
2362 }
2363 void queue_to_execute_next_frame(string s)
2364 {
2365         if(to_execute_next_frame)
2366         {
2367                 s = strcat(s, "\n", to_execute_next_frame);
2368                 strunzone(to_execute_next_frame);
2369         }
2370         to_execute_next_frame = strzone(s);
2371 }
2372
2373 float cubic_speedfunc(float startspeedfactor, float endspeedfactor, float x)
2374 {
2375         return
2376                 (((     startspeedfactor + endspeedfactor - 2
2377                 ) * x - 2 * startspeedfactor - endspeedfactor + 3
2378                 ) * x + startspeedfactor
2379                 ) * x;
2380 }
2381
2382 float cubic_speedfunc_is_sane(float startspeedfactor, float endspeedfactor)
2383 {
2384         if(startspeedfactor < 0 || endspeedfactor < 0)
2385                 return FALSE;
2386
2387         /*
2388         // if this is the case, the possible zeros of the first derivative are outside
2389         // 0..1
2390         We can calculate this condition as condition 
2391         if(se <= 3)
2392                 return TRUE;
2393         */
2394
2395         // better, see below:
2396         if(startspeedfactor <= 3 && endspeedfactor <= 3)
2397                 return TRUE;
2398
2399         // if this is the case, the first derivative has no zeros at all
2400         float se = startspeedfactor + endspeedfactor;
2401         float s_e = startspeedfactor - endspeedfactor;
2402         if(3 * (se - 4) * (se - 4) + s_e * s_e <= 12) // an ellipse
2403                 return TRUE;
2404
2405         // Now let s <= 3, s <= 3, s+e >= 3 (triangle) then we get se <= 6 (top right corner).
2406         // we also get s_e <= 6 - se
2407         // 3 * (se - 4)^2 + (6 - se)^2
2408         // is quadratic, has value 12 at 3 and 6, and value < 12 in between.
2409         // Therefore, above "better" check works!
2410
2411         return FALSE;
2412
2413         // known good cases:
2414         // (0, [0..3])
2415         // (0.5, [0..3.8])
2416         // (1, [0..4])
2417         // (1.5, [0..3.9])
2418         // (2, [0..3.7])
2419         // (2.5, [0..3.4])
2420         // (3, [0..3])
2421         // (3.5, [0.2..2.3])
2422         // (4, 1)
2423 }
2424
2425 #ifndef MENUQC
2426 vector cliptoplane(vector v, vector p)
2427 {
2428         return v - (v * p) * p;
2429 }
2430
2431 vector solve_cubic_pq(float p, float q)
2432 {
2433         float D, u, v, a;
2434         D = q*q/4.0 + p*p*p/27.0;
2435         if(D < 0)
2436         {
2437                 // irreducibilis
2438                 a = 1.0/3.0 * acos(-q/2.0 * sqrt(-27.0/(p*p*p)));
2439                 u = sqrt(-4.0/3.0 * p);
2440                 // a in range 0..pi/3
2441                 // cos(a)
2442                 // cos(a + 2pi/3)
2443                 // cos(a + 4pi/3)
2444                 return
2445                         u *
2446                         (
2447                                 '1 0 0' * cos(a + 2.0/3.0*M_PI)
2448                                 +
2449                                 '0 1 0' * cos(a + 4.0/3.0*M_PI)
2450                                 +
2451                                 '0 0 1' * cos(a)
2452                         );
2453         }
2454         else if(D == 0)
2455         {
2456                 // simple
2457                 if(p == 0)
2458                         return '0 0 0';
2459                 u = 3*q/p;
2460                 v = -u/2;
2461                 if(u >= v)
2462                         return '1 1 0' * v + '0 0 1' * u;
2463                 else
2464                         return '0 1 1' * v + '1 0 0' * u;
2465         }
2466         else
2467         {
2468                 // cardano
2469                 u = cbrt(-q/2.0 + sqrt(D));
2470                 v = cbrt(-q/2.0 - sqrt(D));
2471                 return '1 1 1' * (u + v);
2472         }
2473 }
2474 vector solve_cubic_abcd(float a, float b, float c, float d)
2475 {
2476         // y = 3*a*x + b
2477         // x = (y - b) / 3a
2478         float p, q;
2479         vector v;
2480         p = (9*a*c - 3*b*b);
2481         q = (27*a*a*d - 9*a*b*c + 2*b*b*b);
2482         v = solve_cubic_pq(p, q);
2483         v = (v -  b * '1 1 1') * (1.0 / (3.0 * a));
2484         if(a < 0)
2485                 v += '1 0 -1' * (v_z - v_x); // swap x, z
2486         return v;
2487 }
2488
2489 vector findperpendicular(vector v)
2490 {
2491         vector p;
2492         p_x = v_z;
2493         p_y = -v_x;
2494         p_z = v_y;
2495         return normalize(cliptoplane(p, v));
2496 }
2497
2498 vector W_CalculateSpread(vector forward, float spread, float spreadfactor, float spreadstyle)
2499 {
2500         float sigma;
2501         vector v1, v2;
2502         float dx, dy, r;
2503         float sstyle;
2504         spread *= spreadfactor; //g_weaponspreadfactor;
2505         if(spread <= 0)
2506                 return forward;
2507         sstyle = spreadstyle; //autocvar_g_projectiles_spread_style;
2508         
2509         if(sstyle == 0)
2510         {
2511                 // this is the baseline for the spread value!
2512                 // standard deviation: sqrt(2/5)
2513                 // density function: sqrt(1-r^2)
2514                 return forward + randomvec() * spread;
2515         }
2516         else if(sstyle == 1)
2517         {
2518                 // same thing, basically
2519                 return normalize(forward + cliptoplane(randomvec() * spread, forward));
2520         }
2521         else if(sstyle == 2)
2522         {
2523                 // circle spread... has at sigma=1 a standard deviation of sqrt(1/2)
2524                 sigma = spread * 0.89442719099991587855; // match baseline stddev
2525                 v1 = findperpendicular(forward);
2526                 v2 = cross(forward, v1);
2527                 // random point on unit circle
2528                 dx = random() * 2 * M_PI;
2529                 dy = sin(dx);
2530                 dx = cos(dx);
2531                 // radius in our dist function
2532                 r = random();
2533                 r = sqrt(r);
2534                 return normalize(forward + (v1 * dx + v2 * dy) * r * sigma);
2535         }
2536         else if(sstyle == 3) // gauss 3d
2537         {
2538                 sigma = spread * 0.44721359549996; // match baseline stddev
2539                 // note: 2D gaussian has sqrt(2) times the stddev of 1D, so this factor is right
2540                 v1 = forward;
2541                 v1_x += gsl_ran_gaussian(sigma);
2542                 v1_y += gsl_ran_gaussian(sigma);
2543                 v1_z += gsl_ran_gaussian(sigma);
2544                 return v1;
2545         }
2546         else if(sstyle == 4) // gauss 2d
2547         {
2548                 sigma = spread * 0.44721359549996; // match baseline stddev
2549                 // note: 2D gaussian has sqrt(2) times the stddev of 1D, so this factor is right
2550                 v1_x = gsl_ran_gaussian(sigma);
2551                 v1_y = gsl_ran_gaussian(sigma);
2552                 v1_z = gsl_ran_gaussian(sigma);
2553                 return normalize(forward + cliptoplane(v1, forward));
2554         }
2555         else if(sstyle == 5) // 1-r
2556         {
2557                 sigma = spread * 1.154700538379252; // match baseline stddev
2558                 v1 = findperpendicular(forward);
2559                 v2 = cross(forward, v1);
2560                 // random point on unit circle
2561                 dx = random() * 2 * M_PI;
2562                 dy = sin(dx);
2563                 dx = cos(dx);
2564                 // radius in our dist function
2565                 r = random();
2566                 r = solve_cubic_abcd(-2, 3, 0, -r) * '0 1 0';
2567                 return normalize(forward + (v1 * dx + v2 * dy) * r * sigma);
2568         }
2569         else if(sstyle == 6) // 1-r^2
2570         {
2571                 sigma = spread * 1.095445115010332; // match baseline stddev
2572                 v1 = findperpendicular(forward);
2573                 v2 = cross(forward, v1);
2574                 // random point on unit circle
2575                 dx = random() * 2 * M_PI;
2576                 dy = sin(dx);
2577                 dx = cos(dx);
2578                 // radius in our dist function
2579                 r = random();
2580                 r = sqrt(1 - r);
2581                 r = sqrt(1 - r);
2582                 return normalize(forward + (v1 * dx + v2 * dy) * r * sigma);
2583         }
2584         else if(sstyle == 7) // (1-r) (2-r)
2585         {
2586                 sigma = spread * 1.224744871391589; // match baseline stddev
2587                 v1 = findperpendicular(forward);
2588                 v2 = cross(forward, v1);
2589                 // random point on unit circle
2590                 dx = random() * 2 * M_PI;
2591                 dy = sin(dx);
2592                 dx = cos(dx);
2593                 // radius in our dist function
2594                 r = random();
2595                 r = 1 - sqrt(r);
2596                 r = 1 - sqrt(r);
2597                 return normalize(forward + (v1 * dx + v2 * dy) * r * sigma);
2598         }
2599         else
2600                 error("g_projectiles_spread_style must be 0 (sphere), 1 (flattened sphere), 2 (circle), 3 (gauss 3D), 4 (gauss plane), 5 (linear falloff), 6 (quadratic falloff), 7 (stronger falloff)!");
2601         return '0 0 0';
2602         /*
2603          * how to derive falloff functions:
2604          * rho(r) := (2-r) * (1-r);
2605          * a : 0;
2606          * b : 1;
2607          * rhor(r) := r * rho(r);
2608          * cr(t) := integrate(rhor(r), r, a, t);
2609          * scr(t) := integrate(rhor(r) * r^2, r, a, t);
2610          * variance : scr(b) / cr(b);
2611          * solve(cr(r) = rand * cr(b), r), programmmode:false;
2612          * sqrt(0.4 / variance), numer;
2613          */
2614 }
2615 #endif