Merge branch 'master' into fruitiex/newpanelhud
[xonotic/xonotic-data.pk3dir.git] / qcsrc / client / Main.qc
1 // --------------------------------------------------------------------------
2 // BEGIN REQUIRED CSQC FUNCTIONS
3 //include "main.qh"
4
5 #define DP_CSQC_ENTITY_REMOVE_IS_B0RKED
6
7 void cvar_clientsettemp(string cv, string val)
8 {
9         entity e;
10         for(e = world; (e = find(e, classname, "saved_cvar_value")); )
11                 if(e.netname == cv)
12                         goto saved;
13         e = spawn();
14         e.classname = "saved_cvar_value";
15         e.netname = strzone(cv);
16         e.message = strzone(cvar_string(cv));
17 :saved
18         cvar_set(cv, val);
19 }
20
21 void cvar_clientsettemp_restore()
22 {
23         entity e;
24         for(e = world; (e = find(e, classname, "saved_cvar_value")); )
25                         cvar_set(e.netname, e.message);
26 }
27
28 void() menu_show_error =
29 {
30         drawstring('0 200 0', "ERROR - MENU IS VISIBLE BUT NO MENU WAS DEFINED!", '8 8 0', '1 0 0', 1, 0);
31 };
32
33 // CSQC_Init : Called every time the CSQC code is initialized (essentially at map load)
34 // Useful for precaching things
35
36 void() menu_sub_null =
37 {
38 };
39
40 #ifdef USE_FTE
41 float __engine_check;
42 #endif
43
44 string forcefog;
45 string cl_announcer_prev;
46 void WaypointSprite_Load();
47 void CSQC_Init(void)
48 {
49 #ifdef USE_FTE
50 #pragma target ID
51         __engine_check = checkextension("DP_SV_WRITEPICTURE");
52         if(!__engine_check)
53         {
54                 print("^3Your engine build is outdated\n^3This Server uses a newer QC VM. Please update!\n");
55                 localcmd("\ndisconnect\n");
56                 return;
57         }
58 #pragma target FTE
59 #endif
60         
61         check_unacceptable_compiler_bugs();
62
63 #ifdef WATERMARK
64         print("^4CSQC Build information: ", WATERMARK(), "\n");
65 #endif
66
67         float i;
68         CSQC_CheckEngine();
69
70         binddb = db_create();
71         tempdb = db_create();
72         ClientProgsDB = db_load("client.db");
73         compressShortVector_init();
74
75         drawfont = 0;
76         menu_visible = FALSE;
77         menu_show = menu_show_error;
78         menu_action = menu_sub_null;
79
80         for(i = 0; i < 255; ++i)
81                 if(getplayerkey(i, "viewentity") == "")
82                         break;
83         maxclients = i;
84
85         //ctf_temp_1 = "";
86         // localcmd("alias order \"cmd order $*\""); enable if ctf-command thingy is used
87         //registercmd("ctf_menu");
88         registercmd("ons_map");
89         registercmd("hud_configure");
90         registercmd("hud_save");
91         //registercmd("menu_action");
92
93         registercmd("+button3");
94         registercmd("-button3");
95         registercmd("+button4");
96         registercmd("-button4");
97         registercmd("+showaccuracy");registercmd("-showaccuracy");
98
99 #ifndef CAMERATEST
100         if(isdemo())
101         {
102 #endif
103                 registercmd("+forward");registercmd("-forward");
104                 registercmd("+back");registercmd("-back");
105                 registercmd("+moveup");registercmd("-moveup");
106                 registercmd("+movedown");registercmd("-movedown");
107                 registercmd("+moveright");registercmd("-moveright");
108                 registercmd("+moveleft");registercmd("-moveleft");
109                 registercmd("+roll_right");registercmd("-roll_right");
110                 registercmd("+roll_left");registercmd("-roll_left");
111 #ifndef CAMERATEST
112         }
113 #endif
114         registercvar("hud_usecsqc", "1");
115         registercvar("hud_columns", "default", CVAR_SAVE);
116
117         gametype = 0;
118
119         // hud_fields uses strunzone on the titles!
120         for(i = 0; i < MAX_HUD_FIELDS; ++i)
121                 hud_title[i] = strzone("(null)");
122
123         postinit = false;
124
125         calledhooks = 0;
126
127         teams = Sort_Spawn();
128         players = Sort_Spawn();
129
130         GetTeam(COLOR_SPECTATOR, true); // add specs first
131
132         cvar_clientsettemp("_supports_weaponpriority", "1");
133
134         RegisterWeapons();
135
136         WaypointSprite_Load();
137
138         // precaches
139         Projectile_Precache();
140         GibSplash_Precache();
141         Casings_Precache();
142         DamageInfo_Precache();
143         if(cvar_string("cl_announcer") != cl_announcer_prev) {
144                 Announcer_Precache();
145                 if(cl_announcer_prev)
146                         strunzone(cl_announcer_prev);
147                 cl_announcer_prev = strzone(cvar_string("cl_announcer"));
148         }
149         Tuba_Precache();
150
151 #ifdef UID
152         {
153                 // find the user ID
154                 string uid;
155                 registercvar("_cl_userid", "", CVAR_SAVE);
156                 uid = cvar_string("_cl_userid");
157                 if(strlen(uid) < 16)
158                 {
159                         uid = "";
160                         for(i = 0; i < 4; ++i)
161                                 uid = strcat(uid, substring(ftos(floor(10000 + random() * 10000)), 1, -1));
162                 }
163                 cvar_set("_cl_userid", uid);
164                 localcmd(strcat("\ncmd uid ", uid, "\n"));
165         }
166 #endif
167
168         get_mi_min_max_texcoords(1); // try the CLEVER way first
169         minimapname = strcat("gfx/", mi_shortname, "_radar.tga");
170         shortmapname = mi_shortname;
171
172         if(precache_pic(minimapname) == "")
173         {
174                 // but maybe we have a non-clever minimap
175                 minimapname = strcat("gfx/", mi_shortname, "_mini.tga");
176                 if(precache_pic(minimapname) == "")
177                         minimapname = ""; // FAIL
178                 else
179                         get_mi_min_max_texcoords(0); // load new texcoords
180         }
181
182         mi_center = (mi_min + mi_max) * 0.5;
183         mi_scale = mi_max - mi_min;
184         minimapname = strzone(minimapname);
185
186         WarpZone_Init();
187 }
188
189 // CSQC_Shutdown : Called every time the CSQC code is shutdown (changing maps, quitting, etc)
190 void CSQC_Shutdown(void)
191 {
192 #ifdef USE_FTE
193 #pragma TARGET id
194         if(!__engine_check)
195                 return 0;
196 #pragma TARGET fte
197 #endif
198
199         WarpZone_Shutdown();
200
201         remove(teams);
202         remove(players);
203         db_close(binddb);
204         db_close(tempdb);
205         db_save(ClientProgsDB, "client.db");
206         db_close(ClientProgsDB);
207
208         cvar_clientsettemp_restore();
209
210         if(camera_active)
211                 cvar_set("chase_active",ftos(chase_active_backup));
212
213         if not(isdemo())
214         {
215                 if not(calledhooks & HOOK_START)
216                         localcmd("\n_cl_hook_gamestart nop;");
217                 if not(calledhooks & HOOK_END)
218                         localcmd("\ncl_hook_gameend;");
219         }
220 }
221
222 .float has_team;
223 float SetTeam(entity o, float Team)
224 {
225         entity tm;
226         if(teamplay)
227         {
228                 switch(Team)
229                 {
230                         case -1:
231                         case COLOR_TEAM1:
232                         case COLOR_TEAM2:
233                         case COLOR_TEAM3:
234                         case COLOR_TEAM4:
235                                 break;
236                         default:
237                                 if(GetTeam(Team, false) == NULL)
238                                 {
239                                         print("trying to switch to unsupported team ", ftos(Team), "\n");
240                                         Team = COLOR_SPECTATOR;
241                                 }
242                                 break;
243                 }
244         }
245         else
246         {
247                 switch(Team)
248                 {
249                         case -1:
250                         case 0:
251                                 break;
252                         default:
253                                 if(GetTeam(Team, false) == NULL)
254                                 {
255                                         print("trying to switch to unsupported team ", ftos(Team), "\n");
256                                         Team = COLOR_SPECTATOR;
257                                 }
258                                 break;
259                 }
260         }
261         if(Team == -1) // leave
262         {
263                 if(o.has_team)
264                 {
265                         //print("(DISCONNECT) leave team ", ftos(o.team), "\n");
266                         tm = GetTeam(o.team, false);
267                         tm.team_size -= 1;
268                         o.has_team = 0;
269                         return TRUE;
270                 }
271         }
272         else
273         {
274                 if not(o.has_team)
275                 {
276                         //print("(CONNECT) enter team ", ftos(o.team), "\n");
277                         o.team = Team;
278                         tm = GetTeam(Team, true);
279                         tm.team_size += 1;
280                         o.has_team = 1;
281                         return TRUE;
282                 }
283                 else if(Team != o.team)
284                 {
285                         //print("(CHANGE) leave team ", ftos(o.team), "\n");
286                         tm = GetTeam(o.team, false);
287                         tm.team_size -= 1;
288                         o.team = Team;
289                         //print("(CHANGE) enter team ", ftos(o.team), "\n");
290                         tm = GetTeam(Team, true);
291                         tm.team_size += 1;
292                         return TRUE;
293                 }
294         }
295         return FALSE;
296 }
297
298 void Playerchecker_Think()
299 {
300         float i;
301         entity e;
302         for(i = 0; i < maxclients; ++i)
303         {
304                 e = playerslots[i];
305                 if(GetPlayerName(i) == "")
306                 {
307                         if(e.sort_prev)
308                         {
309                                 //print("playerchecker: KILL KILL KILL\n");
310                                 // player disconnected
311                                 SetTeam(e, -1);
312                                 RemovePlayer(e);
313                                 e.sort_prev = world;
314                                 //e.gotscores = 0;
315                         }
316                 }
317                 else
318                 {
319                         if not(e.sort_prev)
320                         {
321                                 //print("playerchecker: SPAWN SPAWN SPAWN\n");
322                                 // player connected
323                                 if not(e)
324                                         playerslots[i] = e = spawn();
325                                 e.sv_entnum = i;
326                                 e.ping = 0;
327                                 e.ping_packetloss = 0;
328                                 e.ping_movementloss = 0;
329                                 //e.gotscores = 0; // we might already have the scores...
330                                 SetTeam(e, GetPlayerColor(i)); // will not hurt; later updates come with HUD_UpdatePlayerTeams
331                                 RegisterPlayer(e);
332                                 HUD_UpdatePlayerPos(e);
333                         }
334                 }
335         }
336         self.nextthink = time + 0.2;
337 }
338
339 void Porto_Init();
340 void TrueAim_Init();
341 void PostInit(void)
342 {
343         print(strcat("PostInit\n    maxclients = ", ftos(maxclients), "\n"));
344         localcmd(strcat("\nhud_columns_set ", cvar_string("hud_columns"), ";\n"));
345
346         entity playerchecker;
347         playerchecker = spawn();
348         playerchecker.think = Playerchecker_Think;
349         playerchecker.nextthink = time + 0.2;
350
351         Porto_Init();
352         TrueAim_Init();
353
354         postinit = true;
355 }
356
357 // CSQC_ConsoleCommand : Used to parse commands in the console that have been registered with the "registercmd" function
358 // Return value should be 1 if CSQC handled the command, otherwise return 0 to have the engine handle it.
359 float button_zoom;
360 void Cmd_HUD_SetFields(float);
361 void Cmd_HUD_Help(float);
362 float CSQC_ConsoleCommand(string strMessage)
363 {
364         float argc;
365         // Tokenize String
366         //argc = tokenize(strMessage);
367         argc = tokenize_console(strMessage);
368
369         // Acquire Command
370         local string strCmd;
371         strCmd = argv(0);
372
373         if(strCmd == "hud_configure") { // config hud
374                 cvar_set("_hud_configure", ftos(!cvar("_hud_configure")));
375                 return true;
376         } else if(strCmd == "hud_save") { // save hud config
377                 if(argv(1) == "" || argv(2)) {
378                         print("Usage:\n");
379                         print("hud_save configname   (saves to hud_skinname_configname.cfg)\n");
380                 }
381                 else
382                         HUD_Panel_ExportCfg(argv(1));
383                 return true;
384         } else if(strCmd == "+button4") { // zoom
385                 // return false, because the message shall be sent to the server anyway (for demos/speccing)
386                 if(ignore_plus_zoom)
387                 {
388                         --ignore_plus_zoom;
389                         return false;
390                 }
391                 button_zoom = 1;
392                 return true;
393         } else if(strCmd == "-button4") { // zoom
394                 if(ignore_minus_zoom)
395                 {
396                         --ignore_minus_zoom;
397                         return false;
398                 }
399                 button_zoom = 0;
400                 return true;
401         } else if(strCmd == "+button3") { // secondary
402                 button_attack2 = 1;
403                 return false;
404         } else if(strCmd == "-button3") { // secondary
405                 button_attack2 = 0;
406                 return false;
407         } else if(strCmd == "+showscores") {
408                 sb_showscores = true;
409                 return true;
410         } else if(strCmd == "-showscores") {
411                 sb_showscores = false;
412                 return true;
413         } else if(strCmd == "+showaccuracy") {
414                 sb_showaccuracy = true;
415                 return true;
416         } else if(strCmd == "-showaccuracy") {
417                 sb_showaccuracy = false;
418                 return true;
419         }
420
421         if(camera_active)
422         if(strCmd == "+forward" || strCmd == "-back") {
423                 ++camera_direction_x;
424                 return true;
425         } else if(strCmd == "-forward" || strCmd == "+back") {
426                 --camera_direction_x;
427                 return true;
428         } else if(strCmd == "+moveright" || strCmd == "-moveleft") {
429                 --camera_direction_y;
430                 return true;
431         } else if(strCmd == "-moveright" || strCmd == "+moveleft") {
432                 ++camera_direction_y;
433                 return true;
434         } else if(strCmd == "+moveup" || strCmd == "-movedown") {
435                 ++camera_direction_z;
436                 return true;
437         } else if(strCmd == "-moveup" || strCmd == "+movedown") {
438                 --camera_direction_z;
439                 return true;
440         } else if(strCmd == "+roll_right" || strCmd == "-roll_left") {
441                 ++camera_roll;
442                 return true;
443         } else if(strCmd == "+roll_left" || strCmd == "-roll_right") {
444                 --camera_roll;
445                 return true;
446         }
447
448         return false;
449 }
450
451 .vector view_ofs;
452 entity debug_shotorg;
453 void ShotOrg_Draw()
454 {
455         self.origin = view_origin + view_forward * self.view_ofs_x + view_right * self.view_ofs_y + view_up * self.view_ofs_z;
456         self.angles = view_angles;
457         self.angles_x = -self.angles_x;
458         if not(self.cnt)
459                 R_AddEntity(self);
460 }
461 void ShotOrg_Draw2D()
462 {
463         vector coord2d_topleft, coord2d_topright, coord2d;
464         string s;
465         vector fs;
466
467         s = vtos(self.view_ofs);
468         s = substring(s, 1, strlen(s) - 2);
469         if(tokenize_console(s) == 3)
470                 s = strcat(argv(0), " ", argv(1), " ", argv(2));
471
472         coord2d_topleft = project_3d_to_2d(self.origin + view_up * 4 - view_right * 4);
473         coord2d_topright = project_3d_to_2d(self.origin + view_up * 4 + view_right * 4);
474
475         fs = '1 1 0' * ((coord2d_topright_x - coord2d_topleft_x) / stringwidth(s, FALSE, '8 8 0'));
476
477         coord2d = coord2d_topleft;
478         if(fs_x < 8)
479         {
480                 coord2d_x += (coord2d_topright_x - coord2d_topleft_x) * (1 - 8 / fs_x) * 0.5;
481                 fs = '8 8 0';
482         }
483         coord2d_y -= fs_y;
484         coord2d_z = 0;
485         drawstring(coord2d, s, fs, '1 1 1', 1, 0);
486 }
487
488 void ShotOrg_Spawn()
489 {
490         debug_shotorg = spawn();
491         debug_shotorg.draw = ShotOrg_Draw;
492         debug_shotorg.draw2d = ShotOrg_Draw2D;
493         debug_shotorg.renderflags = RF_VIEWMODEL;
494         debug_shotorg.effects = EF_FULLBRIGHT;
495         precache_model("models/shotorg_adjuster.md3");
496         setmodel(debug_shotorg, "models/shotorg_adjuster.md3");
497         debug_shotorg.scale = 2;
498         debug_shotorg.view_ofs = '25 8 -8';
499 }
500
501 void DrawDebugModel()
502 {
503         if(time - floor(time) > 0.5)
504         {
505                 PolyDrawModel(self);
506         }
507         else
508         {
509                 self.renderflags = 0;
510                 R_AddEntity(self);
511         }
512 }
513
514 void GameCommand(string msg)
515 {
516         string s;
517         float argc;
518         entity e;
519         argc = tokenize_console(msg);
520
521         if(argv(0) == "help" || argc == 0)
522         {
523                 print("Usage: cl_cmd COMMAND..., where possible commands are:\n");
524                 print("  settemp cvar value\n");
525                 print("  radar\n");
526                 print("  hud_columns_set ...\n");
527                 print("  hud_columns_help\n");
528                 GameCommand_Generic("help");
529                 return;
530         }
531
532         if(GameCommand_Generic(msg))
533                 return;
534
535         string cmd;
536         cmd = argv(0);
537         if(cmd == "mv_download") {
538                 Cmd_MapVote_MapDownload(argc);
539         }
540         else if(cmd == "settemp") {
541                 cvar_clientsettemp(argv(1), argv(2));
542         }
543         else if(cmd == "radar") {
544                 ons_showmap = !ons_showmap;
545         }
546         else if(cmd == "hud_columns_set") {
547                 Cmd_HUD_SetFields(argc);
548         }
549         else if(cmd == "hud_columns_help") {
550                 Cmd_HUD_Help(argc);
551         }
552 #ifdef BLURTEST
553         else if(cmd == "blurtest") {
554                 blurtest_time0 = time;
555                 blurtest_time1 = time + stof(argv(1));
556                 blurtest_radius = stof(argv(2));
557                 blurtest_power = stof(argv(3));
558         }
559 #endif
560         else if(cmd == "shotorg_move") {
561                 if(!debug_shotorg)
562                         ShotOrg_Spawn();
563                 else
564                         debug_shotorg.view_ofs = debug_shotorg.view_ofs + stov(argv(1));
565                 localcmd("sv_cmd debug_shotorg \"", vtos(debug_shotorg.view_ofs), "\"\n");
566         }
567         else if(cmd == "shotorg_movez") {
568                 if(!debug_shotorg)
569                         ShotOrg_Spawn();
570                 else
571                         debug_shotorg.view_ofs = debug_shotorg.view_ofs + stof(argv(1)) * (debug_shotorg.view_ofs * (1 / debug_shotorg.view_ofs_x)); // closer/farther, same xy pos
572                 localcmd("sv_cmd debug_shotorg \"", vtos(debug_shotorg.view_ofs), "\"\n");
573         }
574         else if(cmd == "shotorg_set") {
575                 if(!debug_shotorg)
576                         ShotOrg_Spawn();
577                 else
578                         debug_shotorg.view_ofs = stov(argv(1));
579                 localcmd("sv_cmd debug_shotorg \"", vtos(debug_shotorg.view_ofs), "\"\n");
580         }
581         else if(cmd == "shotorg_setz") {
582                 if(!debug_shotorg)
583                         ShotOrg_Spawn();
584                 else
585                         debug_shotorg.view_ofs = debug_shotorg.view_ofs * (stof(argv(1)) / debug_shotorg.view_ofs_x); // closer/farther, same xy pos
586                 localcmd("sv_cmd debug_shotorg \"", vtos(debug_shotorg.view_ofs), "\"\n");
587         }
588         else if(cmd == "shotorg_toggle_hide") {
589                 if(debug_shotorg)
590                 {
591                         debug_shotorg.cnt = !debug_shotorg.cnt;
592                 }
593         }
594         else if(cmd == "shotorg_end") {
595                 if(debug_shotorg)
596                 {
597                         print(vtos(debug_shotorg.view_ofs), "\n");
598                         remove(debug_shotorg);
599                         debug_shotorg = world;
600                 }
601                 localcmd("sv_cmd debug_shotorg\n");
602         }
603         else if(cmd == "sendcvar") {
604                 // W_FixWeaponOrder will trash argv, so save what we need.
605                 string cvar;
606                 cvar = strzone(argv(1));
607                 s = cvar_string(cvar);
608                 if(cvar == "cl_weaponpriority")
609                         s = W_FixWeaponOrder(W_NumberWeaponOrder(s), 1);
610                 else if(substring(cvar, 0, 17) == "cl_weaponpriority" && strlen(cvar) == 18)
611                         s = W_FixWeaponOrder(W_NumberWeaponOrder(s), 0);
612                 localcmd("cmd sentcvar ", cvar, " \"", s, "\"\n");
613                 strunzone(cvar);
614         }
615         else if(cmd == "spawn") {
616                 s = argv(1);
617                 e = spawn();
618                 precache_model(s);
619                 setmodel(e, s);
620                 setorigin(e, view_origin);
621                 e.angles = view_angles;
622                 e.draw = DrawDebugModel;
623                 e.classname = "debugmodel";
624         }
625         else
626         {
627                 print("Invalid command. For a list of supported commands, try cl_cmd help.\n");
628         }
629
630         return;
631 }
632
633 // CSQC_InputEvent : Used to perform actions based on any key pressed, key released and mouse on the client.
634 // Return value should be 1 if CSQC handled the input, otherwise return 0 to have the input passed to the engine.
635 // All keys are in ascii.
636 // bInputType = 0 is key pressed, 1 is key released, 2 is mouse input.
637 // In the case of keyboard input, nPrimary is the ascii code, and nSecondary is 0.
638 // In the case of mouse input, nPrimary is xdelta, nSecondary is ydelta.
639 float hudconf_active;
640 float CSQC_InputEvent(float bInputType, float nPrimary, float nSecondary)
641 {
642         local float bSkipKey;
643         bSkipKey = false;
644
645         if(hudconf_active)
646                 if (HUD_Panel_InputEvent(bInputType, nPrimary, nSecondary))
647                         return true;
648
649         if (MapVote_InputEvent(bInputType, nPrimary, nSecondary))
650                 return true;
651
652         if(menu_visible)
653                 if(menu_action(bInputType, nPrimary, nSecondary))
654                         return TRUE;
655         return bSkipKey;
656 }
657
658 // END REQUIRED CSQC FUNCTIONS
659 // --------------------------------------------------------------------------
660
661 // --------------------------------------------------------------------------
662 // BEGIN OPTIONAL CSQC FUNCTIONS
663 void Ent_ReadEntCS()
664 {
665         InterpolateOrigin_Undo();
666
667         self.classname = "entcs_receiver";
668         self.sv_entnum = ReadByte() - 1;
669         self.origin_x = ReadShort();
670         self.origin_y = ReadShort();
671         self.origin_z = ReadShort();
672         self.angles_y = ReadByte() * 360.0 / 256;
673         self.origin_z = self.angles_x = self.angles_z = 0;
674
675         InterpolateOrigin_Note();
676 }
677
678 void Ent_Remove();
679
680 void Ent_RemovePlayerScore()
681 {
682         float i;
683
684         if(self.owner)
685         {
686                 SetTeam(self.owner, -1);
687                 self.owner.gotscores = 0;
688                 for(i = 0; i < MAX_SCORE; ++i)
689                         self.owner.(scores[i]) = 0; // clear all scores
690         }
691 }
692
693 void Ent_ReadPlayerScore()
694 {
695         float i, n;
696         float isNew;
697         entity o;
698
699         // damnit -.- don't want to go change every single .sv_entnum in hud.qc AGAIN
700         // (no I've never heard of M-x replace-string, sed, or anything like that)
701         isNew = !self.owner; // workaround for DP bug
702         n = ReadByte()-1;
703
704 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
705         if(!isNew && n != self.sv_entnum)
706         {
707                 print("A CSQC entity changed its owner!\n");
708                 isNew = true;
709                 Ent_Remove();
710                 self.enttype = ENT_CLIENT_SCORES;
711         }
712 #endif
713
714         self.sv_entnum = n;
715
716         if not(playerslots[self.sv_entnum])
717                 playerslots[self.sv_entnum] = spawn();
718         o = self.owner = playerslots[self.sv_entnum];
719         o.sv_entnum = self.sv_entnum;
720         o.gotscores = 1;
721
722         //if not(o.sort_prev)
723         //      RegisterPlayer(o);
724         //playerchecker will do this for us later, if it has not already done so
725
726         float sf, lf;
727 #if MAX_SCORE <= 8
728         sf = ReadByte();
729         lf = ReadByte();
730 #else
731         sf = ReadShort();
732         lf = ReadShort();
733 #endif
734         float p;
735         for(i = 0, p = 1; i < MAX_SCORE; ++i, p *= 2)
736                 if(sf & p)
737                 {
738                         if(lf & p)
739                                 o.(scores[i]) = ReadInt24_t();
740                         else
741                                 o.(scores[i]) = ReadChar();
742                 }
743
744         if(o.sort_prev)
745                 HUD_UpdatePlayerPos(o); // if not registered, we cannot do this yet!
746
747         self.entremove = Ent_RemovePlayerScore;
748 }
749
750 void Ent_ReadTeamScore()
751 {
752         float i;
753         entity o;
754
755         self.team = ReadByte();
756         o = self.owner = GetTeam(self.team, true); // these team numbers can always be trusted
757
758         float sf, lf;
759 #if MAX_TEAMSCORE <= 8
760         sf = ReadByte();
761         lf = ReadByte();
762 #else
763         sf = ReadShort();
764         lf = ReadShort();
765 #endif
766         float p;
767         for(i = 0, p = 1; i < MAX_TEAMSCORE; ++i, p *= 2)
768                 if(sf & p)
769                 {
770                         if(lf & p)
771                                 o.(teamscores[i]) = ReadInt24_t();
772                         else
773                                 o.(teamscores[i]) = ReadChar();
774                 }
775
776         HUD_UpdateTeamPos(o);
777 }
778
779 void Net_Reset()
780 {
781 }
782
783 void Ent_ClientData()
784 {
785         float f;
786         float newspectatee_status;
787
788         f = ReadByte();
789
790         sb_showscores_force = (f & 1);
791
792         if(f & 2)
793         {
794                 newspectatee_status = ReadByte();
795                 if(newspectatee_status == player_localentnum)
796                         newspectatee_status = -1; // observing
797         }
798         else
799                 newspectatee_status = 0;
800
801         spectatorbutton_zoom = (f & 4);
802
803         if(f & 8)
804         {
805                 angles_held_status = 1;
806                 angles_held_x = ReadAngle();
807                 angles_held_y = ReadAngle();
808                 angles_held_z = 0;
809         }
810         else
811                 angles_held_status = 0;
812
813         if(newspectatee_status != spectatee_status)
814         {
815                 float i;
816                 // clear the weapon accuracy stats
817                 for(i = WEP_FIRST; i <= WEP_LAST; ++i) {
818                         weapon_hits[i] = 0;
819                         weapon_fired[i] = 0;
820                 }
821
822                 // clear race stuff
823                 race_laptime = 0;
824                 race_checkpointtime = 0;
825         }
826         spectatee_status = newspectatee_status;
827 }
828
829 void Ent_Nagger()
830 {
831         float nags, i, j, b, f;
832
833         nags = ReadByte();
834
835         if(nags & 128)
836         {
837                 if(vote_called_vote)
838                         strunzone(vote_called_vote);
839                 vote_called_vote = strzone(ColorTranslateRGB(ReadString()));
840         }
841
842         if(nags & 1)
843         {
844                 for(j = 0; j < maxclients; ++j)
845                         if(playerslots[j])
846                                 playerslots[j].ready = 1;
847                 for(i = 1; i <= maxclients; i += 8)
848                 {
849                         f = ReadByte();
850                         for(j = i-1, b = 1; b < 256; b *= 2, ++j)
851                                 if not(f & b)
852                                         if(playerslots[j])
853                                                 playerslots[j].ready = 0;
854                 }
855         }
856
857         ready_waiting = (nags & 1);
858         ready_waiting_for_me = (nags & 2);
859         vote_waiting = (nags & 4);
860         vote_waiting_for_me = (nags & 8);
861         warmup_stage = (nags & 16);
862 }
863
864 void Ent_RandomSeed()
865 {
866         float s;
867         prandom_debug();
868         s = ReadShort();
869         psrandom(s);
870 }
871
872 // CSQC_Ent_Update : Called every frame that the server has indicated an update to the SSQC / CSQC entity has occured.
873 // The only parameter reflects if the entity is "new" to the client, meaning it just came into the client's PVS.
874 void Ent_RadarLink();
875 void Ent_Init();
876 void Ent_ScoresInfo();
877 void(float bIsNewEntity) CSQC_Ent_Update =
878 {
879         float t;
880         float savetime;
881         t = ReadByte();
882
883         // set up the "time" global for received entities to be correct for interpolation purposes
884         savetime = time;
885         if(servertime)
886         {
887                 time = servertime;
888         }
889         else
890         {
891                 serverprevtime = time;
892                 serverdeltatime = getstatf(STAT_MOVEVARS_TICRATE) * getstatf(STAT_MOVEVARS_TIMESCALE);
893                 time = serverprevtime + serverdeltatime;
894         }
895
896 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
897         if(self.enttype)
898                 if(t != self.enttype)
899                 {
900                         print("A CSQC entity changed its type!\n");
901                         Ent_Remove();
902                         bIsNewEntity = 1;
903                 }
904 #endif
905         self.enttype = t;
906         switch(t)
907         {
908                 case ENT_CLIENT_ENTCS: Ent_ReadEntCS(); break;
909                 case ENT_CLIENT_SCORES: Ent_ReadPlayerScore(); break;
910                 case ENT_CLIENT_TEAMSCORES: Ent_ReadTeamScore(); break;
911                 case ENT_CLIENT_POINTPARTICLES: Ent_PointParticles(); break;
912                 case ENT_CLIENT_RAINSNOW: Ent_RainOrSnow(); break;
913                 case ENT_CLIENT_LASER: Ent_Laser(); break;
914                 case ENT_CLIENT_NAGGER: Ent_Nagger(); break;
915                 case ENT_CLIENT_WAYPOINT: Ent_WaypointSprite(); break;
916                 case ENT_CLIENT_RADARLINK: Ent_RadarLink(); break;
917                 case ENT_CLIENT_PROJECTILE: Ent_Projectile(); break;
918                 case ENT_CLIENT_GIBSPLASH: Ent_GibSplash(bIsNewEntity); break;
919                 case ENT_CLIENT_DAMAGEINFO: Ent_DamageInfo(bIsNewEntity); break;
920                 case ENT_CLIENT_CASING: Ent_Casing(bIsNewEntity); break;
921                 case ENT_CLIENT_INIT: Ent_Init(); break;
922                 case ENT_CLIENT_SCORES_INFO: Ent_ScoresInfo(); break;
923                 case ENT_CLIENT_MAPVOTE: Ent_MapVote(); break;
924                 case ENT_CLIENT_CLIENTDATA: Ent_ClientData(); break;
925                 case ENT_CLIENT_RANDOMSEED: Ent_RandomSeed(); break;
926                 case ENT_CLIENT_WALL: Ent_Wall(); break;
927                 case ENT_CLIENT_MODELEFFECT: Ent_ModelEffect(bIsNewEntity); break;
928                 case ENT_CLIENT_TUBANOTE: Ent_TubaNote(bIsNewEntity); break;
929                 case ENT_CLIENT_WARPZONE: WarpZone_Read(bIsNewEntity); break;
930                 case ENT_CLIENT_WARPZONE_CAMERA: WarpZone_Camera_Read(bIsNewEntity); break;
931                 case ENT_CLIENT_TRIGGER_MUSIC: Ent_ReadTriggerMusic(); break;
932                 default:
933                         error(strcat("unknown entity type in CSQC_Ent_Update: ", ftos(self.enttype), "\n"));
934                         break;
935         }
936
937         time = savetime;
938 };
939 // Destructor, but does NOT deallocate the entity by calling remove(). Also
940 // used when an entity changes its type. For an entity that someone interacts
941 // with others, make sure it can no longer do so.
942 void Ent_Remove()
943 {
944         if(self.entremove)
945                 self.entremove();
946
947         self.enttype = 0;
948         self.classname = "";
949         self.draw = menu_sub_null;
950         self.entremove = menu_sub_null;
951         // TODO possibly set more stuff to defaults
952 }
953 // CSQC_Ent_Remove : Called when the server requests a SSQC / CSQC entity to be removed.  Essentially call remove(self) as well.
954 void CSQC_Ent_Remove()
955 {
956         if(self.enttype)
957                 Ent_Remove();
958         remove(self);
959 }
960
961 void Gamemode_Init()
962 {
963         if(gametype == GAME_ONSLAUGHT) {
964                 print(strcat("Using ", minimapname, " as minimap.\n"));
965                 precache_pic("gfx/ons-cp-neutral.tga");
966                 precache_pic("gfx/ons-cp-red.tga");
967                 precache_pic("gfx/ons-cp-blue.tga");
968                 precache_pic("gfx/ons-frame.tga");
969                 precache_pic("gfx/ons-frame-team.tga");
970         } else if(gametype == GAME_KEYHUNT) {
971                 precache_pic("gfx/sb_key_carrying");
972                 precache_pic("gfx/sb_key_carrying_outline");
973         }
974
975         if not(isdemo())
976         {
977                 localcmd("\n_cl_hook_gamestart ", GametypeNameFromType(gametype), ";");
978                 calledhooks |= HOOK_START;
979         }
980 }
981 // CSQC_Parse_StuffCmd : Provides the stuffcmd string in the first parameter that the server provided.  To execute standard behavior, simply execute localcmd with the string.
982 void CSQC_Parse_StuffCmd(string strMessage)
983 {
984         localcmd(strMessage);
985 }
986 // CSQC_Parse_Print : Provides the print string in the first parameter that the server provided.  To execute standard behavior, simply execute print with the string.
987 void CSQC_Parse_Print(string strMessage)
988 {
989         print(ColorTranslateRGB(strMessage));
990 }
991
992 // CSQC_Parse_CenterPrint : Provides the centerprint string in the first parameter that the server provided.
993 void CSQC_Parse_CenterPrint(string strMessage)
994 {
995         centerprint(strMessage);
996 }
997
998 string notranslate_fogcmd1 = "\nfog ";
999 string notranslate_fogcmd2 = "\nr_fog_exp2 0\nr_drawfog 1\n";
1000 void Fog_Force()
1001 {
1002         // TODO somehow thwart prvm_globalset client ...
1003
1004         if(forcefog != "")
1005                 localcmd(strcat(notranslate_fogcmd1, forcefog, notranslate_fogcmd2));
1006 }
1007
1008 void Gamemode_Init();
1009 void Ent_ScoresInfo()
1010 {
1011         float i;
1012         self.classname = "ent_client_scores_info";
1013         gametype = ReadByte();
1014         for(i = 0; i < MAX_SCORE; ++i)
1015         {
1016                 scores_label[i] = strzone(ReadString());
1017                 scores_flags[i] = ReadByte();
1018         }
1019         for(i = 0; i < MAX_TEAMSCORE; ++i)
1020         {
1021                 teamscores_label[i] = strzone(ReadString());
1022                 teamscores_flags[i] = ReadByte();
1023         }
1024         HUD_InitScores();
1025         Gamemode_Init();
1026 }
1027
1028 void Ent_Init()
1029 {
1030         self.classname = "ent_client_init";
1031
1032         nb_pb_period = ReadByte() / 32; //Accuracy of 1/32th
1033
1034         hook_shotorigin_x = ReadCoord();
1035         hook_shotorigin_y = ReadCoord();
1036         hook_shotorigin_z = ReadCoord();
1037
1038         if(forcefog)
1039                 strunzone(forcefog);
1040         forcefog = strzone(ReadString());
1041
1042         armorblockpercent = ReadByte() / 255.0;
1043
1044         g_weaponswitchdelay = ReadByte() / 255.0;
1045
1046         g_balance_grenadelauncher_secondary_bouncefactor = ReadCoord();
1047         g_balance_grenadelauncher_secondary_bouncestop = ReadCoord();
1048
1049         if(!postinit)
1050                 PostInit();
1051 }
1052
1053 void Net_ReadRace()
1054 {
1055         float b;
1056
1057         b = ReadByte();
1058
1059         switch(b)
1060         {
1061                 case RACE_NET_CHECKPOINT_HIT_QUALIFYING:
1062                         race_checkpoint = ReadByte();
1063                         race_time = ReadInt24_t();
1064                         race_previousbesttime = ReadInt24_t();
1065                         if(race_previousbestname)
1066                                 strunzone(race_previousbestname);
1067                         race_previousbestname = strzone(ColorTranslateRGB(ReadString()));
1068
1069                         race_checkpointtime = time;
1070
1071                         if(race_checkpoint == 0 || race_checkpoint == 254)
1072                         {
1073                                 race_penaltyaccumulator = 0;
1074                                 race_laptime = time; // valid
1075                         }
1076
1077                         break;
1078
1079                 case RACE_NET_CHECKPOINT_CLEAR:
1080                         race_laptime = 0;
1081                         race_checkpointtime = 0;
1082                         break;
1083
1084                 case RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING:
1085                         race_laptime = ReadCoord();
1086                         race_checkpointtime = -99999;
1087                         // fall through
1088                 case RACE_NET_CHECKPOINT_NEXT_QUALIFYING:
1089                         race_nextcheckpoint = ReadByte();
1090
1091                         race_nextbesttime = ReadInt24_t();
1092                         if(race_nextbestname)
1093                                 strunzone(race_nextbestname);
1094                         race_nextbestname = strzone(ColorTranslateRGB(ReadString()));
1095                         break;
1096
1097                 case RACE_NET_CHECKPOINT_HIT_RACE:
1098                         race_mycheckpoint = ReadByte();
1099                         race_mycheckpointtime = time;
1100                         race_mycheckpointdelta = ReadInt24_t();
1101                         race_mycheckpointlapsdelta = ReadByte();
1102                         if(race_mycheckpointlapsdelta >= 128)
1103                                 race_mycheckpointlapsdelta -= 256;
1104                         if(race_mycheckpointenemy)
1105                                 strunzone(race_mycheckpointenemy);
1106                         race_mycheckpointenemy = strzone(ColorTranslateRGB(ReadString()));
1107                         break;
1108
1109                 case RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT:
1110                         race_othercheckpoint = ReadByte();
1111                         race_othercheckpointtime = time;
1112                         race_othercheckpointdelta = ReadInt24_t();
1113                         race_othercheckpointlapsdelta = ReadByte();
1114                         if(race_othercheckpointlapsdelta >= 128)
1115                                 race_othercheckpointlapsdelta -= 256;
1116                         if(race_othercheckpointenemy)
1117                                 strunzone(race_othercheckpointenemy);
1118                         race_othercheckpointenemy = strzone(ColorTranslateRGB(ReadString()));
1119                         break;
1120
1121                 case RACE_NET_PENALTY_RACE:
1122                         race_penaltyeventtime = time;
1123                         race_penaltytime = ReadShort();
1124                         //race_penaltyaccumulator += race_penaltytime;
1125                         if(race_penaltyreason)
1126                                 strunzone(race_penaltyreason);
1127                         race_penaltyreason = strzone(ReadString());
1128                         break;
1129
1130                 case RACE_NET_PENALTY_QUALIFYING:
1131                         race_penaltyeventtime = time;
1132                         race_penaltytime = ReadShort();
1133                         race_penaltyaccumulator += race_penaltytime;
1134                         if(race_penaltyreason)
1135                                 strunzone(race_penaltyreason);
1136                         race_penaltyreason = strzone(ReadString());
1137                         break;
1138
1139                 case RACE_NET_SERVER_RECORD:
1140                         race_server_record = ReadInt24_t();
1141                         break;
1142                 case RACE_NET_SPEED_AWARD:
1143                         race_speedaward = ReadInt24_t();
1144                         if(race_speedaward_holder)
1145                                 strunzone(race_speedaward_holder);
1146                         race_speedaward_holder = strzone(ReadString());
1147                         break;
1148                 case RACE_NET_SPEED_AWARD_BEST:
1149                         race_speedaward_alltimebest = ReadInt24_t();
1150                         if(race_speedaward_alltimebest_holder)
1151                                 strunzone(race_speedaward_alltimebest_holder);
1152                         race_speedaward_alltimebest_holder = strzone(ReadString());
1153                         break;
1154                 case RACE_NET_SERVER_RANKINGS:
1155                         float pos, prevpos, del;
1156                         pos = ReadShort();
1157                         prevpos = ReadShort();
1158                         del = ReadShort();
1159
1160                         // move other rankings out of the way
1161                         float i;
1162                         if (prevpos) {
1163                                 for (i=prevpos-1;i>pos-1;--i) {
1164                                         grecordtime[i] = grecordtime[i-1];
1165                                         if(grecordholder[i])
1166                                                 strunzone(grecordholder[i]);
1167                                         grecordholder[i] = strzone(grecordholder[i-1]);
1168                                 }
1169                         } else if (del) { // a record has been deleted by the admin
1170                                 for (i=pos-1; i<= RANKINGS_CNT-1; ++i) {
1171                                         if (i == RANKINGS_CNT-1) { // clear out last record
1172                                                 grecordtime[i] = 0;
1173                                                 if (grecordholder[i])
1174                                                         strunzone(grecordholder[i]);
1175                                                 grecordholder[i] = string_null;
1176                                         }
1177                                         else {
1178                                                 grecordtime[i] = grecordtime[i+1];
1179                                                 if (grecordholder[i])
1180                                                         strunzone(grecordholder[i]);
1181                                                 grecordholder[i] = strzone(grecordholder[i+1]);
1182                                         }
1183                                 }
1184                         } else { // player has no ranked record yet
1185                                 for (i=RANKINGS_CNT-1;i>pos-1;--i) {
1186                                         grecordtime[i] = grecordtime[i-1];
1187                                         if(grecordholder[i])
1188                                                 strunzone(grecordholder[i]);
1189                                         grecordholder[i] = strzone(grecordholder[i-1]);
1190                                 }
1191                         }
1192
1193                         // store new ranking
1194                         if(grecordholder[pos-1] != "")
1195                                 strunzone(grecordholder[pos-1]);
1196                         grecordholder[pos-1] = strzone(ReadString());
1197                         grecordtime[pos-1] = ReadInt24_t();
1198                         if(grecordholder[pos-1] == GetPlayerName(player_localentnum -1))
1199                                 race_myrank = pos;
1200                         break;
1201                 case RACE_NET_SERVER_STATUS:
1202                         race_status = ReadShort();
1203                         if(race_status_name)
1204                                 strunzone(race_status_name);
1205                         race_status_name = strzone(ReadString());
1206         }
1207 }
1208
1209 void Net_ReadSpawn()
1210 {
1211         zoomin_effect = 1;
1212         current_viewzoom = 0.6;
1213 }
1214
1215 void Net_TeamNagger()
1216 {
1217         teamnagger = 1;
1218 }
1219
1220 void Net_ReadPingPLReport()
1221 {
1222         float e, pi, pl, ml;
1223         e = ReadByte();
1224         pi = ReadShort();
1225         pl = ReadByte();
1226         ml = ReadByte();
1227         if not(playerslots[e])
1228                 return;
1229         playerslots[e].ping = pi;
1230         playerslots[e].ping_packetloss = pl / 255.0;
1231         playerslots[e].ping_movementloss = ml / 255.0;
1232 }
1233
1234 void Net_VoteDialog(float highlight) {
1235         if(highlight) {
1236                 vote_highlighted = ReadShort();
1237                 return;
1238         }
1239
1240         vote_yescount = ReadShort();
1241         vote_nocount = ReadShort();
1242         vote_needed = ReadShort();
1243         vote_active = 1;
1244 }
1245
1246 void Net_VoteDialogReset() {
1247         vote_active = 0;
1248 }
1249
1250 // CSQC_Parse_TempEntity : Handles all temporary entity network data in the CSQC layer.
1251 // You must ALWAYS first acquire the temporary ID, which is sent as a byte.
1252 // Return value should be 1 if CSQC handled the temporary entity, otherwise return 0 to have the engine process the event.
1253 float CSQC_Parse_TempEntity()
1254 {
1255         local float bHandled;
1256                 bHandled  = true;
1257         // Acquire TE ID
1258         local float nTEID;
1259                 nTEID = ReadByte();
1260
1261                 // NOTE: Could just do return instead of break...
1262         switch(nTEID)
1263         {
1264                 case TE_CSQC_TARGET_MUSIC:
1265                         Net_TargetMusic();
1266                         bHandled = true;
1267                         break;
1268                 case TE_CSQC_PICTURE:
1269                         Net_MapVote_Picture();
1270                         bHandled = true;
1271                         break;
1272                 case TE_CSQC_RACE:
1273                         Net_ReadRace();
1274                         bHandled = true;
1275                         break;
1276                 case 13: // TE_BEAM
1277                         Net_GrapplingHook();
1278                         bHandled = true;
1279                         break;
1280                 case TE_CSQC_SPAWN:
1281                         Net_ReadSpawn();
1282                         bHandled = true;
1283                         break;
1284                 case TE_CSQC_ZCURVEPARTICLES:
1285                         Net_ReadZCurveParticles();
1286                         bHandled = true;
1287                         break;
1288                 case TE_CSQC_NEXGUNBEAMPARTICLE:
1289                         Net_ReadNexgunBeamParticle();
1290                         bHandled = true;
1291                         break;
1292                 case TE_CSQC_TEAMNAGGER:
1293                         Net_TeamNagger();
1294                         bHandled = true;
1295                         break;
1296                 case TE_CSQC_VOTE:
1297                         Net_VoteDialog(ReadByte());
1298                         bHandled = true;
1299                         break;
1300                 case TE_CSQC_VOTERESET:
1301                         Net_VoteDialogReset();
1302                         bHandled = true;
1303                         break;
1304                 case TE_CSQC_LIGHTNINGARC:
1305                         Net_ReadLightningarc();
1306                         bHandled = true;
1307                         break;
1308                 case TE_CSQC_PINGPLREPORT:
1309                         Net_ReadPingPLReport();
1310                         bHandled = true;
1311                         break;
1312                 case TE_CSQC_ANNOUNCE:
1313                         announce_snd = strzone(ReadString());
1314                         bHandled = true;
1315                         break;
1316                 default:
1317                         // No special logic for this temporary entity; return 0 so the engine can handle it
1318                         bHandled = false;
1319                         break;
1320         }
1321
1322         return bHandled;
1323 }
1324
1325 string getcommandkey(string text, string command)
1326 {
1327         string keys;
1328         float n, j, k, l;
1329
1330         if (!hud_showbinds)
1331                 return text;
1332
1333         keys = db_get(binddb, command);
1334         if (!keys)
1335         {
1336                 n = tokenize(findkeysforcommand(command)); // uses '...' strings
1337                 for(j = 0; j < n; ++j)
1338                 {
1339                         k = stof(argv(j));
1340                         if(k != -1)
1341                         {
1342                                 if ("" == keys)
1343                                         keys = keynumtostring(k);
1344                                 else
1345                                         keys = strcat(keys, ", ", keynumtostring(k));
1346
1347                                 ++l;
1348                                 if (hud_showbinds_limit > 0 && hud_showbinds_limit >= l) break;
1349                         }
1350
1351                 }
1352                 db_put(binddb, command, keys);
1353         }
1354
1355         if ("" == keys) {
1356                 if (hud_showbinds > 1)
1357                         return strcat(text, " (not bound)");
1358                 else
1359                         return text;
1360         }
1361         else if (hud_showbinds > 1)
1362                 return strcat(text, " (", keys, ")");
1363         else
1364                 return keys;
1365 }