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