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