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