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