Merge branch 'master' into terencehill/music_player
[xonotic/xonotic-data.pk3dir.git] / qcsrc / client / Main.qc
1 // --------------------------------------------------------------------------
2 // BEGIN REQUIRED CSQC FUNCTIONS
3 //include "main.qh"
4
5 entity clearentity_ent;
6 void clearentity(entity e)
7 {
8         if (!clearentity_ent)
9         {
10                 clearentity_ent = spawn();
11                 clearentity_ent.classname = "clearentity";
12         }
13         float n = e.entnum;
14         copyentity(clearentity_ent, e);
15         e.entnum = n;
16 }
17
18 #define DP_CSQC_ENTITY_REMOVE_IS_B0RKED
19 void menu_show_error()
20 {
21         drawstring('0 200 0', _("ERROR - MENU IS VISIBLE BUT NO MENU WAS DEFINED!"), '8 8 0', '1 0 0', 1, 0);
22 }
23
24 // CSQC_Init : Called every time the CSQC code is initialized (essentially at map load)
25 // Useful for precaching things
26
27 void menu_sub_null()
28 {
29 }
30
31 string forcefog;
32 void WaypointSprite_Load();
33 void ConsoleCommand_macro_init();
34 void CSQC_Init(void)
35 {
36         prvm_language = cvar_string("prvm_language");
37
38 #ifdef WATERMARK
39         dprintf("^4CSQC Build information: ^1%s\n", WATERMARK);
40 #endif
41
42         float i;
43
44 #ifdef COMPAT_XON050_ENGINE
45         // old engine lacks implementation of player_localnum
46         player_localnum = player_localentnum - 1;
47 #endif
48
49         binddb = db_create();
50         tempdb = db_create();
51         ClientProgsDB = db_load("client.db");
52         compressShortVector_init();
53
54         draw_endBoldFont();
55         menu_visible = FALSE;
56         menu_show = menu_show_error;
57         menu_action = func_null;
58
59         for(i = 0; i < 255; ++i)
60                 if(getplayerkeyvalue(i, "viewentity") == "")
61                         break;
62         maxclients = i;
63
64         //registercommand("hud_configure");
65         //registercommand("hud_save");
66         //registercommand("menu_action");
67
68         ConsoleCommand_macro_init();
69
70         registercvar("hud_usecsqc", "1");
71         registercvar("scoreboard_columns", "default");
72
73         registercvar("cl_nade_type", "3");
74         registercvar("cl_pokenade_type", "zombie");
75
76         gametype = 0;
77
78         // hud_fields uses strunzone on the titles!
79         for(i = 0; i < MAX_HUD_FIELDS; ++i)
80                 hud_title[i] = strzone("(null)");
81
82         Cmd_HUD_SetFields(0);
83
84         postinit = false;
85
86         calledhooks = 0;
87
88         teams = Sort_Spawn();
89         players = Sort_Spawn();
90
91         GetTeam(NUM_SPECTATOR, true); // add specs first
92
93         // needs to be done so early because of the constants they create
94         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
95         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
96         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
97         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
98         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
99         CALL_ACCUMULATED_FUNCTION(RegisterHUD_Panels);
100         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
101
102         WaypointSprite_Load();
103
104         // precaches
105         precache_model("null");
106         precache_sound("misc/hit.wav");
107         precache_sound("misc/typehit.wav");
108
109         Projectile_Precache();
110         Hook_Precache();
111         GibSplash_Precache();
112         Casings_Precache();
113         Vehicles_Precache();
114         turrets_precache();
115         Tuba_Precache();
116         CSQCPlayer_Precache();
117
118         if(autocvar_cl_reticle)
119         {
120                 precache_pic("gfx/reticle_normal");
121                 // weapon reticles are precached in weapon files
122         }
123
124         get_mi_min_max_texcoords(1); // try the CLEVER way first
125         minimapname = strcat("gfx/", mi_shortname, "_radar.tga");
126         shortmapname = mi_shortname;
127
128         if(precache_pic(minimapname) == "")
129         {
130                 // but maybe we have a non-clever minimap
131                 minimapname = strcat("gfx/", mi_shortname, "_mini.tga");
132                 if(precache_pic(minimapname) == "")
133                         minimapname = ""; // FAIL
134                 else
135                         get_mi_min_max_texcoords(0); // load new texcoords
136         }
137
138         mi_center = (mi_min + mi_max) * 0.5;
139         mi_scale = mi_max - mi_min;
140         minimapname = strzone(minimapname);
141
142         WarpZone_Init();
143
144         hud_skin_path = strzone(strcat("gfx/hud/", autocvar_hud_skin));
145         hud_configure_prev = -1;
146
147         draw_currentSkin = strzone(strcat("gfx/menu/", cvar_string("menu_skin")));
148 }
149
150 // CSQC_Shutdown : Called every time the CSQC code is shutdown (changing maps, quitting, etc)
151 void Shutdown(void)
152 {
153         WarpZone_Shutdown();
154
155         remove(teams);
156         remove(players);
157         db_close(binddb);
158         db_close(tempdb);
159         if(autocvar_cl_db_saveasdump)
160                 db_dump(ClientProgsDB, "client.db");
161         else
162                 db_save(ClientProgsDB, "client.db");
163         db_close(ClientProgsDB);
164
165         if(camera_active)
166                 cvar_set("chase_active",ftos(chase_active_backup));
167
168         // unset the event chasecam's chase_active
169         if(autocvar_chase_active < 0)
170                 cvar_set("chase_active", "0");
171
172         if (!isdemo())
173         {
174                 if (!(calledhooks & HOOK_START))
175                         localcmd("\n_cl_hook_gamestart nop\n");
176                 if (!(calledhooks & HOOK_END))
177                         localcmd("\ncl_hook_gameend\n");
178         }
179 }
180
181 .float has_team;
182 float SetTeam(entity o, float Team)
183 {
184         entity tm;
185         if(teamplay)
186         {
187                 switch(Team)
188                 {
189                         case -1:
190                         case NUM_TEAM_1:
191                         case NUM_TEAM_2:
192                         case NUM_TEAM_3:
193                         case NUM_TEAM_4:
194                                 break;
195                         default:
196                                 if(GetTeam(Team, false) == world)
197                                 {
198                                         dprintf("trying to switch to unsupported team %d\n", Team);
199                                         Team = NUM_SPECTATOR;
200                                 }
201                                 break;
202                 }
203         }
204         else
205         {
206                 switch(Team)
207                 {
208                         case -1:
209                         case 0:
210                                 break;
211                         default:
212                                 if(GetTeam(Team, false) == world)
213                                 {
214                                         dprintf("trying to switch to unsupported team %d\n", Team);
215                                         Team = NUM_SPECTATOR;
216                                 }
217                                 break;
218                 }
219         }
220         if(Team == -1) // leave
221         {
222                 if(o.has_team)
223                 {
224                         tm = GetTeam(o.team, false);
225                         tm.team_size -= 1;
226                         o.has_team = 0;
227                         return TRUE;
228                 }
229         }
230         else
231         {
232                 if (!o.has_team)
233                 {
234                         o.team = Team;
235                         tm = GetTeam(Team, true);
236                         tm.team_size += 1;
237                         o.has_team = 1;
238                         return TRUE;
239                 }
240                 else if(Team != o.team)
241                 {
242                         tm = GetTeam(o.team, false);
243                         tm.team_size -= 1;
244                         o.team = Team;
245                         tm = GetTeam(Team, true);
246                         tm.team_size += 1;
247                         return TRUE;
248                 }
249         }
250         return FALSE;
251 }
252
253 void Playerchecker_Think()
254 {
255         float i;
256         entity e;
257         for(i = 0; i < maxclients; ++i)
258         {
259                 e = playerslots[i];
260                 if(GetPlayerName(i) == "")
261                 {
262                         if(e.sort_prev)
263                         {
264                                 // player disconnected
265                                 SetTeam(e, -1);
266                                 RemovePlayer(e);
267                                 e.sort_prev = world;
268                                 //e.gotscores = 0;
269                         }
270                 }
271                 else
272                 {
273                         if (!e.sort_prev)
274                         {
275                                 // player connected
276                                 if (!e)
277                                         playerslots[i] = e = spawn();
278                                 e.sv_entnum = i;
279                                 e.ping = 0;
280                                 e.ping_packetloss = 0;
281                                 e.ping_movementloss = 0;
282                                 //e.gotscores = 0; // we might already have the scores...
283                                 SetTeam(e, GetPlayerColor(i)); // will not hurt; later updates come with HUD_UpdatePlayerTeams
284                                 RegisterPlayer(e);
285                                 HUD_UpdatePlayerPos(e);
286                         }
287                 }
288         }
289         self.nextthink = time + 0.2;
290 }
291
292 void Porto_Init();
293 void TrueAim_Init();
294 void PostInit(void)
295 {
296         entity playerchecker;
297         playerchecker = spawn();
298         playerchecker.think = Playerchecker_Think;
299         playerchecker.nextthink = time + 0.2;
300
301         Porto_Init();
302         TrueAim_Init();
303
304         postinit = true;
305 }
306
307 float button_zoom;
308
309 // CSQC_InputEvent : Used to perform actions based on any key pressed, key released and mouse on the client.
310 // Return value should be 1 if CSQC handled the input, otherwise return 0 to have the input passed to the engine.
311 // All keys are in ascii.
312 // bInputType = 0 is key pressed, 1 is key released, 2 and 3 are mouse input.
313 // In the case of keyboard input, nPrimary is the ascii code, and nSecondary is 0.
314 // In the case of mouse input, nPrimary is xdelta, nSecondary is ydelta.
315 // In the case of mouse input after a setcursormode(1) call, nPrimary is xpos, nSecondary is ypos.
316 float CSQC_InputEvent(float bInputType, float nPrimary, float nSecondary)
317 {
318         float bSkipKey;
319         bSkipKey = false;
320
321         if (HUD_Panel_InputEvent(bInputType, nPrimary, nSecondary))
322                 return true;
323
324         if (MapVote_InputEvent(bInputType, nPrimary, nSecondary))
325                 return true;
326
327         if(menu_visible && menu_action)
328                 if(menu_action(bInputType, nPrimary, nSecondary))
329                         return TRUE;
330
331         return bSkipKey;
332 }
333
334 // END REQUIRED CSQC FUNCTIONS
335 // --------------------------------------------------------------------------
336
337 // --------------------------------------------------------------------------
338 // BEGIN OPTIONAL CSQC FUNCTIONS
339 void Ent_RemoveEntCS()
340 {
341         entcs_receiver[self.sv_entnum] = world;
342 }
343 void Ent_ReadEntCS()
344 {
345         float sf;
346         InterpolateOrigin_Undo();
347
348         self.classname = "entcs_receiver";
349         sf = ReadByte();
350
351         if(sf & 1)
352                 self.sv_entnum = ReadByte();
353         if(sf & 2)
354         {
355                 self.origin_x = ReadShort();
356                 self.origin_y = ReadShort();
357                 self.origin_z = ReadShort();
358                 setorigin(self, self.origin);
359         }
360         if(sf & 4)
361         {
362                 self.angles_y = ReadByte() * 360.0 / 256;
363                 self.angles_x = self.angles_z = 0;
364         }
365         if(sf & 8)
366                 self.healthvalue = ReadByte() * 10;
367         if(sf & 16)
368                 self.armorvalue = ReadByte() * 10;
369
370         entcs_receiver[self.sv_entnum] = self;
371         self.entremove = Ent_RemoveEntCS;
372         self.iflags |= IFLAG_ORIGIN;
373
374         InterpolateOrigin_Note();
375 }
376
377 void Ent_Remove();
378
379 void Ent_RemovePlayerScore()
380 {
381         float i;
382
383         if(self.owner)
384         {
385                 SetTeam(self.owner, -1);
386                 self.owner.gotscores = 0;
387                 for(i = 0; i < MAX_SCORE; ++i)
388                         self.owner.(scores[i]) = 0; // clear all scores
389         }
390 }
391
392 void Ent_ReadPlayerScore()
393 {
394         float i, n;
395         float isNew;
396         entity o;
397
398         // damnit -.- don't want to go change every single .sv_entnum in hud.qc AGAIN
399         // (no I've never heard of M-x replace-string, sed, or anything like that)
400         isNew = !self.owner; // workaround for DP bug
401         n = ReadByte()-1;
402
403 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
404         if(!isNew && n != self.sv_entnum)
405         {
406                 //print("A CSQC entity changed its owner!\n");
407                 printf("A CSQC entity changed its owner! (edict: %d, classname: %s)\n", num_for_edict(self), self.classname);
408                 isNew = true;
409                 Ent_Remove();
410                 self.enttype = ENT_CLIENT_SCORES;
411         }
412 #endif
413
414         self.sv_entnum = n;
415
416         if (!(playerslots[self.sv_entnum]))
417                 playerslots[self.sv_entnum] = spawn();
418         o = self.owner = playerslots[self.sv_entnum];
419         o.sv_entnum = self.sv_entnum;
420         o.gotscores = 1;
421
422         //if (!o.sort_prev)
423         //      RegisterPlayer(o);
424         //playerchecker will do this for us later, if it has not already done so
425
426         float sf, lf;
427 #if MAX_SCORE <= 8
428         sf = ReadByte();
429         lf = ReadByte();
430 #else
431         sf = ReadShort();
432         lf = ReadShort();
433 #endif
434         float p;
435         for(i = 0, p = 1; i < MAX_SCORE; ++i, p *= 2)
436                 if(sf & p)
437                 {
438                         if(lf & p)
439                                 o.(scores[i]) = ReadInt24_t();
440                         else
441                                 o.(scores[i]) = ReadChar();
442                 }
443
444         if(o.sort_prev)
445                 HUD_UpdatePlayerPos(o); // if not registered, we cannot do this yet!
446
447         self.entremove = Ent_RemovePlayerScore;
448 }
449
450 void Ent_ReadTeamScore()
451 {
452         float i;
453         entity o;
454
455         self.team = ReadByte();
456         o = self.owner = GetTeam(self.team, true); // these team numbers can always be trusted
457
458         float sf, lf;
459 #if MAX_TEAMSCORE <= 8
460         sf = ReadByte();
461         lf = ReadByte();
462 #else
463         sf = ReadShort();
464         lf = ReadShort();
465 #endif
466         float p;
467         for(i = 0, p = 1; i < MAX_TEAMSCORE; ++i, p *= 2)
468                 if(sf & p)
469                 {
470                         if(lf & p)
471                                 o.(teamscores[i]) = ReadInt24_t();
472                         else
473                                 o.(teamscores[i]) = ReadChar();
474                 }
475
476         HUD_UpdateTeamPos(o);
477 }
478
479 void Ent_ClientData()
480 {
481         float f;
482         float newspectatee_status;
483
484         f = ReadByte();
485
486         scoreboard_showscores_force = (f & 1);
487
488         if(f & 2)
489         {
490                 newspectatee_status = ReadByte();
491                 if(newspectatee_status == player_localnum + 1)
492                         newspectatee_status = -1; // observing
493         }
494         else
495                 newspectatee_status = 0;
496
497         spectatorbutton_zoom = (f & 4);
498
499         if(f & 8)
500         {
501                 angles_held_status = 1;
502                 angles_held_x = ReadAngle();
503                 angles_held_y = ReadAngle();
504                 angles_held_z = 0;
505         }
506         else
507                 angles_held_status = 0;
508
509         if(newspectatee_status != spectatee_status)
510         {
511                 // clear race stuff
512                 race_laptime = 0;
513                 race_checkpointtime = 0;
514         }
515         if (autocvar_hud_panel_healtharmor_progressbar_gfx)
516         {
517                 if ( (spectatee_status == -1 && newspectatee_status > 0) //before observing, now spectating
518                   || (spectatee_status > 0 && newspectatee_status > 0 && spectatee_status != newspectatee_status) //changed spectated player
519                 )
520                         prev_p_health = -1;
521                 else if(spectatee_status && !newspectatee_status) //before observing/spectating, now playing
522                         prev_health = -1;
523         }
524         spectatee_status = newspectatee_status;
525
526         // non-COMPAT_XON050_ENGINE: we could get rid of spectatee_status, and derive it from player_localentnum and player_localnum
527 }
528
529 void Ent_Nagger()
530 {
531         float nags, i, j, b, f;
532
533         nags = ReadByte(); // NAGS NAGS NAGS NAGS NAGS NAGS NADZ NAGS NAGS NAGS
534
535         if(!(nags & 4))
536         {
537                 if(vote_called_vote)
538                         strunzone(vote_called_vote);
539                 vote_called_vote = string_null;
540                 vote_active = 0;
541         }
542         else
543         {
544                 vote_active = 1;
545         }
546
547         if(nags & 64)
548         {
549                 vote_yescount = ReadByte();
550                 vote_nocount = ReadByte();
551                 vote_needed = ReadByte();
552                 vote_highlighted = ReadChar();
553         }
554
555         if(nags & 128)
556         {
557                 if(vote_called_vote)
558                         strunzone(vote_called_vote);
559                 vote_called_vote = strzone(ColorTranslateRGB(ReadString()));
560         }
561
562         if(nags & 1)
563         {
564                 for(j = 0; j < maxclients; ++j)
565                         if(playerslots[j])
566                                 playerslots[j].ready = 1;
567                 for(i = 1; i <= maxclients; i += 8)
568                 {
569                         f = ReadByte();
570                         for(j = i-1, b = 1; b < 256; b *= 2, ++j)
571                                 if (!(f & b))
572                                         if(playerslots[j])
573                                                 playerslots[j].ready = 0;
574                 }
575         }
576
577         ready_waiting = (nags & 1);
578         ready_waiting_for_me = (nags & 2);
579         vote_waiting = (nags & 4);
580         vote_waiting_for_me = (nags & 8);
581         warmup_stage = (nags & 16);
582 }
583
584 void Ent_EliminatedPlayers()
585 {
586         float sf, i, j, b, f;
587
588         sf = ReadByte();
589         if(sf & 1)
590         {
591                 for(j = 0; j < maxclients; ++j)
592                         if(playerslots[j])
593                                 playerslots[j].eliminated = 1;
594                 for(i = 1; i <= maxclients; i += 8)
595                 {
596                         f = ReadByte();
597                         for(j = i-1, b = 1; b < 256; b *= 2, ++j)
598                                 if (!(f & b))
599                                         if(playerslots[j])
600                                                 playerslots[j].eliminated = 0;
601                 }
602         }
603 }
604
605 void Ent_RandomSeed()
606 {
607         float s;
608         prandom_debug();
609         s = ReadShort();
610         psrandom(s);
611 }
612
613 void Ent_ReadAccuracy(void)
614 {
615         float sf, f, w, b;
616         sf = ReadInt24_t();
617         if(sf == 0)
618         {
619                 for(w = 0; w <= WEP_LAST - WEP_FIRST; ++w)
620                         weapon_accuracy[w] = -1;
621                 return;
622         }
623
624         for(w = 0, f = 1; w <= WEP_LAST - WEP_FIRST; ++w)
625         {
626                 if(sf & f)
627                 {
628                         b = ReadByte();
629                         if(b == 0)
630                                 weapon_accuracy[w] = -1;
631                         else if(b == 255)
632                                 weapon_accuracy[w] = 1.0; // no better error handling yet, sorry
633                         else
634                                 weapon_accuracy[w] = (b - 1.0) / 100.0;
635                 }
636                 if(f == 0x800000)
637                         f = 1;
638                 else
639                         f *= 2;
640         }
641 }
642
643 void Spawn_Draw(void)
644 {
645         pointparticles(self.cnt, self.origin + '0 0 28', '0 0 2', bound(0, frametime, 0.1));
646 }
647
648 void Ent_ReadSpawnPoint(float is_new) // entity for spawnpoint
649 {
650         float teamnum = (ReadByte() - 1);
651         vector spn_origin;
652         spn_origin_x = ReadShort();
653         spn_origin_y = ReadShort();
654         spn_origin_z = ReadShort();
655
656         if(is_new)
657         {
658                 self.origin = spn_origin;
659                 setsize(self, PL_MIN, PL_MAX);
660                 droptofloor();
661
662                 /*if(autocvar_cl_spawn_point_model) // needs a model first
663                 {
664                         self.mdl = "models/spawnpoint.md3";
665                         self.colormod = Team_ColorRGB(teamnum);
666                         precache_model(self.mdl);
667                         setmodel(self, self.mdl);
668                         self.drawmask = MASK_NORMAL;
669                         //self.movetype = MOVETYPE_NOCLIP;
670                         //self.draw = Spawn_Draw;
671                 }*/
672                 if(autocvar_cl_spawn_point_particles)
673                 {
674                         if((serverflags & SERVERFLAG_TEAMPLAY))
675                         {
676                                 switch(teamnum)
677                                 {
678                                         case NUM_TEAM_1: self.cnt = particleeffectnum("spawn_point_red"); break;
679                                         case NUM_TEAM_2: self.cnt = particleeffectnum("spawn_point_blue"); break;
680                                         case NUM_TEAM_3: self.cnt = particleeffectnum("spawn_point_yellow"); break;
681                                         case NUM_TEAM_4: self.cnt = particleeffectnum("spawn_point_pink"); break;
682                                         default: self.cnt = particleeffectnum("spawn_point_neutral"); break;
683                                 }
684                         }
685                         else { self.cnt = particleeffectnum("spawn_point_neutral"); }
686
687                         self.draw = Spawn_Draw;
688                 }
689         }
690
691         //printf("Ent_ReadSpawnPoint(is_new = %d); origin = %s, team = %d, effect = %d\n", is_new, vtos(self.origin), teamnum, self.cnt);
692 }
693
694 void Ent_ReadSpawnEvent(float is_new)
695 {
696         // If entnum is 0, ONLY do the local spawn actions
697         // this way the server can disable the sending of
698         // spawn origin or such to clients if wanted.
699         float entnum = ReadByte();
700
701         if(entnum)
702         {
703                 self.origin_x = ReadShort();
704                 self.origin_y = ReadShort();
705                 self.origin_z = ReadShort();
706
707                 if(is_new)
708                 {
709                         float teamnum = GetPlayerColor(entnum - 1);
710
711                         if(autocvar_cl_spawn_event_particles)
712                         {
713                                 switch(teamnum)
714                                 {
715                                         case NUM_TEAM_1: pointparticles(particleeffectnum("spawn_event_red"), self.origin, '0 0 0', 1); break;
716                                         case NUM_TEAM_2: pointparticles(particleeffectnum("spawn_event_blue"), self.origin, '0 0 0', 1); break;
717                                         case NUM_TEAM_3: pointparticles(particleeffectnum("spawn_event_yellow"), self.origin, '0 0 0', 1); break;
718                                         case NUM_TEAM_4: pointparticles(particleeffectnum("spawn_event_pink"), self.origin, '0 0 0', 1); break;
719                                         default: pointparticles(particleeffectnum("spawn_event_neutral"), self.origin, '0 0 0', 1); break;
720                                 }
721                         }
722                         if(autocvar_cl_spawn_event_sound)
723                         {
724                                 sound(self, CH_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTEN_NORM);
725                         }
726                 }
727         }
728
729         // local spawn actions
730         if(is_new && (!entnum || (entnum == player_localentnum)))
731         {
732                 zoomin_effect = 1;
733                 current_viewzoom = (1 / bound(1, autocvar_cl_spawnzoom_factor, 16));
734
735                 if(autocvar_cl_unpress_zoom_on_spawn)
736                 {
737                         localcmd("-zoom\n");
738                         button_zoom = FALSE;
739                 }
740         }
741
742         //printf("Ent_ReadSpawnEvent(is_new = %d); origin = %s, entnum = %d, localentnum = %d\n", is_new, vtos(self.origin), entnum, player_localentnum);
743 }
744
745 // CSQC_Ent_Update : Called every frame that the server has indicated an update to the SSQC / CSQC entity has occured.
746 // The only parameter reflects if the entity is "new" to the client, meaning it just came into the client's PVS.
747 void Ent_RadarLink();
748 void Ent_Init();
749 void Ent_ScoresInfo();
750 void CSQC_Ent_Update(float bIsNewEntity)
751 {
752         float t;
753         float savetime;
754         t = ReadByte();
755
756         if(autocvar_developer_csqcentities)
757                 printf("CSQC_Ent_Update(%d) with self=%i self.entnum=%d self.enttype=%d t=%d\n", bIsNewEntity, self, self.entnum, self.enttype, t);
758
759         // set up the "time" global for received entities to be correct for interpolation purposes
760         savetime = time;
761         if(servertime)
762         {
763                 time = servertime;
764         }
765         else
766         {
767                 serverprevtime = time;
768                 serverdeltatime = getstatf(STAT_MOVEVARS_TICRATE) * getstatf(STAT_MOVEVARS_TIMESCALE);
769                 time = serverprevtime + serverdeltatime;
770         }
771
772 #ifdef DP_CSQC_ENTITY_REMOVE_IS_B0RKED
773         if(self.enttype)
774         {
775                 if(t != self.enttype || bIsNewEntity)
776                 {
777                         //print("A CSQC entity changed its type!\n");
778                         printf("A CSQC entity changed its type! (edict: %d, server: %d, type: %d -> %d)\n", num_for_edict(self), self.entnum, self.enttype, t);
779                         Ent_Remove();
780                         clearentity(self);
781                         bIsNewEntity = 1;
782                 }
783         }
784         else
785         {
786                 if(!bIsNewEntity)
787                 {
788                         printf("A CSQC entity appeared out of nowhere! (edict: %d, server: %d, type: %d)\n", num_for_edict(self), self.entnum, t);
789                         bIsNewEntity = 1;
790                 }
791         }
792 #endif
793         self.enttype = t;
794         switch(t)
795         {
796                 case ENT_CLIENT_ENTCS: Ent_ReadEntCS(); break;
797                 case ENT_CLIENT_SCORES: Ent_ReadPlayerScore(); break;
798                 case ENT_CLIENT_TEAMSCORES: Ent_ReadTeamScore(); break;
799                 case ENT_CLIENT_POINTPARTICLES: Ent_PointParticles(); break;
800                 case ENT_CLIENT_RAINSNOW: Ent_RainOrSnow(); break;
801                 case ENT_CLIENT_LASER: Ent_Laser(); break;
802                 case ENT_CLIENT_NAGGER: Ent_Nagger(); break;
803                 case ENT_CLIENT_ELIMINATEDPLAYERS: Ent_EliminatedPlayers(); break;
804                 case ENT_CLIENT_WAYPOINT: Ent_WaypointSprite(); break;
805                 case ENT_CLIENT_RADARLINK: Ent_RadarLink(); break;
806                 case ENT_CLIENT_PROJECTILE: Ent_Projectile(); break;
807                 case ENT_CLIENT_GIBSPLASH: Ent_GibSplash(bIsNewEntity); break;
808                 case ENT_CLIENT_DAMAGEINFO: Ent_DamageInfo(bIsNewEntity); break;
809                 case ENT_CLIENT_CASING: Ent_Casing(bIsNewEntity); break;
810                 case ENT_CLIENT_INIT: Ent_Init(); break;
811                 case ENT_CLIENT_SCORES_INFO: Ent_ScoresInfo(); break;
812                 case ENT_CLIENT_MAPVOTE: Ent_MapVote(); break;
813                 case ENT_CLIENT_CLIENTDATA: Ent_ClientData(); break;
814                 case ENT_CLIENT_RANDOMSEED: Ent_RandomSeed(); break;
815                 case ENT_CLIENT_WALL: Ent_Wall(); break;
816                 case ENT_CLIENT_MODELEFFECT: Ent_ModelEffect(bIsNewEntity); break;
817                 case ENT_CLIENT_TUBANOTE: Ent_TubaNote(bIsNewEntity); break;
818                 case ENT_CLIENT_WARPZONE: WarpZone_Read(bIsNewEntity); break;
819                 case ENT_CLIENT_WARPZONE_CAMERA: WarpZone_Camera_Read(bIsNewEntity); break;
820                 case ENT_CLIENT_WARPZONE_TELEPORTED: WarpZone_Teleported_Read(bIsNewEntity); break;
821                 case ENT_CLIENT_TRIGGER_MUSIC: Ent_ReadTriggerMusic(); break;
822                 case ENT_CLIENT_HOOK: Ent_ReadHook(bIsNewEntity, ENT_CLIENT_HOOK); break;
823                 case ENT_CLIENT_ARC_BEAM: Ent_ReadArcBeam(bIsNewEntity); break;
824                 case ENT_CLIENT_ACCURACY: Ent_ReadAccuracy(); break;
825                 case ENT_CLIENT_AUXILIARYXHAIR: Net_AuXair2(bIsNewEntity); break;
826                 case ENT_CLIENT_TURRET: ent_turret(); break;
827                 case ENT_CLIENT_MODEL: CSQCModel_Read(bIsNewEntity); break;
828                 case ENT_CLIENT_ITEM: ItemRead(bIsNewEntity); break;
829                 case ENT_CLIENT_BUMBLE_RAYGUN: bumble_raygun_read(bIsNewEntity); break;
830                 case ENT_CLIENT_SPAWNPOINT: Ent_ReadSpawnPoint(bIsNewEntity); break;
831                 case ENT_CLIENT_SPAWNEVENT: Ent_ReadSpawnEvent(bIsNewEntity); break;
832                 case ENT_CLIENT_NOTIFICATION: Read_Notification(bIsNewEntity); break;
833                 case ENT_CLIENT_HEALING_ORB: ent_healer(); break;
834
835                 default:
836                         //error(strcat(_("unknown entity type in CSQC_Ent_Update: %d\n"), self.enttype));
837                         error(sprintf("Unknown entity type in CSQC_Ent_Update (enttype: %d, edict: %d, classname: %s)\n", self.enttype, num_for_edict(self), self.classname));
838                         break;
839         }
840
841         time = savetime;
842 }
843 // Destructor, but does NOT deallocate the entity by calling remove(). Also
844 // used when an entity changes its type. For an entity that someone interacts
845 // with others, make sure it can no longer do so.
846 void Ent_Remove()
847 {
848         if(self.entremove)
849                 self.entremove();
850
851         if(self.skeletonindex)
852         {
853                 skel_delete(self.skeletonindex);
854                 self.skeletonindex = 0;
855         }
856
857         if(self.snd_looping > 0)
858         {
859                 sound(self, self.snd_looping, "misc/null.wav", VOL_BASE, autocvar_g_jetpack_attenuation);
860                 self.snd_looping = 0;
861         }
862
863         self.enttype = 0;
864         self.classname = "";
865         self.draw = menu_sub_null;
866         self.entremove = menu_sub_null;
867         // TODO possibly set more stuff to defaults
868 }
869 // CSQC_Ent_Remove : Called when the server requests a SSQC / CSQC entity to be removed.  Essentially call remove(self) as well.
870 void CSQC_Ent_Remove()
871 {
872         if(autocvar_developer_csqcentities)
873                 printf("CSQC_Ent_Remove() with self=%i self.entnum=%d self.enttype=%d\n", self, self.entnum, self.enttype);
874
875         if(wasfreed(self))
876         {
877                 print("WARNING: CSQC_Ent_Remove called for already removed entity. Packet loss?\n");
878                 return;
879         }
880         if(self.enttype)
881                 Ent_Remove();
882         remove(self);
883 }
884
885 void Gamemode_Init()
886 {
887         if (!isdemo())
888         {
889                 if(!(calledhooks & HOOK_START))
890                         localcmd("\n_cl_hook_gamestart ", MapInfo_Type_ToString(gametype), "\n");
891                 calledhooks |= HOOK_START;
892         }
893 }
894 // 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.
895 void CSQC_Parse_StuffCmd(string strMessage)
896 {
897         if(autocvar_developer_csqcentities)
898                 printf("CSQC_Parse_StuffCmd(\"%s\")\n", strMessage);
899
900         localcmd(strMessage);
901 }
902 // 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.
903 void CSQC_Parse_Print(string strMessage)
904 {
905         if(autocvar_developer_csqcentities)
906                 printf("CSQC_Parse_Print(\"%s\")\n", strMessage);
907
908         print(ColorTranslateRGB(strMessage));
909 }
910
911 // CSQC_Parse_CenterPrint : Provides the centerprint_hud string in the first parameter that the server provided.
912 void CSQC_Parse_CenterPrint(string strMessage)
913 {
914         if(autocvar_developer_csqcentities)
915                 printf("CSQC_Parse_CenterPrint(\"%s\")\n", strMessage);
916
917         centerprint_hud(strMessage);
918 }
919
920 string notranslate_fogcmd1 = "\nfog ";
921 string notranslate_fogcmd2 = "\nr_fog_exp2 0\nr_drawfog 1\n";
922 void Fog_Force()
923 {
924         // TODO somehow thwart prvm_globalset client ...
925
926         if(autocvar_cl_orthoview && autocvar_cl_orthoview_nofog)
927                 { localcmd("\nr_drawfog 0\n"); }
928         else if(forcefog != "")
929                 { localcmd(strcat(notranslate_fogcmd1, forcefog, notranslate_fogcmd2)); }
930 }
931
932 void Gamemode_Init();
933 void Ent_ScoresInfo()
934 {
935         float i;
936         self.classname = "ent_client_scores_info";
937         gametype = ReadInt24_t();
938         HUD_ModIcons_SetFunc();
939         for(i = 0; i < MAX_SCORE; ++i)
940         {
941                 if(scores_label[i])
942                         strunzone(scores_label[i]);
943                 scores_label[i] = strzone(ReadString());
944                 scores_flags[i] = ReadByte();
945         }
946         for(i = 0; i < MAX_TEAMSCORE; ++i)
947         {
948                 if(teamscores_label[i])
949                         strunzone(teamscores_label[i]);
950                 teamscores_label[i] = strzone(ReadString());
951                 teamscores_flags[i] = ReadByte();
952         }
953         HUD_InitScores();
954         Gamemode_Init();
955 }
956
957 void Ent_Init()
958 {
959         self.classname = "ent_client_init";
960
961         nb_pb_period = ReadByte() / 32; //Accuracy of 1/32th
962
963         hook_shotorigin[0] = decompressShotOrigin(ReadInt24_t());
964         hook_shotorigin[1] = decompressShotOrigin(ReadInt24_t());
965         hook_shotorigin[2] = decompressShotOrigin(ReadInt24_t());
966         hook_shotorigin[3] = decompressShotOrigin(ReadInt24_t());
967         arc_shotorigin[0] = decompressShotOrigin(ReadInt24_t());
968         arc_shotorigin[1] = decompressShotOrigin(ReadInt24_t());
969         arc_shotorigin[2] = decompressShotOrigin(ReadInt24_t());
970         arc_shotorigin[3] = decompressShotOrigin(ReadInt24_t());
971
972         if(forcefog)
973                 strunzone(forcefog);
974         forcefog = strzone(ReadString());
975
976         armorblockpercent = ReadByte() / 255.0;
977
978         g_balance_mortar_bouncefactor = ReadCoord();
979         g_balance_mortar_bouncestop = ReadCoord();
980         g_balance_electro_secondary_bouncefactor = ReadCoord();
981         g_balance_electro_secondary_bouncestop = ReadCoord();
982
983         vortex_scope = !ReadByte();
984         rifle_scope = !ReadByte();
985
986         serverflags = ReadByte();
987
988         minelayer_maxmines = ReadByte();
989
990         hagar_maxrockets = ReadByte();
991
992         g_trueaim_minrange = ReadCoord();
993         g_balance_porto_secondary = ReadByte();
994
995         if(!postinit)
996                 PostInit();
997 }
998
999 void Net_ReadRace()
1000 {
1001         float b;
1002
1003         b = ReadByte();
1004
1005         switch(b)
1006         {
1007                 case RACE_NET_CHECKPOINT_HIT_QUALIFYING:
1008                         race_checkpoint = ReadByte();
1009                         race_time = ReadInt24_t();
1010                         race_previousbesttime = ReadInt24_t();
1011                         if(race_previousbestname)
1012                                 strunzone(race_previousbestname);
1013                         race_previousbestname = strzone(ColorTranslateRGB(ReadString()));
1014
1015                         race_checkpointtime = time;
1016
1017                         if(race_checkpoint == 0 || race_checkpoint == 254)
1018                         {
1019                                 race_penaltyaccumulator = 0;
1020                                 race_laptime = time; // valid
1021                         }
1022
1023                         break;
1024
1025                 case RACE_NET_CHECKPOINT_CLEAR:
1026                         race_laptime = 0;
1027                         race_checkpointtime = 0;
1028                         break;
1029
1030                 case RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING:
1031                         race_laptime = ReadCoord();
1032                         race_checkpointtime = -99999;
1033                         // fall through
1034                 case RACE_NET_CHECKPOINT_NEXT_QUALIFYING:
1035                         race_nextcheckpoint = ReadByte();
1036
1037                         race_nextbesttime = ReadInt24_t();
1038                         if(race_nextbestname)
1039                                 strunzone(race_nextbestname);
1040                         race_nextbestname = strzone(ColorTranslateRGB(ReadString()));
1041                         break;
1042
1043                 case RACE_NET_CHECKPOINT_HIT_RACE:
1044                         race_mycheckpoint = ReadByte();
1045                         race_mycheckpointtime = time;
1046                         race_mycheckpointdelta = ReadInt24_t();
1047                         race_mycheckpointlapsdelta = ReadByte();
1048                         if(race_mycheckpointlapsdelta >= 128)
1049                                 race_mycheckpointlapsdelta -= 256;
1050                         if(race_mycheckpointenemy)
1051                                 strunzone(race_mycheckpointenemy);
1052                         race_mycheckpointenemy = strzone(ColorTranslateRGB(ReadString()));
1053                         break;
1054
1055                 case RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT:
1056                         race_othercheckpoint = ReadByte();
1057                         race_othercheckpointtime = time;
1058                         race_othercheckpointdelta = ReadInt24_t();
1059                         race_othercheckpointlapsdelta = ReadByte();
1060                         if(race_othercheckpointlapsdelta >= 128)
1061                                 race_othercheckpointlapsdelta -= 256;
1062                         if(race_othercheckpointenemy)
1063                                 strunzone(race_othercheckpointenemy);
1064                         race_othercheckpointenemy = strzone(ColorTranslateRGB(ReadString()));
1065                         break;
1066
1067                 case RACE_NET_PENALTY_RACE:
1068                         race_penaltyeventtime = time;
1069                         race_penaltytime = ReadShort();
1070                         //race_penaltyaccumulator += race_penaltytime;
1071                         if(race_penaltyreason)
1072                                 strunzone(race_penaltyreason);
1073                         race_penaltyreason = strzone(ReadString());
1074                         break;
1075
1076                 case RACE_NET_PENALTY_QUALIFYING:
1077                         race_penaltyeventtime = time;
1078                         race_penaltytime = ReadShort();
1079                         race_penaltyaccumulator += race_penaltytime;
1080                         if(race_penaltyreason)
1081                                 strunzone(race_penaltyreason);
1082                         race_penaltyreason = strzone(ReadString());
1083                         break;
1084
1085                 case RACE_NET_SERVER_RECORD:
1086                         race_server_record = ReadInt24_t();
1087                         break;
1088                 case RACE_NET_SPEED_AWARD:
1089                         race_speedaward = ReadInt24_t();
1090                         if(race_speedaward_holder)
1091                                 strunzone(race_speedaward_holder);
1092                         race_speedaward_holder = strzone(ReadString());
1093                         break;
1094                 case RACE_NET_SPEED_AWARD_BEST:
1095                         race_speedaward_alltimebest = ReadInt24_t();
1096                         if(race_speedaward_alltimebest_holder)
1097                                 strunzone(race_speedaward_alltimebest_holder);
1098                         race_speedaward_alltimebest_holder = strzone(ReadString());
1099                         break;
1100                 case RACE_NET_SERVER_RANKINGS:
1101                         float pos, prevpos, del;
1102                         pos = ReadShort();
1103                         prevpos = ReadShort();
1104                         del = ReadShort();
1105
1106                         // move other rankings out of the way
1107                         float i;
1108                         if (prevpos) {
1109                                 for (i=prevpos-1;i>pos-1;--i) {
1110                                         grecordtime[i] = grecordtime[i-1];
1111                                         if(grecordholder[i])
1112                                                 strunzone(grecordholder[i]);
1113                                         grecordholder[i] = strzone(grecordholder[i-1]);
1114                                 }
1115                         } else if (del) { // a record has been deleted by the admin
1116                                 for (i=pos-1; i<= RANKINGS_CNT-1; ++i) {
1117                                         if (i == RANKINGS_CNT-1) { // clear out last record
1118                                                 grecordtime[i] = 0;
1119                                                 if (grecordholder[i])
1120                                                         strunzone(grecordholder[i]);
1121                                                 grecordholder[i] = string_null;
1122                                         }
1123                                         else {
1124                                                 grecordtime[i] = grecordtime[i+1];
1125                                                 if (grecordholder[i])
1126                                                         strunzone(grecordholder[i]);
1127                                                 grecordholder[i] = strzone(grecordholder[i+1]);
1128                                         }
1129                                 }
1130                         } else { // player has no ranked record yet
1131                                 for (i=RANKINGS_CNT-1;i>pos-1;--i) {
1132                                         grecordtime[i] = grecordtime[i-1];
1133                                         if(grecordholder[i])
1134                                                 strunzone(grecordholder[i]);
1135                                         grecordholder[i] = strzone(grecordholder[i-1]);
1136                                 }
1137                         }
1138
1139                         // store new ranking
1140                         if(grecordholder[pos-1] != "")
1141                                 strunzone(grecordholder[pos-1]);
1142                         grecordholder[pos-1] = strzone(ReadString());
1143                         grecordtime[pos-1] = ReadInt24_t();
1144                         if(grecordholder[pos-1] == GetPlayerName(player_localnum))
1145                                 race_myrank = pos;
1146                         break;
1147                 case RACE_NET_SERVER_STATUS:
1148                         race_status = ReadShort();
1149                         if(race_status_name)
1150                                 strunzone(race_status_name);
1151                         race_status_name = strzone(ReadString());
1152         }
1153 }
1154
1155 void Net_TeamNagger()
1156 {
1157         teamnagger = 1;
1158 }
1159
1160 void Net_ReadPingPLReport()
1161 {
1162         float e, pi, pl, ml;
1163         e = ReadByte();
1164         pi = ReadShort();
1165         pl = ReadByte();
1166         ml = ReadByte();
1167         if (!(playerslots[e]))
1168                 return;
1169         playerslots[e].ping = pi;
1170         playerslots[e].ping_packetloss = pl / 255.0;
1171         playerslots[e].ping_movementloss = ml / 255.0;
1172 }
1173
1174 void Net_WeaponComplain()
1175 {
1176         complain_weapon = ReadByte();
1177
1178         if(complain_weapon_name)
1179                 strunzone(complain_weapon_name);
1180         complain_weapon_name = strzone(WEP_NAME(complain_weapon));
1181
1182         complain_weapon_type = ReadByte();
1183
1184         complain_weapon_time = time;
1185         weapontime = time; // ping the weapon panel
1186
1187         switch(complain_weapon_type)
1188         {
1189                 case 0: Local_Notification(MSG_MULTI, ITEM_WEAPON_NOAMMO, complain_weapon); break;
1190                 case 1: Local_Notification(MSG_MULTI, ITEM_WEAPON_DONTHAVE, complain_weapon); break;
1191                 default: Local_Notification(MSG_MULTI, ITEM_WEAPON_UNAVAILABLE, complain_weapon); break;
1192         }
1193 }
1194
1195 // CSQC_Parse_TempEntity : Handles all temporary entity network data in the CSQC layer.
1196 // You must ALWAYS first acquire the temporary ID, which is sent as a byte.
1197 // Return value should be 1 if CSQC handled the temporary entity, otherwise return 0 to have the engine process the event.
1198 float CSQC_Parse_TempEntity()
1199 {
1200         float bHandled;
1201                 bHandled  = true;
1202         // Acquire TE ID
1203         float nTEID;
1204                 nTEID = ReadByte();
1205
1206         if(autocvar_developer_csqcentities)
1207                 printf("CSQC_Parse_TempEntity() with nTEID=%d\n", nTEID);
1208
1209                 // NOTE: Could just do return instead of break...
1210         switch(nTEID)
1211         {
1212                 case TE_CSQC_TARGET_MUSIC:
1213                         Net_TargetMusic();
1214                         bHandled = true;
1215                         break;
1216                 case TE_CSQC_PICTURE:
1217                         Net_MapVote_Picture();
1218                         bHandled = true;
1219                         break;
1220                 case TE_CSQC_RACE:
1221                         Net_ReadRace();
1222                         bHandled = true;
1223                         break;
1224                 case TE_CSQC_VORTEXBEAMPARTICLE:
1225                         Net_ReadVortexBeamParticle();
1226                         bHandled = true;
1227                         break;
1228                 case TE_CSQC_TEAMNAGGER:
1229                         Net_TeamNagger();
1230                         bHandled = true;
1231                         break;
1232                 case TE_CSQC_ARC:
1233                         Net_ReadArc();
1234                         bHandled = true;
1235                         break;
1236                 case TE_CSQC_PINGPLREPORT:
1237                         Net_ReadPingPLReport();
1238                         bHandled = true;
1239                         break;
1240                 case TE_CSQC_WEAPONCOMPLAIN:
1241                         Net_WeaponComplain();
1242                         bHandled = true;
1243                         break;
1244                 case TE_CSQC_VEHICLESETUP:
1245                         Net_VehicleSetup();
1246                         bHandled = true;
1247                         break;
1248                 case TE_CSQC_SVNOTICE:
1249                         cl_notice_read();
1250                         bHandled = true;
1251                         break;
1252                 case TE_CSQC_SHOCKWAVEPARTICLE:
1253                         Net_ReadShockwaveParticle();
1254                         bHandled = true;
1255                         break;
1256                 default:
1257                         // No special logic for this temporary entity; return 0 so the engine can handle it
1258                         bHandled = false;
1259                         break;
1260         }
1261
1262         return bHandled;
1263 }
1264
1265 string getcommandkey(string text, string command)
1266 {
1267         string keys;
1268         float n, j, k, l = 0;
1269
1270         if (!autocvar_hud_showbinds)
1271                 return text;
1272
1273         keys = db_get(binddb, command);
1274         if (keys == "")
1275         {
1276                 n = tokenize(findkeysforcommand(command, 0)); // uses '...' strings
1277                 for(j = 0; j < n; ++j)
1278                 {
1279                         k = stof(argv(j));
1280                         if(k != -1)
1281                         {
1282                                 if ("" == keys)
1283                                         keys = keynumtostring(k);
1284                                 else
1285                                         keys = strcat(keys, ", ", keynumtostring(k));
1286
1287                                 ++l;
1288                                 if (autocvar_hud_showbinds_limit > 0 && autocvar_hud_showbinds_limit <= l)
1289                                         break;
1290                         }
1291
1292                 }
1293                 if (keys == "")
1294                         keys = "NO_KEY";
1295                 db_put(binddb, command, keys);
1296         }
1297
1298         if (keys == "NO_KEY") {
1299                 if (autocvar_hud_showbinds > 1)
1300                         return sprintf(_("%s (not bound)"), text);
1301                 else
1302                         return text;
1303         }
1304         else if (autocvar_hud_showbinds > 1)
1305                 return sprintf("%s (%s)", text, keys);
1306         else
1307                 return keys;
1308 }