]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/util.qc
Merge branch 'master' into terencehill/spectatee_status_update
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / util.qc
1 #include "util.qh"
2
3 #if defined(CSQC)
4     #include "../client/defs.qh"
5     #include "constants.qh"
6         #include "../client/mutators/events.qh"
7     #include "mapinfo.qh"
8     #include "notifications/all.qh"
9     #include <common/deathtypes/all.qh>
10 #elif defined(MENUQC)
11 #elif defined(SVQC)
12     #include "constants.qh"
13     #include "../server/autocvars.qh"
14     #include "../server/defs.qh"
15         #include "../server/mutators/events.qh"
16     #include "notifications/all.qh"
17     #include <common/deathtypes/all.qh>
18     #include "mapinfo.qh"
19 #endif
20
21 #ifdef GAMEQC
22 /*
23 * Get "real" origin, in worldspace, even if ent is attached to something else.
24 */
25 vector real_origin(entity ent)
26 {
27         entity e;
28         vector v = ((ent.absmin + ent.absmax) * 0.5);
29
30         e = ent.tag_entity;
31         while(e)
32         {
33                 v = v + ((e.absmin + e.absmax) * 0.5);
34                 e = e.tag_entity;
35         }
36
37         return v;
38 }
39 #endif
40
41 string wordwrap_buffer;
42
43 void wordwrap_buffer_put(string s)
44 {
45         wordwrap_buffer = strcat(wordwrap_buffer, s);
46 }
47
48 string wordwrap(string s, float l)
49 {
50         string r;
51         wordwrap_buffer = "";
52         wordwrap_cb(s, l, wordwrap_buffer_put);
53         r = wordwrap_buffer;
54         wordwrap_buffer = "";
55         return r;
56 }
57
58 #ifdef SVQC
59 entity _wordwrap_buffer_sprint_ent;
60 void wordwrap_buffer_sprint(string s)
61 {
62         wordwrap_buffer = strcat(wordwrap_buffer, s);
63         if(s == "\n")
64         {
65                 sprint(_wordwrap_buffer_sprint_ent, wordwrap_buffer);
66                 wordwrap_buffer = "";
67         }
68 }
69
70 void wordwrap_sprint(entity to, string s, float l)
71 {
72         wordwrap_buffer = "";
73         _wordwrap_buffer_sprint_ent = to;
74         wordwrap_cb(s, l, wordwrap_buffer_sprint);
75         _wordwrap_buffer_sprint_ent = NULL;
76         if(wordwrap_buffer != "")
77                 sprint(to, strcat(wordwrap_buffer, "\n"));
78         wordwrap_buffer = "";
79         return;
80 }
81 #endif
82
83 #ifndef SVQC
84 string draw_UseSkinFor(string pic)
85 {
86         if(substring(pic, 0, 1) == "/")
87                 return substring(pic, 1, strlen(pic)-1);
88         else
89                 return strcat(draw_currentSkin, "/", pic);
90 }
91 #endif
92
93 void wordwrap_cb(string s, float l, void(string) callback)
94 {
95         string c;
96         float lleft, i, j, wlen;
97
98         s = strzone(s);
99         lleft = l;
100         for (i = 0;i < strlen(s);++i)
101         {
102                 if (substring(s, i, 2) == "\\n")
103                 {
104                         callback("\n");
105                         lleft = l;
106                         ++i;
107                 }
108                 else if (substring(s, i, 1) == "\n")
109                 {
110                         callback("\n");
111                         lleft = l;
112                 }
113                 else if (substring(s, i, 1) == " ")
114                 {
115                         if (lleft > 0)
116                         {
117                                 callback(" ");
118                                 lleft = lleft - 1;
119                         }
120                 }
121                 else
122                 {
123                         for (j = i+1;j < strlen(s);++j)
124                                 //    ^^ this skips over the first character of a word, which
125                                 //       is ALWAYS part of the word
126                                 //       this is safe since if i+1 == strlen(s), i will become
127                                 //       strlen(s)-1 at the end of this block and the function
128                                 //       will terminate. A space can't be the first character we
129                                 //       read here, and neither can a \n be the start, since these
130                                 //       two cases have been handled above.
131                         {
132                                 c = substring(s, j, 1);
133                                 if (c == " ")
134                                         break;
135                                 if (c == "\\")
136                                         break;
137                                 if (c == "\n")
138                                         break;
139                                 // we need to keep this tempstring alive even if substring is
140                                 // called repeatedly, so call strcat even though we're not
141                                 // doing anything
142                                 callback("");
143                         }
144                         wlen = j - i;
145                         if (lleft < wlen)
146                         {
147                                 callback("\n");
148                                 lleft = l;
149                         }
150                         callback(substring(s, i, wlen));
151                         lleft = lleft - wlen;
152                         i = j - 1;
153                 }
154         }
155         strunzone(s);
156 }
157
158 void depthfirst(entity start, .entity up, .entity downleft, .entity right, void(entity, entity) funcPre, void(entity, entity) funcPost, entity pass)
159 {
160         entity e;
161         e = start;
162         funcPre(pass, e);
163         while (e.(downleft))
164         {
165                 e = e.(downleft);
166                 funcPre(pass, e);
167         }
168         funcPost(pass, e);
169         while(e != start)
170         {
171                 if (e.(right))
172                 {
173                         e = e.(right);
174                         funcPre(pass, e);
175                         while (e.(downleft))
176                         {
177                                 e = e.(downleft);
178                                 funcPre(pass, e);
179                         }
180                 }
181                 else
182                         e = e.(up);
183                 funcPost(pass, e);
184         }
185 }
186
187 string ScoreString(int pFlags, float pValue)
188 {
189         string valstr;
190         float l;
191
192         pValue = floor(pValue + 0.5); // round
193
194         if((pValue == 0) && (pFlags & (SFL_HIDE_ZERO | SFL_RANK | SFL_TIME)))
195                 valstr = "";
196         else if(pFlags & SFL_RANK)
197         {
198                 valstr = ftos(pValue);
199                 l = strlen(valstr);
200                 if((l >= 2) && (substring(valstr, l - 2, 1) == "1"))
201                         valstr = strcat(valstr, "th");
202                 else if(substring(valstr, l - 1, 1) == "1")
203                         valstr = strcat(valstr, "st");
204                 else if(substring(valstr, l - 1, 1) == "2")
205                         valstr = strcat(valstr, "nd");
206                 else if(substring(valstr, l - 1, 1) == "3")
207                         valstr = strcat(valstr, "rd");
208                 else
209                         valstr = strcat(valstr, "th");
210         }
211         else if(pFlags & SFL_TIME)
212                 valstr = TIME_ENCODED_TOSTRING(pValue);
213         else
214                 valstr = ftos(pValue);
215
216         return valstr;
217 }
218
219 // compressed vector format:
220 // like MD3, just even shorter
221 //   4 bit pitch (16 angles), 0 is -90, 8 is 0, 16 would be 90
222 //   5 bit yaw (32 angles), 0=0, 8=90, 16=180, 24=270
223 //   7 bit length (logarithmic encoding), 1/8 .. about 7844
224 //     length = 2^(length_encoded/8) / 8
225 // if pitch is 90, yaw does nothing and therefore indicates the sign (yaw is then either 11111 or 11110); 11111 is pointing DOWN
226 // thus, valid values are from 0000.11110.0000000 to 1111.11111.1111111
227 // the special value 0 indicates the zero vector
228
229 float lengthLogTable[128];
230
231 float invertLengthLog(float x)
232 {
233         int l, r, m;
234
235         if(x >= lengthLogTable[127])
236                 return 127;
237         if(x <= lengthLogTable[0])
238                 return 0;
239
240         l = 0;
241         r = 127;
242
243         while(r - l > 1)
244         {
245                 m = floor((l + r) / 2);
246                 if(lengthLogTable[m] < x)
247                         l = m;
248                 else
249                         r = m;
250         }
251
252         // now: r is >=, l is <
253         float lerr = (x - lengthLogTable[l]);
254         float rerr = (lengthLogTable[r] - x);
255         if(lerr < rerr)
256                 return l;
257         return r;
258 }
259
260 vector decompressShortVector(int data)
261 {
262         vector out;
263         if(data == 0)
264                 return '0 0 0';
265         float p = (data & 0xF000) / 0x1000;
266         float y = (data & 0x0F80) / 0x80;
267         int len = (data & 0x007F);
268
269         //print("\ndecompress: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
270
271         if(p == 0)
272         {
273                 out.x = 0;
274                 out.y = 0;
275                 if(y == 31)
276                         out.z = -1;
277                 else
278                         out.z = +1;
279         }
280         else
281         {
282                 y   = .19634954084936207740 * y;
283                 p = .19634954084936207740 * p - 1.57079632679489661922;
284                 out.x = cos(y) *  cos(p);
285                 out.y = sin(y) *  cos(p);
286                 out.z =          -sin(p);
287         }
288
289         //print("decompressed: ", vtos(out), "\n");
290
291         return out * lengthLogTable[len];
292 }
293
294 float compressShortVector(vector vec)
295 {
296         vector ang;
297         float p, y, len;
298         if(vec == '0 0 0')
299                 return 0;
300         //print("compress: ", vtos(vec), "\n");
301         ang = vectoangles(vec);
302         ang.x = -ang.x;
303         if(ang.x < -90)
304                 ang.x += 360;
305         if(ang.x < -90 && ang.x > +90)
306                 error("BOGUS vectoangles");
307         //print("angles: ", vtos(ang), "\n");
308
309         p = floor(0.5 + (ang.x + 90) * 16 / 180) & 15; // -90..90 to 0..14
310         if(p == 0)
311         {
312                 if(vec.z < 0)
313                         y = 31;
314                 else
315                         y = 30;
316         }
317         else
318                 y = floor(0.5 + ang.y * 32 / 360)          & 31; // 0..360 to 0..32
319         len = invertLengthLog(vlen(vec));
320
321         //print("compressed: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
322
323         return (p * 0x1000) + (y * 0x80) + len;
324 }
325
326 STATIC_INIT(compressShortVector)
327 {
328         float l = 1;
329         float f = pow(2, 1/8);
330         int i;
331         for(i = 0; i < 128; ++i)
332         {
333                 lengthLogTable[i] = l;
334                 l *= f;
335         }
336
337         if(cvar("developer"))
338         {
339                 LOG_INFO("Verifying vector compression table...\n");
340                 for(i = 0x0F00; i < 0xFFFF; ++i)
341                         if(i != compressShortVector(decompressShortVector(i)))
342                         {
343                                 LOG_INFO("BROKEN vector compression: ", ftos(i));
344                                 LOG_INFO(" -> ", vtos(decompressShortVector(i)));
345                                 LOG_INFO(" -> ", ftos(compressShortVector(decompressShortVector(i))));
346                                 LOG_INFO("\n");
347                                 error("b0rk");
348                         }
349                 LOG_INFO("Done.\n");
350         }
351 }
352
353 #ifdef GAMEQC
354 float CheckWireframeBox(entity forent, vector v0, vector dvx, vector dvy, vector dvz)
355 {
356         traceline(v0, v0 + dvx, true, forent); if(trace_fraction < 1) return 0;
357         traceline(v0, v0 + dvy, true, forent); if(trace_fraction < 1) return 0;
358         traceline(v0, v0 + dvz, true, forent); if(trace_fraction < 1) return 0;
359         traceline(v0 + dvx, v0 + dvx + dvy, true, forent); if(trace_fraction < 1) return 0;
360         traceline(v0 + dvx, v0 + dvx + dvz, true, forent); if(trace_fraction < 1) return 0;
361         traceline(v0 + dvy, v0 + dvy + dvx, true, forent); if(trace_fraction < 1) return 0;
362         traceline(v0 + dvy, v0 + dvy + dvz, true, forent); if(trace_fraction < 1) return 0;
363         traceline(v0 + dvz, v0 + dvz + dvx, true, forent); if(trace_fraction < 1) return 0;
364         traceline(v0 + dvz, v0 + dvz + dvy, true, forent); if(trace_fraction < 1) return 0;
365         traceline(v0 + dvx + dvy, v0 + dvx + dvy + dvz, true, forent); if(trace_fraction < 1) return 0;
366         traceline(v0 + dvx + dvz, v0 + dvx + dvy + dvz, true, forent); if(trace_fraction < 1) return 0;
367         traceline(v0 + dvy + dvz, v0 + dvx + dvy + dvz, true, forent); if(trace_fraction < 1) return 0;
368         return 1;
369 }
370 #endif
371
372 string fixPriorityList(string order, float from, float to, float subtract, float complete)
373 {
374         string neworder;
375         float i, n, w;
376
377         n = tokenize_console(order);
378         neworder = "";
379         for(i = 0; i < n; ++i)
380         {
381                 w = stof(argv(i));
382                 if(w == floor(w))
383                 {
384                         if(w >= from && w <= to)
385                                 neworder = strcat(neworder, ftos(w), " ");
386                         else
387                         {
388                                 w -= subtract;
389                                 if(w >= from && w <= to)
390                                         neworder = strcat(neworder, ftos(w), " ");
391                         }
392                 }
393         }
394
395         if(complete)
396         {
397                 n = tokenize_console(neworder);
398                 for(w = to; w >= from; --w)
399                 {
400                         for(i = 0; i < n; ++i)
401                                 if(stof(argv(i)) == w)
402                                         break;
403                         if(i == n) // not found
404                                 neworder = strcat(neworder, ftos(w), " ");
405                 }
406         }
407
408         return substring(neworder, 0, strlen(neworder) - 1);
409 }
410
411 string mapPriorityList(string order, string(string) mapfunc)
412 {
413         string neworder;
414         float i, n;
415
416         n = tokenize_console(order);
417         neworder = "";
418         for(i = 0; i < n; ++i)
419                 neworder = strcat(neworder, mapfunc(argv(i)), " ");
420
421         return substring(neworder, 0, strlen(neworder) - 1);
422 }
423
424 string swapInPriorityList(string order, float i, float j)
425 {
426         string s;
427         float w, n;
428
429         n = tokenize_console(order);
430
431         if(i >= 0 && i < n && j >= 0 && j < n && i != j)
432         {
433                 s = "";
434                 for(w = 0; w < n; ++w)
435                 {
436                         if(w == i)
437                                 s = strcat(s, argv(j), " ");
438                         else if(w == j)
439                                 s = strcat(s, argv(i), " ");
440                         else
441                                 s = strcat(s, argv(w), " ");
442                 }
443                 return substring(s, 0, strlen(s) - 1);
444         }
445
446         return order;
447 }
448
449 #ifdef GAMEQC
450 void get_mi_min_max(float mode)
451 {
452         vector mi, ma;
453
454         if(mi_shortname)
455                 strunzone(mi_shortname);
456         mi_shortname = mapname;
457         if(!strcasecmp(substring(mi_shortname, 0, 5), "maps/"))
458                 mi_shortname = substring(mi_shortname, 5, strlen(mi_shortname) - 5);
459         if(!strcasecmp(substring(mi_shortname, strlen(mi_shortname) - 4, 4), ".bsp"))
460                 mi_shortname = substring(mi_shortname, 0, strlen(mi_shortname) - 4);
461         mi_shortname = strzone(mi_shortname);
462
463 #ifdef CSQC
464         mi = world.mins;
465         ma = world.maxs;
466 #else
467         mi = world.absmin;
468         ma = world.absmax;
469 #endif
470
471         mi_min = mi;
472         mi_max = ma;
473         MapInfo_Get_ByName(mi_shortname, 0, NULL);
474         if(MapInfo_Map_mins.x < MapInfo_Map_maxs.x)
475         {
476                 mi_min = MapInfo_Map_mins;
477                 mi_max = MapInfo_Map_maxs;
478         }
479         else
480         {
481                 // not specified
482                 if(mode)
483                 {
484                         // be clever
485                         tracebox('1 0 0' * mi.x,
486                                          '0 1 0' * mi.y + '0 0 1' * mi.z,
487                                          '0 1 0' * ma.y + '0 0 1' * ma.z,
488                                          '1 0 0' * ma.x,
489                                          MOVE_WORLDONLY,
490                                          NULL);
491                         if(!trace_startsolid)
492                                 mi_min.x = trace_endpos.x;
493
494                         tracebox('0 1 0' * mi.y,
495                                          '1 0 0' * mi.x + '0 0 1' * mi.z,
496                                          '1 0 0' * ma.x + '0 0 1' * ma.z,
497                                          '0 1 0' * ma.y,
498                                          MOVE_WORLDONLY,
499                                          NULL);
500                         if(!trace_startsolid)
501                                 mi_min.y = trace_endpos.y;
502
503                         tracebox('0 0 1' * mi.z,
504                                          '1 0 0' * mi.x + '0 1 0' * mi.y,
505                                          '1 0 0' * ma.x + '0 1 0' * ma.y,
506                                          '0 0 1' * ma.z,
507                                          MOVE_WORLDONLY,
508                                          NULL);
509                         if(!trace_startsolid)
510                                 mi_min.z = trace_endpos.z;
511
512                         tracebox('1 0 0' * ma.x,
513                                          '0 1 0' * mi.y + '0 0 1' * mi.z,
514                                          '0 1 0' * ma.y + '0 0 1' * ma.z,
515                                          '1 0 0' * mi.x,
516                                          MOVE_WORLDONLY,
517                                          NULL);
518                         if(!trace_startsolid)
519                                 mi_max.x = trace_endpos.x;
520
521                         tracebox('0 1 0' * ma.y,
522                                          '1 0 0' * mi.x + '0 0 1' * mi.z,
523                                          '1 0 0' * ma.x + '0 0 1' * ma.z,
524                                          '0 1 0' * mi.y,
525                                          MOVE_WORLDONLY,
526                                          NULL);
527                         if(!trace_startsolid)
528                                 mi_max.y = trace_endpos.y;
529
530                         tracebox('0 0 1' * ma.z,
531                                          '1 0 0' * mi.x + '0 1 0' * mi.y,
532                                          '1 0 0' * ma.x + '0 1 0' * ma.y,
533                                          '0 0 1' * mi.z,
534                                          MOVE_WORLDONLY,
535                                          NULL);
536                         if(!trace_startsolid)
537                                 mi_max.z = trace_endpos.z;
538                 }
539         }
540 }
541
542 void get_mi_min_max_texcoords(float mode)
543 {
544         vector extend;
545
546         get_mi_min_max(mode);
547
548         mi_picmin = mi_min;
549         mi_picmax = mi_max;
550
551         // extend mi_picmax to get a square aspect ratio
552         // center the map in that area
553         extend = mi_picmax - mi_picmin;
554         if(extend.y > extend.x)
555         {
556                 mi_picmin.x -= (extend.y - extend.x) * 0.5;
557                 mi_picmax.x += (extend.y - extend.x) * 0.5;
558         }
559         else
560         {
561                 mi_picmin.y -= (extend.x - extend.y) * 0.5;
562                 mi_picmax.y += (extend.x - extend.y) * 0.5;
563         }
564
565         // add another some percent
566         extend = (mi_picmax - mi_picmin) * (1 / 64.0);
567         mi_picmin -= extend;
568         mi_picmax += extend;
569
570         // calculate the texcoords
571         mi_pictexcoord0 = mi_pictexcoord1 = mi_pictexcoord2 = mi_pictexcoord3 = '0 0 0';
572         // first the two corners of the origin
573         mi_pictexcoord0_x = (mi_min.x - mi_picmin.x) / (mi_picmax.x - mi_picmin.x);
574         mi_pictexcoord0_y = (mi_min.y - mi_picmin.y) / (mi_picmax.y - mi_picmin.y);
575         mi_pictexcoord2_x = (mi_max.x - mi_picmin.x) / (mi_picmax.x - mi_picmin.x);
576         mi_pictexcoord2_y = (mi_max.y - mi_picmin.y) / (mi_picmax.y - mi_picmin.y);
577         // then the other corners
578         mi_pictexcoord1_x = mi_pictexcoord0_x;
579         mi_pictexcoord1_y = mi_pictexcoord2_y;
580         mi_pictexcoord3_x = mi_pictexcoord2_x;
581         mi_pictexcoord3_y = mi_pictexcoord0_y;
582 }
583 #endif
584
585 float cvar_settemp(string tmp_cvar, string tmp_value)
586 {
587         float created_saved_value;
588
589         created_saved_value = 0;
590
591         if (!(tmp_cvar || tmp_value))
592         {
593                 LOG_TRACE("Error: Invalid usage of cvar_settemp(string, string); !");
594                 return 0;
595         }
596
597         if(!cvar_type(tmp_cvar))
598         {
599                 LOG_INFOF("Error: cvar %s doesn't exist!\n", tmp_cvar);
600                 return 0;
601         }
602
603         FOREACH_ENTITY_CLASS("saved_cvar_value", it.netname == tmp_cvar,
604         {
605                 created_saved_value = -1; // skip creation
606                 break; // no need to continue
607         });
608
609         if(created_saved_value != -1)
610         {
611                 // creating a new entity to keep track of this cvar
612                 entity e = new_pure(saved_cvar_value);
613                 e.netname = strzone(tmp_cvar);
614                 e.message = strzone(cvar_string(tmp_cvar));
615                 created_saved_value = 1;
616         }
617
618         // update the cvar to the value given
619         cvar_set(tmp_cvar, tmp_value);
620
621         return created_saved_value;
622 }
623
624 int cvar_settemp_restore()
625 {
626         int j = 0;
627         // FIXME this new-style loop fails!
628 #if 0
629         FOREACH_ENTITY_CLASS("saved_cvar_value", true,
630         {
631                 if(cvar_type(it.netname))
632                 {
633                         cvar_set(it.netname, it.message);
634                         strunzone(it.netname);
635                         strunzone(it.message);
636                         delete(it);
637                         ++j;
638                 }
639                 else
640                         LOG_INFOF("Error: cvar %s doesn't exist anymore! It can still be restored once it's manually recreated.\n", it.netname);
641         });
642
643 #else
644         entity e = NULL;
645         while((e = find(e, classname, "saved_cvar_value")))
646         {
647                 if(cvar_type(e.netname))
648                 {
649                         cvar_set(e.netname, e.message);
650                         delete(e);
651                         ++j;
652                 }
653                 else
654                         print(sprintf("Error: cvar %s doesn't exist anymore! It can still be restored once it's manually recreated.\n", e.netname));
655         }
656 #endif
657
658         return j;
659 }
660
661 float textLengthUpToWidth(string theText, float maxWidth, vector theSize, textLengthUpToWidth_widthFunction_t w)
662 {
663         // STOP.
664         // The following function is SLOW.
665         // For your safety and for the protection of those around you...
666         // DO NOT CALL THIS AT HOME.
667         // No really, don't.
668         if(w(theText, theSize) <= maxWidth)
669                 return strlen(theText); // yeah!
670
671         // binary search for right place to cut string
672         float ch;
673         float left, right, middle; // this always works
674         left = 0;
675         right = strlen(theText); // this always fails
676         do
677         {
678                 middle = floor((left + right) / 2);
679                 if(w(substring(theText, 0, middle), theSize) <= maxWidth)
680                         left = middle;
681                 else
682                         right = middle;
683         }
684         while(left < right - 1);
685
686         if(w("^7", theSize) == 0) // detect color codes support in the width function
687         {
688                 // NOTE: when color codes are involved, this binary search is,
689                 // mathematically, BROKEN. However, it is obviously guaranteed to
690                 // terminate, as the range still halves each time - but nevertheless, it is
691                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
692                 // range, and "right" is outside).
693
694                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
695                 // and decrease left on the basis of the chars detected of the truncated tag
696                 // Even if the ^xrgb tag is not complete/correct, left is decreased
697                 // (sometimes too much but with a correct result)
698                 // it fixes also ^[0-9]
699                 while(left >= 1 && substring(theText, left-1, 1) == "^")
700                         left-=1;
701
702                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
703                         left-=2;
704                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
705                         {
706                                 ch = str2chr(theText, left-1);
707                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
708                                         left-=3;
709                         }
710                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
711                         {
712                                 ch = str2chr(theText, left-2);
713                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
714                                 {
715                                         ch = str2chr(theText, left-1);
716                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
717                                                 left-=4;
718                                 }
719                         }
720         }
721
722         return left;
723 }
724
725 float textLengthUpToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t w)
726 {
727         // STOP.
728         // The following function is SLOW.
729         // For your safety and for the protection of those around you...
730         // DO NOT CALL THIS AT HOME.
731         // No really, don't.
732         if(w(theText) <= maxWidth)
733                 return strlen(theText); // yeah!
734
735         // binary search for right place to cut string
736         float ch;
737         float left, right, middle; // this always works
738         left = 0;
739         right = strlen(theText); // this always fails
740         do
741         {
742                 middle = floor((left + right) / 2);
743                 if(w(substring(theText, 0, middle)) <= maxWidth)
744                         left = middle;
745                 else
746                         right = middle;
747         }
748         while(left < right - 1);
749
750         if(w("^7") == 0) // detect color codes support in the width function
751         {
752                 // NOTE: when color codes are involved, this binary search is,
753                 // mathematically, BROKEN. However, it is obviously guaranteed to
754                 // terminate, as the range still halves each time - but nevertheless, it is
755                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
756                 // range, and "right" is outside).
757
758                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
759                 // and decrease left on the basis of the chars detected of the truncated tag
760                 // Even if the ^xrgb tag is not complete/correct, left is decreased
761                 // (sometimes too much but with a correct result)
762                 // it fixes also ^[0-9]
763                 while(left >= 1 && substring(theText, left-1, 1) == "^")
764                         left-=1;
765
766                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
767                         left-=2;
768                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
769                         {
770                                 ch = str2chr(theText, left-1);
771                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
772                                         left-=3;
773                         }
774                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
775                         {
776                                 ch = str2chr(theText, left-2);
777                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
778                                 {
779                                         ch = str2chr(theText, left-1);
780                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
781                                                 left-=4;
782                                 }
783                         }
784         }
785
786         return left;
787 }
788
789 string find_last_color_code(string s)
790 {
791         int start = strstrofs(s, "^", 0);
792         if (start == -1) // no caret found
793                 return "";
794         int len = strlen(s)-1;
795         int i;
796         for(i = len; i >= start; --i)
797         {
798                 if(substring(s, i, 1) != "^")
799                         continue;
800
801                 int carets = 1;
802                 while (i-carets >= start && substring(s, i-carets, 1) == "^")
803                         ++carets;
804
805                 // check if carets aren't all escaped
806                 if (carets & 1)
807                 {
808                         if(i+1 <= len)
809                         if(strstrofs("0123456789", substring(s, i+1, 1), 0) >= 0)
810                                 return substring(s, i, 2);
811
812                         if(i+4 <= len)
813                         if(substring(s, i+1, 1) == "x")
814                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+2, 1), 0) >= 0)
815                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+3, 1), 0) >= 0)
816                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+4, 1), 0) >= 0)
817                                 return substring(s, i, 5);
818                 }
819                 i -= carets; // this also skips one char before the carets
820         }
821
822         return "";
823 }
824
825 string getWrappedLine(float w, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
826 {
827         float cantake;
828         float take;
829         string s;
830
831         s = getWrappedLine_remaining;
832
833         if(w <= 0)
834         {
835                 getWrappedLine_remaining = string_null;
836                 return s; // the line has no size ANYWAY, nothing would be displayed.
837         }
838
839         cantake = textLengthUpToWidth(s, w, theFontSize, tw);
840         if(cantake > 0 && cantake < strlen(s))
841         {
842                 take = cantake - 1;
843                 while(take > 0 && substring(s, take, 1) != " ")
844                         --take;
845                 if(take == 0)
846                 {
847                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
848                         if(getWrappedLine_remaining == "")
849                                 getWrappedLine_remaining = string_null;
850                         else if (tw("^7", theFontSize) == 0)
851                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
852                         return substring(s, 0, cantake);
853                 }
854                 else
855                 {
856                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
857                         if(getWrappedLine_remaining == "")
858                                 getWrappedLine_remaining = string_null;
859                         else if (tw("^7", theFontSize) == 0)
860                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
861                         return substring(s, 0, take);
862                 }
863         }
864         else
865         {
866                 getWrappedLine_remaining = string_null;
867                 return s;
868         }
869 }
870
871 string getWrappedLineLen(float w, textLengthUpToLength_lenFunction_t tw)
872 {
873         float cantake;
874         float take;
875         string s;
876
877         s = getWrappedLine_remaining;
878
879         if(w <= 0)
880         {
881                 getWrappedLine_remaining = string_null;
882                 return s; // the line has no size ANYWAY, nothing would be displayed.
883         }
884
885         cantake = textLengthUpToLength(s, w, tw);
886         if(cantake > 0 && cantake < strlen(s))
887         {
888                 take = cantake - 1;
889                 while(take > 0 && substring(s, take, 1) != " ")
890                         --take;
891                 if(take == 0)
892                 {
893                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
894                         if(getWrappedLine_remaining == "")
895                                 getWrappedLine_remaining = string_null;
896                         else if (tw("^7") == 0)
897                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
898                         return substring(s, 0, cantake);
899                 }
900                 else
901                 {
902                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
903                         if(getWrappedLine_remaining == "")
904                                 getWrappedLine_remaining = string_null;
905                         else if (tw("^7") == 0)
906                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
907                         return substring(s, 0, take);
908                 }
909         }
910         else
911         {
912                 getWrappedLine_remaining = string_null;
913                 return s;
914         }
915 }
916
917 string textShortenToWidth(string theText, float maxWidth, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
918 {
919         if(tw(theText, theFontSize) <= maxWidth)
920                 return theText;
921         else
922                 return strcat(substring(theText, 0, textLengthUpToWidth(theText, maxWidth - tw("...", theFontSize), theFontSize, tw)), "...");
923 }
924
925 string textShortenToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t tw)
926 {
927         if(tw(theText) <= maxWidth)
928                 return theText;
929         else
930                 return strcat(substring(theText, 0, textLengthUpToLength(theText, maxWidth - tw("..."), tw)), "...");
931 }
932
933 float isGametypeInFilter(Gametype gt, float tp, float ts, string pattern)
934 {
935         string subpattern, subpattern2, subpattern3, subpattern4;
936         subpattern = strcat(",", MapInfo_Type_ToString(gt), ",");
937         if(tp)
938                 subpattern2 = ",teams,";
939         else
940                 subpattern2 = ",noteams,";
941         if(ts)
942                 subpattern3 = ",teamspawns,";
943         else
944                 subpattern3 = ",noteamspawns,";
945         if(gt == MAPINFO_TYPE_RACE || gt == MAPINFO_TYPE_CTS)
946                 subpattern4 = ",race,";
947         else
948                 subpattern4 = string_null;
949
950         if(substring(pattern, 0, 1) == "-")
951         {
952                 pattern = substring(pattern, 1, strlen(pattern) - 1);
953                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) >= 0)
954                         return 0;
955                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) >= 0)
956                         return 0;
957                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) >= 0)
958                         return 0;
959                 if(subpattern4 && strstrofs(strcat(",", pattern, ","), subpattern4, 0) >= 0)
960                         return 0;
961         }
962         else
963         {
964                 if(substring(pattern, 0, 1) == "+")
965                         pattern = substring(pattern, 1, strlen(pattern) - 1);
966                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) < 0)
967                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) < 0)
968                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) < 0)
969                 {
970                         if (!subpattern4)
971                                 return 0;
972                         if(strstrofs(strcat(",", pattern, ","), subpattern4, 0) < 0)
973                                 return 0;
974                 }
975         }
976         return 1;
977 }
978
979 vector solve_shotdirection(vector myorg, vector myvel, vector eorg, vector evel, float spd, float newton_style)
980 {
981         vector ret;
982
983         // make origin and speed relative
984         eorg -= myorg;
985         if(newton_style)
986                 evel -= myvel;
987
988         // now solve for ret, ret normalized:
989         //   eorg + t * evel == t * ret * spd
990         // or, rather, solve for t:
991         //   |eorg + t * evel| == t * spd
992         //   eorg^2 + t^2 * evel^2 + 2 * t * (eorg * evel) == t^2 * spd^2
993         //   t^2 * (evel^2 - spd^2) + t * (2 * (eorg * evel)) + eorg^2 == 0
994         vector solution = solve_quadratic(evel * evel - spd * spd, 2 * (eorg * evel), eorg * eorg);
995         // p = 2 * (eorg * evel) / (evel * evel - spd * spd)
996         // q = (eorg * eorg) / (evel * evel - spd * spd)
997         if(!solution.z) // no real solution
998         {
999                 // happens if D < 0
1000                 // (eorg * evel)^2 < (evel^2 - spd^2) * eorg^2
1001                 // (eorg * evel)^2 / eorg^2 < evel^2 - spd^2
1002                 // spd^2 < ((evel^2 * eorg^2) - (eorg * evel)^2) / eorg^2
1003                 // spd^2 < evel^2 * (1 - cos^2 angle(evel, eorg))
1004                 // spd^2 < evel^2 * sin^2 angle(evel, eorg)
1005                 // spd < |evel| * sin angle(evel, eorg)
1006                 return '0 0 0';
1007         }
1008         else if(solution.x > 0)
1009         {
1010                 // both solutions > 0: take the smaller one
1011                 // happens if p < 0 and q > 0
1012                 ret = normalize(eorg + solution.x * evel);
1013         }
1014         else if(solution.y > 0)
1015         {
1016                 // one solution > 0: take the larger one
1017                 // happens if q < 0 or q == 0 and p < 0
1018                 ret = normalize(eorg + solution.y * evel);
1019         }
1020         else
1021         {
1022                 // no solution > 0: reject
1023                 // happens if p > 0 and q >= 0
1024                 // 2 * (eorg * evel) / (evel * evel - spd * spd) > 0
1025                 // (eorg * eorg) / (evel * evel - spd * spd) >= 0
1026                 //
1027                 // |evel| >= spd
1028                 // eorg * evel > 0
1029                 //
1030                 // "Enemy is moving away from me at more than spd"
1031                 return '0 0 0';
1032         }
1033
1034         // NOTE: we always got a solution if spd > |evel|
1035
1036         if(newton_style == 2)
1037                 ret = normalize(ret * spd + myvel);
1038
1039         return ret;
1040 }
1041
1042 vector get_shotvelocity(vector myvel, vector mydir, float spd, float newton_style, float mi, float ma)
1043 {
1044         if(!newton_style)
1045                 return spd * mydir;
1046
1047         if(newton_style == 2)
1048         {
1049                 // true Newtonian projectiles with automatic aim adjustment
1050                 //
1051                 // solve: |outspeed * mydir - myvel| = spd
1052                 // outspeed^2 - 2 * outspeed * (mydir * myvel) + myvel^2 - spd^2 = 0
1053                 // outspeed = (mydir * myvel) +- sqrt((mydir * myvel)^2 - myvel^2 + spd^2)
1054                 // PLUS SIGN!
1055                 // not defined?
1056                 // then...
1057                 // myvel^2 - (mydir * myvel)^2 > spd^2
1058                 // velocity without mydir component > spd
1059                 // fire at smallest possible spd that works?
1060                 // |(mydir * myvel) * myvel - myvel| = spd
1061
1062                 vector solution = solve_quadratic(1, -2 * (mydir * myvel), myvel * myvel - spd * spd);
1063
1064                 float outspeed;
1065                 if(solution.z)
1066                         outspeed = solution.y; // the larger one
1067                 else
1068                 {
1069                         //outspeed = 0; // slowest possible shot
1070                         outspeed = solution.x; // the real part (that is, the average!)
1071                         //dprint("impossible shot, adjusting\n");
1072                 }
1073
1074                 outspeed = bound(spd * mi, outspeed, spd * ma);
1075                 return mydir * outspeed;
1076         }
1077
1078         // real Newtonian
1079         return myvel + spd * mydir;
1080 }
1081
1082 float compressShotOrigin(vector v)
1083 {
1084         float x, y, z;
1085         x = rint(v.x * 2);
1086         y = rint(v.y * 4) + 128;
1087         z = rint(v.z * 4) + 128;
1088         if(x > 255 || x < 0)
1089         {
1090                 LOG_INFO("shot origin ", vtos(v), " x out of bounds\n");
1091                 x = bound(0, x, 255);
1092         }
1093         if(y > 255 || y < 0)
1094         {
1095                 LOG_INFO("shot origin ", vtos(v), " y out of bounds\n");
1096                 y = bound(0, y, 255);
1097         }
1098         if(z > 255 || z < 0)
1099         {
1100                 LOG_INFO("shot origin ", vtos(v), " z out of bounds\n");
1101                 z = bound(0, z, 255);
1102         }
1103         return x * 0x10000 + y * 0x100 + z;
1104 }
1105 vector decompressShotOrigin(int f)
1106 {
1107         vector v;
1108         v.x = ((f & 0xFF0000) / 0x10000) / 2;
1109         v.y = ((f & 0xFF00) / 0x100 - 128) / 4;
1110         v.z = ((f & 0xFF) - 128) / 4;
1111         return v;
1112 }
1113
1114 #ifdef GAMEQC
1115 vector healtharmor_maxdamage(float h, float a, float armorblock, int deathtype)
1116 {
1117         // NOTE: we'll always choose the SMALLER value...
1118         float healthdamage, armordamage, armorideal;
1119         if (DEATH_IS(deathtype, DEATH_DROWN))  // Why should armor help here...
1120                 armorblock = 0;
1121         vector v;
1122         healthdamage = (h - 1) / (1 - armorblock); // damage we can take if we could use more health
1123         armordamage = a + (h - 1); // damage we can take if we could use more armor
1124         armorideal = healthdamage * armorblock;
1125         v.y = armorideal;
1126         if(armordamage < healthdamage)
1127         {
1128                 v.x = armordamage;
1129                 v.z = 1;
1130         }
1131         else
1132         {
1133                 v.x = healthdamage;
1134                 v.z = 0;
1135         }
1136         return v;
1137 }
1138
1139 vector healtharmor_applydamage(float a, float armorblock, int deathtype, float damage)
1140 {
1141         vector v;
1142         if (DEATH_IS(deathtype, DEATH_DROWN))  // Why should armor help here...
1143                 armorblock = 0;
1144         v.y = bound(0, damage * armorblock, a); // save
1145         v.x = bound(0, damage - v.y, damage); // take
1146         v.z = 0;
1147         return v;
1148 }
1149 #endif
1150
1151 string getcurrentmod()
1152 {
1153         float n;
1154         string m;
1155         m = cvar_string("fs_gamedir");
1156         n = tokenize_console(m);
1157         if(n == 0)
1158                 return "data";
1159         else
1160                 return argv(n - 1);
1161 }
1162
1163 float matchacl(string acl, string str)
1164 {
1165         string t, s;
1166         float r, d;
1167         r = 0;
1168         while(acl)
1169         {
1170                 t = car(acl); acl = cdr(acl);
1171
1172                 d = 1;
1173                 if(substring(t, 0, 1) == "-")
1174                 {
1175                         d = -1;
1176                         t = substring(t, 1, strlen(t) - 1);
1177                 }
1178                 else if(substring(t, 0, 1) == "+")
1179                         t = substring(t, 1, strlen(t) - 1);
1180
1181                 if(substring(t, -1, 1) == "*")
1182                 {
1183                         t = substring(t, 0, strlen(t) - 1);
1184                         s = substring(str, 0, strlen(t));
1185                 }
1186                 else
1187                         s = str;
1188
1189                 if(s == t)
1190                 {
1191                         r = d;
1192                 }
1193         }
1194         return r;
1195 }
1196
1197 string get_model_datafilename(string m, float sk, string fil)
1198 {
1199         if(m)
1200                 m = strcat(m, "_");
1201         else
1202                 m = "models/player/*_";
1203         if(sk >= 0)
1204                 m = strcat(m, ftos(sk));
1205         else
1206                 m = strcat(m, "*");
1207         return strcat(m, ".", fil);
1208 }
1209
1210 float get_model_parameters(string m, float sk)
1211 {
1212         get_model_parameters_modelname = string_null;
1213         get_model_parameters_modelskin = -1;
1214         get_model_parameters_name = string_null;
1215         get_model_parameters_species = -1;
1216         get_model_parameters_sex = string_null;
1217         get_model_parameters_weight = -1;
1218         get_model_parameters_age = -1;
1219         get_model_parameters_desc = string_null;
1220         get_model_parameters_bone_upperbody = string_null;
1221         get_model_parameters_bone_weapon = string_null;
1222         for(int i = 0; i < MAX_AIM_BONES; ++i)
1223         {
1224                 get_model_parameters_bone_aim[i] = string_null;
1225                 get_model_parameters_bone_aimweight[i] = 0;
1226         }
1227         get_model_parameters_fixbone = 0;
1228
1229 #ifdef GAMEQC
1230         MUTATOR_CALLHOOK(ClearModelParams);
1231 #endif
1232
1233         if (!m)
1234                 return 1;
1235
1236         if(substring(m, -9, 5) == "_lod1" || substring(m, -9, 5) == "_lod2")
1237                 m = strcat(substring(m, 0, -10), substring(m, -4, -1));
1238
1239         if(sk < 0)
1240         {
1241                 if(substring(m, -4, -1) != ".txt")
1242                         return 0;
1243                 if(substring(m, -6, 1) != "_")
1244                         return 0;
1245                 sk = stof(substring(m, -5, 1));
1246                 m = substring(m, 0, -7);
1247         }
1248
1249         string fn = get_model_datafilename(m, sk, "txt");
1250         int fh = fopen(fn, FILE_READ);
1251         if(fh < 0)
1252         {
1253                 sk = 0;
1254                 fn = get_model_datafilename(m, sk, "txt");
1255                 fh = fopen(fn, FILE_READ);
1256                 if(fh < 0)
1257                         return 0;
1258         }
1259
1260         get_model_parameters_modelname = m;
1261         get_model_parameters_modelskin = sk;
1262         string s, c;
1263         while((s = fgets(fh)))
1264         {
1265                 if(s == "")
1266                         break; // next lines will be description
1267                 c = car(s);
1268                 s = cdr(s);
1269                 if(c == "name")
1270                         get_model_parameters_name = s;
1271                 if(c == "species")
1272                         switch(s)
1273                         {
1274                                 case "human":       get_model_parameters_species = SPECIES_HUMAN;       break;
1275                                 case "alien":       get_model_parameters_species = SPECIES_ALIEN;       break;
1276                                 case "robot_shiny": get_model_parameters_species = SPECIES_ROBOT_SHINY; break;
1277                                 case "robot_rusty": get_model_parameters_species = SPECIES_ROBOT_RUSTY; break;
1278                                 case "robot_solid": get_model_parameters_species = SPECIES_ROBOT_SOLID; break;
1279                                 case "animal":      get_model_parameters_species = SPECIES_ANIMAL;      break;
1280                                 case "reserved":    get_model_parameters_species = SPECIES_RESERVED;    break;
1281                         }
1282                 if(c == "sex")
1283                         get_model_parameters_sex = s;
1284                 if(c == "weight")
1285                         get_model_parameters_weight = stof(s);
1286                 if(c == "age")
1287                         get_model_parameters_age = stof(s);
1288                 if(c == "description")
1289                         get_model_parameters_description = s;
1290                 if(c == "bone_upperbody")
1291                         get_model_parameters_bone_upperbody = s;
1292                 if(c == "bone_weapon")
1293                         get_model_parameters_bone_weapon = s;
1294         #ifdef GAMEQC
1295                 MUTATOR_CALLHOOK(GetModelParams, c, s);
1296         #endif
1297                 for(int i = 0; i < MAX_AIM_BONES; ++i)
1298                         if(c == strcat("bone_aim", ftos(i)))
1299                         {
1300                                 get_model_parameters_bone_aimweight[i] = stof(car(s));
1301                                 get_model_parameters_bone_aim[i] = cdr(s);
1302                         }
1303                 if(c == "fixbone")
1304                         get_model_parameters_fixbone = stof(s);
1305         }
1306
1307         while((s = fgets(fh)))
1308         {
1309                 if(get_model_parameters_desc)
1310                         get_model_parameters_desc = strcat(get_model_parameters_desc, "\n");
1311                 if(s != "")
1312                         get_model_parameters_desc = strcat(get_model_parameters_desc, s);
1313         }
1314
1315         fclose(fh);
1316
1317         return 1;
1318 }
1319
1320 // x-encoding (encoding as zero length invisible string)
1321 const string XENCODE_2  = "xX";
1322 const string XENCODE_22 = "0123456789abcdefABCDEF";
1323 string xencode(int f)
1324 {
1325         float a, b, c, d;
1326         d = f % 22; f = floor(f / 22);
1327         c = f % 22; f = floor(f / 22);
1328         b = f % 22; f = floor(f / 22);
1329         a = f %  2; // f = floor(f /  2);
1330         return strcat(
1331                 "^",
1332                 substring(XENCODE_2,  a, 1),
1333                 substring(XENCODE_22, b, 1),
1334                 substring(XENCODE_22, c, 1),
1335                 substring(XENCODE_22, d, 1)
1336         );
1337 }
1338 float xdecode(string s)
1339 {
1340         float a, b, c, d;
1341         if(substring(s, 0, 1) != "^")
1342                 return -1;
1343         if(strlen(s) < 5)
1344                 return -1;
1345         a = strstrofs(XENCODE_2,  substring(s, 1, 1), 0);
1346         b = strstrofs(XENCODE_22, substring(s, 2, 1), 0);
1347         c = strstrofs(XENCODE_22, substring(s, 3, 1), 0);
1348         d = strstrofs(XENCODE_22, substring(s, 4, 1), 0);
1349         if(a < 0 || b < 0 || c < 0 || d < 0)
1350                 return -1;
1351         return ((a * 22 + b) * 22 + c) * 22 + d;
1352 }
1353
1354 /*
1355 string strlimitedlen(string input, string truncation, float strip_colors, float limit)
1356 {
1357         if(strlen((strip_colors ? strdecolorize(input) : input)) <= limit)
1358                 return input;
1359         else
1360                 return strcat(substring(input, 0, (strlen(input) - strlen(truncation))), truncation);
1361 }*/
1362
1363 float shutdown_running;
1364 #ifdef SVQC
1365 void SV_Shutdown()
1366 #endif
1367 #ifdef CSQC
1368 void CSQC_Shutdown()
1369 #endif
1370 #ifdef MENUQC
1371 void m_shutdown()
1372 #endif
1373 {
1374         if(shutdown_running)
1375         {
1376                 LOG_INFO("Recursive shutdown detected! Only restoring cvars...\n");
1377         }
1378         else
1379         {
1380                 shutdown_running = 1;
1381                 Shutdown();
1382                 shutdownhooks();
1383         }
1384         cvar_settemp_restore(); // this must be done LAST, but in any case
1385 }
1386
1387 #ifdef GAMEQC
1388 .float skeleton_bones_index;
1389 void Skeleton_SetBones(entity e)
1390 {
1391         // set skeleton_bones to the total number of bones on the model
1392         if(e.skeleton_bones_index == e.modelindex)
1393                 return; // same model, nothing to update
1394
1395         float skelindex;
1396         skelindex = skel_create(e.modelindex);
1397         e.skeleton_bones = skel_get_numbones(skelindex);
1398         skel_delete(skelindex);
1399         e.skeleton_bones_index = e.modelindex;
1400 }
1401 #endif
1402
1403 string to_execute_next_frame;
1404 void execute_next_frame()
1405 {
1406         if(to_execute_next_frame)
1407         {
1408                 localcmd("\n", to_execute_next_frame, "\n");
1409                 strunzone(to_execute_next_frame);
1410                 to_execute_next_frame = string_null;
1411         }
1412 }
1413 void queue_to_execute_next_frame(string s)
1414 {
1415         if(to_execute_next_frame)
1416         {
1417                 s = strcat(s, "\n", to_execute_next_frame);
1418                 strunzone(to_execute_next_frame);
1419         }
1420         to_execute_next_frame = strzone(s);
1421 }
1422
1423 .float FindConnectedComponent_processing;
1424 void FindConnectedComponent(entity e, .entity fld, findNextEntityNearFunction_t nxt, isConnectedFunction_t iscon, entity pass)
1425 {
1426         entity queue_start, queue_end;
1427
1428         // we build a queue of to-be-processed entities.
1429         // queue_start is the next entity to be checked for neighbors
1430         // queue_end is the last entity added
1431
1432         if(e.FindConnectedComponent_processing)
1433                 error("recursion or broken cleanup");
1434
1435         // start with a 1-element queue
1436         queue_start = queue_end = e;
1437         queue_end.(fld) = NULL;
1438         queue_end.FindConnectedComponent_processing = 1;
1439
1440         // for each queued item:
1441         for (; queue_start; queue_start = queue_start.(fld))
1442         {
1443                 // find all neighbors of queue_start
1444                 entity t;
1445                 for(t = NULL; (t = nxt(t, queue_start, pass)); )
1446                 {
1447                         if(t.FindConnectedComponent_processing)
1448                                 continue;
1449                         if(iscon(t, queue_start, pass))
1450                         {
1451                                 // it is connected? ADD IT. It will look for neighbors soon too.
1452                                 queue_end.(fld) = t;
1453                                 queue_end = t;
1454                                 queue_end.(fld) = NULL;
1455                                 queue_end.FindConnectedComponent_processing = 1;
1456                         }
1457                 }
1458         }
1459
1460         // unmark
1461         for (queue_start = e; queue_start; queue_start = queue_start.(fld))
1462                 queue_start.FindConnectedComponent_processing = 0;
1463 }
1464
1465 #ifdef GAMEQC
1466 vector animfixfps(entity e, vector a, vector b)
1467 {
1468         // multi-frame anim: keep as-is
1469         if(a.y == 1)
1470         {
1471                 float dur = frameduration(e.modelindex, a.x);
1472                 if (dur <= 0 && b.y)
1473                 {
1474                         a = b;
1475                         dur = frameduration(e.modelindex, a.x);
1476                 }
1477                 if (dur > 0)
1478                         a.z = 1.0 / dur;
1479         }
1480         return a;
1481 }
1482 #endif
1483
1484 #ifdef GAMEQC
1485 Notification Announcer_PickNumber(int type, int num)
1486 {
1487     return = NULL;
1488         switch (type)
1489         {
1490                 case CNT_GAMESTART:
1491                 {
1492                         switch(num)
1493                         {
1494                                 case 10: return ANNCE_NUM_GAMESTART_10;
1495                                 case 9:  return ANNCE_NUM_GAMESTART_9;
1496                                 case 8:  return ANNCE_NUM_GAMESTART_8;
1497                                 case 7:  return ANNCE_NUM_GAMESTART_7;
1498                                 case 6:  return ANNCE_NUM_GAMESTART_6;
1499                                 case 5:  return ANNCE_NUM_GAMESTART_5;
1500                                 case 4:  return ANNCE_NUM_GAMESTART_4;
1501                                 case 3:  return ANNCE_NUM_GAMESTART_3;
1502                                 case 2:  return ANNCE_NUM_GAMESTART_2;
1503                                 case 1:  return ANNCE_NUM_GAMESTART_1;
1504                         }
1505                         break;
1506                 }
1507                 case CNT_IDLE:
1508                 {
1509                         switch(num)
1510                         {
1511                                 case 10: return ANNCE_NUM_IDLE_10;
1512                                 case 9:  return ANNCE_NUM_IDLE_9;
1513                                 case 8:  return ANNCE_NUM_IDLE_8;
1514                                 case 7:  return ANNCE_NUM_IDLE_7;
1515                                 case 6:  return ANNCE_NUM_IDLE_6;
1516                                 case 5:  return ANNCE_NUM_IDLE_5;
1517                                 case 4:  return ANNCE_NUM_IDLE_4;
1518                                 case 3:  return ANNCE_NUM_IDLE_3;
1519                                 case 2:  return ANNCE_NUM_IDLE_2;
1520                                 case 1:  return ANNCE_NUM_IDLE_1;
1521                         }
1522                         break;
1523                 }
1524                 case CNT_KILL:
1525                 {
1526                         switch(num)
1527                         {
1528                                 case 10: return ANNCE_NUM_KILL_10;
1529                                 case 9:  return ANNCE_NUM_KILL_9;
1530                                 case 8:  return ANNCE_NUM_KILL_8;
1531                                 case 7:  return ANNCE_NUM_KILL_7;
1532                                 case 6:  return ANNCE_NUM_KILL_6;
1533                                 case 5:  return ANNCE_NUM_KILL_5;
1534                                 case 4:  return ANNCE_NUM_KILL_4;
1535                                 case 3:  return ANNCE_NUM_KILL_3;
1536                                 case 2:  return ANNCE_NUM_KILL_2;
1537                                 case 1:  return ANNCE_NUM_KILL_1;
1538                         }
1539                         break;
1540                 }
1541                 case CNT_RESPAWN:
1542                 {
1543                         switch(num)
1544                         {
1545                                 case 10: return ANNCE_NUM_RESPAWN_10;
1546                                 case 9:  return ANNCE_NUM_RESPAWN_9;
1547                                 case 8:  return ANNCE_NUM_RESPAWN_8;
1548                                 case 7:  return ANNCE_NUM_RESPAWN_7;
1549                                 case 6:  return ANNCE_NUM_RESPAWN_6;
1550                                 case 5:  return ANNCE_NUM_RESPAWN_5;
1551                                 case 4:  return ANNCE_NUM_RESPAWN_4;
1552                                 case 3:  return ANNCE_NUM_RESPAWN_3;
1553                                 case 2:  return ANNCE_NUM_RESPAWN_2;
1554                                 case 1:  return ANNCE_NUM_RESPAWN_1;
1555                         }
1556                         break;
1557                 }
1558                 case CNT_ROUNDSTART:
1559                 {
1560                         switch(num)
1561                         {
1562                                 case 10: return ANNCE_NUM_ROUNDSTART_10;
1563                                 case 9:  return ANNCE_NUM_ROUNDSTART_9;
1564                                 case 8:  return ANNCE_NUM_ROUNDSTART_8;
1565                                 case 7:  return ANNCE_NUM_ROUNDSTART_7;
1566                                 case 6:  return ANNCE_NUM_ROUNDSTART_6;
1567                                 case 5:  return ANNCE_NUM_ROUNDSTART_5;
1568                                 case 4:  return ANNCE_NUM_ROUNDSTART_4;
1569                                 case 3:  return ANNCE_NUM_ROUNDSTART_3;
1570                                 case 2:  return ANNCE_NUM_ROUNDSTART_2;
1571                                 case 1:  return ANNCE_NUM_ROUNDSTART_1;
1572                         }
1573                         break;
1574                 }
1575                 default:
1576                 {
1577                         switch(num)
1578                         {
1579                                 case 10: return ANNCE_NUM_10;
1580                                 case 9:  return ANNCE_NUM_9;
1581                                 case 8:  return ANNCE_NUM_8;
1582                                 case 7:  return ANNCE_NUM_7;
1583                                 case 6:  return ANNCE_NUM_6;
1584                                 case 5:  return ANNCE_NUM_5;
1585                                 case 4:  return ANNCE_NUM_4;
1586                                 case 3:  return ANNCE_NUM_3;
1587                                 case 2:  return ANNCE_NUM_2;
1588                                 case 1:  return ANNCE_NUM_1;
1589                         }
1590                         break;
1591                 }
1592         }
1593 }
1594 #endif
1595
1596 #ifdef GAMEQC
1597 int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
1598 {
1599         switch(nativecontents)
1600         {
1601                 case CONTENT_EMPTY:
1602                         return 0;
1603                 case CONTENT_SOLID:
1604                         return DPCONTENTS_SOLID | DPCONTENTS_OPAQUE;
1605                 case CONTENT_WATER:
1606                         return DPCONTENTS_WATER;
1607                 case CONTENT_SLIME:
1608                         return DPCONTENTS_SLIME;
1609                 case CONTENT_LAVA:
1610                         return DPCONTENTS_LAVA | DPCONTENTS_NODROP;
1611                 case CONTENT_SKY:
1612                         return DPCONTENTS_SKY | DPCONTENTS_NODROP | DPCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
1613         }
1614         return 0;
1615 }
1616
1617 int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
1618 {
1619         if(supercontents & (DPCONTENTS_SOLID | DPCONTENTS_BODY))
1620                 return CONTENT_SOLID;
1621         if(supercontents & DPCONTENTS_SKY)
1622                 return CONTENT_SKY;
1623         if(supercontents & DPCONTENTS_LAVA)
1624                 return CONTENT_LAVA;
1625         if(supercontents & DPCONTENTS_SLIME)
1626                 return CONTENT_SLIME;
1627         if(supercontents & DPCONTENTS_WATER)
1628                 return CONTENT_WATER;
1629         return CONTENT_EMPTY;
1630 }
1631 #endif