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