more cleanups and bugfixes to the race hud code
[divverent/nexuiz.git] / data / qcsrc / client / sbar.qc
1 void drawstringright(vector, string, vector, vector, float, float);
2 void drawstringcenter(vector, string, vector, vector, float, float);
3
4 float weapon_hits[WEP_COUNT];
5 float weapon_fired[WEP_COUNT];
6 float weapon_number;
7
8 float last_weapon;
9 float weapontime;
10
11 float sbar_alpha_fg;
12 float sbar_alpha_bg;
13 float sbar_color_bg_team;
14 float sbar_border_thickness;
15 float sbar_scoreboard_alpha_bg;
16 float sbar_scoreboard_alpha_fg;
17 float sbar_scoreboard_highlight;
18 float sbar_scoreboard_highlight_alpha;
19 float sbar_scoreboard_highlight_alpha_self;
20 float sbar_hudselector;
21 float sbar_hud_accuracy;
22 float sbar_scoreboard_alpha_name;
23 float sbar_scoreboard_alpha_name_self;
24
25 float ps_primary, ps_secondary;
26 float ts_primary, ts_secondary;
27
28 vector color;
29 float SCOREBOARD_OFFSET = 50;
30
31 void CSQC_kh_hudreset();
32 void CSQC_kh_hud();
33 void CSQC_ctf_hudreset();
34 void CSQC_ctf_hud();
35 void CSQC_nb_hud();
36 void CSQC_race_hud();
37 void MapVote_Draw();
38 void Sbar_FinaleOverlay()
39 {
40         /*vector pos;
41         pos_x = (vid_conwidth - 1)/2;
42         pos_y = 16;
43         pos_z = 0;*/
44
45         //drawpic(pos, "gfx/finale", '0 0 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
46
47         //drawstring(pos, "END", sbar_fontsize, '1 1 1', 1, DRAWFLAG_NORMAL);
48         MapVote_Draw();
49 }
50
51 float weaponspace[10];
52 float weapon_first, weapon_last;
53 void Sbar_DrawWeapon_Clear()
54 {
55         float idx;
56         weapon_first = -2;
57         weapon_last = -1;
58         for(idx = 0; idx < 10; ++idx)
59                 weaponspace[idx] = 0;
60         for(idx = 0; idx <= 23; ++idx)
61         {
62                 if(weaponimpulse[idx] >= 0)
63                 {
64                         if(weapon_first < 0)
65                                 weapon_first = idx;
66                         weapon_last = idx;
67                 }
68         }
69 }
70 void Sbar_DrawWeapon(float nr, float fade, float active, float wc)
71 {
72         vector pos, vsize, fill_colour;
73         float value, idx, imp, sp, weapon_hit, weapon_damage, weapon_stats;
74
75         imp = weaponimpulse[nr];
76         weapon_hit = weapon_hits[wc];
77         weapon_damage = weapon_fired[wc];
78         if(imp == 0)
79                 idx = 9;
80         else
81                 idx = imp - 1;
82
83         value = (active) ? 1 : 0.6;
84         color_x = color_y = color_z = value;
85
86         // width = 300, height = 100
87         const float w_width = 24, w_height = 12, w_space = 2, font_size = 8;
88
89         sp = weaponspace[idx] + 1;
90         weaponspace[idx] = sp;
91
92         pos_x = (vid_conwidth + 6 - w_width * 9) * 0.5 + w_width * idx;
93         pos_y = (vid_conheight - w_height * sp) - 38; // move 38 pixels up
94         pos_z = 0;
95         vsize_x = w_width;
96         vsize_y = w_height;
97         vsize_z = 0;
98         if (active)
99                 drawpic(pos, "gfx/hud/sb_ammobg", vsize, color, value * fade * sbar_alpha_fg, DRAWFLAG_NORMAL);
100         drawpic(pos, strcat("gfx/hud/inv_weapon", ftos(nr)), vsize, color, value * fade * sbar_alpha_fg, DRAWFLAG_NORMAL);
101         pos_x += w_space;
102         pos_y += w_space;
103         vsize_x = font_size;
104         vsize_y = font_size;
105         vsize_z = 0;
106         drawstring(pos, ftos(imp), vsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
107
108         // draw the weapon accuracy on the HUD
109         if(sbar_hud_accuracy)
110         {
111                 weapon_stats = rint(100*weapon_hit/weapon_damage);
112                 fill_colour_x = 1 - 0.015 * weapon_stats;
113                 fill_colour_y = 1 - 0.015 * (100 - weapon_stats);
114                 drawstringright(pos + '22 0 0', strcat(ftos(weapon_stats),"%"), '6 6 0', fill_colour, sbar_alpha_fg, 0);
115         }
116 }
117
118 void Sbar_DrawXNum (vector pos, float num, float digits, float showminusplus, float lettersize, vector rgb, float highlighted, float stroke, float alpha, float dflags)
119 {
120         float l, i;
121         string str, tmp, l_length;
122         float minus, plus;
123         vector vsize, num_color;
124
125         vsize_x = vsize_y = lettersize;
126         vsize_z = 0;
127
128         // showminusplus 1: always prefix with minus sign (useful in race distribution display)
129         // showminusplus 2: always prefix with plus sign (useful in race distribution display)
130         // showminusplus 3: prefix with minus sign if negative, plus sign if positive (useful in score distribution display)
131
132         if((showminusplus == 2 && num >= 0) || (num > 0 && showminusplus == 3))
133         {
134                 plus = true;
135                 pos_x -= lettersize;
136         } else
137                 plus = false;   
138
139         if(num < 0 || (num < 0 && showminusplus == 3) || (showminusplus == 1 && num <= 0))
140         {
141                 minus = true;
142                 num = -num;
143                 pos_x -= lettersize;
144         } else
145                 minus = false;
146
147         if(digits < 0)
148         {
149                 tmp = ftos(num);
150                 digits = -digits;
151                 str = strcat(substring("0000000000", 0, digits - strlen(tmp)), tmp);
152         } else
153                 str = ftos(num);
154
155         l = strlen(str);
156         l_length = ftos(l);
157
158         if(l > digits)
159         {
160                 str = substring(str, l-digits, 999);
161                 l = strlen(str);
162         } else if(l < digits)
163                 pos_x += (digits-l) * lettersize;
164
165         if (highlighted == 1) {
166                 vector hl_size;
167                 hl_size_x = vsize_x * l + vsize_x * 0.2;
168                 hl_size_y = vsize_y * 1.1;
169                 hl_size_z = 0;
170                 if(minus)
171                         hl_size_x = hl_size_x + vsize_x;
172
173                 vector hl_pos;
174                 hl_pos_x = pos_x - lettersize/10;
175                 hl_pos_y = pos_y - lettersize/20;
176                 hl_pos_z = 0;
177
178                 drawpic(hl_pos, strcat("gfx/hud/sb_highlight_", l_length), hl_size, '1 1 1', alpha, dflags);
179         }
180
181         if (stroke == 1)
182                 num_color = '1 1 1';
183         else
184                 num_color = rgb;
185
186         if(minus)
187         {
188                 if (stroke == 1)
189                         drawpic(pos, "gfx/hud/num_minus_stroke", vsize, rgb, alpha, dflags);
190                 drawpic(pos, "gfx/hud/num_minus", vsize, num_color, alpha, dflags);
191                 pos_x += lettersize;
192         } else if(plus)
193         {
194                 if (stroke == 1)
195                         drawpic(pos, "gfx/hud/num_plus_stroke", vsize, rgb, alpha, dflags);
196                 drawpic(pos, "gfx/hud/num_plus", vsize, num_color, alpha, dflags);
197                 pos_x += lettersize;
198         }
199
200         for(i = 0; i < l; ++i)
201         {
202                 tmp = substring(str, i, 1);
203                 if (stroke == 1)
204                         drawpic(pos, strcat("gfx/hud/num_", tmp, "_stroke"), vsize, rgb, alpha, dflags);
205                 drawpic(pos, strcat("gfx/hud/num_", tmp), vsize, num_color, alpha, dflags);
206                 pos_x += lettersize;
207         }
208 }
209
210 void Sbar_DrawXNum_Colored (vector pos, float x, float lettersize, float alpha)
211 {
212         if(x > 200) {
213                 color_x = 0;
214                 color_y = 1;
215                 color_z = 0;
216         }
217         else if(x > 150) {
218                 color_x = 0.4 - (x-150)*0.02 * 0.4; //red value between 0.4 -> 0
219                 color_y = 0.9 + (x-150)*0.02 * 0.1; // green value between 0.9 -> 1
220                 color_z = 0;
221         }
222         else if(x > 100) {
223                 color_x = 1 - (x-100)*0.02 * 0.6; //red value between 1 -> 0.4
224                 color_y = 1 - (x-100)*0.02 * 0.1; // green value between 1 -> 0.9
225                 color_z = 1 - (x-100)*0.02; // blue value between 1 -> 0
226         }
227         else if(x > 50) {
228                 color_x = 1;
229                 color_y = 1;
230                 color_z = 0.2 + (x-50)*0.02 * 0.8; // blue value between 0.2 -> 1
231         }
232         else if(x > 20) {
233                 color_x = 1;
234                 color_y = (x-20)*90/27/100; // green value between 0 -> 1
235                 color_z = (x-20)*90/27/100 * 0.2; // blue value between 0 -> 0.2
236         }
237         else {
238                 color_x = 1;
239                 color_y = 0;
240                 color_z = 0;
241         }
242         Sbar_DrawXNum(pos, x, 3, 0, lettersize, color, 0, 0, alpha, DRAWFLAG_NORMAL);
243 }
244
245 void Cmd_Sbar_SetFields(float argc);
246 void Sbar_InitScores()
247 {
248         float i, f;
249
250         ps_primary = ps_secondary = ts_primary = ts_secondary = -1;
251         for(i = 0; i < MAX_SCORE; ++i)
252         {
253                 f = (scores_flags[i] & SFL_SORT_PRIO_MASK);
254                 if(f == SFL_SORT_PRIO_PRIMARY)
255                         ps_primary = i;
256                 if(f == SFL_SORT_PRIO_SECONDARY)
257                         ps_secondary = i;
258         }
259         if(ps_secondary == -1)
260                 ps_secondary = ps_primary;
261
262         for(i = 0; i < MAX_TEAMSCORE; ++i)
263         {
264                 f = (teamscores_flags[i] & SFL_SORT_PRIO_MASK);
265                 if(f == SFL_SORT_PRIO_PRIMARY)
266                         ts_primary = i;
267                 if(f == SFL_SORT_PRIO_SECONDARY)
268                         ts_secondary = i;
269         }
270         if(ts_secondary == -1)
271                 ts_secondary = ts_primary;
272
273         Cmd_Sbar_SetFields(0);
274 }
275
276 void Sbar_UpdatePlayerPos(entity pl);
277 float SetTeam(entity pl, float Team);
278 //float lastpnum;
279 void Sbar_UpdatePlayerTeams()
280 {
281         float Team;
282         entity pl, tmp;
283         float num;
284
285         num = 0;
286         for(pl = players.sort_next; pl; pl = pl.sort_next)
287         {
288                 num += 1;
289                 Team = GetPlayerColor(pl.sv_entnum);
290                 if(SetTeam(pl, Team))
291                 {
292                         tmp = pl.sort_prev;
293                         Sbar_UpdatePlayerPos(pl);
294                         if(tmp)
295                                 pl = tmp;
296                         else
297                                 pl = players.sort_next;
298                 }
299         }
300         /*
301         if(num != lastpnum)
302                 print(strcat("PNUM: ", ftos(num), "\n"));
303         lastpnum = num;
304         */
305 }
306
307 float Sbar_ComparePlayerScores(entity left, entity right)
308 {
309         float vl, vr;
310         vl = GetPlayerColor(left.sv_entnum);
311         vr = GetPlayerColor(right.sv_entnum);
312
313         if(!left.gotscores)
314                 vl = COLOR_SPECTATOR;
315         if(!right.gotscores)
316                 vr = COLOR_SPECTATOR;
317
318         if(vl > vr)
319                 return true;
320         if(vl < vr)
321                 return false;
322
323         if(vl == COLOR_SPECTATOR)
324         {
325                 // FIRST the one with scores (spectators), THEN the ones without (downloaders)
326                 // no other sorting
327                 if(!left.gotscores && right.gotscores)
328                         return true;
329                 return false;
330         }
331
332         vl = left.scores[ps_primary];
333         vr = right.scores[ps_primary];
334         if(scores_flags[ps_primary] & SFL_ZERO_IS_WORST)
335         {
336                 if(vl == 0 && vr != 0)
337                         return 1;
338                 if(vl != 0 && vr == 0)
339                         return 0;
340         }
341         if(vl > vr)
342                 return IS_INCREASING(scores_flags[ps_primary]);
343         if(vl < vr)
344                 return IS_DECREASING(scores_flags[ps_primary]);
345
346         vl = left.scores[ps_secondary];
347         vr = right.scores[ps_secondary];
348         if(scores_flags[ps_secondary] & SFL_ZERO_IS_WORST)
349         {
350                 if(vl == 0 && vr != 0)
351                         return 1;
352                 if(vl != 0 && vr == 0)
353                         return 0;
354         }
355         if(vl > vr)
356                 return IS_INCREASING(scores_flags[ps_secondary]);
357         if(vl < vr)
358                 return IS_DECREASING(scores_flags[ps_secondary]);
359
360         return false;
361 }
362
363 void Sbar_UpdatePlayerPos(entity player)
364 {
365         for(other = player.sort_next; other && Sbar_ComparePlayerScores(player, other); other = player.sort_next)
366         {
367                 SORT_SWAP(player, other);
368         }
369         for(other = player.sort_prev; other != players && Sbar_ComparePlayerScores(other, player); other = player.sort_prev)
370         {
371                 SORT_SWAP(other, player);
372         }
373 }
374
375 float Sbar_CompareTeamScores(entity left, entity right)
376 {
377         float vl, vr;
378
379         if(left.team == COLOR_SPECTATOR)
380                 return 1;
381         if(right.team == COLOR_SPECTATOR)
382                 return 0;
383
384         vl = left.teamscores[ts_primary];
385         vr = right.teamscores[ts_primary];
386         if(vl > vr)
387                 return IS_INCREASING(teamscores_flags[ts_primary]);
388         if(vl < vr)
389                 return IS_DECREASING(teamscores_flags[ts_primary]);
390
391         vl = left.teamscores[ts_secondary];
392         vr = right.teamscores[ts_secondary];
393         if(vl > vr)
394                 return IS_INCREASING(teamscores_flags[ts_secondary]);
395         if(vl < vr)
396                 return IS_DECREASING(teamscores_flags[ts_secondary]);
397
398         return false;
399 }
400
401 void Sbar_UpdateTeamPos(entity Team)
402 {
403         for(other = Team.sort_next; other && Sbar_CompareTeamScores(Team, other); other = Team.sort_next)
404         {
405                 SORT_SWAP(Team, other);
406         }
407         for(other = Team.sort_prev; other != teams && Sbar_CompareTeamScores(other, Team); other = Team.sort_prev)
408         {
409                 SORT_SWAP(other, Team);
410         }
411 }
412
413 void Cmd_Sbar_Help(float argc)
414 {
415         print("You can modify the scoreboard using the ^2sbar_columns_set command.\n");
416         print("^3|---------------------------------------------------------------|\n");
417         print("Usage:\n");
418         print("^2sbar_columns_set default\n");
419         print("^2sbar_columns_set ^7filed1 field2 ...\n");
420         print("The following field names are recognized (case insensitive):\n");
421         print("You can use a ^3|^7 to start the right-aligned fields.\n\n");
422
423         print("^3name^7 or ^3nick^7         Name of a player\n");
424         print("^3ping^7                     Ping time\n");
425         print("^3pl^7                       Packet loss\n");
426         print("^3kills^7                    Number of kills\n");
427         print("^3deaths^7                   Number of deaths\n");
428         print("^3suicides^7                 Number of suicides\n");
429         print("^3frags^7                    kills - suicides\n");
430         print("^3kd^7                       The kill-death ratio\n");
431         print("^3caps^7                     How often a flag (CTF) or a key (KeyHunt) was captured\n");
432         print("^3pickups^7                  How often a flag (CTF) or a key (KeyHunt) was picked up\n");
433         print("^3fckills^7                  Number of flag carrier kills\n");
434         print("^3returns^7                  Number of flag returns\n");
435         print("^3drops^7                    Number of flag drops\n");
436         print("^3lives^7                    Number of lives (LMS)\n");
437         print("^3rank^7                     Player rank\n");
438         print("^3pushes^7                   Number of players pushed into void\n");
439         print("^3destroyed^7                Number of keys destroyed by pushing them into void\n");
440         print("^3kckills^7                  Number of keys carrier kills\n");
441         print("^3losses^7                   Number of times a key was lost\n");
442         print("^3laps^7                     Number of laps finished (race/cts)\n");
443         print("^3time^7                     Total time raced (race/cts)\n");
444         print("^3fastest^7                  Time of fastest lap (race/cts)\n");
445         print("^3ticks^7                    Number of ticks (DOM)\n");
446         print("^3takes^7                    Number of domination points taken (DOM)\n");
447         print("^3score^7                    Total score\n\n");
448
449         print("Before a field you can put a + or - sign, then a comma separated list\n");
450         print("of game types, then a slash, to make the field show up only in these\n");
451         print("or in all but these game types. You can also specify 'all' as a\n");
452         print("field to show all fields available for the current game mode.\n\n");
453         
454         print("The special game type names 'teams' and 'noteams' can be used to\n");
455         print("include/exclude ALL teams/noteams game modes.\n\n");
456
457         print("Example: sbar_columns_set name ping pl | +ctf/field3 -dm/field4\n");
458         print("will display name, ping and pl aligned to the left, and the fields\n");
459         print("right of the vertical bar aligned to the right.\n");
460         print("'field3' will only be shown in CTF, and 'field4' will be shown in all\n");
461         print("other gamemodes except DM.\n");
462 }
463
464 string Sbar_DefaultColumnLayout()
465 {
466         return strcat( // fteqcc sucks
467                 "ping pl name | ",
468                 "-teams,race,lms/kills -teams,lms/deaths -teams,lms,race/suicides -race,dm,tdm/frags ", // tdm already has this in "score"
469                 "+ctf/caps +ctf/pickups +ctf/fckills +ctf/returns ",
470                 "+lms/lives +lms/rank ",
471                 "+kh/caps +kh/pushes +kh/destroyed ",
472                 "?+race/laps ?+race/time ?+race/fastest ",
473                 "+as/objectives +nexball/faults +nexball/goals ",
474                 "-lms,race,nexball/score");
475 }
476
477 void Cmd_Sbar_SetFields(float argc)
478 {
479         float i, j, slash;
480         string str, pattern;
481         float digit;
482         float have_name, have_primary, have_secondary, have_separator;
483         float missing;
484
485         // TODO: re enable with gametype dependant cvars?
486         if(argc < 2) // no arguments provided
487                 argc = tokenizebyseparator(strcat("x ", cvar_string("sbar_columns")), " ");
488
489         if(argc < 2)
490                 argc = tokenizebyseparator(strcat("x ", Sbar_DefaultColumnLayout()), " ");
491
492         if(argc == 2)
493         {
494                 if(argv(1) == "default")
495                         argc = tokenizebyseparator(strcat("x ", Sbar_DefaultColumnLayout()), " ");
496                 else if(argv(1) == "all")
497                 {
498                         string s;
499                         s = "ping pl color name |";
500                         for(i = 0; i < MAX_SCORE; ++i)
501                         {
502                                 if(i != ps_primary)
503                                 if(i != ps_secondary)
504                                 if(scores_label[i] != "")
505                                         s = strcat(s, " ", scores_label[i]);
506                         }
507                         if(ps_secondary != ps_primary)
508                                 s = strcat(s, " ", scores_label[ps_secondary]);
509                         s = strcat(s, " ", scores_label[ps_primary]);
510                         argc = tokenizebyseparator(strcat("x ", s), " ");
511                 }
512         }
513
514
515         sbar_num_fields = 0;
516
517         drawfont = sbar_font;
518         digit = stringwidth("0123456789", FALSE) / 10;
519
520         for(i = 0; i < argc - 1; ++i)
521         {
522                 float nocomplain;
523                 str = argv(i+1);
524
525                 nocomplain = FALSE;
526                 if(substring(str, 0, 1) == "?")
527                 {
528                         nocomplain = TRUE;
529                         str = substring(str, 1, strlen(str) - 1);
530                 }
531
532                 slash = strstrofs(str, "/", 0);
533                 if(slash >= 0)
534                 {
535                         pattern = substring(str, 0, slash);
536                         str = substring(str, slash + 1, strlen(str) - (slash + 1));
537
538                         if not(isGametypeInFilter(gametype, teamplay, pattern))
539                                 continue;
540                 }
541
542                 strunzone(sbar_title[sbar_num_fields]);
543                 sbar_title[sbar_num_fields] = strzone(str);
544                 sbar_size[sbar_num_fields] = stringwidth(str, FALSE);
545                 str = strtolower(str);
546
547                 if(str == "ping") {
548                         sbar_field[sbar_num_fields] = SP_PING;
549                 } else if(str == "pl") {
550                         sbar_field[sbar_num_fields] = SP_PL;
551                 } else if(str == "kd" || str == "kdr" || str == "kdratio" || str == "k/d") {
552                         sbar_field[sbar_num_fields] = SP_KDRATIO;
553                 } else if(str == "name" || str == "nick") {
554                         sbar_field[sbar_num_fields] = SP_NAME;
555                         have_name = 1;
556                 } else if(str == "|") {
557                         sbar_field[sbar_num_fields] = SP_SEPARATOR;
558                         have_separator = 1;
559                 } else {
560                         for(j = 0; j < MAX_SCORE; ++j)
561                                 if(str == strtolower(scores_label[j]))
562                                         goto found; // sorry, but otherwise fteqcc -O3 miscompiles this and warns about "unreachable code"
563 :notfound
564                         if(str == "frags")
565                         {
566                                 j = SP_FRAGS;
567                         }
568                         else
569                         {
570                                 if not(nocomplain)
571                                         print(strcat("^1Error:^7 Unknown score field: '", str, "'\n"));
572                                 continue;
573                         }
574 :found
575                         sbar_field[sbar_num_fields] = j;
576                         if(j == ps_primary)
577                                 have_primary = 1;
578                         if(j == ps_secondary)
579                                 have_secondary = 1;
580                 }
581                 ++sbar_num_fields;
582                 if(sbar_num_fields >= MAX_SBAR_FIELDS)
583                         break;
584         }
585
586         if(scores_flags[ps_primary] & SFL_ALLOW_HIDE)
587                 have_primary = 1;
588         if(scores_flags[ps_secondary] & SFL_ALLOW_HIDE)
589                 have_secondary = 1;
590         if(ps_primary == ps_secondary)
591                 have_secondary = 1;
592         missing = (!have_primary) + (!have_secondary) + (!have_separator) + (!have_name);
593
594         if(sbar_num_fields+missing < MAX_SBAR_FIELDS)
595         {
596                 if(!have_name)
597                 {
598                         strunzone(sbar_title[sbar_num_fields]);
599                         for(i = sbar_num_fields; i > 0; --i)
600                         {
601                                 sbar_title[i] = sbar_title[i-1];
602                                 sbar_size[i] = sbar_size[i-1];
603                                 sbar_field[i] = sbar_field[i-1];
604                         }
605                         sbar_title[0] = strzone("name");
606                         sbar_field[0] = SP_NAME;
607                         ++sbar_num_fields;
608                         print("fixed missing field 'name'\n");
609
610                         if(!have_separator)
611                         {
612                                 strunzone(sbar_title[sbar_num_fields]);
613                                 for(i = sbar_num_fields; i > 1; --i)
614                                 {
615                                         sbar_title[i] = sbar_title[i-1];
616                                         sbar_size[i] = sbar_size[i-1];
617                                         sbar_field[i] = sbar_field[i-1];
618                                 }
619                                 sbar_title[1] = strzone("|");
620                                 sbar_field[1] = SP_SEPARATOR;
621                                 sbar_size[1] = stringwidth("|", FALSE);
622                                 ++sbar_num_fields;
623                                 print("fixed missing field '|'\n");
624                         }
625                 }
626                 else if(!have_separator)
627                 {
628                         strunzone(sbar_title[sbar_num_fields]);
629                         sbar_title[sbar_num_fields] = strzone("|");
630                         sbar_size[sbar_num_fields] = stringwidth("|", FALSE);
631                         sbar_field[sbar_num_fields] = SP_SEPARATOR;
632                         ++sbar_num_fields;
633                         print("fixed missing field '|'\n");
634                 }
635                 if(!have_secondary)
636                 {
637                         strunzone(sbar_title[sbar_num_fields]);
638                         sbar_title[sbar_num_fields] = strzone(scores_label[ps_secondary]);
639                         sbar_size[sbar_num_fields] = stringwidth(sbar_title[sbar_num_fields], FALSE);
640                         sbar_field[sbar_num_fields] = ps_secondary;
641                         ++sbar_num_fields;
642                         print("fixed missing field '", scores_label[ps_secondary], "'\n");
643                 }
644                 if(!have_primary)
645                 {
646                         strunzone(sbar_title[sbar_num_fields]);
647                         sbar_title[sbar_num_fields] = strzone(scores_label[ps_primary]);
648                         sbar_size[sbar_num_fields] = stringwidth(sbar_title[sbar_num_fields], FALSE);
649                         sbar_field[sbar_num_fields] = ps_primary;
650                         ++sbar_num_fields;
651                         print("fixed missing field '", scores_label[ps_primary], "'\n");
652                 }
653         }
654
655         sbar_field[sbar_num_fields] = SP_END;
656 }
657
658 // MOVEUP::
659 vector sbar_field_rgb;
660 string sbar_field_icon0;
661 string sbar_field_icon1;
662 string sbar_field_icon2;
663 vector sbar_field_icon0_rgb;
664 vector sbar_field_icon1_rgb;
665 vector sbar_field_icon2_rgb;
666 float sbar_field_icon0_alpha;
667 float sbar_field_icon1_alpha;
668 float sbar_field_icon2_alpha;
669 string Sbar_GetField(entity pl, float field)
670 {
671         float tmp, num, denom, f;
672         string str;
673         sbar_field_rgb = '1 1 1';
674         sbar_field_icon0 = "";
675         sbar_field_icon1 = "";
676         sbar_field_icon2 = "";
677         sbar_field_icon0_rgb = '1 1 1';
678         sbar_field_icon1_rgb = '1 1 1';
679         sbar_field_icon2_rgb = '1 1 1';
680         sbar_field_icon0_alpha = 1;
681         sbar_field_icon1_alpha = 1;
682         sbar_field_icon2_alpha = 1;
683         switch(field)
684         {
685                 case SP_PING:
686                         if not(pl.gotscores)
687                                 return "\x8D\x8D\x8D"; // >>> sign
688                         str = getplayerkey(pl.sv_entnum, "ping");
689                         if(str == "0")
690                                 return "N/A";
691                         tmp = max(0, min(220, stof(str)-80)) / 220;
692                         sbar_field_rgb = '1 1 1' - '0 1 1'*tmp;
693                         return str;
694
695                 case SP_PL:
696                         if not(pl.gotscores)
697                                 return "N/A";
698                         str = getplayerkey(pl.sv_entnum, "pl");
699                         if(str == "0")
700                                 return "";
701                         tmp = bound(0, stof(str), 20) / 20; // 20% is REALLY BAD pl
702                         sbar_field_rgb = '1 0.5 0.5' - '0 0.5 0.5'*tmp;
703                         return str;
704
705                 case SP_NAME:
706                         if(ready_waiting && pl.ready)
707                         {
708                                 sbar_field_icon0 = "gfx/sb_player_ready";
709                         }
710                         else if(!teamplay)
711                         {
712                                 f = stof(getplayerkey(pl.sv_entnum, "colors"));
713                                 {
714                                         sbar_field_icon0 = "gfx/sb_playercolor_base";
715                                         sbar_field_icon1 = "gfx/sb_playercolor_shirt";
716                                         sbar_field_icon1_rgb = colormapPaletteColor(floor(f / 16), 0);
717                                         sbar_field_icon2 = "gfx/sb_playercolor_pants";
718                                         sbar_field_icon2_rgb = colormapPaletteColor(mod(f, 16), 1);
719                                 }
720                         }
721                         return GetPlayerName(pl.sv_entnum);
722
723                 case SP_FRAGS:
724                         f = pl.(scores[SP_KILLS]);
725                         f -= pl.(scores[SP_SUICIDES]);
726                         return ftos(f);
727
728                 case SP_KDRATIO:
729                         num = pl.(scores[SP_KILLS]);
730                         denom = pl.(scores[SP_DEATHS]);
731
732                         if(denom == 0) {
733                                 sbar_field_rgb = '0 1 0';
734                                 str = ftos(num);
735                         } else if(num <= 0) {
736                                 sbar_field_rgb = '1 0 0';
737                                 str = ftos(num/denom);
738                         } else
739                                 str = ftos(num/denom);
740
741                         tmp = strstrofs(str, ".", 0);
742                         if(tmp > 0)
743                                 str = substring(str, 0, tmp+2);
744                         return str;
745
746                 default:
747                         tmp = pl.(scores[field]);
748                         f = scores_flags[field];
749                         if(field == ps_primary)
750                                 sbar_field_rgb = '1 1 0';
751                         else if(field == ps_secondary)
752                                 sbar_field_rgb = '0 1 1';
753                         else
754                                 sbar_field_rgb = '1 1 1';
755                         return ScoreString(f, tmp);
756         }
757         //return "error";
758 }
759
760 float xmin, xmax, ymin, ymax, sbwidth;
761 float sbar_fixscoreboardcolumnwidth_len;
762 float sbar_fixscoreboardcolumnwidth_iconlen;
763 float sbar_fixscoreboardcolumnwidth_marginlen;
764
765 float stringwidth_colors(string s)
766 {
767         return stringwidth(s, TRUE);
768 }
769
770 float stringwidth_nocolors(string s)
771 {
772         return stringwidth(s, FALSE);
773 }
774
775 string Sbar_FixScoreboardColumnWidth(float i, string str)
776 {
777         float field, f;
778         vector sz;
779         field = sbar_field[i];
780
781         sbar_fixscoreboardcolumnwidth_iconlen = 0;
782
783         if(sbar_field_icon0 != "")
784         {
785                 sz = drawgetimagesize(sbar_field_icon0);
786                 f = sz_x / sz_y;
787                 if(sbar_fixscoreboardcolumnwidth_iconlen < f)
788                         sbar_fixscoreboardcolumnwidth_iconlen = f;
789         }
790
791         if(sbar_field_icon1 != "")
792         {
793                 sz = drawgetimagesize(sbar_field_icon1);
794                 f = sz_x / sz_y;
795                 if(sbar_fixscoreboardcolumnwidth_iconlen < f)
796                         sbar_fixscoreboardcolumnwidth_iconlen = f;
797         }
798
799         if(sbar_field_icon2 != "")
800         {
801                 sz = drawgetimagesize(sbar_field_icon2);
802                 f = sz_x / sz_y;
803                 if(sbar_fixscoreboardcolumnwidth_iconlen < f)
804                         sbar_fixscoreboardcolumnwidth_iconlen = f;
805         }
806
807         sbar_fixscoreboardcolumnwidth_iconlen *= sbar_fontsize_y / sbar_fontsize_x; // fix icon aspect
808
809         if(sbar_fixscoreboardcolumnwidth_iconlen != 0)
810                 sbar_fixscoreboardcolumnwidth_marginlen = stringwidth(" ", FALSE);
811         else
812                 sbar_fixscoreboardcolumnwidth_marginlen = 0;
813
814         if(field == SP_NAME) // name gets all remaining space
815         {
816                 float namesize, j;
817                 namesize = sbwidth / sbar_fontsize_x;
818                 for(j = 0; j < sbar_num_fields; ++j)
819                         if(j != i)
820                                 if (sbar_field[i] != SP_SEPARATOR)
821                                         namesize -= sbar_size[j] + 1;
822                 namesize += 1;
823                 sbar_size[i] = namesize;
824                 
825                 if (sbar_fixscoreboardcolumnwidth_iconlen != 0)
826                         namesize -= sbar_fixscoreboardcolumnwidth_marginlen + sbar_fixscoreboardcolumnwidth_iconlen;
827                 str = textShortenToWidth(str, namesize, stringwidth_colors);
828                 sbar_fixscoreboardcolumnwidth_len = stringwidth(str, TRUE);
829         }
830         else
831                 sbar_fixscoreboardcolumnwidth_len = stringwidth(str, FALSE);
832         
833         f = sbar_fixscoreboardcolumnwidth_len + sbar_fixscoreboardcolumnwidth_marginlen + sbar_fixscoreboardcolumnwidth_iconlen;
834         if(sbar_size[i] < f)
835                 sbar_size[i] = f;
836
837         return str;
838 }
839
840 void Sbar_PrintScoreboardItem(vector pos, entity pl, float is_self, float pl_number)
841 {
842         vector tmp, plteamrgb;
843         plteamrgb = GetTeamRGB(pl.team); 
844         string str;
845         float i, field;
846         float is_spec;
847         is_spec = (GetPlayerColor(pl.sv_entnum) == COLOR_SPECTATOR);
848
849         // Layout:
850         tmp_x = sbwidth;
851         tmp_y = sbar_fontsize_y * 1.25;
852         tmp_z = 0;
853
854         // alternated rows highlighting
855         if (is_self)
856                 drawfill(pos - '1 1 0', tmp + '2 0 0', plteamrgb, sbar_scoreboard_highlight_alpha_self, DRAWFLAG_NORMAL);
857         else
858         {
859                 if (sbar_scoreboard_highlight)
860                         if(!mod(pl_number,2))
861                                 drawfill(pos - '1 1 0', tmp + '2 0 0', plteamrgb, sbar_scoreboard_highlight_alpha, DRAWFLAG_NORMAL);
862         }
863
864         tmp_y = 0;
865
866         for(i = 0; i < sbar_num_fields; ++i)
867         {
868                 field = sbar_field[i];
869                 if(field == SP_SEPARATOR)
870                         break;
871
872                 if(is_spec && field != SP_NAME && field != SP_PING) {
873                         pos_x += sbar_fontsize_x*sbar_size[i] + sbar_fontsize_x;
874                         continue;
875                 }
876                 str = Sbar_GetField(pl, field);
877                 str = Sbar_FixScoreboardColumnWidth(i, str);
878
879                 pos_x += sbar_fontsize_x*sbar_size[i] + sbar_fontsize_x;
880
881                 if(field == SP_NAME) {
882                         tmp_x = sbar_fontsize_x*(sbar_size[i] - sbar_fixscoreboardcolumnwidth_iconlen - sbar_fixscoreboardcolumnwidth_marginlen) + sbar_fontsize_x;
883                         if (is_self)
884                                 drawcolorcodedstring(pos - tmp, str, sbar_fontsize, sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
885                         else
886                                 drawcolorcodedstring(pos - tmp, str, sbar_fontsize, sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
887                 } else {
888                         tmp_x = sbar_fixscoreboardcolumnwidth_len*sbar_fontsize_x + sbar_fontsize_x;
889                         if (is_self)
890                                 drawstring(pos - tmp, str, sbar_fontsize, sbar_field_rgb, sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
891                         else
892                                 drawstring(pos - tmp, str, sbar_fontsize, sbar_field_rgb, sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
893                 }
894
895                 tmp_x = sbar_fontsize_x*sbar_size[i] + sbar_fontsize_x;
896                 if(sbar_field_icon0 != "")
897                         if (is_self)
898                                 drawpic(pos - tmp, sbar_field_icon0, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon1_rgb, sbar_field_icon0_alpha * sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
899                         else
900                                 drawpic(pos - tmp, sbar_field_icon0, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon1_rgb, sbar_field_icon0_alpha * sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
901                 if(sbar_field_icon1 != "")
902                         if (is_self)
903                                 drawpic(pos - tmp, sbar_field_icon1, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon1_rgb, sbar_field_icon1_alpha * sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
904                         else
905                                 drawpic(pos - tmp, sbar_field_icon1, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon1_rgb, sbar_field_icon1_alpha * sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
906                 if(sbar_field_icon2 != "")
907                         if (is_self)
908                                 drawpic(pos - tmp, sbar_field_icon2, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon2_rgb, sbar_field_icon2_alpha * sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
909                         else
910                                 drawpic(pos - tmp, sbar_field_icon2, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon2_rgb, sbar_field_icon2_alpha * sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
911         }
912
913         if(sbar_field[i] == SP_SEPARATOR)
914         {
915                 pos_x = xmax;
916                 for(i = sbar_num_fields-1; i > 0; --i)
917                 {
918                         field = sbar_field[i];
919                         if(field == SP_SEPARATOR)
920                                 break;
921
922                         if(is_spec && field != SP_NAME && field != SP_PING) {
923                                 pos_x -= sbar_fontsize_x*sbar_size[i] + sbar_fontsize_x;
924                                 continue;
925                         }
926
927                         str = Sbar_GetField(pl, field);
928                         str = Sbar_FixScoreboardColumnWidth(i, str);
929
930                         if(field == SP_NAME) {
931                                 tmp_x = sbar_fontsize_x*sbar_fixscoreboardcolumnwidth_len; // left or right aligned? let's put it right...
932                                 if(is_self)
933                                         drawcolorcodedstring(pos - tmp, str, sbar_fontsize, sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
934                                 else
935                                         drawcolorcodedstring(pos - tmp, str, sbar_fontsize, sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
936                         } else {
937                                 tmp_x = sbar_fontsize_x*sbar_fixscoreboardcolumnwidth_len;
938                                 if(is_self)
939                                         drawstring(pos - tmp, str, sbar_fontsize, sbar_field_rgb, sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
940                                 else
941                                         drawstring(pos - tmp, str, sbar_fontsize, sbar_field_rgb, sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
942                         }
943
944                         tmp_x = sbar_fontsize_x*sbar_size[i];
945                         if(sbar_field_icon0 != "")
946                                 if (is_self)
947                                         drawpic(pos - tmp, sbar_field_icon0, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon1_rgb, sbar_field_icon0_alpha * sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
948                                 else
949                                         drawpic(pos - tmp, sbar_field_icon0, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon1_rgb, sbar_field_icon0_alpha * sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
950                         if(sbar_field_icon1 != "")
951                                 if (is_self)
952                                         drawpic(pos - tmp, sbar_field_icon1, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon1_rgb, sbar_field_icon1_alpha * sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
953                                 else
954                                         drawpic(pos - tmp, sbar_field_icon1, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon1_rgb, sbar_field_icon1_alpha * sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
955                         if(sbar_field_icon2 != "")
956                                 if (is_self)
957                                         drawpic(pos - tmp, sbar_field_icon2, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon2_rgb, sbar_field_icon2_alpha * sbar_scoreboard_alpha_name_self, DRAWFLAG_NORMAL);
958                                 else
959                                         drawpic(pos - tmp, sbar_field_icon2, '0 1 0' * sbar_fontsize_y + '1 0 0' * sbar_fontsize_x * sbar_fixscoreboardcolumnwidth_iconlen, sbar_field_icon2_rgb, sbar_field_icon2_alpha * sbar_scoreboard_alpha_name, DRAWFLAG_NORMAL);
960                         pos_x -= sbar_fontsize_x*sbar_size[i] + sbar_fontsize_x;
961                 }
962         }
963 }
964
965 /*
966  * Sbar_Scoreboard_MakeTable
967  *
968  * Makes a table for a team (for all playing players in DM) and fills it
969  */
970
971 vector Sbar_Scoreboard_MakeTable(vector pos, entity tm, vector rgb, vector bg_size)
972 {
973         float body_table_height, i;
974         vector tmp, column_dim;
975         entity pl;
976
977         body_table_height = 1.25 * sbar_fontsize_y * max(1, tm.team_size); // no player? show 1 empty line
978
979         pos -= '1 1 0';
980
981         tmp_x = sbwidth + 2;
982         tmp_y = 1.25 * sbar_fontsize_y;
983
984         // rounded header
985         drawpic(pos, "gfx/hud/sb_scoreboard_tableheader", tmp, '0.5 0.5 0.5', sbar_scoreboard_alpha_bg, DRAWFLAG_NORMAL);
986
987         // table border
988         tmp_y += sbar_border_thickness;
989         tmp_y += body_table_height;
990         drawborderlines(sbar_border_thickness, pos, tmp, '0 0 0', sbar_scoreboard_alpha_bg, DRAWFLAG_NORMAL); // more transparency for the scoreboard
991
992         // separator header/table
993         pos_y += 1.25 * sbar_fontsize_y;
994         tmp_y = sbar_border_thickness;
995         drawfill(pos, tmp, '0 0 0', sbar_scoreboard_alpha_bg, DRAWFLAG_NORMAL);
996
997         pos_y += sbar_border_thickness;
998
999         // table background
1000         tmp_y = body_table_height;
1001         drawpic_tiled(pos, "gfx/hud/sb_scoreboard_bg", bg_size, tmp, rgb * sbar_color_bg_team, sbar_scoreboard_alpha_bg, DRAWFLAG_NORMAL);
1002
1003         // anyway, apply some color
1004         //drawfill(pos, tmp + '2 0 0', rgb, 0.1, DRAWFLAG_NORMAL);
1005
1006         // go back to the top to make alternated columns highlighting and to print the strings
1007         pos_y -= 1.25 * sbar_fontsize_y;
1008         pos_y -= sbar_border_thickness;
1009
1010         pos += '1 1 0';
1011
1012         if (sbar_scoreboard_highlight)
1013         {
1014                 column_dim_y = 1.25 * sbar_fontsize_y; // header
1015                 column_dim_y += sbar_border_thickness;
1016                 column_dim_y += body_table_height;
1017         }
1018
1019         // print the strings of the columns headers and draw the columns
1020         for(i = 0; i < sbar_num_fields; ++i)
1021         {
1022                 if(sbar_field[i] == SP_SEPARATOR)
1023                         break;
1024                 column_dim_x = sbar_fontsize_x*sbar_size[i] + sbar_fontsize_x;
1025                 if (sbar_scoreboard_highlight)
1026                 {
1027                         if (mod(i,2))
1028                                 drawfill(pos - '0 1 0' - sbar_fontsize_x / 2 * '1 0 0', column_dim, '0 0 0', sbar_scoreboard_alpha_bg * 0.2, DRAWFLAG_NORMAL);
1029                 }
1030                 drawstring(pos, sbar_title[i], sbar_fontsize, rgb, sbar_scoreboard_alpha_fg, DRAWFLAG_NORMAL);
1031                 pos_x += column_dim_x;
1032         }
1033         if(sbar_field[i] == SP_SEPARATOR)
1034         {
1035                 pos_x = xmax;
1036                 tmp_y = 0;
1037                 for(i = sbar_num_fields-1; i > 0; --i)
1038                 {
1039                         if(sbar_field[i] == SP_SEPARATOR)
1040                                 break;
1041
1042                         pos_x -= sbar_size[i]*sbar_fontsize_x;
1043
1044                         if (sbar_scoreboard_highlight)
1045                         {
1046                                 if (!mod(i,2))
1047                                 {
1048                                         if (i == sbar_num_fields-1)
1049                                                 column_dim_x = sbar_fontsize_x*sbar_size[i] + sbar_fontsize_x / 2 + 1;
1050                                         else
1051                                                 column_dim_x = sbar_fontsize_x*sbar_size[i] + sbar_fontsize_x;
1052                                         drawfill(pos - '0 1 0' - sbar_fontsize_x / 2 * '1 0 0', column_dim, '0 0 0', sbar_scoreboard_alpha_bg * 0.2, DRAWFLAG_NORMAL);
1053                                 }
1054                         }
1055
1056                         tmp_x = stringwidth(sbar_title[i], FALSE);
1057                         tmp_x = (sbar_size[i] - tmp_x) * sbar_fontsize_x;
1058                         drawstring(pos + tmp, sbar_title[i], sbar_fontsize, rgb, sbar_scoreboard_alpha_fg, DRAWFLAG_NORMAL);
1059                         pos_x -= sbar_fontsize_x;
1060                 }
1061         }
1062         
1063         pos_x = xmin;
1064         pos_y += 1.25 * sbar_fontsize_y; // skip the header
1065         pos_y += sbar_border_thickness;
1066
1067         // fill the table and draw the rows
1068         i = 0;
1069         if (teamplay)
1070                 for(pl = players.sort_next; pl; pl = pl.sort_next)
1071                 {
1072                         if(pl.team != tm.team)
1073                                 continue;
1074                         Sbar_PrintScoreboardItem(pos, pl, (pl.sv_entnum == player_localentnum - 1), i);
1075                         pos_y += 1.25 * sbar_fontsize_y;
1076                         ++i;
1077                 }
1078         else
1079                 for(pl = players.sort_next; pl; pl = pl.sort_next)
1080                 {
1081                         if(pl.team == COLOR_SPECTATOR)
1082                                 continue;
1083                         Sbar_PrintScoreboardItem(pos, pl, (pl.sv_entnum == player_localentnum - 1), i);
1084                         pos_y += 1.25 * sbar_fontsize_y;
1085                         ++i;
1086                 }
1087         
1088         if (i == 0)
1089                 pos_y += 1.25 * sbar_fontsize_y; // move to the end of the table
1090         pos_y += 1.25 * sbar_fontsize_y; // move empty row (out of the table)
1091
1092         return pos;
1093 }
1094
1095 float Sbar_WouldDrawScoreboard() {
1096         if (sb_showscores)
1097                 return 1;
1098         else if (intermission == 1)
1099                 return 1;
1100         else if (intermission == 2)
1101                 return 1;
1102         else if (getstati(STAT_HEALTH) <= 0 && cvar("cl_deathscoreboard"))
1103                 return 1;
1104         else if(sb_showscores_force)
1105                 return 1;
1106         return 0;
1107 }
1108
1109 float lastpingstime;
1110 float scoreboard_bottom;
1111 float sbar_scoreboard_fade_alpha;
1112 float sbar_woulddrawscoreboard_prev;
1113 float sbar_woulddrawscoreboard_change; // "time" at which Sbar_WouldDrawScoreboard() changed
1114 void Sbar_DrawScoreboard()
1115 {
1116         float sbar_woulddrawscoreboard; 
1117         sbar_woulddrawscoreboard = Sbar_WouldDrawScoreboard();
1118         if(sbar_woulddrawscoreboard != sbar_woulddrawscoreboard_prev) {
1119                 sbar_woulddrawscoreboard_change = time;
1120                 sbar_woulddrawscoreboard_prev = sbar_woulddrawscoreboard;
1121         }
1122
1123         float scoreboard_fadeinspeed = cvar_or("sbar_scoreboard_fadeinspeed", 10);
1124         float scoreboard_fadeoutspeed = cvar_or("sbar_scoreboard_fadeoutspeed", 5);
1125         if(sbar_woulddrawscoreboard) {
1126                 if (scoreboard_fadeinspeed)
1127                         sbar_scoreboard_fade_alpha = bound (0, (time - sbar_woulddrawscoreboard_change) * scoreboard_fadeinspeed, 1);
1128                 else
1129                         sbar_scoreboard_fade_alpha = 1;
1130         }
1131         else
1132                 if (scoreboard_fadeoutspeed)
1133                         sbar_scoreboard_fade_alpha = bound (0, (1/scoreboard_fadeoutspeed - (time - sbar_woulddrawscoreboard_change)) * scoreboard_fadeoutspeed, 1);
1134                 else
1135                         sbar_scoreboard_fade_alpha = 0;
1136
1137         if not(sbar_scoreboard_fade_alpha)
1138                 return;
1139                 
1140         sbar_scoreboard_alpha_bg = cvar("sbar_scoreboard_alpha_bg") * sbar_scoreboard_fade_alpha;
1141         sbar_scoreboard_alpha_fg = cvar_or("sbar_scoreboard_alpha_fg", 1.0) * sbar_scoreboard_fade_alpha;
1142         sbar_scoreboard_highlight = cvar("sbar_scoreboard_highlight");
1143         sbar_scoreboard_highlight_alpha = cvar_or("sbar_scoreboard_highlight_alpha", 0.10) * sbar_scoreboard_alpha_fg;
1144         sbar_scoreboard_highlight_alpha_self = cvar_or("sbar_scoreboard_highlight_alpha_self", 0.25) * sbar_scoreboard_alpha_fg;
1145         sbar_scoreboard_alpha_name = cvar_or("sbar_scoreboard_alpha_name", 0.9) * sbar_scoreboard_alpha_fg;
1146         sbar_scoreboard_alpha_name_self = cvar_or("sbar_scoreboard_alpha_name_self", 1) * sbar_scoreboard_alpha_fg;
1147         
1148         vector rgb, pos, tmp;
1149         entity pl, tm;
1150
1151         if(time > lastpingstime + bound(1, cvar_or("sbar_pingrefreshinterval", 10), 60)) {
1152                 localcmd("pings\n");
1153                 lastpingstime = time;
1154         }
1155
1156         sbwidth = Sbar_GetWidth(6.5 * sbar_fontsize_y);
1157
1158         xmin = 0.5 * (vid_conwidth - sbwidth);
1159         ymin = SCOREBOARD_OFFSET;
1160
1161         xmax = vid_conwidth - xmin;
1162         ymax = vid_conheight - 0.2*vid_conheight;
1163
1164         // Initializes position
1165         pos_x = xmin;
1166         pos_y = ymin;
1167         pos_z = 0;
1168
1169         // Heading
1170         drawfont = sbar_bigfont;
1171         drawstringcenter('0 1 0' * ymin, "Scoreboard", '24 24 0', '1 1 1', sbar_scoreboard_alpha_fg, DRAWFLAG_NORMAL);
1172
1173         pos_y += 24 + 4;
1174         pos_y += sbar_fontsize_y;
1175
1176         drawfont = sbar_font;
1177         
1178         // Draw the scoreboard
1179         vector bg_size;
1180         bg_size = drawgetimagesize("gfx/hud/sb_scoreboard_bg");
1181
1182         if(teamplay)
1183         {
1184                 for(tm = teams.sort_next; tm; tm = tm.sort_next)
1185                 {
1186                         if(tm.team == COLOR_SPECTATOR)
1187                                 continue;
1188
1189                         rgb = GetTeamRGB(tm.team);
1190                         Sbar_DrawXNum(pos - '6.5 0 0' * sbar_fontsize_y + '0 1 0' * sbar_fontsize_y, tm.(teamscores[ts_primary]), 4, 0, sbar_fontsize_y * 1.5, rgb, 0, 1, sbar_scoreboard_alpha_fg, DRAWFLAG_NORMAL);
1191                                 
1192                         if(ts_primary != ts_secondary)
1193                                 Sbar_DrawXNum(pos - '4.5 0 0' * sbar_fontsize_y + '0 2.5 0' * sbar_fontsize_y, tm.(teamscores[ts_secondary]), 4, 0, sbar_fontsize_y * 1, rgb, 0, 1, sbar_scoreboard_alpha_fg, DRAWFLAG_NORMAL);
1194
1195                         pos = Sbar_Scoreboard_MakeTable(pos, tm, rgb, bg_size);
1196                 }
1197         }
1198         else
1199         {
1200                 rgb_x = cvar("sbar_color_bg_r");
1201                 rgb_y = cvar("sbar_color_bg_g");
1202                 rgb_z = cvar("sbar_color_bg_b");
1203
1204                 for(tm = teams.sort_next; tm; tm = tm.sort_next)
1205                 {
1206                         if(tm.team == COLOR_SPECTATOR)
1207                                 continue;
1208
1209                         pos = Sbar_Scoreboard_MakeTable(pos, tm, rgb, bg_size);
1210                 }
1211         }
1212
1213         tmp = pos + '0 1.5 0' * sbar_fontsize_y;
1214         pos_y += 3 * sbar_fontsize_y;
1215         
1216         // List spectators
1217         float specs;
1218         specs = 0;
1219         for(pl = players.sort_next; pl; pl = pl.sort_next)
1220         {
1221                 if(pl.team != COLOR_SPECTATOR)
1222                         continue;
1223                 Sbar_PrintScoreboardItem(pos, pl, (pl.sv_entnum == player_localentnum - 1), specs);
1224                 pos_y += 1.25 * sbar_fontsize_y;
1225                 ++specs;
1226         }
1227
1228         if(specs)
1229                 drawstring(tmp, "Spectators", sbar_fontsize, '1 1 1', sbar_scoreboard_alpha_fg, DRAWFLAG_NORMAL);
1230
1231         // Print info string
1232         string str;
1233         float tl, fl, ll;
1234         str = strcat("playing on ^2", shortmapname, "^7");
1235         tl = getstatf(STAT_TIMELIMIT);
1236         fl = getstatf(STAT_FRAGLIMIT);
1237         ll = getstatf(STAT_LEADLIMIT);
1238         if(gametype == GAME_LMS)
1239         {
1240                 if(tl > 0)
1241                         str = strcat(str, " for up to ^1", ftos(tl), " minutes^7");
1242         }
1243         else
1244         {
1245                 if(tl > 0)
1246                         str = strcat(str, " for ^1", ftos(tl), " minutes^7");
1247                 if(fl > 0)
1248                 {
1249                         if(tl > 0)
1250                                 str = strcat(str, " or");
1251                         if(teamplay)
1252                         {
1253                                 str = strcat(str, " until ^3", ScoreString(teamscores_flags[ts_primary], fl));
1254                                 if(teamscores_label[ts_primary] == "score")
1255                                         str = strcat(str, " points^7");
1256                                 else if(teamscores_label[ts_primary] == "fastest")
1257                                         str = strcat(str, " is beaten^7");
1258                                 else
1259                                         str = strcat(str, " ", teamscores_label[ts_primary]);
1260                         }
1261                         else
1262                         {
1263                                 str = strcat(str, " until ^3", ScoreString(scores_flags[ps_primary], fl));
1264                                 if(scores_label[ps_primary] == "score")
1265                                         str = strcat(str, " points^7");
1266                                 else if(scores_label[ps_primary] == "fastest")
1267                                         str = strcat(str, " is beaten^7");
1268                                 else
1269                                         str = strcat(str, " ", scores_label[ps_primary]);
1270                         }
1271                 }
1272                 if(ll > 0)
1273                 {
1274                         if(tl > 0 || fl > 0)
1275                                 str = strcat(str, " or");
1276                         if(teamplay)
1277                         {
1278                                 str = strcat(str, " until a lead of ^3", ScoreString(teamscores_flags[ts_primary], ll));
1279                                 if(teamscores_label[ts_primary] == "score")
1280                                         str = strcat(str, " points^7");
1281                                 else if(teamscores_label[ts_primary] == "fastest")
1282                                         str = strcat(str, " is beaten^7");
1283                                 else
1284                                         str = strcat(str, " ", teamscores_label[ts_primary]);
1285                         }
1286                         else
1287                         {
1288                                 str = strcat(str, " until a lead of ^3", ScoreString(scores_flags[ps_primary], ll));
1289                                 if(scores_label[ps_primary] == "score")
1290                                         str = strcat(str, " points^7");
1291                                 else if(scores_label[ps_primary] == "fastest")
1292                                         str = strcat(str, " is beaten^7");
1293                                 else
1294                                         str = strcat(str, " ", scores_label[ps_primary]);
1295                         }
1296                 }
1297         }
1298
1299
1300         pos_y += 1.2 * sbar_fontsize_y;
1301         drawcolorcodedstring(pos + '0.5 0 0' * (sbwidth - sbar_fontsize_x * stringwidth(str, TRUE)), str, sbar_fontsize, sbar_scoreboard_alpha_fg, DRAWFLAG_NORMAL);
1302
1303         scoreboard_bottom = pos_y + 2 * sbar_fontsize_y;
1304 }
1305
1306 string MakeRaceString(float cp, float mytime, float histime, float lapdelta, string hisname)
1307 {
1308         string col;
1309         string timestr;
1310         string cpname;
1311         string lapstr;
1312         lapstr = "";
1313
1314         if(histime == 0) // goal hit
1315         {
1316                 if(mytime > 0)
1317                 {
1318                         timestr = strcat("+", ftos_decimals(+mytime, TIME_DECIMALS));
1319                         col = "^1";
1320                 }
1321                 else if(mytime == 0)
1322                 {
1323                         timestr = "+0.0";
1324                         col = "^3";
1325                 }
1326                 else
1327                 {
1328                         timestr = strcat("-", ftos_decimals(-mytime, TIME_DECIMALS));
1329                         col = "^2";
1330                 }
1331
1332                 if(lapdelta > 0)
1333                 {
1334                         lapstr = strcat(" (-", ftos(lapdelta), "L)");
1335                         col = "^2";
1336                 }
1337                 else if(lapdelta < 0)
1338                 {
1339                         lapstr = strcat(" (+", ftos(-lapdelta), "L)");
1340                         col = "^1";
1341                 }
1342         }
1343         else if(histime > 0) // anticipation
1344         {
1345                 if(mytime >= histime)
1346                         timestr = strcat("+", ftos_decimals(mytime - histime, TIME_DECIMALS));
1347                 else
1348                         timestr = TIME_ENCODED_TOSTRING(TIME_ENCODE(histime));
1349                 col = "^3";
1350         }
1351         else
1352                 col = "^7";
1353
1354         if(cp == 254)
1355                 cpname = "Start line";
1356         else if(cp == 255)
1357                 cpname = "Finish line";
1358         else if(cp)
1359                 cpname = strcat("Intermediate ", ftos(cp));
1360         else
1361                 cpname = "Finish line";
1362
1363         if(histime < 0)
1364                 return strcat(col, cpname);
1365         else if(hisname == "")
1366                 return strcat(col, cpname, " (", timestr, ")");
1367         else
1368                 return strcat(col, cpname, " (", timestr, " ", strcat(hisname, col, lapstr), ")");
1369 }
1370
1371 void Sbar_Score()
1372 {
1373         float score, distribution, leader;
1374         vector score_pos, secondary_score_pos, distribution_color;
1375         entity tm, pl, me;
1376         me = (spectatee_status > 0) ? playerslots[spectatee_status - 1] : playerslots[player_localentnum - 1];
1377
1378         vector bottomright;
1379         bottomright_x = vid_conwidth;
1380         bottomright_y = vid_conheight;
1381         bottomright_z = 0;
1382
1383         score_pos = bottomright - '196 42 0';
1384         secondary_score_pos = score_pos + '132 -6 0';
1385
1386         if((scores_flags[ps_primary] & SFL_TIME) && !teamplay) { // race/cts record display on HUD
1387                 pl = players.sort_next;
1388                 if(pl == me)
1389                         pl = pl.sort_next;
1390                 if(scores_flags[ps_primary] & SFL_ZERO_IS_WORST)
1391                         if(pl.scores[ps_primary] == 0)
1392                                 pl = world;
1393
1394                 score = me.(scores[ps_primary]);
1395
1396                 float racemin, racesec, racemsec;
1397                 float distsec, distmsec, minusplus;
1398                 
1399                 racemin = floor(score/(60 * TIME_FACTOR));
1400                 racesec = floor((score - racemin*(60 * TIME_FACTOR))/TIME_FACTOR);
1401                 racemsec = score - racemin*60*TIME_FACTOR - racesec*TIME_FACTOR;
1402
1403                 if (pl && ((!(scores_flags[ps_primary] & SFL_ZERO_IS_WORST)) || score)) {
1404                         // distribution display
1405                         distribution = me.(scores[ps_primary]) - pl.(scores[ps_primary]);
1406
1407                         if (distribution < TIME_FACTOR && distribution > -TIME_FACTOR)
1408                                 distmsec = fabs(distribution);
1409                         else {
1410                                 distsec = floor(fabs(distribution)/TIME_FACTOR);
1411                                 distmsec = fabs(distribution) - distsec*TIME_FACTOR;
1412                                 if (distribution < 0)
1413                                         distsec = -distsec;
1414                         }
1415
1416                         if (distribution <= 0) {
1417                                 distribution_color = '0 1 0';
1418                                 minusplus = 1; // minusplus 1: always prefix with minus sign
1419                         }
1420                         else {
1421                                 distribution_color = '1 0 0';
1422                                 minusplus = 2; // minusplus 1: always prefix with plus sign
1423                         }
1424                         Sbar_DrawXNum(bottomright - '0 48 0' - '16 0 0' * TIME_DECIMALS, distmsec, -TIME_DECIMALS, 0, 16, distribution_color, 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1425                         Sbar_DrawXNum(bottomright - '68 48 0' - '16 0 0' * TIME_DECIMALS, distsec, 4, minusplus, 16, distribution_color, 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1426                         drawpic(bottomright - '10 48 0' - '16 0 0' * TIME_DECIMALS, "gfx/hud/num_dot", '16 16 0', distribution_color, sbar_alpha_fg, DRAWFLAG_ADDITIVE);
1427                 }
1428                 // race record display
1429                 if (distribution <= 0 || distribution == score) // draw the highlight background behind the timer if we have the lead
1430                         drawpic(bottomright - '0 32 0' - '32 0 0' * (4 + TIME_DECIMALS), "gfx/hud/sb_highlight_4", '0 28 0' + '32 0 0' * (4 + TIME_DECIMALS), '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
1431
1432                 Sbar_DrawXNum(bottomright - '0 32 0' - TIME_DECIMALS * '30 0 0', racemsec, -TIME_DECIMALS, 0, 30, '1 1 1', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1433                 Sbar_DrawXNum(bottomright - '0 32 0' - TIME_DECIMALS * '30 0 0'  - '66 0 0', racesec, -2, 0, 30, '1 1 1', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1434                 drawpic(bottomright - '0 32 0' - TIME_DECIMALS * '30 0 0' - '18 0 0', "gfx/hud/num_dot", '30 30 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_ADDITIVE);
1435
1436                 Sbar_DrawXNum(bottomright - '0 32 0' - TIME_DECIMALS * '30 0 0' - '132 0 0', racemin, -2, 0, 30, '1 1 1', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1437                 drawpic(bottomright - '0 32 0' - TIME_DECIMALS * '30 0 0' - '84 0 0', "gfx/hud/num_colon", '30 30 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_ADDITIVE);
1438
1439         } else if (!teamplay) { // non-teamgames, except race/cts
1440                 // me vector := [team/connected frags id]
1441                 pl = players.sort_next;
1442                 if(pl == me)
1443                         pl = pl.sort_next;
1444
1445                 if(pl)
1446                         distribution = me.(scores[ps_primary]) - pl.(scores[ps_primary]);
1447                 else
1448                         distribution = 0;
1449
1450                 score = me.(scores[ps_primary]);
1451                 
1452                 if(distribution >= 5) {
1453                         distribution_color = '0 1 0';
1454                         leader = 1;
1455                 } else if(distribution >= 0) {
1456                         distribution_color = '1 1 1';
1457                         leader = 1;
1458                 } else if(distribution >= -5)
1459                         distribution_color = '1 1 0';
1460                 else
1461                         distribution_color = '1 0 0';
1462                 
1463                 Sbar_DrawXNum(secondary_score_pos, distribution, 4, 3, 16, distribution_color, 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1464                 Sbar_DrawXNum(score_pos, score, 4, 0, 34, distribution_color, leader, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1465         } else { // teamgames
1466                 float max_fragcount;
1467                 max_fragcount = -999;
1468
1469                 for(tm = teams.sort_next; tm; tm = tm.sort_next) {
1470                         if(tm.team == COLOR_SPECTATOR || !tm.team_size) // no players? don't display
1471                                 continue;
1472                         score = tm.(teamscores[ts_primary]);
1473                         leader = 0;
1474
1475                         if (score > max_fragcount)
1476                                 max_fragcount = score;
1477         
1478                         if(tm.team == myteam) {
1479                                 if (max_fragcount == score)
1480                                         leader = 1;
1481                                 Sbar_DrawXNum(score_pos, score, 4, 0, 34, GetTeamRGB(tm.team) * 0.8, leader, 1, sbar_alpha_fg, DRAWFLAG_NORMAL);
1482                         } else {
1483                                 if (max_fragcount == score)
1484                                         leader = 1;
1485                                 Sbar_DrawXNum(secondary_score_pos, score, 4, 0, 16, GetTeamRGB(tm.team) * 0.8, leader, 1, sbar_alpha_fg, DRAWFLAG_NORMAL);
1486                                 secondary_score_pos = secondary_score_pos + '0 16 0';
1487                         }
1488                 }
1489         }
1490
1491         if(gametype == GAME_RACE || gametype == GAME_CTS)
1492         {
1493                 drawfont = sbar_bigfont;
1494                 float a, t;
1495                 vector m;
1496                 string s, forcetime;
1497
1498                 m = '0.5 0 0' * vid_conwidth + '0 0.25 0' * vid_conheight;
1499
1500                 if(race_checkpointtime)
1501                 {
1502                         a = bound(0, 2 - (time - race_checkpointtime), 1);
1503                         s = "";
1504                         forcetime = "";
1505                         if(a > 0) // just hit a checkpoint?
1506                         {
1507                                 if(race_checkpoint != 254)
1508                                 {
1509                                         if(race_time && race_previousbesttime)
1510                                                 s = MakeRaceString(race_checkpoint, TIME_DECODE(race_time) - TIME_DECODE(race_previousbesttime), 0, 0, race_previousbestname);
1511                                         else
1512                                                 s = MakeRaceString(race_checkpoint, 0, -1, 0, race_previousbestname);
1513                                         if(race_time)
1514                                                 forcetime = TIME_ENCODED_TOSTRING(race_time);
1515                                 }
1516                         }
1517                         else
1518                         {
1519                                 if(race_laptime && race_nextbesttime && race_nextcheckpoint != 254)
1520                                 {
1521                                         a = bound(0, 2 - ((race_laptime + TIME_DECODE(race_nextbesttime)) - (time + TIME_DECODE(race_penaltyaccumulator))), 1);
1522                                         if(a > 0) // next one?
1523                                         {
1524                                                 s = MakeRaceString(race_nextcheckpoint, (time + TIME_DECODE(race_penaltyaccumulator)) - race_laptime, TIME_DECODE(race_nextbesttime), 0, race_nextbestname);
1525                                         }
1526                                 }
1527                         }
1528
1529                         if(s != "" && a > 0)
1530                         {
1531                                 dummyfunction(0, 0, 0, 0, 0, 0, 0, 0); // work around DP bug (set OFS_PARAM5 to 0)
1532                                 drawcolorcodedstring(m - '0 16 0' - '8 0 0' * stringwidth(s, TRUE), s, '16 16 0', sbar_alpha_fg * a, DRAWFLAG_NORMAL);
1533                         }
1534
1535                         if(race_penaltytime)
1536                         {
1537                                 a = bound(0, 2 - (time - race_penaltyeventtime), 1);
1538                                 if(a > 0)
1539                                 {
1540                                         s = strcat("^1PENALTY: ", ftos_decimals(race_penaltytime * 0.1, 1), " (", race_penaltyreason, ")");
1541                                         dummyfunction(0, 0, 0, 0, 0, 0, 0, 0); // work around DP bug (set OFS_PARAM5 to 0)
1542                                         drawcolorcodedstring(m - '0 32 0' - '8 0 0' * stringwidth(s, TRUE), s, '16 16 0', sbar_alpha_fg * a, DRAWFLAG_NORMAL);
1543                                 }
1544                         }
1545
1546                         if(forcetime != "")
1547                         {
1548                                 a = bound(0, (time - race_checkpointtime) / 0.5, 1);
1549                                 drawstring_expanding(m - '16 0 0' * stringwidth(forcetime, FALSE), forcetime, '32 32 0', '1 1 1', sbar_alpha_fg, 0, a);
1550                         }
1551                         else
1552                                 a = 1;
1553
1554                         if(race_laptime && race_checkpoint != 255)
1555                         {
1556                                 s = TIME_ENCODED_TOSTRING(TIME_ENCODE(time + TIME_DECODE(race_penaltyaccumulator) - race_laptime));
1557                                 drawstring(m - '16 0 0' * stringwidth(s, FALSE), s, '32 32 0', '1 1 1', sbar_alpha_fg * a, DRAWFLAG_NORMAL);
1558                         }
1559                 }
1560                 else
1561                 {
1562                         if(race_mycheckpointtime)
1563                         {
1564                                 a = bound(0, 2 - (time - race_mycheckpointtime), 1);
1565                                 s = MakeRaceString(race_mycheckpoint, TIME_DECODE(race_mycheckpointdelta), -!race_mycheckpointenemy, race_mycheckpointlapsdelta, race_mycheckpointenemy);
1566                                 dummyfunction(0, 0, 0, 0, 0, 0, 0, 0); // work around DP bug (set OFS_PARAM5 to 0)
1567                                 drawcolorcodedstring(m - '0 16 0' - '8 0 0' * stringwidth(s, TRUE), s, '16 16 0', sbar_alpha_fg * a, DRAWFLAG_NORMAL);
1568                         }
1569                         if(race_othercheckpointtime && race_othercheckpointenemy != "")
1570                         {
1571                                 a = bound(0, 2 - (time - race_othercheckpointtime), 1);
1572                                 s = MakeRaceString(race_othercheckpoint, -TIME_DECODE(race_othercheckpointdelta), -!race_othercheckpointenemy, race_othercheckpointlapsdelta, race_othercheckpointenemy);
1573                                 dummyfunction(0, 0, 0, 0, 0, 0, 0, 0); // work around DP bug (set OFS_PARAM5 to 0)
1574                                 drawcolorcodedstring(m - '0 0 0' - '8 0 0' * stringwidth(s, TRUE), s, '16 16 0', sbar_alpha_fg * a, DRAWFLAG_NORMAL);
1575                         }
1576
1577                         if(race_penaltytime && !race_penaltyaccumulator)
1578                         {
1579                                 t = race_penaltytime * 0.1 + race_penaltyeventtime;
1580                                 a = bound(0, (1 + t - time), 1);
1581                                 if(a > 0)
1582                                 {
1583                                         if(time < t)
1584                                                 s = strcat("^1PENALTY: ", ftos_decimals(t - time, 1), " (", race_penaltyreason, ")");
1585                                         else
1586                                                 s = strcat("^2PENALTY: 0.0 (", race_penaltyreason, ")");
1587                                         dummyfunction(0, 0, 0, 0, 0, 0, 0, 0); // work around DP bug (set OFS_PARAM5 to 0)
1588                                         drawcolorcodedstring(m - '0 32 0' - '8 0 0' * stringwidth(s, TRUE), s, '16 16 0', sbar_alpha_fg * a, DRAWFLAG_NORMAL);
1589                                 }
1590                         }
1591                 }
1592
1593                 drawfont = sbar_font;
1594         }
1595 }
1596
1597 void Sbar_Timer()
1598 {
1599         float timelimit, elapsedTime, minutes, seconds, timeleft, minutesLeft, secondsLeft;
1600         vector bgpos, timer_color;
1601         bgpos = '0 0 0';
1602         
1603         vector topright;
1604         topright = '0 0 0';
1605         topright_x = vid_conwidth;
1606         
1607         timelimit = getstatf(STAT_TIMELIMIT);
1608         
1609         timeleft = max(0, timelimit * 60 + getstatf(STAT_GAMESTARTTIME) - time);
1610         timeleft = ceil(timeleft);
1611         minutesLeft = floor(timeleft / 60);
1612         secondsLeft = timeleft - minutesLeft*60;
1613
1614         if(minutesLeft >= 5 || warmup_stage || timelimit == 0) //don't use red or yellow in warmup or when there is no timelimit
1615                 timer_color = '1 1 1'; //white
1616         else if(minutesLeft >= 1)
1617                 timer_color = '1 1 0'; //yellow
1618         else
1619                 timer_color = '1 0 0'; //red
1620
1621         if (cvar("sbar_increment_maptime") || timelimit == 0 || warmup_stage) {
1622                 if (time < getstatf(STAT_GAMESTARTTIME)) {
1623                         //while restart is still active, show 00:00
1624                         minutes = seconds = 0;
1625                 } else {
1626                         elapsedTime = floor(time - getstatf(STAT_GAMESTARTTIME)); //127
1627                         minutes = floor(elapsedTime / 60);
1628                         seconds = elapsedTime - minutes*60;
1629                 }
1630                 if (minutes < 10)
1631                         bgpos_x = topright_x - 54 - 17 - 12;
1632                 else if (minutes < 100) // nudge the timer background left if more digits are drawn
1633                         bgpos_x = topright_x - 72 - 17 - 12;
1634                 else
1635                         bgpos_x = topright_x - 90 - 17 - 12;
1636                 bgpos_y = 0;
1637                 bgpos_z = 0;
1638         } else {
1639                 minutes = minutesLeft;
1640                 seconds = secondsLeft;
1641                 if (minutes == 0)
1642                 bgpos_x = topright_x - 36 - 7 - 12;
1643                 else if (minutes < 10) // nudge the timer background left if more digits are drawn
1644                         bgpos_x = topright_x - 54 - 17 - 12;
1645                 else if (minutes < 100)
1646                         bgpos_x = topright_x - 72 - 17 - 12;
1647                 else
1648                         bgpos_x = topright_x - 90 - 17 - 12;
1649                 bgpos_y = 0;
1650                 bgpos_z = 0;
1651         }
1652
1653         if (cvar("viewsize") <= 100) { // draw timer background when viewsize <= 100
1654                 if (teamplay)
1655                         drawpic(bgpos, "gfx/hud/sb_timerbg", '120 30 0', GetTeamRGB(myteam) * sbar_color_bg_team, sbar_alpha_bg, DRAWFLAG_NORMAL); // timer bg color = myteam color
1656                 else {
1657                         color_x = cvar("sbar_color_bg_r");
1658                         color_y = cvar("sbar_color_bg_g");
1659                         color_z = cvar("sbar_color_bg_b");
1660
1661                         drawpic(bgpos, "gfx/hud/sb_timerbg", '120 30 0', color, sbar_alpha_bg, DRAWFLAG_NORMAL);
1662                 }
1663         }
1664
1665         if(minutesLeft >= 1 || cvar("sbar_increment_maptime") || timelimit == 0 || warmup_stage) {
1666                 Sbar_DrawXNum(topright - '103 0 0' + '0 2 0', minutes, 3, 0, 18, timer_color, 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1667                 drawpic(topright - '53 0 0' + '0 1 0', "gfx/hud/num_colon", '18 18 0', timer_color, sbar_alpha_fg, DRAWFLAG_NORMAL);
1668         }
1669         Sbar_DrawXNum(topright - '36 0 0' - '3 0 0' + '0 2 0', seconds, -2, 0, 18, timer_color, 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1670 }
1671
1672 void CSQC_Strength_Timer() {
1673         vector pos;
1674         vector bottom;
1675
1676         bottom_x = vid_conwidth/2;
1677         bottom_y = vid_conheight;
1678         bottom_z = 0;
1679
1680         float stat_items, dt;
1681         stat_items = getstati(STAT_ITEMS);
1682         /*
1683         if not(stat_items & IT_STRENGTH)
1684                 if not(stat_items & IT_INVINCIBLE)
1685                         return;
1686         */
1687
1688         if (getstati(STAT_HEALTH) <= 0)
1689                 return;
1690
1691         vector picsize;
1692         float strength_time, invincibility_time, countdown_fontsize;
1693
1694         picsize = '22 22 0';
1695         countdown_fontsize = 18;
1696
1697         if (vid_conwidth >= 800)
1698                 pos = bottom + '192 -46 0';
1699         else
1700                 pos = bottom + '192 -94 0';
1701
1702         //strength
1703         strength_time = getstatf(STAT_STRENGTH_FINISHED);
1704         invincibility_time = getstatf(STAT_INVINCIBLE_FINISHED);
1705
1706         if (strength_time) {
1707                 dt = strength_time - time;
1708                 if(dt > 0)
1709                 {
1710                         if(dt < 5)
1711                         {
1712                                 drawpic_expanding_two(pos, "gfx/hud/sb_str", picsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_ADDITIVE,
1713                                         bound(0, (ceil(dt) - dt) / 0.5, 1));
1714                         }
1715                         else
1716                         {
1717                                 drawpic(pos, "gfx/hud/sb_str", picsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_ADDITIVE);
1718                         }
1719                         Sbar_DrawXNum(pos - '40 -2 0', ceil(dt), 2, 0, countdown_fontsize, '1 1 1', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1720                 }
1721                 else if(dt > -1)
1722                 {
1723                         drawpic_expanding(pos, "gfx/hud/sb_str", picsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_ADDITIVE,
1724                                 bound(0, -dt / 0.5, 1));
1725                 }
1726         }
1727
1728         //invincibility
1729         if (invincibility_time) {
1730                 dt = invincibility_time - time;
1731                 if(dt > 0)
1732                 {
1733                         if(dt < 5)
1734                         {
1735                                 drawpic_expanding_two(pos - '0 -22 0', "gfx/hud/sb_invinc", picsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_ADDITIVE,
1736                                         bound(0, (ceil(dt) - dt) / 0.5, 1));
1737                         }
1738                         else
1739                         {
1740                                 drawpic(pos - '0 -22 0', "gfx/hud/sb_invinc", picsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_ADDITIVE);
1741                         }
1742                         Sbar_DrawXNum(pos - '40 -24 0', ceil(dt), 2, 0, countdown_fontsize, '1 1 1', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
1743                 }
1744                 else if(dt > -1)
1745                 {
1746                         drawpic_expanding(pos - '0 -22 0', "gfx/hud/sb_invinc", picsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_ADDITIVE,
1747                                 bound(0, -dt / 0.5, 1));
1748                 }
1749         }
1750 }
1751
1752 #define CENTERPRINT_MAX_LINES 30
1753 string centerprint_messages[CENTERPRINT_MAX_LINES];
1754 float centerprint_width[CENTERPRINT_MAX_LINES];
1755 vector centerprint_start;
1756 float centerprint_expire;
1757 float centerprint_num;
1758 float centerprint_offset_hint;
1759 vector centerprint_fontsize;
1760
1761 void centerprint(string strMessage)
1762 {
1763         float i, j, n, hcount;
1764         string s;
1765
1766         centerprint_fontsize = Sbar_GetFontsize("scr_centersize");
1767
1768         centerprint_expire = min(centerprint_expire, time); // if any of the returns happens, this message will fade out
1769
1770         if(cvar("scr_centertime") <= 0)
1771                 return;
1772
1773         if(strMessage == "")
1774                 return;
1775
1776         // strip trailing newlines
1777         j = strlen(strMessage) - 1;
1778         while(substring(strMessage, j, 1) == "\n" && j >= 0)
1779                 j = j - 1;
1780         strMessage = substring(strMessage, 0, j + 1);
1781
1782         if(strMessage == "")
1783                 return;
1784
1785         // strip leading newlines and remember them, they are a hint that the message should be lower on the screen
1786         j = 0;
1787         while(substring(strMessage, j, 1) == "\n" && j < strlen(strMessage))
1788                 j = j + 1;
1789         strMessage = substring(strMessage, j, strlen(strMessage) - j);
1790         centerprint_offset_hint = j;
1791
1792         if(strMessage == "")
1793                 return;
1794
1795         // if we get here, we have a message. Initialize its height.
1796         centerprint_num = 0;
1797
1798         n = tokenizebyseparator(strMessage, "\n");
1799         i = hcount = 0;
1800         for(j = 0; j < n; ++j)
1801         {
1802                 getWrappedLine_remaining = argv(j);
1803                 while(getWrappedLine_remaining)
1804                 {
1805                         s = getWrappedLine(vid_conwidth * 0.75 / centerprint_fontsize_x, stringwidth_colors);
1806                         if(centerprint_messages[i])
1807                                 strunzone(centerprint_messages[i]);
1808                         centerprint_messages[i] = strzone(s);
1809                         centerprint_width[i] = stringwidth(s, TRUE);
1810                         ++i;
1811
1812                         // half height for empty lines looks better
1813                         if(s == "")
1814                                 hcount += 0.5;
1815                         else
1816                                 hcount += 1;
1817
1818                         if(i >= CENTERPRINT_MAX_LINES)
1819                                 break;
1820                 }
1821         }
1822
1823         float h, havail;
1824         h = centerprint_fontsize_y*hcount;
1825
1826         havail = vid_conheight;
1827         if(cvar("con_chatpos") < 0)
1828                 havail -= (-cvar("con_chatpos") + cvar("con_chat")) * cvar("con_chatsize"); // avoid overlapping chat
1829         if(havail > vid_conheight - 70)
1830                 havail = vid_conheight - 70; // avoid overlapping HUD
1831
1832         centerprint_start_x = 0;
1833
1834 #if 0
1835         float forbiddenmin, forbiddenmax, allowedmin, allowedmax, preferred;
1836
1837         // here, the centerprint would cover the crosshair. REALLY BAD.
1838         forbiddenmin = vid_conheight * 0.5 - h - 16;
1839         forbiddenmax = vid_conheight * 0.5 + 16;
1840
1841         allowedmin = scoreboard_bottom;
1842         allowedmax = havail - h;
1843         preferred = (havail - h)/2;
1844
1845
1846         // possible orderings (total: 4! / 4 = 6)
1847         //  allowedmin allowedmax forbiddenmin forbiddenmax
1848         //  forbiddenmin forbiddenmax allowedmin allowedmax
1849         if(allowedmax < forbiddenmin || allowedmin > forbiddenmax)
1850         {
1851                 // forbidden doesn't matter in this case
1852                 centerprint_start_y = bound(allowedmin, preferred, allowedmax);
1853         }
1854         //  allowedmin forbiddenmin allowedmax forbiddenmax
1855         else if(allowedmin < forbiddenmin && allowedmax < forbiddenmax)
1856         {
1857                 centerprint_start_y = bound(allowedmin, preferred, forbiddenmin);
1858         }
1859         //  allowedmin forbiddenmin forbiddenmax allowedmax
1860         else if(allowedmin < forbiddenmin)
1861         {
1862                 // make sure the forbidden zone is not covered
1863                 if(preferred > (forbiddenmin + forbiddenmax) * 0.5)
1864                         centerprint_start_y = bound(allowedmin, preferred, forbiddenmin);
1865                 else
1866                         centerprint_start_y = bound(forbiddenmax, preferred, allowedmin);
1867         }
1868         //  forbiddenmin allowedmin allowedmax forbiddenmax
1869         else if(allowedmax < forbiddenmax)
1870         {
1871                 // it's better to leave the allowed zone (overlap with scoreboard) than
1872                 // to cover the forbidden zone (crosshair)
1873                 if(preferred > (forbiddenmin + forbiddenmax) * 0.5)
1874                         centerprint_start_y = forbiddenmax;
1875                 else
1876                         centerprint_start_y = forbiddenmin;
1877         }
1878         //  forbiddenmin allowedmin forbiddenmax allowedmax
1879         else
1880         {
1881                 centerprint_start_y = bound(forbiddenmax, preferred, allowedmax);
1882         }
1883 #else
1884         centerprint_start_y =
1885                 min(
1886                         max(
1887                                 max(scoreboard_bottom, vid_conheight * 0.5 + 16),
1888                                 (havail - h)/2
1889                         ),
1890                         havail - h
1891                 );
1892 #endif
1893
1894         centerprint_num = i;
1895         centerprint_expire = time + cvar("scr_centertime");
1896 }
1897
1898 void Sbar_DrawCenterPrint (void)
1899 {
1900         float i;
1901         vector pos;
1902         string ts;
1903         float a;
1904
1905         //if(time > centerprint_expire)
1906         //      return;
1907
1908         //a = bound(0, 1 - 2 * (time - centerprint_expire), 1);
1909         a = bound(0, 1 - 4 * (time - centerprint_expire), 1);
1910         //sz = 1.2 / (a + 0.2);
1911
1912         if(a <= 0)
1913                 return;
1914
1915         pos = centerprint_start;
1916         for (i=0; i<centerprint_num; i = i + 1)
1917         {
1918                 pos_x = (vid_conwidth - centerprint_fontsize_x * centerprint_width[i]) * 0.5;
1919                 ts = centerprint_messages[i];
1920                 if (ts != "")
1921                 {
1922                         dummyfunction(0, 0, 0, 0, 0, 0, 0, 0); // work around DP bug (set OFS_PARAM5 to 0)
1923                         drawcolorcodedstring(pos, ts, centerprint_fontsize, a, DRAWFLAG_NORMAL);
1924                         //  - '0 0.5 0' * (sz - 1) * centerprint_fontsize_x - '0.5 0 0' * (sz - 1) * centerprint_width[i] * centerprint_fontsize_y, centerprint_fontsize * sz
1925                         pos_y = pos_y + centerprint_fontsize_y;
1926                 }
1927                 else
1928                         // half height for empty lines looks better
1929                         pos_y = pos_y + centerprint_fontsize_y * 0.5;
1930         }
1931 }
1932
1933 vector Sbar_DrawNoteLine(vector offset, string s)
1934 {
1935         dummyfunction(0, 0, 0, 0, 0, 0, 0, 0); // work around DP bug (set OFS_PARAM5 to 0)
1936         drawcolorcodedstring(
1937                 offset - sbar_fontsize_x * '1 0 0' * stringwidth(s, TRUE),
1938                 s,
1939                 sbar_fontsize,
1940                 sbar_alpha_fg,
1941                 0
1942         );
1943         return offset + sbar_fontsize_y * '0 1 0';
1944 }
1945
1946 void Sbar_DrawPressedKeys(void)
1947 {
1948         vector pos, bgsize;
1949         float pressedkeys;
1950
1951         pos = stov(cvar_string("cl_showpressedkeys_position"));
1952
1953         bgsize = '126 75 0';
1954
1955         pos = '1 0 0' * (vid_conwidth - bgsize_x) * pos_x
1956             + '0 1 0' * (vid_conheight - bgsize_y) * pos_y;
1957         pos -= '-15 -6 0'; // adjust to the origin of these numbers
1958
1959         pressedkeys = getstatf(STAT_PRESSED_KEYS);
1960         drawpic(pos + '-15   -6   0', "gfx/hud/keys/key_bg.tga",           bgsize, '1 1 1', 0.1 * sbar_alpha_fg, DRAWFLAG_NORMAL);
1961         drawpic(pos + ' 83.5  9   0', ((pressedkeys & KEY_CROUCH) ? "gfx/hud/keys/key_crouch_inv.tga" : "gfx/hud/keys/key_crouch.tga"), ' 24 24 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
1962         drawpic(pos + ' 32   -1.5 0', ((pressedkeys & KEY_FORWARD) ? "gfx/hud/keys/key_forward_inv.tga" : "gfx/hud/keys/key_forward.tga"),  ' 32 32 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
1963         drawpic(pos + '-11.5  9   0', ((pressedkeys & KEY_JUMP) ? "gfx/hud/keys/key_jump_inv.tga" : "gfx/hud/keys/key_jump.tga"),     ' 24 24 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
1964         drawpic(pos + ' -1   32   0', ((pressedkeys & KEY_LEFT) ? "gfx/hud/keys/key_left_inv.tga" : "gfx/hud/keys/key_left.tga"),     ' 32 32 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
1965         drawpic(pos + ' 32   32   0', ((pressedkeys & KEY_BACKWARD) ? "gfx/hud/keys/key_backward_inv.tga" : "gfx/hud/keys/key_backward.tga"), ' 32 32 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
1966         drawpic(pos + ' 65   32   0', ((pressedkeys & KEY_RIGHT) ? "gfx/hud/keys/key_right_inv.tga" : "gfx/hud/keys/key_right.tga"),    ' 32 32 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
1967 }
1968
1969 void Sbar_ShowSpeed(void)
1970 {
1971         vector numsize;
1972         float pos, conversion_factor;
1973         string speed, unit;
1974
1975         switch(cvar("cl_showspeed_unit"))
1976         {
1977                 default:
1978                 case 0:
1979                         unit = "";
1980                         conversion_factor = 1.0;
1981                         break;
1982                 case 1:
1983                         unit = " qu/s";
1984                         conversion_factor = 1.0;
1985                         break;
1986                 case 2:
1987                         unit = " m/s";
1988                         conversion_factor = 0.0254;
1989                         break;
1990                 case 3:
1991                         unit = " km/h";
1992                         conversion_factor = 0.0254 * 3.6;
1993                         break;
1994                 case 4:
1995                         unit = " mph";
1996                         conversion_factor = 0.0254 * 3.6 * 0.6213711922;
1997                         break;
1998                 case 5:
1999                         unit = " knots";
2000                         conversion_factor = 0.0254 * 1.943844492; // 1 m/s = 1.943844492 knots, because 1 knot = 1.852 km/h
2001                         break;
2002         }
2003
2004         if (cvar("cl_showspeed_z") == 1)
2005                 speed = strcat(ftos(floor( vlen(pmove_vel) * conversion_factor + 0.5 )), unit);
2006         else
2007                 speed = strcat(ftos(floor( vlen(pmove_vel - pmove_vel_z * '0 0 1') * conversion_factor + 0.5 )), unit);
2008
2009         numsize_x = numsize_y = cvar("cl_showspeed_size");
2010         pos = (vid_conheight - numsize_y) * cvar("cl_showspeed_position");
2011         
2012         drawfont = sbar_bigfont;
2013         drawstringcenter('1 0 0' + pos * '0 1 0', speed, numsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2014         drawfont = sbar_font;
2015 }
2016
2017 vector acc_prevspeed;
2018 float acc_prevtime;
2019 float acc_avg;
2020
2021 void Sbar_ShowAcceleration(void)
2022 {
2023         float acceleration, sz, scale, alpha, f;
2024         vector pos, top, rgb;
2025         top_x = vid_conwidth/2;
2026         top_y = 0;
2027
2028         f = time - acc_prevtime;
2029         if(cvar("cl_showacceleration_z"))
2030                 acceleration = (vlen(pmove_vel) - vlen(acc_prevspeed)) * (1 / f);
2031         else
2032                 acceleration = (vlen(pmove_vel - '0 0 1' * pmove_vel_z) - vlen(acc_prevspeed - '0 0 1' * acc_prevspeed_z)) * (1 / f);
2033         acc_prevspeed = pmove_vel;
2034         acc_prevtime = time;
2035
2036         f = bound(0, f * 10, 1);
2037         acc_avg = acc_avg * (1 - f) + acceleration * f;
2038         acceleration = acc_avg / getstatf(STAT_MOVEVARS_MAXSPEED);
2039
2040         pos = top - sz/2 * '0 1 0' + (cvar("cl_showacceleration_position") * vid_conheight) * '0 1 0';
2041
2042         sz = cvar("cl_showacceleration_size");
2043         scale = cvar("cl_showacceleration_scale");
2044         alpha = cvar("cl_showacceleration_alpha");
2045         if (cvar("cl_showacceleration_color_custom"))
2046                 rgb = stov(cvar_string("cl_showacceleration_color"));
2047         else {
2048                 rgb = '1 1 1';
2049                 if (acceleration < 0) {
2050                         rgb = '1 .5 .5' - '0 .5 .5' * bound(0, -acceleration * 0.2, 1);
2051                 } else if (acceleration > 0) {
2052                         rgb = '.5 1 .5' - '.5 0 .5' * bound(0, +acceleration * 0.2, 1);
2053                 }
2054         }
2055                 
2056         if (acceleration > 0)
2057                 drawpic(pos, "gfx/hud/accelerometer_gradient", acceleration * scale * '40 0 0' + sz * '0 1 0', rgb, alpha * sbar_alpha_fg, DRAWFLAG_NORMAL);
2058         else if (acceleration < 0)
2059                 drawpic(pos + acceleration * scale * '40 0 0', "gfx/hud/accelerometer_gradient", -acceleration * scale * '40 0 0' + sz * '0 1 0', rgb, alpha * sbar_alpha_fg, DRAWFLAG_NORMAL);
2060 }
2061
2062 void Sbar_DrawAccuracyStats_Description_Hitscan(vector position)
2063 {
2064         drawstring(position + '0 3 0' * sbar_fontsize_y, "Shots fired:", sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2065         drawstring(position + '0 5 0' * sbar_fontsize_y, "Shots hit:", sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2066         drawstring(position + '0 7 0' * sbar_fontsize_y, "Accuracy:", sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2067         drawstring(position + '0 9 0' * sbar_fontsize_y, "Shots missed:", sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2068 }
2069
2070 void Sbar_DrawAccuracyStats_Description_Splash(vector position)
2071 {
2072         drawstring(position + '0 3 0' * sbar_fontsize_y, "Maximum damage:", sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2073         drawstring(position + '0 5 0' * sbar_fontsize_y, "Actual damage:", sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2074         drawstring(position + '0 7 0' * sbar_fontsize_y, "Accuracy:", sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2075         drawstring(position + '0 9 0' * sbar_fontsize_y, "Damage wasted:", sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2076 }
2077
2078 void Sbar_DrawAccuracyStats()
2079 {
2080         float i, count_hitscan, count_splash, row;  // count is the number of 'colums'
2081         float weapon_hit, weapon_damage, weapon_stats;
2082         float left_border;  // position where the weapons start, the description is in the border
2083         vector fill_colour, fill_size;
2084         vector pos;
2085
2086         float col_margin = 20;  // pixels between the columns
2087         float row_margin = 20;  // pixels between the rows
2088
2089         fill_size_x = 5 * sbar_fontsize_x;  // width of the background
2090         fill_size_y = 10 * sbar_fontsize_y;  // height of the background
2091
2092         drawfont = sbar_bigfont;
2093         pos_x = 0;
2094         pos_y = SCOREBOARD_OFFSET;
2095         pos_z = 0;
2096         drawstringcenter(pos, "Weapon Accuracy", 2 * sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2097
2098         left_border = col_margin + 11 * sbar_fontsize_x;
2099
2100         drawfont = sbar_font;
2101
2102         if(warmup_stage)
2103         {
2104                 pos_y += 40;
2105                 if(mod(time, 1) >= 0.4)
2106                         drawstringcenter(pos, "Stats are not tracked during warmup stage", sbar_fontsize, '1 1 0', sbar_alpha_fg, DRAWFLAG_NORMAL);
2107
2108                 return;
2109         }
2110
2111         float top_border_hitscan = SCOREBOARD_OFFSET + 55;  // position where the hitscan row starts: pixels down the screen
2112         Sbar_DrawAccuracyStats_Description_Hitscan('1 0 0' * col_margin + '0 1 0' * top_border_hitscan);
2113
2114         float top_border_splash = SCOREBOARD_OFFSET + 175;  // position where the splash row starts: pixels down the screen
2115         Sbar_DrawAccuracyStats_Description_Splash('1 0 0' * col_margin + '0 1 0' * top_border_splash);
2116
2117         for(i = WEP_FIRST; i <= WEP_LAST; ++i)
2118         {
2119                 weapon_hit = weapon_hits[i];
2120                 weapon_damage = weapon_fired[i];
2121                 self = get_weaponinfo(i);
2122
2123                 //if ((weapon_number != 42))  // print them all :)
2124                 if (weapon_damage) {
2125                         if (self.weapon_type == WEP_TYPE_SPLASH) {
2126                                 weapon_stats = bound(0, rint(100 * weapon_hit / weapon_damage), 100);
2127
2128                                 fill_colour_x = 1 - 0.015 * weapon_stats;
2129                                 fill_colour_y = 1 - 0.015 * (100 - weapon_stats);
2130
2131                                 // how the background colour is calculated
2132                                 // %    red             green   red_2                   green_2
2133                                 // 0    1               0               1 - % * 0.015   1 - (100 - %) * 0.015
2134                                 // 10   0.85    0               1 - % * 0.015   1 - (100 - %) * 0.015
2135                                 // 20   0.70    0               1 - % * 0.015   1 - (100 - %) * 0.015
2136                                 // 30   0.55    0               1 - % * 0.015   1 - (100 - %) * 0.015
2137                                 // 40   0.40    0.10    1 - % * 0.015   1 - (100 - %) * 0.015
2138                                 // 50   0.25    0.25    1 - % * 0.015   1 - (100 - %) * 0.015
2139                                 // 60   0.10    0.40    1 - % * 0.015   1 - (100 - %) * 0.015
2140                                 // 70   0               0.55    1 - % * 0.015   1 - (100 - %) * 0.015
2141                                 // 80   0               0.70    1 - % * 0.015   1 - (100 - %) * 0.015
2142                                 // 90   0               0.85    1 - % * 0.015   1 - (100 - %) * 0.015
2143                                 // 100  0               1               1 - % * 0.015   1 - (100 - %) * 0.015
2144
2145                                 if ((left_border + count_splash * (fill_size_x + col_margin) + fill_size_x) >= vid_conwidth)
2146                                 {
2147                                         count_splash = 0;
2148                                         ++row;
2149                                         Sbar_DrawAccuracyStats_Description_Splash('1 0 0' * col_margin + '0 1 0' * (top_border_splash + row * (fill_size_y + row_margin)));
2150                                 }
2151
2152                                 pos_x = left_border + count_splash * (fill_size_x + col_margin);
2153                                 pos_y = top_border_splash + row * (fill_size_y + row_margin);
2154
2155                                 // background
2156                                 drawpic(pos, "gfx/hud/sb_accuracy", fill_size , fill_colour, sbar_alpha_bg, DRAWFLAG_NORMAL);
2157                                 drawborderlines(sbar_border_thickness, pos, fill_size, '0 0 0', sbar_alpha_bg, DRAWFLAG_NORMAL);
2158
2159                                 // the weapon
2160                                 drawpic(pos, strcat("gfx/hud/inv_weapon", ftos(i-1)), '1 0.5 0' * fill_size_x , '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2161
2162                                 // the amount of shots fired or max damage
2163                                 drawstringright(pos + '4.5 0 0' * sbar_fontsize_x + '0 3 0' * sbar_fontsize_y, ftos(weapon_damage), sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2164
2165                                 // the amount of hits or actual damage
2166                                 drawstringright(pos + '4.5 0 0' * sbar_fontsize_x + '0 5 0' * sbar_fontsize_y, ftos(weapon_hit), sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2167
2168                                 // the accuracy
2169                                 drawstringright(pos + '4.5 0 0' * sbar_fontsize_x + '0 7 0' * sbar_fontsize_y, strcat(ftos(weapon_stats),"%"), sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2170
2171                                 // the amount of shots missed or damage wasted
2172                                 drawstringright(pos + '4.5 0 0' * sbar_fontsize_x + '0 9 0' * sbar_fontsize_y, ftos(max(0, weapon_damage - weapon_hit)), sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2173
2174                                 ++count_splash;
2175                         } else if ((self.weapon_type == WEP_TYPE_HITSCAN) && (weapon_damage)) {
2176                                 weapon_stats = bound(0, rint(100 * weapon_hit / weapon_damage), 100);
2177
2178                                 fill_colour_x = 1 - 0.015 * weapon_stats;
2179                                 fill_colour_y = 1 - 0.015 * (100 - weapon_stats);
2180
2181                                 // how the background colour is calculated
2182                                 // %    red             green   red_2                   green_2
2183                                 // 0    1               0               1 - % * 0.015   1 - (100 - %) * 0.015
2184                                 // 10   0.850   0               1 - % * 0.015   1 - (100 - %) * 0.015
2185                                 // 20   0.70    0               1 - % * 0.015   1 - (100 - %) * 0.015
2186                                 // 30   0.55    0               1 - % * 0.015   1 - (100 - %) * 0.015
2187                                 // 40   0.40    0.10    1 - % * 0.015   1 - (100 - %) * 0.015
2188                                 // 50   0.25    0.25    1 - % * 0.015   1 - (100 - %) * 0.015
2189                                 // 60   0.10    0.40    1 - % * 0.015   1 - (100 - %) * 0.015
2190                                 // 70   0               0.55    1 - % * 0.015   1 - (100 - %) * 0.015
2191                                 // 80   0               0.70    1 - % * 0.015   1 - (100 - %) * 0.015
2192                                 // 90   0               0.85    1 - % * 0.015   1 - (100 - %) * 0.015
2193                                 // 100  0               1               1 - % * 0.015   1 - (100 - %) * 0.015
2194
2195                                 if ((left_border + count_hitscan * (fill_size_x + col_margin) + fill_size_x + cvar("stats_right_margin")) >= vid_conwidth)
2196                                 {
2197                                         count_hitscan = 0;
2198                                         ++row;
2199                                         Sbar_DrawAccuracyStats_Description_Hitscan('1 0 0' * col_margin + '0 1 0' * (top_border_hitscan + row * (fill_size_y + row_margin)));
2200                                 }
2201
2202                                 pos_x = left_border + count_hitscan * (fill_size_x + col_margin);
2203                                 pos_y = top_border_hitscan + row * (fill_size_y + row_margin);
2204
2205                                 // background
2206                                 drawpic(pos, "gfx/hud/sb_accuracy", fill_size , fill_colour, sbar_alpha_bg, DRAWFLAG_NORMAL);
2207                                 drawborderlines(sbar_border_thickness, pos, fill_size, '0 0 0', sbar_alpha_bg, DRAWFLAG_NORMAL);
2208
2209                                 // the weapon
2210                                 drawpic(pos, strcat("gfx/hud/inv_weapon", ftos(i-1)), '1 0.5 0' * fill_size_x , '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2211
2212                                 // the amount of shots fired or max damage
2213                                 drawstringright(pos + '4.5 0 0' * sbar_fontsize_x + '0 3 0' * sbar_fontsize_y, ftos(weapon_damage), sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2214
2215                                 // the amount of hits or actual damage
2216                                 drawstringright(pos + '4.5 0 0' * sbar_fontsize_x + '0 5 0' * sbar_fontsize_y, ftos(weapon_hit), sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2217
2218                                 // the accuracy
2219                                 drawstringright(pos + '4.5 0 0' * sbar_fontsize_x + '0 7 0' * sbar_fontsize_y, strcat(ftos(weapon_stats),"%"), sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2220
2221                                 // the amount of shots missed or damage wasted
2222                                 drawstringright(pos + '4.5 0 0' * sbar_fontsize_x + '0 9 0' * sbar_fontsize_y, ftos(max(0, weapon_damage - weapon_hit)), sbar_fontsize, '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2223
2224                                 ++count_hitscan;
2225                         }
2226                 }
2227         }
2228 }
2229
2230 void drawstringright(vector position, string text, vector scale, vector rgb, float alpha, float flag)
2231 {
2232         position_x -= 2 / 3 * strlen(text) * scale_x;
2233         drawstring(position, text, scale, rgb, alpha, flag);
2234 }
2235
2236 void drawstringcenter(vector position, string text, vector scale, vector rgb, float alpha, float flag)
2237 {
2238         position_x = 0.5 * (vid_conwidth - 0.6025 * strlen(text) * scale_x);
2239         drawstring(position, text, scale, rgb, alpha, flag);
2240 }
2241
2242 float GetAmmoStat(float i)
2243 {
2244         switch(i)
2245         {
2246                 case 0: return STAT_SHELLS;
2247                 case 1: return STAT_NAILS;
2248                 case 2: return STAT_ROCKETS;
2249                 case 3: return STAT_CELLS;
2250                 case 4: return STAT_FUEL;
2251                 default: return -1;
2252         }
2253 }
2254
2255 float GetAmmoItemCode(float i)
2256 {
2257         switch(i)
2258         {
2259                 case 0: return IT_SHELLS;
2260                 case 1: return IT_NAILS;
2261                 case 2: return IT_ROCKETS;
2262                 case 3: return IT_CELLS;
2263                 case 4: return IT_FUEL;
2264                 default: return -1;
2265         }
2266 }
2267
2268 string GetAmmoPicture(float i)
2269 {
2270         switch(i)
2271         {
2272                 case 0: return "gfx/hud/sb_shells";
2273                 case 1: return "gfx/hud/sb_bullets";
2274                 case 2: return "gfx/hud/sb_rocket";
2275                 case 3: return "gfx/hud/sb_cells";
2276                 case 4: return "gfx/hud/sb_fuel";
2277                 default: return "";
2278         }
2279 }
2280
2281 void Sbar_Reset (void)
2282 {
2283         // reset gametype specific icons
2284         if(gametype == GAME_KEYHUNT)
2285                 CSQC_kh_hudreset();
2286         else if(gametype == GAME_CTF)
2287                 CSQC_ctf_hudreset();
2288 }
2289
2290 void Sbar_Draw (void)
2291 {
2292         // vectors for top right, bottom right, bottom and bottom left corners
2293         vector topright;
2294         vector bottom;
2295         vector bottomright;
2296         vector bottomleft;
2297
2298         topright_x = vid_conwidth;
2299         topright_y = 0;
2300         topright_z = 0;
2301
2302         bottom_x = vid_conwidth/2;
2303         bottom_y = vid_conheight;
2304         bottom_z = 0;
2305
2306         bottomright_x = vid_conwidth;
2307         bottomright_y = vid_conheight;
2308         bottomright_z = 0;
2309
2310         bottomleft_x = 0;
2311         bottomleft_y = vid_conheight;
2312         bottomleft_z = 0;
2313
2314         sbar_alpha_bg = cvar("sbar_alpha_bg") * (1 - cvar("_menu_alpha"));
2315         sbar_border_thickness = bound(0, cvar("sbar_border_thickness"), 5);
2316         sbar_color_bg_team = cvar("sbar_color_bg_team");
2317
2318         float i;
2319         float weapon_stats;
2320         float x, fade;
2321         float stat_items, stat_weapons;
2322
2323         weapon_stats = getstati(STAT_DAMAGE_HITS);
2324         weapon_number = weapon_stats & 63;
2325         weapon_hits[weapon_number] = rint(weapon_stats / 64);
2326
2327         weapon_stats = getstati(STAT_DAMAGE_FIRED);
2328         weapon_number = weapon_stats & 63;
2329         weapon_fired[weapon_number] = rint(weapon_stats / 64);
2330
2331         vector o; o = '1 0 0' * vid_conwidth;
2332         o_y = 28; // move spectator text slightly down to prevent overlapping the timer
2333
2334         string s;
2335         vector pos;
2336         pos = '0 0 0';
2337
2338         sbar_fontsize = Sbar_GetFontsize("sbar_fontsize");
2339         sbar_fontsize_spec = Sbar_GetFontsize("sbar_fontsize_spec");
2340
2341         if(spectatee_status && !intermission)
2342         {
2343                 drawfont = sbar_bigfont;
2344                 if(spectatee_status == -1)
2345                         s = "^1Observing";
2346                 else
2347                         s = GetPlayerName(spectatee_status - 1);
2348                 // spectated player name between HUD and chat area, aligned to the left
2349                 pos_x = bottomleft_x;
2350                 pos_y = bottom_y - 50 - sbar_fontsize_spec_y;
2351                 s = textShortenToWidth(s, vid_conwidth/2.5/sbar_fontsize_spec_x, stringwidth_colors);
2352                 drawcolorcodedstring(pos, s, sbar_fontsize_spec, sbar_alpha_fg, DRAWFLAG_NORMAL);
2353                 drawfont = sbar_font;
2354
2355                 // spectator text in the upper right corner
2356                 if(spectatee_status == -1)
2357                         s = strcat("^1Press ^3", getcommandkey("primary fire", "+attack"), "^1 to spectate");
2358                 else
2359                         s = strcat("^1Press ^3", getcommandkey("primary fire", "+attack"), "^1 for another player");
2360                 o = Sbar_DrawNoteLine(o, s);
2361
2362                 if(spectatee_status == -1)
2363                         s = strcat("^1Use ^3", getcommandkey("next weapon", "weapnext"), "^1 or ^3", getcommandkey("previous weapon", "weapprev"), "^1 to change the speed");
2364                 else
2365                         s = strcat("^1Press ^3", getcommandkey("secondary fire", "+attack2"), "^1 to observe");
2366                 o = Sbar_DrawNoteLine(o, s);
2367
2368                 s = strcat("^1Press ^3", getcommandkey("server info", "+show_info"), "^1 for gamemode info");
2369                 o = Sbar_DrawNoteLine(o, s);
2370
2371                 if(gametype == GAME_ARENA)
2372                         s = "^1Wait for your turn to join";
2373                 else if(gametype == GAME_LMS)
2374                 {
2375                         entity sk;
2376                         sk = playerslots[player_localentnum - 1];
2377                         if(sk.(scores[ps_primary]) >= 666)
2378                                 s = "^1Match has already begun";
2379                         else if(sk.(scores[ps_primary]) > 0)
2380                                 s = "^1You have no more lives left";
2381                         else
2382                                 s = strcat("^1Press ^3", getcommandkey("jump", "+jump"), "^1 to join");
2383                 }
2384                 else
2385                         s = strcat("^1Press ^3", getcommandkey("jump", "+jump"), "^1 to join");
2386                 o = Sbar_DrawNoteLine(o, s);
2387
2388                 //show restart countdown:
2389                 if (time < getstatf(STAT_GAMESTARTTIME)) {
2390                         float countdown;
2391                         //we need to ceil, otherwise the countdown would be off by .5 when using round()
2392                         countdown = ceil(getstatf(STAT_GAMESTARTTIME) - time);
2393                         s = strcat("^1Game starts in ^3", ftos(countdown), "^1 seconds");
2394                         o = Sbar_DrawNoteLine(o, s);
2395                 }
2396         }
2397         if(warmup_stage && !intermission)
2398         {
2399                 s = "^2Currently in ^1warmup^2 stage!";
2400                 o = Sbar_DrawNoteLine(o, s);
2401         }
2402
2403         // move more important stuff more to the middle so its more visible
2404         o_y = vid_conheight * 0.66;
2405
2406         string blinkcolor;
2407         if(mod(time, 1) >= 0.5)
2408                 blinkcolor = "^1";
2409         else
2410                 blinkcolor = "^3";
2411
2412         if(ready_waiting && !intermission && !spectatee_status)
2413         {
2414                 if(ready_waiting_for_me)
2415                 {
2416                         if(warmup_stage)
2417                                 s = strcat(blinkcolor, "Press ^3", getcommandkey("ready", "ready"), blinkcolor, " to end warmup");
2418                         else
2419                                 s = strcat(blinkcolor, "Press ^3", getcommandkey("ready", "ready"), blinkcolor, " once you are ready");
2420                 }
2421                 else
2422                 {
2423                         if(warmup_stage)
2424                                 s = strcat("^2Waiting for others to ready up to end warmup...");
2425                         else
2426                                 s = strcat("^2Waiting for others to ready up...");
2427                 }
2428                 o = Sbar_DrawNoteLine(o, s);
2429         }
2430         else if(warmup_stage && !intermission && !spectatee_status)
2431         {
2432                 s = strcat("^2Press ^3", getcommandkey("ready", "ready"), "^2 to end warmup");
2433                 o = Sbar_DrawNoteLine(o, s);
2434         }
2435         if(vote_waiting)
2436         {
2437                 s = strcat("^2A vote has been called for ^1", vote_called_vote);
2438                 o = Sbar_DrawNoteLine(o, s);
2439
2440                 if(vote_waiting_for_me)
2441                 {
2442                         s = strcat(blinkcolor, "Press ^3", getcommandkey("vote yes", "vyes"), blinkcolor, " to accept");
2443                         o = Sbar_DrawNoteLine(o, s);
2444
2445                         s = strcat(blinkcolor, "Press ^3", getcommandkey("vote no", "vno"), blinkcolor, " to reject");
2446                         o = Sbar_DrawNoteLine(o, s);
2447
2448                         s = strcat(blinkcolor, "Press ^3", getcommandkey("vote abstain", "vabstain"), blinkcolor, " to abstain");
2449                         o = Sbar_DrawNoteLine(o, s);
2450                 }
2451                 else
2452                 {
2453                         s = strcat("^2Waiting for others to vote...");
2454                         o = Sbar_DrawNoteLine(o, s);
2455                 }
2456         }
2457         if(teamplay && !intermission && !spectatee_status)
2458         {
2459                 entity tm;
2460                 float ts_min, ts_max;
2461                 tm = teams.sort_next;
2462                 if (tm)
2463                 {
2464                         for(; tm.sort_next; tm = tm.sort_next)
2465                         {
2466                                 if(!tm.team_size || tm.team == COLOR_SPECTATOR)
2467                                         continue;
2468                                 if(!ts_min) ts_min = tm.team_size;
2469                                 else ts_min = min(ts_min, tm.team_size);
2470                                 if(!ts_max) ts_max = tm.team_size;
2471                                 else ts_max = max(ts_max, tm.team_size);
2472                         }
2473                         if ((ts_max - ts_min) > 1)
2474                         {
2475                                 s = strcat(blinkcolor, "Teamnumbers are unbalanced!");
2476                                 tm = GetTeam(myteam, false);
2477                                 if (tm)
2478                                 if (tm.team != COLOR_SPECTATOR)
2479                                 if (tm.team_size == ts_max)
2480                                         s = strcat(s, " Press ^3", getcommandkey("team menu", "menu_showteamselect"), blinkcolor, " to adjust");
2481
2482                                 o = Sbar_DrawNoteLine(o, s);
2483                         }
2484                 }
2485         }
2486
2487         Sbar_UpdatePlayerTeams();
2488         if (intermission == 2) // map voting screen
2489         {
2490                 if(sb_showaccuracy) {
2491                         Sbar_DrawAccuracyStats();
2492                         Sbar_Score();
2493                         Sbar_Timer();
2494                 }
2495                 else if(sb_showscores) {
2496                         Sbar_DrawScoreboard();
2497                         Sbar_Score();
2498                         Sbar_Timer();
2499                 }
2500                 else
2501                         Sbar_FinaleOverlay();
2502
2503                 Sbar_Reset();
2504         }
2505         else if (sb_showscores_force || getstati(STAT_HEALTH) <= 0 || intermission == 1)
2506         {
2507                 if(sb_showaccuracy)
2508                         Sbar_DrawAccuracyStats();
2509                 else
2510                         Sbar_DrawScoreboard();
2511                 Sbar_Score();
2512                 Sbar_Timer();
2513
2514                 Sbar_Reset();
2515         }
2516         else
2517         {
2518                 if(sb_showaccuracy)
2519                         Sbar_DrawAccuracyStats();
2520                 else
2521                         Sbar_DrawScoreboard();
2522                 float armor, health;
2523                 armor = getstati(STAT_ARMOR);
2524                 health = getstati(STAT_HEALTH);
2525
2526                 stat_items = getstati(STAT_ITEMS);
2527                 stat_weapons = getstati(STAT_WEAPONS);
2528
2529                 fade = 3.2 - 2 * (time - weapontime);
2530                 fade = bound(0.7, fade, 1);
2531
2532                 vector bg_size; // hud background size
2533                 bg_size = '1600 58 0';
2534
2535                 if (cvar("viewsize") <= 100 && vid_conwidth <= 1600) {
2536                         if (teamplay)
2537                                 drawpic(bottom - '800 58 0', "gfx/hud/sbar", bg_size, GetTeamRGB(myteam) * sbar_color_bg_team, sbar_alpha_bg, DRAWFLAG_NORMAL); // hud color = myteam color
2538                         else {
2539                                 // allow for custom HUD colors in non-teamgames
2540                                 color_x = cvar("sbar_color_bg_r");
2541                                 color_y = cvar("sbar_color_bg_g");
2542                                 color_z = cvar("sbar_color_bg_b");
2543
2544                                 drawpic(bottom - '800 58 0', "gfx/hud/sbar", bg_size, color, sbar_alpha_bg, DRAWFLAG_NORMAL);
2545                         }
2546                 }
2547
2548                 if(sbar_hudselector == 2) // combined health and armor display
2549                 {
2550                         vector v;
2551                         v = healtharmor_maxdamage(health, armor, armorblockpercent);
2552
2553                         vector num_pos;
2554                         num_pos = bottom - '96 28 0';
2555
2556                         x = floor(v_x + 1);
2557
2558                         if(v_z) // fully armored
2559                         {
2560                                 // here, armorideal > armor
2561                                 drawpic(num_pos + '78 -4.5 0', "gfx/hud/sb_health", '32 32 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2562                                 drawpic(num_pos + '108 -4.5 0', "gfx/hud/sb_armor", '20 20 0', '1 1 1', sbar_alpha_fg * armor / v_y, DRAWFLAG_NORMAL);
2563                         }
2564                         else
2565                         {
2566                                 drawpic(num_pos + '108 -4.5 0', "gfx/hud/sb_health", '20 20 0', '1 1 1', sbar_alpha_fg * v_y / armor, DRAWFLAG_NORMAL);
2567                                 drawpic(num_pos + '78 -4.5 0', "gfx/hud/sb_armor", '32 32 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2568                         }
2569                         Sbar_DrawXNum_Colored(num_pos, x, 24, sbar_alpha_fg); // draw the combined health and armor
2570                 }
2571
2572                 else
2573                 {
2574                         vector health_pos, armor_pos;
2575
2576                         if (sbar_hudselector == 0) { // old style layout with armor left of health
2577                                 armor_pos = bottom - '96 28 0';
2578                                 health_pos = bottom - '-14 28 0';
2579                         }
2580                         else {
2581                                 health_pos = bottom - '96 28 0';                                
2582                                 armor_pos = bottom - '-14 28 0';
2583                         }
2584
2585                         // armor
2586                         x = armor;
2587                         if (x > 0)
2588                         {
2589                                 if (x > 45) {
2590                                         drawpic(armor_pos + '78 -4.5 0', "gfx/hud/sb_armor", '32 32 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2591                                         Sbar_DrawXNum_Colored(armor_pos, x, 24, sbar_alpha_fg);
2592                                 }
2593                                 else {
2594                                         drawpic(armor_pos + '78 -4.5 0', "gfx/hud/sb_armor", '32 32 0', '1 1 1', (x+10)/55 * sbar_alpha_fg, DRAWFLAG_NORMAL);
2595                                         Sbar_DrawXNum_Colored(armor_pos, x, 24, sbar_alpha_fg);
2596                                 }
2597                         }
2598
2599                         // health
2600                         x = health;
2601                         drawpic(health_pos + '78 -4.5 0', "gfx/hud/sb_health", '32 32 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2602                         Sbar_DrawXNum_Colored(health_pos, x, 24, sbar_alpha_fg);
2603                 }
2604
2605                 // ammo
2606                 float a; // i will be the ammo type (already declared), a will contain how much ammo there is of type i
2607
2608                 for (i = 0; i < 4; ++i) {
2609                         a = getstati(GetAmmoStat(i)); // how much ammo do we have of type i?
2610
2611                         if(sbar_currentammo || vid_conwidth < 800) { // force showing current ammo only with conwidths < 800
2612                                 if (stat_items & GetAmmoItemCode(i)) {
2613                                         if (vid_conwidth >= 800) {
2614                                                 pos_x = 230;
2615                                                 pos_y = 40;
2616                                         } else {
2617                                                 pos_x = 206;
2618                                                 pos_y = 33;
2619                                         }
2620
2621                                         pos = bottom - pos;
2622                                         if(vid_conwidth >= 800)
2623                                                 drawpic(pos + '0 1.5 0', "gfx/hud/sb_ammobg", '107 29 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2624                                         drawpic(pos + '76 3 0', GetAmmoPicture(i), '24 24 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2625                                         if(a < 10)
2626                                                 Sbar_DrawXNum(pos + '5 5 0', a, 3, 0, 24, '0.7 0 0', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
2627                                         else
2628                                                 Sbar_DrawXNum(pos + '5 5 0', a, 3, 0, 24, '1 1 1', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
2629                                 }
2630                         } else {
2631                                 if (a > 0) {
2632                                         switch (i) {
2633                                                 case 0: pos_x = 286; pos_y = 48; break; // shells
2634                                                 case 1: pos_x = 286; pos_y = 26; break; // bullets
2635                                                 case 2: pos_x = 200; pos_y = 48; break; // rockets
2636                                                 case 3: pos_x = 200; pos_y = 26; break; // cells
2637                                         }
2638
2639                                         pos = bottom - pos;
2640                                         if (stat_items & GetAmmoItemCode(i))
2641                                                 drawpic(pos + '0 1.5 0', "gfx/hud/sb_ammobg", '80 22 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2642                                         drawpic(pos + '56 3 0', GetAmmoPicture(i), '18 18 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2643                                         if (a < 10) {
2644                                                 if(stat_items & GetAmmoItemCode(i))
2645                                                         Sbar_DrawXNum(pos + '6 4.5 0', a, 3, 0, 16, '0.7 0 0', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
2646                                                 else
2647                                                         Sbar_DrawXNum(pos + '6 4.5 0', a, 3, 0, 16, '0.7 0 0', 0, 0, sbar_alpha_fg * 0.7, DRAWFLAG_NORMAL);
2648                                         } else {
2649                                                 if(stat_items & GetAmmoItemCode(i))
2650                                                         Sbar_DrawXNum(pos + '6 4.5 0', a, 3, 0, 16, '1 1 1', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
2651                                                 else
2652                                                         Sbar_DrawXNum(pos + '6 4.5 0', a, 3, 0, 16, '0.7 0.7 0.7', 0, 0, sbar_alpha_fg * 0.7, DRAWFLAG_NORMAL);
2653                                         }
2654                                 }
2655                         }
2656                 }
2657
2658                 // fuel ammo
2659                 a = getstati(GetAmmoStat(4)); // how much fuel do we have?
2660
2661                 if (a > 0) { // if we have fuel, draw the amount
2662                         float invincibility_time, dt;
2663                         invincibility_time = getstatf(STAT_INVINCIBLE_FINISHED);
2664                         dt = invincibility_time - time;
2665                         if (vid_conwidth >= 800) {
2666                                 if (dt > 0) { // if the invincibility timer is active, draw fuel ammo elsewhere
2667                                         pos_x = bottom_x + 140;
2668                                         pos_y = bottom_y - 72;
2669                                 }
2670                                 else { // if the invincibility timer is inactive, draw the fuel ammo there (it's rare to have invincibility + fuel anyway)
2671                                         pos_x = bottom_x + 140;
2672                                         pos_y = bottom_y - 20;
2673                                 }
2674                         }
2675                         else { // draw fuel on top of ammo if vid_conwidth < 800
2676                                 pos_x = bottom_x - 200;
2677                                 pos_y = bottom_y - 45;
2678                         }
2679                         drawpic(pos - '0 2 0' + '52 0 0', GetAmmoPicture(4), '20 20 0', '1 1 1', sbar_alpha_fg, DRAWFLAG_NORMAL);
2680                         if (a > 10)
2681                                 Sbar_DrawXNum(pos, a, 3, 0, 16, '1 1 1', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
2682                         else
2683                                 Sbar_DrawXNum(pos, a, 3, 0, 16, '0.7 0 0', 0, 0, sbar_alpha_fg, DRAWFLAG_NORMAL);
2684                 }
2685
2686                 // draw scores and timer
2687                 Sbar_Score();
2688                 Sbar_Timer();
2689
2690                 // draw strength/invincibility icon and timer
2691                 CSQC_Strength_Timer();
2692
2693                 // weapon icons
2694                 if(cvar("sbar_showweaponicons")) {
2695                         x = 1.0;
2696                         Sbar_DrawWeapon_Clear();
2697                         for(i = 1; i <= 24; ++i)
2698                         {
2699                                 if(weaponimpulse[i-1] >= 0)
2700                                 if(stat_weapons & x)
2701                                         Sbar_DrawWeapon(i-1, fade, (i == activeweapon), i);
2702                                 x *= 2;
2703                         }
2704                 }
2705
2706                 // draw gametype specific icons
2707                 if(gametype == GAME_KEYHUNT)
2708                         CSQC_kh_hud();
2709                 else if(gametype == GAME_CTF)
2710                         CSQC_ctf_hud();
2711                 else if(gametype == GAME_NEXBALL)
2712                         CSQC_nb_hud();
2713                 else if(gametype == GAME_CTS || gametype == GAME_RACE)
2714                         CSQC_race_hud();
2715         }
2716         return;
2717 }
2718
2719 // CTF HUD
2720 float redflag_prevframe, blueflag_prevframe; // status during previous frame
2721 float redflag_prevstatus, blueflag_prevstatus; // last remembered status
2722 float redflag_statuschange_time, blueflag_statuschange_time; // time when the status changed
2723
2724 void CSQC_ctf_hudreset(void)
2725 {
2726         redflag_prevstatus = blueflag_prevstatus = redflag_prevframe = blueflag_prevframe = redflag_statuschange_time = blueflag_statuschange_time = 0;
2727 }
2728
2729 void CSQC_ctf_hud(void)
2730 {
2731         vector bottomleft, redflag_pos, blueflag_pos, sz;
2732         float f; // every function should have that
2733         bottomleft_x = 0;
2734         bottomleft_y = vid_conheight;
2735         bottomleft_z = 0;
2736
2737         float redflag, blueflag; // current status
2738         float redflag_statuschange_elapsedtime, blueflag_statuschange_elapsedtime; // time since the status changed
2739         float stat_items;
2740
2741         stat_items = getstati(STAT_ITEMS);
2742         redflag = (stat_items/IT_RED_FLAG_TAKEN) & 3;
2743         blueflag = (stat_items/IT_BLUE_FLAG_TAKEN) & 3;
2744
2745         // when status CHANGES, set old status into prevstatus and current status into status
2746         if (redflag != redflag_prevframe)
2747         {
2748                 redflag_statuschange_time = time;
2749                 redflag_prevstatus = redflag_prevframe;
2750                 redflag_prevframe = redflag;
2751         }
2752
2753         if (blueflag != blueflag_prevframe)
2754         {
2755                 blueflag_statuschange_time = time;
2756                 blueflag_prevstatus = blueflag_prevframe;
2757                 blueflag_prevframe = blueflag;
2758         }
2759         
2760         redflag_statuschange_elapsedtime = time - redflag_statuschange_time;
2761         blueflag_statuschange_elapsedtime = time - blueflag_statuschange_time;
2762
2763         float BLINK_FACTOR = 0.15;
2764         float BLINK_BASE = 0.85;
2765         // note:
2766         //   RMS = sqrt(BLINK_BASE^2 + 0.5 * BLINK_FACTOR^2)
2767         // thus
2768         //   BLINK_BASE = sqrt(RMS^2 - 0.5 * BLINK_FACTOR^2)
2769         // ensure RMS == 1
2770         float BLINK_FREQ = 5; // circle frequency, = 2*pi*frequency in hertz
2771
2772         string red_icon, red_icon_prevstatus;
2773         float red_alpha, red_alpha_prevstatus;
2774         red_alpha = red_alpha_prevstatus = 1;
2775         switch(redflag) {
2776                 case 1: red_icon = "gfx/hud/sb_flag_red_taken"; break;
2777                 case 2: red_icon = "gfx/hud/sb_flag_red_lost"; break;
2778                 case 3: red_icon = "gfx/hud/sb_flag_red_carrying"; red_alpha = BLINK_BASE + BLINK_FACTOR * cos(time * BLINK_FREQ); break;
2779                 default:
2780                         if((stat_items & IT_CTF_SHIELDED) && (myteam == COLOR_TEAM2))
2781                                 red_icon = "gfx/hud/sb_flag_red_shielded";
2782                         else
2783                                 red_icon = string_null;
2784                         break;
2785         }
2786         switch(redflag_prevstatus) {
2787                 case 1: red_icon_prevstatus = "gfx/hud/sb_flag_red_taken"; break;
2788                 case 2: red_icon_prevstatus = "gfx/hud/sb_flag_red_lost"; break;
2789                 case 3: red_icon_prevstatus = "gfx/hud/sb_flag_red_carrying"; red_alpha_prevstatus = BLINK_BASE + BLINK_FACTOR * cos(time * BLINK_FREQ); break;
2790                 default:
2791                         if(redflag == 3)
2792                                 red_icon_prevstatus = "gfx/hud/sb_flag_red_carrying"; // make it more visible
2793                         else if((stat_items & IT_CTF_SHIELDED) && (myteam == COLOR_TEAM2))
2794                                 red_icon_prevstatus = "gfx/hud/sb_flag_red_shielded";
2795                         else
2796                                 red_icon_prevstatus = string_null;
2797                         break;
2798         }
2799
2800         string blue_icon, blue_icon_prevstatus;
2801         float blue_alpha, blue_alpha_prevstatus;
2802         blue_alpha = blue_alpha_prevstatus = 1;
2803         switch(blueflag) {
2804                 case 1: blue_icon = "gfx/hud/sb_flag_blue_taken"; break;
2805                 case 2: blue_icon = "gfx/hud/sb_flag_blue_lost"; break;
2806                 case 3: blue_icon = "gfx/hud/sb_flag_blue_carrying"; blue_alpha = BLINK_BASE + BLINK_FACTOR * cos(time * BLINK_FREQ); break;
2807                 default:
2808                         if((stat_items & IT_CTF_SHIELDED) && (myteam == COLOR_TEAM1))
2809                                 blue_icon = "gfx/hud/sb_flag_blue_shielded";
2810                         else
2811                                 blue_icon = string_null;
2812                         break;
2813         }
2814         switch(blueflag_prevstatus) {
2815                 case 1: blue_icon_prevstatus = "gfx/hud/sb_flag_blue_taken"; break;
2816                 case 2: blue_icon_prevstatus = "gfx/hud/sb_flag_blue_lost"; break;
2817                 case 3: blue_icon_prevstatus = "gfx/hud/sb_flag_blue_carrying"; blue_alpha_prevstatus = BLINK_BASE + BLINK_FACTOR * cos(time * BLINK_FREQ); break;
2818                 default:
2819                         if(blueflag == 3)
2820                                 blue_icon_prevstatus = "gfx/hud/sb_flag_blue_carrying"; // make it more visible
2821                         else if((stat_items & IT_CTF_SHIELDED) && (myteam == COLOR_TEAM1))
2822                                 blue_icon_prevstatus = "gfx/hud/sb_flag_blue_shielded";
2823                         else
2824                                 blue_icon_prevstatus = string_null;
2825                         break;
2826         }
2827
2828         if (myteam == COLOR_TEAM1) { // always draw own flag on left
2829                 redflag_pos = bottomleft - '-4 50 0';
2830                 blueflag_pos = bottomleft - '-62 50 0';
2831         } else {
2832                 blueflag_pos = bottomleft - '-4 50 0';
2833                 redflag_pos = bottomleft - '-62 50 0';
2834         }
2835         
2836         sz = '52 52 0';
2837         
2838         f = bound(0, redflag_statuschange_elapsedtime*2, 1);
2839         if(red_icon_prevstatus && f < 1)
2840                 drawpic_expanding(redflag_pos, red_icon_prevstatus, sz, '1 1 1', sbar_alpha_fg * red_alpha_prevstatus, DRAWFLAG_NORMAL, f);
2841         if(red_icon)
2842                 drawpic(redflag_pos, red_icon, sz, '1 1 1', sbar_alpha_fg * red_alpha * f, DRAWFLAG_NORMAL);
2843
2844         f = bound(0, blueflag_statuschange_elapsedtime*2, 1);
2845         if(blue_icon_prevstatus && f < 1)
2846                 drawpic_expanding(blueflag_pos, blue_icon_prevstatus, sz, '1 1 1', sbar_alpha_fg * blue_alpha_prevstatus, DRAWFLAG_NORMAL, f);
2847         if(blue_icon)
2848                 drawpic(blueflag_pos, blue_icon, sz, '1 1 1', sbar_alpha_fg * blue_alpha * f, DRAWFLAG_NORMAL);
2849 }
2850
2851 // Keyhunt HUD
2852 float kh_runheretime;
2853
2854 void CSQC_kh_hudreset(void)
2855 {
2856         kh_runheretime = 0;
2857 }
2858
2859 void CSQC_kh_hud(void)
2860 {
2861         float kh_keys;
2862         float keyteam;
2863         float a, aa;
2864         vector p, pa, kh_size, kh_asize;
2865
2866         vector bottomleft;
2867         bottomleft_x = 0;
2868         bottomleft_y = vid_conheight;
2869         bottomleft_z = 0;
2870
2871         p_x = 6;
2872         p_y = vid_conheight - 34 - 3;
2873         p_z = 0;
2874
2875         kh_keys = getstati(STAT_KH_KEYS);
2876
2877         kh_size = '19 34 0';
2878         kh_asize = '19 10 0';
2879         pa = p + '0 -10 0';
2880
2881         float i, key;
2882
2883         float keycount;
2884         keycount = 0;
2885         for(i = 0; i < 4; ++i)
2886         {
2887                 key = floor(kh_keys / pow(32, i)) & 31;
2888                 keyteam = key - 1;
2889                 if(keyteam == 30 && keycount <= 4)
2890                         keycount += 4;
2891                 if(keyteam == myteam || keyteam == -1 || keyteam == 30)
2892                         keycount += 1;
2893         }
2894         // this yields 8 exactly if "RUN HERE" shows
2895
2896         if(keycount == 8)
2897         {
2898                 if(!kh_runheretime)
2899                         kh_runheretime = time;
2900                 pa_y -= fabs(sin((time - kh_runheretime) * 3.5)) * 6; // make the arrows jump in case of RUN HERE
2901         }
2902         else
2903                 kh_runheretime = 0;
2904
2905         for(i = 0; i < 4; ++i)
2906         {
2907                 key = floor(kh_keys / pow(32, i)) & 31;
2908                 keyteam = key - 1;
2909                 switch(keyteam)
2910                 {
2911                         case 30: // my key
2912                                 keyteam = myteam;
2913                                 a = 1;
2914                                 aa = 1;
2915                                 break;
2916                         case -1: // no key
2917                                 a = 0;
2918                                 aa = 0;
2919                                 break;
2920                         default: // owned or dropped
2921                                 a = 0.2;
2922            &nbs