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