]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/cl_client.qc
Make the legacy announcer code useless/strip most of it out
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / cl_client.qc
1 void race_send_recordtime(float msg);
2 void race_SendRankings(float pos, float prevpos, float del, float msg);
3
4 void send_CSQC_teamnagger() {
5         WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
6         WriteByte(MSG_BROADCAST, TE_CSQC_TEAMNAGGER);
7 }
8
9
10 void AnnounceTo(entity e, string snd)
11 {
12         // foobar
13 }
14
15 float ClientData_Send(entity to, float sf)
16 {
17         if(to != self.owner)
18         {
19                 error("wtf");
20                 return FALSE;
21         }
22
23         entity e;
24
25         e = to;
26         if(to.classname == "spectator")
27                 e = to.enemy;
28
29         sf = 0;
30
31         if(e.race_completed)
32                 sf |= 1; // forced scoreboard
33         if(to.spectatee_status)
34                 sf |= 2; // spectator ent number follows
35         if(e.zoomstate)
36                 sf |= 4; // zoomed
37         if(e.porto_v_angle_held)
38                 sf |= 8; // angles held
39
40         WriteByte(MSG_ENTITY, ENT_CLIENT_CLIENTDATA);
41         WriteByte(MSG_ENTITY, sf);
42
43         if(sf & 2)
44                 WriteByte(MSG_ENTITY, to.spectatee_status);
45
46         if(sf & 8)
47         {
48                 WriteAngle(MSG_ENTITY, e.v_angle_x);
49                 WriteAngle(MSG_ENTITY, e.v_angle_y);
50         }
51
52         return TRUE;
53 }
54
55 void ClientData_Attach()
56 {
57         Net_LinkEntity(self.clientdata = spawn(), FALSE, 0, ClientData_Send);
58         self.clientdata.drawonlytoclient = self;
59         self.clientdata.owner = self;
60 }
61
62 void ClientData_Detach()
63 {
64         remove(self.clientdata);
65         self.clientdata = world;
66 }
67
68 void ClientData_Touch(entity e)
69 {
70         e.clientdata.SendFlags = 1;
71
72         // make it spectatable
73         entity e2;
74         FOR_EACH_REALCLIENT(e2)
75         {
76                 if(e2 != e)
77                         if(e2.classname == "spectator")
78                                 if(e2.enemy == e)
79                                         e2.clientdata.SendFlags = 1;
80         }
81 }
82
83
84 .vector spawnpoint_score;
85 .string netname_previous;
86
87 void spawnfunc_info_player_survivor (void)
88 {
89         spawnfunc_info_player_deathmatch();
90 }
91
92 void spawnfunc_info_player_start (void)
93 {
94         spawnfunc_info_player_deathmatch();
95 }
96
97 void spawnfunc_info_player_deathmatch (void)
98 {
99         self.classname = "info_player_deathmatch";
100         relocate_spawnpoint();
101 }
102
103 void spawnpoint_use()
104 {
105         if(teamplay)
106         if(have_team_spawns > 0)
107         {
108                 self.team = activator.team;
109                 some_spawn_has_been_used = 1;
110         }
111 }
112
113 // Returns:
114 //   _x: prio (-1 if unusable)
115 //   _y: weight
116 vector Spawn_Score(entity spot, float mindist, float teamcheck)
117 {
118         float shortest, thisdist;
119         float prio;
120         entity player;
121
122         prio = 0;
123
124         // filter out spots for the wrong team
125         if(teamcheck >= 0)
126                 if(spot.team != teamcheck)
127                         return '-1 0 0';
128
129         if(race_spawns)
130                 if(spot.target == "")
131                         return '-1 0 0';
132
133         if(clienttype(self) == CLIENTTYPE_REAL)
134         {
135                 if(spot.restriction == 1)
136                         return '-1 0 0';
137         }
138         else
139         {
140                 if(spot.restriction == 2)
141                         return '-1 0 0';
142         }
143
144         shortest = vlen(world.maxs - world.mins);
145         FOR_EACH_PLAYER(player) if (player != self)
146         {
147                 thisdist = vlen(player.origin - spot.origin);
148                 if (thisdist < shortest)
149                         shortest = thisdist;
150         }
151         if(shortest > mindist)
152                 prio += SPAWN_PRIO_GOOD_DISTANCE;
153
154         spawn_score = prio * '1 0 0' + shortest * '0 1 0';
155         spawn_spot = spot;
156
157         // filter out spots for assault
158         if(spot.target != "") {
159                 entity ent;
160                 float found;
161
162                 found = 0;
163                 for(ent = world; (ent = find(ent, targetname, spot.target)); )
164                 {
165                         ++found;
166                         if(ent.spawn_evalfunc)
167                         {
168                                 entity oldself = self;
169                                 self = ent;
170                                 spawn_score = ent.spawn_evalfunc(oldself, spot, spawn_score);
171                                 self = oldself;
172                                 if(spawn_score_x < 0)
173                                         return spawn_score;
174                         }
175                 }
176
177                 if(!found)
178                 {
179                         dprint("WARNING: spawnpoint at ", vtos(spot.origin), " could not find its target ", spot.target, "\n");
180                         return '-1 0 0';
181                 }
182         }
183
184         MUTATOR_CALLHOOK(Spawn_Score);
185         return spawn_score;
186 }
187
188 void Spawn_ScoreAll(entity firstspot, float mindist, float teamcheck)
189 {
190         entity spot;
191         for(spot = firstspot; spot; spot = spot.chain)
192                 spot.spawnpoint_score = Spawn_Score(spot, mindist, teamcheck);
193 }
194
195 entity Spawn_FilterOutBadSpots(entity firstspot, float mindist, float teamcheck)
196 {
197         entity spot, spotlist, spotlistend;
198
199         spotlist = world;
200         spotlistend = world;
201
202         Spawn_ScoreAll(firstspot, mindist, teamcheck);
203
204         for(spot = firstspot; spot; spot = spot.chain)
205         {
206                 if(spot.spawnpoint_score_x >= 0) // spawning allowed here
207                 {
208                         if(spotlistend)
209                                 spotlistend.chain = spot;
210                         spotlistend = spot;
211                         if(!spotlist)
212                                 spotlist = spot;
213                 }
214         }
215         if(spotlistend)
216                 spotlistend.chain = world;
217
218         return spotlist;
219 }
220
221 entity Spawn_WeightedPoint(entity firstspot, float lower, float upper, float exponent)
222 {
223         // weight of a point: bound(lower, mindisttoplayer, upper)^exponent
224         // multiplied by spot.cnt (useful if you distribute many spawnpoints in a small area)
225         entity spot;
226
227         RandomSelection_Init();
228         for(spot = firstspot; spot; spot = spot.chain)
229                 RandomSelection_Add(spot, 0, string_null, pow(bound(lower, spot.spawnpoint_score_y, upper), exponent) * spot.cnt, (spot.spawnpoint_score_y >= lower) * 0.5 + spot.spawnpoint_score_x);
230
231         return RandomSelection_chosen_ent;
232 }
233
234 /*
235 =============
236 SelectSpawnPoint
237
238 Finds a point to respawn
239 =============
240 */
241 entity SelectSpawnPoint (float anypoint)
242 {
243         float teamcheck;
244         entity spot, firstspot;
245
246         spot = find (world, classname, "testplayerstart");
247         if (spot)
248                 return spot;
249
250         if(anypoint || autocvar_g_spawn_useallspawns)
251                 teamcheck = -1;
252         else if(have_team_spawns > 0)
253         {
254                 if(have_team_spawns_forteam[self.team] == 0)
255                 {
256                         // we request a spawn for a team, and we have team
257                         // spawns, but that team has no spawns?
258                         if(have_team_spawns_forteam[0])
259                                 // try noteam spawns
260                                 teamcheck = 0;
261                         else
262                                 // if not, any spawn has to do
263                                 teamcheck = -1;
264                 }
265                 else
266                         teamcheck = self.team; // MUST be team
267         }
268         else if(have_team_spawns == 0 && have_team_spawns_forteam[0])
269                 teamcheck = 0; // MUST be noteam
270         else
271                 teamcheck = -1;
272                 // if we get here, we either require team spawns but have none, or we require non-team spawns and have none; use any spawn then
273
274
275         // get the entire list of spots
276         firstspot = findchain(classname, "info_player_deathmatch");
277         // filter out the bad ones
278         // (note this returns the original list if none survived)
279         if(anypoint)
280         {
281                 spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
282         }
283         else
284         {
285                 float mindist;
286                 if (arena_roundbased && !g_ca)
287                         mindist = 800;
288                 else
289                         mindist = 100;
290                 firstspot = Spawn_FilterOutBadSpots(firstspot, mindist, teamcheck);
291
292                 // there is 50/50 chance of choosing a random spot or the furthest spot
293                 // (this means that roughly every other spawn will be furthest, so you
294                 // usually won't get fragged at spawn twice in a row)
295                 if (random() > autocvar_g_spawn_furthest)
296                         spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
297                 else
298                         spot = Spawn_WeightedPoint(firstspot, 1, 5000, 5); // chooses a far far away spawnpoint
299         }
300
301         if (!spot)
302         {
303                 if(autocvar_spawn_debug)
304                         GotoNextMap(0);
305                 else
306                 {
307                         if(some_spawn_has_been_used)
308                                 return world; // team can't spawn any more, because of actions of other team
309                         else
310                                 error("Cannot find a spawn point - please fix the map!");
311                 }
312         }
313
314         return spot;
315 }
316
317 /*
318 =============
319 CheckPlayerModel
320
321 Checks if the argument string can be a valid playermodel.
322 Returns a valid one in doubt.
323 =============
324 */
325 string FallbackPlayerModel;
326 string CheckPlayerModel(string plyermodel) {
327         if(FallbackPlayerModel != cvar_defstring("_cl_playermodel"))
328         {
329                 // note: we cannot summon Don Strunzone here, some player may
330                 // still have the model string set. In case anyone manages how
331                 // to change a cvar default, we'll have a small leak here.
332                 FallbackPlayerModel = strzone(cvar_defstring("_cl_playermodel"));
333         }
334         // only in right path
335         if( substring(plyermodel,0,14) != "models/player/")
336                 return FallbackPlayerModel;
337         // only good file extensions
338         if(substring(plyermodel,-4,4) != ".zym")
339         if(substring(plyermodel,-4,4) != ".dpm")
340         if(substring(plyermodel,-4,4) != ".iqm")
341         if(substring(plyermodel,-4,4) != ".md3")
342         if(substring(plyermodel,-4,4) != ".psk")
343                 return FallbackPlayerModel;
344         // forbid the LOD models
345         if(substring(plyermodel, -9,5) == "_lod1")
346                 return FallbackPlayerModel;
347         if(substring(plyermodel, -9,5) == "_lod2")
348                 return FallbackPlayerModel;
349         if(plyermodel != strtolower(plyermodel))
350                 return FallbackPlayerModel;
351         // also, restrict to server models
352         if(autocvar_sv_servermodelsonly)
353         {
354                 if(!fexists(plyermodel))
355                         return FallbackPlayerModel;
356         }
357         return plyermodel;
358 }
359
360 void setplayermodel(entity e, string modelname)
361 {
362         precache_model(modelname);
363         setmodel(e, modelname);
364         player_setupanimsformodel();
365         UpdatePlayerSounds();
366 }
367
368 /*
369 =============
370 PutObserverInServer
371
372 putting a client as observer in the server
373 =============
374 */
375 void FixPlayermodel();
376 void PutObserverInServer (void)
377 {
378         entity  spot;
379     self.hud = HUD_NORMAL;
380         race_PreSpawnObserver();
381
382         spot = SelectSpawnPoint (TRUE);
383         if(!spot)
384                 error("No spawnpoints for observers?!?\n");
385         RemoveGrapplingHook(self); // Wazat's Grappling Hook
386
387         if(clienttype(self) == CLIENTTYPE_REAL)
388         {
389                 msg_entity = self;
390                 WriteByte(MSG_ONE, SVC_SETVIEW);
391                 WriteEntity(MSG_ONE, self);
392         }
393
394         MUTATOR_CALLHOOK(MakePlayerObserver);
395
396         minstagib_stop_countdown(self);
397
398         Portal_ClearAll(self);
399         
400         if(self.alivetime)
401         {
402                 if(!inWarmupStage)
403                         PlayerStats_Event(self, PLAYERSTATS_ALIVETIME, time - self.alivetime);
404                 self.alivetime = 0;
405         }
406
407         if(self.vehicle)
408                 vehicles_exit(VHEF_RELESE);         
409
410         WaypointSprite_PlayerDead();
411
412         if not(g_ca)  // don't reset teams when moving a ca player to the spectators
413                 self.team = -1;  // move this as it is needed to log the player spectating in eventlog
414
415         if(self.killcount != -666) {
416                 if(g_lms) {
417                         if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0 && self.lms_spectate_warning != 2)
418                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_LMS_NOLIVES, self.netname);
419                         else
420                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_LMS_FORFEIT, self.netname);
421                 } else { Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_SPECTATE, self.netname); }
422
423                 if(self.just_joined == FALSE) {
424                         LogTeamchange(self.playerid, -1, 4);
425                 } else
426                         self.just_joined = FALSE;
427         }
428
429         PlayerScore_Clear(self); // clear scores when needed
430
431         accuracy_resend(self);
432
433         self.spectatortime = time;
434         
435         self.classname = "observer";
436         self.iscreature = FALSE;
437         self.teleportable = TELEPORT_SIMPLE;
438         self.damagedbycontents = FALSE;
439         self.health = -666;
440         self.takedamage = DAMAGE_NO;
441         self.solid = SOLID_NOT;
442         self.movetype = MOVETYPE_FLY_WORLDONLY; // user preference is controlled by playerprethink
443         self.flags = FL_CLIENT | FL_NOTARGET;
444         self.armorvalue = 666;
445         self.effects = 0;
446         self.armorvalue = autocvar_g_balance_armor_start;
447         self.pauserotarmor_finished = 0;
448         self.pauserothealth_finished = 0;
449         self.pauseregen_finished = 0;
450         self.damageforcescale = 0;
451         self.death_time = 0;
452         self.respawn_time = 0;
453         self.alpha = 0;
454         self.scale = 0;
455         self.fade_time = 0;
456         self.pain_frame = 0;
457         self.pain_finished = 0;
458         self.strength_finished = 0;
459         self.invincible_finished = 0;
460         self.superweapons_finished = 0;
461         self.pushltime = 0;
462         self.istypefrag = 0;
463         self.think = func_null;
464         self.nextthink = 0;
465         self.hook_time = 0;
466         self.deadflag = DEAD_NO;
467         self.angles = spot.angles;
468         self.angles_z = 0;
469         self.fixangle = TRUE;
470         self.crouch = FALSE;
471
472         setorigin (self, (spot.origin + PL_VIEW_OFS)); // offset it so that the spectator spawns higher off the ground, looks better this way
473         self.prevorigin = self.origin;
474         self.items = 0;
475         WEPSET_CLEAR_E(self);
476         self.model = "";
477         FixPlayermodel();
478         setmodel(self, "null");
479         self.drawonlytoclient = self;
480
481         setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX); // give the spectator some space between walls for MOVETYPE_FLY_WORLDONLY
482         self.view_ofs = '0 0 0'; // so that your view doesn't go into the ceiling with MOVETYPE_FLY_WORLDONLY, previously "PL_VIEW_OFS"
483
484         self.weapon = 0;
485         self.weaponname = "";
486         self.switchingweapon = 0;
487         self.weaponmodel = "";
488         self.weaponentity = world;
489         self.exteriorweaponentity = world;
490         self.killcount = -666;
491         self.velocity = '0 0 0';
492         self.avelocity = '0 0 0';
493         self.punchangle = '0 0 0';
494         self.punchvector = '0 0 0';
495         self.oldvelocity = self.velocity;
496         self.fire_endtime = -1;
497
498         if(g_arena)
499         {
500                 if(self.version_mismatch)
501                 {
502                         self.frags = FRAGS_SPECTATOR;
503                         Spawnqueue_Unmark(self);
504                         Spawnqueue_Remove(self);
505                 }
506                 else
507                 {
508                         self.frags = FRAGS_LMS_LOSER;
509                         Spawnqueue_Insert(self);
510                 }
511         }
512         else if(g_lms)
513         {
514                 // Only if the player cannot play at all
515                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) == 666)
516                         self.frags = FRAGS_SPECTATOR;
517                 else
518                         self.frags = FRAGS_LMS_LOSER;
519         }
520         else if(g_ca)
521         {
522                 if(self.caplayer)
523                         self.frags = FRAGS_LMS_LOSER;
524                 else
525                         self.frags = FRAGS_SPECTATOR;
526         }
527         else if((g_race && g_race_qualifying) || g_cts)
528         {
529                 if(PlayerScore_Add(self, SP_RACE_FASTEST, 0))
530                         self.frags = FRAGS_LMS_LOSER;
531                 else
532                         self.frags = FRAGS_SPECTATOR;
533         }
534         else
535                 self.frags = FRAGS_SPECTATOR;
536 }
537
538 .float model_randomizer;
539 void FixPlayermodel()
540 {
541         string defaultmodel;
542         float defaultskin, chmdl, oldskin, n, i;
543         vector m1, m2;
544
545         defaultmodel = "";
546         defaultskin = 0;
547         chmdl = FALSE;
548
549         if(autocvar_sv_defaultcharacter == 1)
550         {
551                 if(teamplay)
552                 {
553                         string s;
554                         s = Team_ColorName_Lower(self.team);
555                         if(s != "neutral")
556                         {
557                                 defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", s));
558                                 defaultskin = cvar(strcat("sv_defaultplayerskin_", s));
559                         }
560                 }
561
562                 if(defaultmodel == "")
563                 {
564                         defaultmodel = autocvar_sv_defaultplayermodel;
565                         defaultskin = autocvar_sv_defaultplayerskin;
566                 }
567
568                 n = tokenize_console(defaultmodel);
569                 if(n > 0)
570                         defaultmodel = argv(floor(n * self.model_randomizer));
571
572                 i = strstrofs(defaultmodel, ":", 0);
573                 if(i >= 0)
574                 {
575                         defaultskin = stof(substring(defaultmodel, i+1, -1));
576                         defaultmodel = substring(defaultmodel, 0, i);
577                 }
578         }
579
580         if(defaultmodel != "")
581         {
582                 if (defaultmodel != self.model)
583                 {
584                         m1 = self.mins;
585                         m2 = self.maxs;
586                         setplayermodel (self, defaultmodel);
587                         setsize (self, m1, m2);
588                         chmdl = TRUE;
589                 }
590
591                 oldskin = self.skin;
592                 self.skin = defaultskin;
593         } else {
594                 if (self.playermodel != self.model || self.playermodel == "")
595                 {
596                         self.playermodel = CheckPlayerModel(self.playermodel); // this is never "", so no endless loop
597                         m1 = self.mins;
598                         m2 = self.maxs;
599                         setplayermodel (self, self.playermodel);
600                         setsize (self, m1, m2);
601                         chmdl = TRUE;
602                 }
603
604                 oldskin = self.skin;
605                 self.skin = stof(self.playerskin);
606         }
607
608         if(chmdl || oldskin != self.skin) // model or skin has changed
609         {
610                 self.species = player_getspecies(); // update species
611                 UpdatePlayerSounds(); // update skin sounds
612         }
613
614         if(!teamplay)
615                 if(strlen(autocvar_sv_defaultplayercolors))
616                         if(self.clientcolors != stof(autocvar_sv_defaultplayercolors))
617                                 setcolor(self, stof(autocvar_sv_defaultplayercolors));
618 }
619
620 void PlayerTouchExplode(entity p1, entity p2)
621 {
622         vector org;
623         org = (p1.origin + p2.origin) * 0.5;
624         org_z += (p1.mins_z + p2.mins_z) * 0.5;
625
626         te_explosion(org);
627
628         entity e;
629         e = spawn();
630         setorigin(e, org);
631         RadiusDamage(e, world, g_touchexplode_damage, g_touchexplode_edgedamage, g_touchexplode_radius, world, g_touchexplode_force, DEATH_TOUCHEXPLODE, world);
632         remove(e);
633 }
634
635 /*
636 =============
637 PutClientInServer
638
639 Called when a client spawns in the server
640 =============
641 */
642
643 void PutClientInServer (void)
644 {
645         if(clienttype(self) == CLIENTTYPE_BOT)
646         {
647                 self.classname = "player";
648                 if(g_ca)
649                         self.caplayer = 1;
650         }
651         else if(clienttype(self) == CLIENTTYPE_REAL)
652         {
653                 msg_entity = self;
654                 WriteByte(MSG_ONE, SVC_SETVIEW);
655                 WriteEntity(MSG_ONE, self);
656         }
657
658         // reset player keys
659         self.itemkeys = 0;
660
661         // player is dead and becomes observer
662         // FIXME fix LMS scoring for new system
663         if(g_lms)
664         {
665                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
666                         self.classname = "observer";
667         }
668
669         if((g_arena && !self.spawned) || (g_ca && !allowed_to_spawn))
670                 self.classname = "observer";
671
672         if(gameover)
673                 self.classname = "observer";
674
675         if(self.classname == "player" && (!g_ca || (g_ca && allowed_to_spawn))) {
676                 entity spot, oldself;
677                 float j;
678
679                 accuracy_resend(self);
680
681                 if(self.team < 0)
682                         JoinBestTeam(self, FALSE, TRUE);
683
684                 race_PreSpawn();
685
686                 spot = SelectSpawnPoint (FALSE);
687                 if(!spot)
688                 {
689                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_JOIN_NOSPAWNS);
690                         return; // spawn failed
691                 }
692
693                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
694
695                 self.classname = "player";
696                 self.wasplayer = TRUE;
697                 self.iscreature = TRUE;
698                 self.teleportable = TELEPORT_NORMAL;
699                 self.damagedbycontents = TRUE;
700                 self.movetype = MOVETYPE_WALK;
701                 self.solid = SOLID_SLIDEBOX;
702                 self.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_SOLID;
703                 if(autocvar_g_playerclip_collisions)
704                         self.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
705                 if(clienttype(self) == CLIENTTYPE_BOT && autocvar_g_botclip_collisions)
706                         self.dphitcontentsmask |= DPCONTENTS_BOTCLIP;
707                 self.frags = FRAGS_PLAYER;
708                 if(INDEPENDENT_PLAYERS)
709                         MAKE_INDEPENDENT_PLAYER(self);
710                 self.flags = FL_CLIENT;
711                 if(autocvar__notarget)
712                         self.flags |= FL_NOTARGET;
713                 self.takedamage = DAMAGE_AIM;
714                 if(g_minstagib)
715                         self.effects = EF_FULLBRIGHT;
716                 else
717                         self.effects = 0;
718                 self.effects |= EF_TELEPORT_BIT | EF_RESTARTANIM_BIT;
719                 self.air_finished = time + 12;
720                 self.dmg = 2;
721                 if(autocvar_g_balance_nex_charge)
722                 {
723                         if(autocvar_g_balance_nex_secondary_chargepool)
724                                 self.nex_chargepool_ammo = 1;
725                         self.nex_charge = autocvar_g_balance_nex_charge_start;
726                 }
727
728                 if(inWarmupStage)
729                 {
730                         self.ammo_shells = warmup_start_ammo_shells;
731                         self.ammo_nails = warmup_start_ammo_nails;
732                         self.ammo_rockets = warmup_start_ammo_rockets;
733                         self.ammo_cells = warmup_start_ammo_cells;
734                         self.ammo_fuel = warmup_start_ammo_fuel;
735                         self.health = warmup_start_health;
736                         self.armorvalue = warmup_start_armorvalue;
737                         WEPSET_COPY_EA(self, warmup_start_weapons);
738                 }
739                 else
740                 {
741                         self.ammo_shells = start_ammo_shells;
742                         self.ammo_nails = start_ammo_nails;
743                         self.ammo_rockets = start_ammo_rockets;
744                         self.ammo_cells = start_ammo_cells;
745                         self.ammo_fuel = start_ammo_fuel;
746                         self.health = start_health;
747                         self.armorvalue = start_armorvalue;
748                         WEPSET_COPY_EA(self, start_weapons);
749                 }
750
751                 if(WEPSET_CONTAINS_ANY_EA(self, WEPBIT_SUPERWEAPONS)) // exception for minstagib, as minstanex is a superweapon
752                         self.superweapons_finished = time + autocvar_g_balance_superweapons_time;
753                 else
754                         self.superweapons_finished = 0;
755
756                 if(g_weaponarena_random)
757                 {
758                         if(g_weaponarena_random_with_laser)
759                                 WEPSET_ANDNOT_EW(self, WEP_LASER);
760                         W_RandomWeapons(self, g_weaponarena_random);
761                         if(g_weaponarena_random_with_laser)
762                                 WEPSET_OR_EW(self, WEP_LASER);
763                 }
764
765                 self.items = start_items;
766
767                 self.spawnshieldtime = time + autocvar_g_spawnshieldtime;
768                 self.pauserotarmor_finished = time + autocvar_g_balance_pause_armor_rot_spawn;
769                 self.pauserothealth_finished = time + autocvar_g_balance_pause_health_rot_spawn;
770                 self.pauserotfuel_finished = time + autocvar_g_balance_pause_fuel_rot_spawn;
771                 self.pauseregen_finished = time + autocvar_g_balance_pause_health_regen_spawn;
772                 //extend the pause of rotting if client was reset at the beginning of the countdown
773                 if(!autocvar_sv_ready_restart_after_countdown && time < game_starttime) { // TODO why is this cvar NOTted?
774                         self.spawnshieldtime += game_starttime - time;
775                         self.pauserotarmor_finished += game_starttime - time;
776                         self.pauserothealth_finished += game_starttime - time;
777                         self.pauseregen_finished += game_starttime - time;
778                 }
779                 self.damageforcescale = 2;
780                 self.death_time = 0;
781                 self.respawn_time = 0;
782                 self.scale = 0;
783                 self.fade_time = 0;
784                 self.pain_frame = 0;
785                 self.pain_finished = 0;
786                 self.strength_finished = 0;
787                 self.invincible_finished = 0;
788                 self.pushltime = 0;
789                 // players have no think function
790                 self.think = func_null;
791                 self.nextthink = 0;
792                 self.hook_time = 0;
793                 self.dmg_team = 0;
794                 self.ballistics_density = autocvar_g_ballistics_density_player;
795
796                 self.metertime = 0;
797
798                 self.deadflag = DEAD_NO;
799
800                 self.angles = spot.angles;
801
802                 self.angles_z = 0; // never spawn tilted even if the spot says to
803                 self.fixangle = TRUE; // turn this way immediately
804                 self.velocity = '0 0 0';
805                 self.avelocity = '0 0 0';
806                 self.punchangle = '0 0 0';
807                 self.punchvector = '0 0 0';
808                 self.oldvelocity = self.velocity;
809                 self.fire_endtime = -1;
810
811                 msg_entity = self;
812                 WRITESPECTATABLE_MSG_ONE({
813                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
814                         WriteByte(MSG_ONE, TE_CSQC_SPAWN);
815                 });
816
817                 self.model = "";
818                 FixPlayermodel();
819                 self.drawonlytoclient = world;
820
821                 self.crouch = FALSE;
822                 self.view_ofs = PL_VIEW_OFS;
823                 setsize (self, PL_MIN, PL_MAX);
824                 self.spawnorigin = spot.origin;
825                 setorigin (self, spot.origin + '0 0 1' * (1 - self.mins_z - 24));
826                 // don't reset back to last position, even if new position is stuck in solid
827                 self.oldorigin = self.origin;
828                 self.prevorigin = self.origin;
829                 self.lastrocket = world; // stop rocket guiding, no revenge from the grave!
830                 self.lastteleporttime = time; // prevent insane speeds due to changing origin
831         self.hud = HUD_NORMAL;
832
833                 if(g_arena)
834                 {
835                         Spawnqueue_Remove(self);
836                         Spawnqueue_Mark(self);
837                 }
838                 else if(g_ca)
839                         self.caplayer = 1;
840
841                 self.event_damage = PlayerDamage;
842
843                 self.bot_attack = TRUE;
844
845                 self.statdraintime = time + 5;
846                 self.BUTTON_ATCK = self.BUTTON_JUMP = self.BUTTON_ATCK2 = 0;
847
848                 if(self.killcount == -666) {
849                         PlayerScore_Clear(self);
850                         self.killcount = 0;
851                 }
852
853                 CL_SpawnWeaponentity();
854                 self.alpha = default_player_alpha;
855                 self.colormod = '1 1 1' * autocvar_g_player_brightness;
856                 self.exteriorweaponentity.alpha = default_weapon_alpha;
857
858                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval*2;
859                 self.lms_traveled_distance = 0;
860                 self.speedrunning = FALSE;
861
862                 race_PostSpawn(spot);
863
864                 //stuffcmd(self, "chase_active 0");
865                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
866
867                 if(g_assault) {
868                         if(self.team == assault_attacker_team)
869                                 Send_Notification(NOTIF_TEAM, self, MSG_CENTER, CENTER_ASSAULT_ATTACKING);
870                         else
871                                 Send_Notification(NOTIF_TEAM, self, MSG_CENTER, CENTER_ASSAULT_DEFENDING);
872                 }
873
874                 target_voicescript_clear(self);
875
876                 // reset fields the weapons may use
877                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
878                 {
879                         weapon_action(j, WR_RESETPLAYER);
880
881                         // all weapons must be fully loaded when we spawn
882                         entity e;
883                         e = get_weaponinfo(j);
884                         if(e.spawnflags & WEP_FLAG_RELOADABLE) // prevent accessing undefined cvars
885                                 self.(weapon_load[j]) = cvar(strcat("g_balance_", e.netname, "_reload_ammo"));
886                 }
887
888                 oldself = self;
889                 self = spot;
890                         activator = oldself;
891                                 string s;
892                                 s = self.target;
893                                 self.target = string_null;
894                                 SUB_UseTargets();
895                                 self.target = s;
896                         activator = world;
897                 self = oldself;
898
899                 spawn_spot = spot;
900                 MUTATOR_CALLHOOK(PlayerSpawn);
901
902                 if(autocvar_spawn_debug)
903                 {
904                         sprint(self, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
905                         remove(spot);   // usefull for checking if there are spawnpoints, that let drop through the floor
906                 }
907
908                 self.switchweapon = w_getbestweapon(self);
909                 self.cnt = -1; // W_LastWeapon will not complain
910                 self.weapon = 0;
911                 self.weaponname = "";
912                 self.switchingweapon = 0;
913
914                 if(!inWarmupStage)
915                         if(!self.alivetime)
916                                 self.alivetime = time;
917
918                 antilag_clear(self);
919
920                 if (autocvar_g_spawnsound)
921                         soundat(world, self.origin, CH_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTN_NORM);
922         } else if(self.classname == "observer") {
923                 PutObserverInServer ();
924         }
925 }
926
927 .float ebouncefactor, ebouncestop; // electro's values
928 // TODO do we need all these fields, or should we stop autodetecting runtime
929 // changes and just have a console command to update this?
930 float ClientInit_SendEntity(entity to, float sf)
931 {
932         WriteByte(MSG_ENTITY, ENT_CLIENT_INIT);
933         WriteByte(MSG_ENTITY, g_nexball_meter_period * 32);
934         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[0]));
935         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[1]));
936         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[2]));
937         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[3]));
938         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[0]));
939         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[1]));
940         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[2]));
941         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[3]));
942         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[0]));
943         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[1]));
944         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[2]));
945         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[3]));
946         if(sv_foginterval && world.fog != "")
947                 WriteString(MSG_ENTITY, world.fog);
948         else
949                 WriteString(MSG_ENTITY, "");
950         WriteByte(MSG_ENTITY, self.count * 255.0); // g_balance_armor_blockpercent
951         WriteByte(MSG_ENTITY, self.cnt * 255.0); // g_balance_weaponswitchdelay
952         WriteCoord(MSG_ENTITY, self.bouncefactor); // g_balance_grenadelauncher_bouncefactor
953         WriteCoord(MSG_ENTITY, self.bouncestop); // g_balance_grenadelauncher_bouncestop
954         WriteCoord(MSG_ENTITY, self.ebouncefactor); // g_balance_grenadelauncher_bouncefactor
955         WriteCoord(MSG_ENTITY, self.ebouncestop); // g_balance_grenadelauncher_bouncestop
956         WriteByte(MSG_ENTITY, autocvar_g_balance_nex_secondary); // client has to know if it should zoom or not
957         WriteByte(MSG_ENTITY, autocvar_g_balance_rifle_secondary); // client has to know if it should zoom or not
958         WriteByte(MSG_ENTITY, serverflags); // client has to know if it should zoom or not
959         WriteByte(MSG_ENTITY, autocvar_g_balance_minelayer_limit); // minelayer max mines
960         WriteByte(MSG_ENTITY, autocvar_g_balance_hagar_secondary_load_max); // hagar max loadable rockets
961         WriteCoord(MSG_ENTITY, autocvar_g_trueaim_minrange);
962         WriteByte(MSG_ENTITY, autocvar_g_balance_porto_secondary);
963         return TRUE;
964 }
965
966 void ClientInit_CheckUpdate()
967 {
968         self.nextthink = time;
969         if(self.count != autocvar_g_balance_armor_blockpercent)
970         {
971                 self.count = autocvar_g_balance_armor_blockpercent;
972                 self.SendFlags |= 1;
973         }
974         if(self.cnt != autocvar_g_balance_weaponswitchdelay)
975         {
976                 self.cnt = autocvar_g_balance_weaponswitchdelay;
977                 self.SendFlags |= 1;
978         }
979         if(self.bouncefactor != autocvar_g_balance_grenadelauncher_bouncefactor)
980         {
981                 self.bouncefactor = autocvar_g_balance_grenadelauncher_bouncefactor;
982                 self.SendFlags |= 1;
983         }
984         if(self.bouncestop != autocvar_g_balance_grenadelauncher_bouncestop)
985         {
986                 self.bouncestop = autocvar_g_balance_grenadelauncher_bouncestop;
987                 self.SendFlags |= 1;
988         }
989         if(self.ebouncefactor != autocvar_g_balance_electro_secondary_bouncefactor)
990         {
991                 self.ebouncefactor = autocvar_g_balance_electro_secondary_bouncefactor;
992                 self.SendFlags |= 1;
993         }
994         if(self.ebouncestop != autocvar_g_balance_electro_secondary_bouncestop)
995         {
996                 self.ebouncestop = autocvar_g_balance_electro_secondary_bouncestop;
997                 self.SendFlags |= 1;
998         }
999 }
1000
1001 void ClientInit_Spawn()
1002 {
1003         entity o;
1004         entity e;
1005         e = spawn();
1006         e.classname = "clientinit";
1007         e.think = ClientInit_CheckUpdate;
1008         Net_LinkEntity(e, FALSE, 0, ClientInit_SendEntity);
1009
1010         o = self;
1011         self = e;
1012         ClientInit_CheckUpdate();
1013         self = o;
1014 }
1015
1016 /*
1017 =============
1018 SetNewParms
1019 =============
1020 */
1021 void SetNewParms (void)
1022 {
1023         // initialize parms for a new player
1024         parm1 = -(86400 * 366);
1025 }
1026
1027 /*
1028 =============
1029 SetChangeParms
1030 =============
1031 */
1032 void SetChangeParms (void)
1033 {
1034         // save parms for level change
1035         parm1 = self.parm_idlesince - time;
1036 }
1037
1038 /*
1039 =============
1040 DecodeLevelParms
1041 =============
1042 */
1043 void DecodeLevelParms (void)
1044 {
1045         // load parms
1046         self.parm_idlesince = parm1;
1047         if(self.parm_idlesince == -(86400 * 366))
1048                 self.parm_idlesince = time;
1049
1050         // whatever happens, allow 60 seconds of idling directly after connect for map loading
1051         self.parm_idlesince = max(self.parm_idlesince, time - sv_maxidle + 60);
1052 }
1053
1054 /*
1055 =============
1056 ClientKill
1057
1058 Called when a client types 'kill' in the console
1059 =============
1060 */
1061
1062 .float clientkill_nexttime;
1063 void ClientKill_Now_TeamChange()
1064 {
1065         if(self.killindicator_teamchange == -1)
1066         {
1067                 JoinBestTeam( self, FALSE, TRUE );
1068         }
1069         else if(self.killindicator_teamchange == -2)
1070         {
1071                 if(g_ca)
1072                         self.caplayer = 0;
1073                 if(blockSpectators)
1074                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
1075                 PutObserverInServer();
1076         }
1077         else
1078                 SV_ChangeTeam(self.killindicator_teamchange - 1);
1079 }
1080
1081 void ClientKill_Now()
1082 {
1083         if(self.vehicle)
1084         {
1085             vehicles_exit(VHEF_RELESE);
1086             if(!self.killindicator_teamchange)
1087             {
1088             self.vehicle_health = -1;
1089             Damage(self, self, self, 1 , DEATH_KILL, self.origin, '0 0 0');             
1090             }
1091         }
1092
1093         if(self.killindicator && !wasfreed(self.killindicator))
1094                 remove(self.killindicator);
1095
1096         self.killindicator = world;
1097
1098         if(self.killindicator_teamchange)
1099                 ClientKill_Now_TeamChange();
1100
1101         // in any case:
1102         Damage(self, self, self, 100000, DEATH_KILL, self.origin, '0 0 0');
1103
1104         // now I am sure the player IS dead
1105 }
1106 void KillIndicator_Think()
1107 {
1108         if (gameover)
1109         {
1110                 self.owner.killindicator = world;
1111                 remove(self);
1112                 return;
1113         }
1114
1115         if (self.owner.alpha < 0 && !self.owner.vehicle)
1116         {
1117                 self.owner.killindicator = world;
1118                 remove(self);
1119                 return;
1120         }
1121
1122         if(self.cnt <= 0)
1123         {
1124                 self = self.owner;
1125                 ClientKill_Now(); // no oldself needed
1126                 return;
1127         }
1128     else if(g_cts && self.health == 1) // health == 1 means that it's silent
1129     {
1130         self.nextthink = time + 1;
1131         self.cnt -= 1;
1132     }
1133         else
1134         {
1135                 if(self.cnt <= 10)
1136                         setmodel(self, strcat("models/sprites/", ftos(self.cnt), ".spr32"));
1137                 if(clienttype(self.owner) == CLIENTTYPE_REAL)
1138                 {
1139                         if(self.cnt <= 10)
1140                                 AnnounceTo(self.owner, strcat(ftos(self.cnt), ""));
1141                 }
1142                 self.nextthink = time + 1;
1143                 self.cnt -= 1;
1144         }
1145 }
1146
1147 float clientkilltime;
1148 void ClientKill_TeamChange (float targetteam) // 0 = don't change, -1 = auto, -2 = spec
1149 {
1150         float killtime;
1151         float starttime;
1152         entity e;
1153
1154         if (gameover)
1155                 return;
1156
1157         killtime = autocvar_g_balance_kill_delay;
1158
1159         if(g_race_qualifying || g_cts)
1160                 killtime = 0;
1161
1162     if(g_cts && self.killindicator && self.killindicator.health == 1) // self.killindicator.health == 1 means that the kill indicator was spawned by CTS_ClientKill
1163     {
1164                 remove(self.killindicator);
1165                 self.killindicator = world;
1166
1167         ClientKill_Now(); // allow instant kill in this case
1168         return;
1169     }
1170
1171         self.killindicator_teamchange = targetteam;
1172
1173     if(!self.killindicator)
1174         {
1175                 if(self.deadflag == DEAD_NO)
1176                 {
1177                         killtime = max(killtime, self.clientkill_nexttime - time);
1178                         self.clientkill_nexttime = time + killtime + autocvar_g_balance_kill_antispam;
1179                 }
1180
1181                 if(killtime <= 0 || self.classname != "player" || self.deadflag != DEAD_NO)
1182                 {
1183                         ClientKill_Now();
1184                 }
1185                 else
1186                 {
1187                         starttime = max(time, clientkilltime);
1188
1189                         self.killindicator = spawn();
1190                         self.killindicator.owner = self;
1191                         self.killindicator.scale = 0.5;
1192                         setattachment(self.killindicator, self, "");
1193                         setorigin(self.killindicator, '0 0 52');
1194                         self.killindicator.think = KillIndicator_Think;
1195                         self.killindicator.nextthink = starttime + (self.lip) * 0.05;
1196                         clientkilltime = max(clientkilltime, self.killindicator.nextthink + 0.05);
1197                         self.killindicator.cnt = ceil(killtime);
1198                         self.killindicator.count = bound(0, ceil(killtime), 10);
1199                         //sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
1200
1201                         for(e = world; (e = find(e, classname, "body")) != world; )
1202                         {
1203                                 if(e.enemy != self)
1204                                         continue;
1205                                 e.killindicator = spawn();
1206                                 e.killindicator.owner = e;
1207                                 e.killindicator.scale = 0.5;
1208                                 setattachment(e.killindicator, e, "");
1209                                 setorigin(e.killindicator, '0 0 52');
1210                                 e.killindicator.think = KillIndicator_Think;
1211                                 e.killindicator.nextthink = starttime + (e.lip) * 0.05;
1212                                 clientkilltime = max(clientkilltime, e.killindicator.nextthink + 0.05);
1213                                 e.killindicator.cnt = ceil(killtime);
1214                         }
1215                         self.lip = 0;
1216                 }
1217         }
1218         if(self.killindicator)
1219         {
1220                 if(targetteam == 0) // just die
1221                 {
1222                         self.killindicator.colormod = '0 0 0';
1223                         if(clienttype(self) == CLIENTTYPE_REAL)
1224                         if(self.killindicator.cnt > 0)
1225                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_SUICIDE, self.killindicator.cnt);
1226                 }
1227                 else if(targetteam == -1) // auto
1228                 {
1229                         self.killindicator.colormod = '0 1 0';
1230                         if(clienttype(self) == CLIENTTYPE_REAL)
1231                         if(self.killindicator.cnt > 0)
1232                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_AUTO, self.killindicator.cnt);
1233                 }
1234                 else if(targetteam == -2) // spectate
1235                 {
1236                         self.killindicator.colormod = '0.5 0.5 0.5';
1237                         if(clienttype(self) == CLIENTTYPE_REAL)
1238                         if(self.killindicator.cnt > 0)
1239                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_TEAMCHANGE_SPECTATE, self.killindicator.cnt);
1240                 }
1241                 else
1242                 {
1243                         self.killindicator.colormod = Team_ColorRGB(targetteam);
1244                         if(clienttype(self) == CLIENTTYPE_REAL)
1245                         if(self.killindicator.cnt > 0)
1246                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, APP_TEAM_NUM_4(targetteam, CENTER_TEAMCHANGE_), self.killindicator.cnt);
1247                 }
1248         }
1249
1250 }
1251
1252 void ClientKill (void)
1253 {
1254         if (gameover)
1255                 return;
1256
1257         if((g_arena || g_ca) && ((champion && champion.classname == "player" && player_count > 1) || player_count == 1)) // don't allow a kill in this case either
1258         {
1259                 // do nothing
1260         }
1261     else if(self.freezetag_frozen)
1262     {
1263         // do nothing
1264     }
1265         else
1266                 ClientKill_TeamChange(0);
1267 }
1268
1269 void CTS_ClientKill (entity e) // silent version of ClientKill, used when player finishes a CTS run. Useful to prevent cheating by running back to the start line and starting out with more speed
1270 {
1271     e.killindicator = spawn();
1272     e.killindicator.owner = e;
1273     e.killindicator.think = KillIndicator_Think;
1274     e.killindicator.nextthink = time + (e.lip) * 0.05;
1275     e.killindicator.cnt = ceil(autocvar_g_cts_finish_kill_delay);
1276     e.killindicator.health = 1; // this is used to indicate that it should be silent
1277     e.lip = 0;
1278 }
1279
1280 void FixClientCvars(entity e)
1281 {
1282         // send prediction settings to the client
1283         stuffcmd(e, "\nin_bindmap 0 0\n");
1284         if(g_race || g_cts)
1285                 stuffcmd(e, "cl_cmd settemp cl_movecliptokeyboard 2\n");
1286         if(autocvar_g_antilag == 3) // client side hitscan
1287                 stuffcmd(e, "cl_cmd settemp cl_prydoncursor_notrace 0\n");
1288         if(autocvar_sv_gentle)
1289                 stuffcmd(e, "cl_cmd settemp cl_gentle 1\n");
1290         /*
1291          * we no longer need to stuff this. Remove this comment block if you feel
1292          * 2.3 and higher (or was it 2.2.3?) don't need these any more
1293         stuffcmd(e, strcat("cl_gravity ", ftos(autocvar_sv_gravity), "\n"));
1294         stuffcmd(e, strcat("cl_movement_accelerate ", ftos(autocvar_sv_accelerate), "\n"));
1295         stuffcmd(e, strcat("cl_movement_friction ", ftos(autocvar_sv_friction), "\n"));
1296         stuffcmd(e, strcat("cl_movement_maxspeed ", ftos(autocvar_sv_maxspeed), "\n"));
1297         stuffcmd(e, strcat("cl_movement_airaccelerate ", ftos(autocvar_sv_airaccelerate), "\n"));
1298         stuffcmd(e, strcat("cl_movement_maxairspeed ", ftos(autocvar_sv_maxairspeed), "\n"));
1299         stuffcmd(e, strcat("cl_movement_stopspeed ", ftos(autocvar_sv_stopspeed), "\n"));
1300         stuffcmd(e, strcat("cl_movement_jumpvelocity ", ftos(autocvar_sv_jumpvelocity), "\n"));
1301         stuffcmd(e, strcat("cl_movement_stepheight ", ftos(autocvar_sv_stepheight), "\n"));
1302         stuffcmd(e, strcat("set cl_movement_friction_on_land ", ftos(autocvar_sv_friction_on_land), "\n"));
1303         stuffcmd(e, strcat("set cl_movement_airaccel_qw ", ftos(autocvar_sv_airaccel_qw), "\n"));
1304         stuffcmd(e, strcat("set cl_movement_airaccel_sideways_friction ", ftos(autocvar_sv_airaccel_sideways_friction), "\n"));
1305         stuffcmd(e, "cl_movement_edgefriction 1\n");
1306          */
1307 }
1308
1309 float PlayerInIDList(entity p, string idlist)
1310 {
1311         float n, i;
1312         string s;
1313
1314         // NOTE: we do NOT check crypto_keyfp here, an unsigned ID is fine too for this
1315         if not(p.crypto_idfp)
1316                 return 0;
1317
1318         // this function allows abbreviated player IDs too!
1319         n = tokenize_console(idlist);
1320         for(i = 0; i < n; ++i)
1321         {
1322                 s = argv(i);
1323                 if(s == substring(p.crypto_idfp, 0, strlen(s)))
1324                         return 1;
1325         }
1326
1327         return 0;
1328 }
1329
1330 /*
1331 =============
1332 ClientConnect
1333
1334 Called when a client connects to the server
1335 =============
1336 */
1337 void DecodeLevelParms (void);
1338 //void dom_player_join_team(entity pl);
1339 void set_dom_state(entity e);
1340 void ClientConnect (void)
1341 {
1342         float t;
1343
1344         if(self.flags & FL_CLIENT)
1345         {
1346                 print("Warning: ClientConnect, but already connected!\n");
1347                 return;
1348         }
1349
1350         if(Ban_MaybeEnforceBanOnce(self))
1351                 return;
1352
1353         DecodeLevelParms();
1354
1355 #ifdef WATERMARK
1356         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_WATERMARK, WATERMARK);
1357 #endif
1358
1359         self.classname = "player_joining";
1360
1361         self.flags = FL_CLIENT;
1362         self.version_nagtime = time + 10 + random() * 10;
1363
1364         if(player_count<0)
1365         {
1366                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1367                 player_count = 0;
1368         }
1369
1370         PlayerScore_Attach(self);
1371         ClientData_Attach();
1372         accuracy_init(self);
1373
1374         bot_clientconnect();
1375
1376         playerdemo_init();
1377
1378         anticheat_init();
1379
1380         race_PreSpawnObserver();
1381
1382         // identify the right forced team
1383         if(autocvar_g_campaign)
1384         {
1385                 if(clienttype(self) == CLIENTTYPE_REAL) // only players, not bots
1386                 {
1387                         switch(autocvar_g_campaign_forceteam)
1388                         {
1389                                 case 1: self.team_forced = NUM_TEAM_1; break;
1390                                 case 2: self.team_forced = NUM_TEAM_2; break;
1391                                 case 3: self.team_forced = NUM_TEAM_3; break;
1392                                 case 4: self.team_forced = NUM_TEAM_4; break;
1393                                 default: self.team_forced = 0;
1394                         }
1395                 }
1396         }
1397         else if(PlayerInIDList(self, autocvar_g_forced_team_red))
1398                 self.team_forced = NUM_TEAM_1;
1399         else if(PlayerInIDList(self, autocvar_g_forced_team_blue))
1400                 self.team_forced = NUM_TEAM_2;
1401         else if(PlayerInIDList(self, autocvar_g_forced_team_yellow))
1402                 self.team_forced = NUM_TEAM_3;
1403         else if(PlayerInIDList(self, autocvar_g_forced_team_pink))
1404                 self.team_forced = NUM_TEAM_4;
1405         else if(autocvar_g_forced_team_otherwise == "red")
1406                 self.team_forced = NUM_TEAM_1;
1407         else if(autocvar_g_forced_team_otherwise == "blue")
1408                 self.team_forced = NUM_TEAM_2;
1409         else if(autocvar_g_forced_team_otherwise == "yellow")
1410                 self.team_forced = NUM_TEAM_3;
1411         else if(autocvar_g_forced_team_otherwise == "pink")
1412                 self.team_forced = NUM_TEAM_4;
1413         else if(autocvar_g_forced_team_otherwise == "spectate")
1414                 self.team_forced = -1;
1415         else if(autocvar_g_forced_team_otherwise == "spectator")
1416                 self.team_forced = -1;
1417         else
1418                 self.team_forced = 0;
1419
1420         if(!teamplay)
1421                 if(self.team_forced > 0)
1422                         self.team_forced = 0;
1423
1424         JoinBestTeam(self, FALSE, FALSE); // if the team number is valid, keep it
1425
1426         if((autocvar_sv_spectate == 1 && !g_lms) || autocvar_g_campaign || self.team_forced < 0) {
1427                 self.classname = "observer";
1428         } else {
1429                 if(teamplay)
1430                 {
1431                         if(autocvar_g_balance_teams)
1432                         {
1433                                 self.classname = "player";
1434                                 campaign_bots_may_start = 1;
1435                         }
1436                         else
1437                         {
1438                                 self.classname = "observer"; // do it anyway
1439                         }
1440                 }
1441                 else
1442                 {
1443                         self.classname = "player";
1444                         campaign_bots_may_start = 1;
1445                 }
1446         }
1447
1448         self.playerid = (playerid_last = playerid_last + 1);
1449
1450         PlayerStats_AddEvent(sprintf("kills-%d", self.playerid));
1451
1452     if(clienttype(self) == CLIENTTYPE_BOT)
1453         PlayerStats_AddPlayer(self);
1454
1455         if(autocvar_sv_eventlog)
1456                 GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", ((clienttype(self) == CLIENTTYPE_REAL) ? self.netaddress : "bot"), ":", self.netname));
1457
1458         LogTeamchange(self.playerid, self.team, 1);
1459
1460         self.just_joined = TRUE;  // stop spamming the eventlog with additional lines when the client connects
1461
1462         self.netname_previous = strzone(self.netname);
1463
1464         if((self.classname == STR_PLAYER && teamplay))
1465                 Send_Notification(NOTIF_ALL, world, MSG_INFO, APP_TEAM_ENT_4(self, INFO_JOIN_CONNECT_TEAM_), self.netname);
1466         else
1467                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_JOIN_CONNECT, self.netname);
1468
1469         stuffcmd(self, strcat(clientstuff, "\n"));
1470         stuffcmd(self, "cl_particles_reloadeffects\n"); // TODO do we still need this?
1471
1472         FixClientCvars(self);
1473
1474         // spawnfunc_waypoint sprites
1475         WaypointSprite_InitClient(self);
1476
1477         // Wazat's grappling hook
1478         SetGrappleHookBindings();
1479
1480         // get version info from player
1481         stuffcmd(self, "cmd clientversion $gameversion\n");
1482
1483         // get other cvars from player
1484         GetCvars(0);
1485
1486         // notify about available teams
1487         if(teamplay)
1488         {
1489                 CheckAllowedTeams(self);
1490                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1491                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1492         }
1493         else
1494                 stuffcmd(self, "set _teams_available 0\n");
1495
1496         if(g_arena || g_ca)
1497         {
1498                 self.classname = "observer";
1499                 if(g_arena)
1500                         Spawnqueue_Insert(self);
1501         }
1502
1503         attach_entcs();
1504
1505         bot_relinkplayerlist();
1506
1507         self.spectatortime = time;
1508         if(blockSpectators)
1509         {
1510                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
1511         }
1512
1513         self.jointime = time;
1514         self.allowed_timeouts = autocvar_sv_timeout_number;
1515
1516         if(clienttype(self) == CLIENTTYPE_REAL)
1517         {
1518                 if(autocvar_g_bugrigs || WEPSET_EQ_AW(g_weaponarena_weapons, WEP_TUBA))
1519                         stuffcmd(self, "cl_cmd settemp chase_active 1\n");
1520         }
1521
1522         if(g_lms)
1523         {
1524                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1525                 {
1526                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1527                         self.frags = FRAGS_SPECTATOR;
1528                 }
1529         }
1530
1531         if(!sv_foginterval && world.fog != "")
1532                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1533
1534         if(autocvar_g_hitplots || strstrofs(strcat(" ", autocvar_g_hitplots_individuals, " "), strcat(" ", self.netaddress, " "), 0) >= 0)
1535         {
1536                 self.hitplotfh = fopen(strcat("hits-", matchid, "-", self.netaddress, "-", ftos(self.playerid), ".plot"), FILE_WRITE);
1537                 fputs(self.hitplotfh, strcat("#name ", self.netname, "\n"));
1538         }
1539         else
1540                 self.hitplotfh = -1;
1541
1542         if(g_race || g_cts) {
1543                 string rr;
1544                 if(g_cts)
1545                         rr = CTS_RECORD;
1546                 else
1547                         rr = RACE_RECORD;
1548
1549                 msg_entity = self;
1550                 race_send_recordtime(MSG_ONE);
1551                 race_send_speedaward(MSG_ONE);
1552
1553                 speedaward_alltimebest = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/speed")));
1554                 speedaward_alltimebest_holder = uid2name(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/crypto_idfp")));
1555                 race_send_speedaward_alltimebest(MSG_ONE);
1556
1557                 float i;
1558                 for (i = 1; i <= RANKINGS_CNT; ++i) {
1559                         race_SendRankings(i, 0, 0, MSG_ONE);
1560                 }
1561         }
1562         else if(autocvar_sv_teamnagger && !(autocvar_bot_vs_human && (c3==-1 && c4==-1)) && !g_ca) // teamnagger is currently bad for ca
1563                 send_CSQC_teamnagger();
1564
1565         CheatInitClient();
1566
1567         if(!autocvar_g_campaign)
1568                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, getwelcomemessage());
1569
1570         CSQCMODEL_AUTOINIT();
1571
1572         self.model_randomizer = random();
1573     
1574     if(clienttype(self) != CLIENTTYPE_REAL)
1575         return;
1576         
1577     sv_notice_join();
1578     
1579     MUTATOR_CALLHOOK(ClientConnect);
1580 }
1581 /*
1582 =============
1583 ClientDisconnect
1584
1585 Called when a client disconnects from the server
1586 =============
1587 */
1588 .entity chatbubbleentity;
1589 void ReadyCount();
1590 void ClientDisconnect (void)
1591 {
1592         if(self.vehicle)
1593             vehicles_exit(VHEF_RELESE);
1594
1595         if not(self.flags & FL_CLIENT)
1596         {
1597                 print("Warning: ClientDisconnect without ClientConnect\n");
1598                 return;
1599         }
1600
1601         PlayerStats_AddGlobalInfo(self);
1602
1603         CheatShutdownClient();
1604
1605         if(self.hitplotfh >= 0)
1606         {
1607                 fclose(self.hitplotfh);
1608                 self.hitplotfh = -1;
1609         }
1610
1611         anticheat_report();
1612         anticheat_shutdown();
1613
1614         playerdemo_shutdown();
1615
1616         bot_clientdisconnect();
1617
1618         if(self.entcs)
1619                 detach_entcs();
1620
1621         if(autocvar_sv_eventlog)
1622                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1623                 
1624         Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_DISCONNECT, self.netname);
1625
1626         MUTATOR_CALLHOOK(ClientDisconnect);
1627
1628         Portal_ClearAll(self);
1629
1630         RemoveGrapplingHook(self);
1631
1632         // Here, everything has been done that requires this player to be a client.
1633
1634         self.flags &~= FL_CLIENT;
1635
1636         if (self.chatbubbleentity)
1637                 remove (self.chatbubbleentity);
1638
1639         if (self.killindicator)
1640                 remove (self.killindicator);
1641
1642         WaypointSprite_PlayerGone();
1643
1644         bot_relinkplayerlist();
1645
1646         if(g_arena)
1647         {
1648                 Spawnqueue_Unmark(self);
1649                 Spawnqueue_Remove(self);
1650         }
1651
1652         accuracy_free(self);
1653         ClientData_Detach();
1654         PlayerScore_Detach(self);
1655
1656         if(self.netname_previous)
1657                 strunzone(self.netname_previous);
1658         if(self.clientstatus)
1659                 strunzone(self.clientstatus);
1660         if(self.weaponorder_byimpulse)
1661                 strunzone(self.weaponorder_byimpulse);
1662
1663         ClearPlayerSounds();
1664
1665         if(self.personal)
1666                 remove(self.personal);
1667
1668         self.playerid = 0;
1669         ReadyCount();
1670
1671         // free cvars
1672         GetCvars(-1);
1673 }
1674
1675 .float BUTTON_CHAT;
1676 void ChatBubbleThink()
1677 {
1678         self.nextthink = time;
1679         if ((self.owner.alpha < 0) || self.owner.chatbubbleentity != self)
1680         {
1681                 if(self.owner) // but why can that ever be world?
1682                         self.owner.chatbubbleentity = world;
1683                 remove(self);
1684                 return;
1685         }
1686         if ((self.owner.BUTTON_CHAT && !self.owner.deadflag)
1687 #ifdef TETRIS
1688                 || self.owner.tetris_on
1689 #endif
1690         )
1691                 self.model = self.mdl;
1692         else
1693                 self.model = "";
1694 }
1695
1696 void UpdateChatBubble()
1697 {
1698         if (self.alpha < 0)
1699                 return;
1700         // spawn a chatbubble entity if needed
1701         if (!self.chatbubbleentity)
1702         {
1703                 self.chatbubbleentity = spawn();
1704                 self.chatbubbleentity.owner = self;
1705                 self.chatbubbleentity.exteriormodeltoclient = self;
1706                 self.chatbubbleentity.think = ChatBubbleThink;
1707                 self.chatbubbleentity.nextthink = time;
1708                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1709                 //setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1710                 setorigin(self.chatbubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1711                 setattachment(self.chatbubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1712                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1713                 self.chatbubbleentity.model = "";
1714                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1715         }
1716 }
1717
1718
1719 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1720 // added to the model skins
1721 /*void UpdateColorModHack()
1722 {
1723         float c;
1724         c = self.clientcolors & 15;
1725         // LordHavoc: only bothering to support white, green, red, yellow, blue
1726              if (!teamplay) self.colormod = '0 0 0';
1727         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1728         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1729         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1730         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1731         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1732         else self.colormod = '1 1 1';
1733 }*/
1734
1735 void respawn(void)
1736 {
1737         if(self.alpha >= 0 && autocvar_g_respawn_ghosts)
1738         {
1739                 self.solid = SOLID_NOT;
1740                 self.takedamage = DAMAGE_NO;
1741                 self.movetype = MOVETYPE_FLY;
1742                 self.velocity = '0 0 1' * autocvar_g_respawn_ghosts_speed;
1743                 self.avelocity = randomvec() * autocvar_g_respawn_ghosts_speed * 3 - randomvec() * autocvar_g_respawn_ghosts_speed * 3;
1744                 self.effects |= CSQCMODEL_EF_RESPAWNGHOST;
1745                 pointparticles(particleeffectnum("respawn_ghost"), self.origin, '0 0 0', 1);
1746                 if(autocvar_g_respawn_ghosts_maxtime)
1747                         SUB_SetFade (self, time + autocvar_g_respawn_ghosts_maxtime / 2 + random () * (autocvar_g_respawn_ghosts_maxtime - autocvar_g_respawn_ghosts_maxtime / 2), 1.5);
1748         }
1749
1750         CopyBody(1);
1751
1752         self.effects |= EF_NODRAW; // prevent another CopyBody
1753         PutClientInServer();
1754 }
1755
1756 void play_countdown(float finished, string samp)
1757 {
1758         if(clienttype(self) == CLIENTTYPE_REAL)
1759                 if(floor(finished - time - frametime) != floor(finished - time))
1760                         if(finished - time < 6)
1761                                 sound (self, CH_INFO, samp, VOL_BASE, ATTN_NORM);
1762 }
1763
1764 void player_powerups (void)
1765 {
1766         // add a way to see what the items were BEFORE all of these checks for the mutator hook
1767         olditems = self.items;
1768
1769         if((self.items & IT_USING_JETPACK) && !self.deadflag)
1770                 self.modelflags |= MF_ROCKET;
1771         else
1772                 self.modelflags &~= MF_ROCKET;
1773
1774         self.effects &~= (EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
1775
1776         if(self.alpha < 0 || self.deadflag) // don't apply the flags if the player is gibbed
1777                 return;
1778
1779         Fire_ApplyDamage(self);
1780         Fire_ApplyEffect(self);
1781
1782         if (g_minstagib)
1783         {
1784                 self.effects |= EF_FULLBRIGHT;
1785
1786                 if (self.items & IT_STRENGTH)
1787                 {
1788                         play_countdown(self.strength_finished, "misc/poweroff.wav");
1789                         if (time > self.strength_finished)
1790                         {
1791                                 self.alpha = default_player_alpha;
1792                                 self.exteriorweaponentity.alpha = default_weapon_alpha;
1793                                 self.items &~= IT_STRENGTH;
1794                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERDOWN_INVISIBILITY, self.netname);
1795                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERDOWN_INVISIBILITY);
1796                         }
1797                 }
1798                 else
1799                 {
1800                         if (time < self.strength_finished)
1801                         {
1802                                 self.alpha = g_minstagib_invis_alpha;
1803                                 self.exteriorweaponentity.alpha = g_minstagib_invis_alpha;
1804                                 self.items |= IT_STRENGTH;
1805                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERUP_INVISIBILITY, self.netname);
1806                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERUP_INVISIBILITY);
1807                         }
1808                 }
1809
1810                 if (self.items & IT_INVINCIBLE)
1811                 {
1812                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
1813                         if (time > self.invincible_finished)
1814                         {
1815                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1816                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERDOWN_SPEED, self.netname);
1817                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERDOWN_SPEED);
1818                         }
1819                 }
1820                 else
1821                 {
1822                         if (time < self.invincible_finished)
1823                         {
1824                                 self.items = self.items | IT_INVINCIBLE;
1825                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERUP_SPEED, self.netname);
1826                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERUP_SPEED);
1827                         }
1828                 }
1829         }
1830         else // if we're not in minstagib, continue. I added this else to replace the "return" which was here that broke the callhook for this function -- This code is nasty.
1831         {
1832                 if (self.items & IT_STRENGTH)
1833                 {
1834                         play_countdown(self.strength_finished, "misc/poweroff.wav");
1835                         self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1836                         if (time > self.strength_finished)
1837                         {
1838                                 self.items = self.items - (self.items & IT_STRENGTH);
1839                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERDOWN_STRENGTH, self.netname);
1840                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERDOWN_STRENGTH);
1841                         }
1842                 }
1843                 else
1844                 {
1845                         if (time < self.strength_finished)
1846                         {
1847                                 self.items = self.items | IT_STRENGTH;
1848                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERUP_STRENGTH, self.netname);
1849                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERUP_STRENGTH);
1850                         }
1851                 }
1852                 if (self.items & IT_INVINCIBLE)
1853                 {
1854                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
1855                         self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1856                         if (time > self.invincible_finished)
1857                         {
1858                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1859                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERDOWN_SHIELD, self.netname);
1860                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERDOWN_SHIELD);
1861                         }
1862                 }
1863                 else
1864                 {
1865                         if (time < self.invincible_finished)
1866                         {
1867                                 self.items = self.items | IT_INVINCIBLE;
1868                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_POWERUP_SHIELD, self.netname);
1869                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_POWERUP_SHIELD);
1870                         }
1871                 }
1872                 if (self.items & IT_SUPERWEAPON)
1873                 {
1874                         if (!WEPSET_CONTAINS_ANY_EA(self, WEPBIT_SUPERWEAPONS))
1875                         {
1876                                 self.superweapons_finished = 0;
1877                                 self.items = self.items - (self.items & IT_SUPERWEAPON);
1878                                 //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_LOST, self.netname);
1879                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_LOST);
1880                         }
1881                         else if (self.items & IT_UNLIMITED_SUPERWEAPONS)
1882                         {
1883                                 // don't let them run out
1884                         }
1885                         else
1886                         {
1887                                 play_countdown(self.superweapons_finished, "misc/poweroff.wav");
1888                                 if (time > self.superweapons_finished)
1889                                 {
1890                                         self.items = self.items - (self.items & IT_SUPERWEAPON);
1891                                         WEPSET_ANDNOT_EA(self, WEPBIT_SUPERWEAPONS);
1892                                         //Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_BROKEN, self.netname);
1893                                         Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_BROKEN);
1894                                 }
1895                         }
1896                 }
1897                 else if(WEPSET_CONTAINS_ANY_EA(self, WEPBIT_SUPERWEAPONS))
1898                 {
1899                         if (time < self.superweapons_finished || (self.items & IT_UNLIMITED_SUPERWEAPONS))
1900                         {
1901                                 self.items = self.items | IT_SUPERWEAPON;
1902                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_SUPERWEAPON_PICKUP, self.netname);
1903                                 Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_SUPERWEAPON_PICKUP);
1904                         }
1905                         else
1906                         {
1907                                 self.superweapons_finished = 0;
1908                                 WEPSET_ANDNOT_EA(self, WEPBIT_SUPERWEAPONS);
1909                         }
1910                 }
1911                 else
1912                 {
1913                         self.superweapons_finished = 0;
1914                 }
1915         }
1916         
1917         if(autocvar_g_nodepthtestplayers)
1918                 self.effects = self.effects | EF_NODEPTHTEST;
1919
1920         if(autocvar_g_fullbrightplayers)
1921                 self.effects = self.effects | EF_FULLBRIGHT;
1922
1923         // midair gamemode: damage only while in the air
1924         // if in midair mode, being on ground grants temporary invulnerability
1925         // (this is so that multishot weapon don't clear the ground flag on the
1926         // first damage in the frame, leaving the player vulnerable to the
1927         // remaining hits in the same frame)
1928         if (self.flags & FL_ONGROUND)
1929         if (g_midair)
1930                 self.spawnshieldtime = max(self.spawnshieldtime, time + autocvar_g_midair_shieldtime);
1931
1932         if (time >= game_starttime)
1933         if (time < self.spawnshieldtime)
1934                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1935
1936         MUTATOR_CALLHOOK(PlayerPowerups);
1937 }
1938
1939 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1940 {
1941         if(current > stable)
1942                 return current;
1943         else if(current > stable - 0.25) // when close enough, "snap"
1944                 return stable;
1945         else
1946                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1947 }
1948
1949 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1950 {
1951         if(current < stable)
1952                 return current;
1953         else if(current < stable + 0.25) // when close enough, "snap"
1954                 return stable;
1955         else
1956                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1957 }
1958
1959 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
1960 {
1961         if(current > rotstable)
1962         {
1963                 if(rotframetime > 0)
1964                 {
1965                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1966                         current = max(rotstable, current - rotlinear * rotframetime);
1967                 }
1968         }
1969         else if(current < regenstable)
1970         {
1971                 if(regenframetime > 0)
1972                 {
1973                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1974                         current = min(regenstable, current + regenlinear * regenframetime);
1975                 }
1976         }
1977
1978         if(current > limit)
1979                 current = limit;
1980
1981         return current;
1982 }
1983
1984 void player_regen (void)
1985 {
1986         float minh, mina, minf, maxh, maxa, maxf, limith, limita, limitf, max_mod, regen_mod, rot_mod, limit_mod;
1987         maxh = autocvar_g_balance_health_rotstable;
1988         maxa = autocvar_g_balance_armor_rotstable;
1989         maxf = autocvar_g_balance_fuel_rotstable;
1990         minh = autocvar_g_balance_health_regenstable;
1991         mina = autocvar_g_balance_armor_regenstable;
1992         minf = autocvar_g_balance_fuel_regenstable;
1993         limith = autocvar_g_balance_health_limit;
1994         limita = autocvar_g_balance_armor_limit;
1995         limitf = autocvar_g_balance_fuel_limit;
1996
1997         max_mod = regen_mod = rot_mod = limit_mod = 1;
1998
1999         maxh = maxh * max_mod;
2000         //maxa = maxa * max_mod;
2001         //maxf = maxf * max_mod;
2002         minh = minh * max_mod;
2003         //mina = mina * max_mod;
2004         //minf = minf * max_mod;
2005         limith = limith * limit_mod;
2006         limita = limita * limit_mod;
2007         //limitf = limitf * limit_mod;
2008
2009         if(g_lms && g_ca)
2010                 rot_mod = 0;
2011
2012         if (!g_minstagib && !g_ca && (!g_lms || autocvar_g_lms_regenerate))
2013         {
2014                 self.armorvalue = CalcRotRegen(self.armorvalue, mina, autocvar_g_balance_armor_regen, autocvar_g_balance_armor_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished), maxa, autocvar_g_balance_armor_rot, autocvar_g_balance_armor_rotlinear, rot_mod * frametime * (time > self.pauserotarmor_finished), limita);
2015                 self.health = CalcRotRegen(self.health, minh, autocvar_g_balance_health_regen, autocvar_g_balance_health_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished), maxh, autocvar_g_balance_health_rot, autocvar_g_balance_health_rotlinear, rot_mod * frametime * (time > self.pauserothealth_finished), limith);
2016
2017                 // if player rotted to death...  die!
2018                 if(self.health < 1)
2019                         self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
2020         }
2021
2022         if not(self.items & IT_UNLIMITED_WEAPON_AMMO)
2023                 self.ammo_fuel = CalcRotRegen(self.ammo_fuel, minf, autocvar_g_balance_fuel_regen, autocvar_g_balance_fuel_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished) * (self.items & IT_FUEL_REGEN != 0), maxf, autocvar_g_balance_fuel_rot, autocvar_g_balance_fuel_rotlinear, rot_mod * frametime * (time > self.pauserotfuel_finished), limitf);
2024 }
2025
2026 float zoomstate_set;
2027 void SetZoomState(float z)
2028 {
2029         if(z != self.zoomstate)
2030         {
2031                 self.zoomstate = z;
2032                 ClientData_Touch(self);
2033         }
2034         zoomstate_set = 1;
2035 }
2036
2037 void GetPressedKeys(void) {
2038         MUTATOR_CALLHOOK(GetPressedKeys);
2039         if (self.movement_x > 0) // get if movement keys are pressed
2040         {       // forward key pressed
2041                 self.pressedkeys |= KEY_FORWARD;
2042                 self.pressedkeys &~= KEY_BACKWARD;
2043         }
2044         else if (self.movement_x < 0)
2045         {       // backward key pressed
2046                 self.pressedkeys |= KEY_BACKWARD;
2047                 self.pressedkeys &~= KEY_FORWARD;
2048         }
2049         else
2050         {       // no x input
2051                 self.pressedkeys &~= KEY_FORWARD;
2052                 self.pressedkeys &~= KEY_BACKWARD;
2053         }
2054
2055         if (self.movement_y > 0)
2056         {       // right key pressed
2057                 self.pressedkeys |= KEY_RIGHT;
2058                 self.pressedkeys &~= KEY_LEFT;
2059         }
2060         else if (self.movement_y < 0)
2061         {       // left key pressed
2062                 self.pressedkeys |= KEY_LEFT;
2063                 self.pressedkeys &~= KEY_RIGHT;
2064         }
2065         else
2066         {       // no y input
2067                 self.pressedkeys &~= KEY_RIGHT;
2068                 self.pressedkeys &~= KEY_LEFT;
2069         }
2070
2071         if (self.BUTTON_JUMP) // get if jump and crouch keys are pressed
2072                 self.pressedkeys |= KEY_JUMP;
2073         else
2074                 self.pressedkeys &~= KEY_JUMP;
2075         if (self.BUTTON_CROUCH)
2076                 self.pressedkeys |= KEY_CROUCH;
2077         else
2078                 self.pressedkeys &~= KEY_CROUCH;
2079
2080         if (self.BUTTON_ATCK)
2081                 self.pressedkeys |= KEY_ATCK;
2082         else
2083                 self.pressedkeys &~= KEY_ATCK;
2084         if (self.BUTTON_ATCK2)
2085                 self.pressedkeys |= KEY_ATCK2;
2086         else
2087                 self.pressedkeys &~= KEY_ATCK2;
2088 }
2089
2090 /*
2091 ======================
2092 spectate mode routines
2093 ======================
2094 */
2095
2096 void SpectateCopy(entity spectatee) {
2097         other = spectatee;
2098         MUTATOR_CALLHOOK(SpectateCopy);
2099         self.armortype = spectatee.armortype;
2100         self.armorvalue = spectatee.armorvalue;
2101         self.ammo_cells = spectatee.ammo_cells;
2102         self.ammo_shells = spectatee.ammo_shells;
2103         self.ammo_nails = spectatee.ammo_nails;
2104         self.ammo_rockets = spectatee.ammo_rockets;
2105         self.ammo_fuel = spectatee.ammo_fuel;
2106         self.clip_load = spectatee.clip_load;
2107         self.clip_size = spectatee.clip_size;
2108         self.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
2109         self.health = spectatee.health;
2110         self.impulse = 0;
2111         self.items = spectatee.items;
2112         self.last_pickup = spectatee.last_pickup;
2113         self.hit_time = spectatee.hit_time;
2114         self.metertime = spectatee.metertime;
2115         self.strength_finished = spectatee.strength_finished;
2116         self.invincible_finished = spectatee.invincible_finished;
2117         self.pressedkeys = spectatee.pressedkeys;
2118         WEPSET_COPY_EE(self, spectatee);
2119         self.switchweapon = spectatee.switchweapon;
2120         self.switchingweapon = spectatee.switchingweapon;
2121         self.weapon = spectatee.weapon;
2122         self.nex_charge = spectatee.nex_charge;
2123         self.nex_chargepool_ammo = spectatee.nex_chargepool_ammo;
2124         self.hagar_load = spectatee.hagar_load;
2125         self.minelayer_mines = spectatee.minelayer_mines;
2126         self.punchangle = spectatee.punchangle;
2127         self.view_ofs = spectatee.view_ofs;
2128         self.velocity = spectatee.velocity;
2129         self.dmg_take = spectatee.dmg_take;
2130         self.dmg_save = spectatee.dmg_save;
2131         self.dmg_inflictor = spectatee.dmg_inflictor;
2132         self.v_angle = spectatee.v_angle;
2133         self.angles = spectatee.v_angle;
2134         self.stat_respawn_time = spectatee.stat_respawn_time;
2135         if(!self.BUTTON_USE)
2136                 self.fixangle = TRUE;
2137         setorigin(self, spectatee.origin);
2138         setsize(self, spectatee.mins, spectatee.maxs);
2139         SetZoomState(spectatee.zoomstate);
2140     
2141     anticheat_spectatecopy(spectatee);
2142         self.hud = spectatee.hud;
2143         if(spectatee.vehicle)
2144     {
2145         self.fixangle = FALSE;
2146         //self.velocity = spectatee.vehicle.velocity;
2147         self.vehicle_health = spectatee.vehicle_health;
2148         self.vehicle_shield = spectatee.vehicle_shield;
2149         self.vehicle_energy = spectatee.vehicle_energy;
2150         self.vehicle_ammo1 = spectatee.vehicle_ammo1;
2151         self.vehicle_ammo2 = spectatee.vehicle_ammo2;
2152         self.vehicle_reload1 = spectatee.vehicle_reload1;
2153         self.vehicle_reload2 = spectatee.vehicle_reload2;
2154
2155         msg_entity = self;
2156         
2157         WriteByte (MSG_ONE, SVC_SETVIEWANGLES);
2158             WriteAngle(MSG_ONE,  spectatee.v_angle_x);
2159             WriteAngle(MSG_ONE,  spectatee.v_angle_y);
2160             WriteAngle(MSG_ONE,  spectatee.v_angle_z);
2161
2162         //WriteByte (MSG_ONE, SVC_SETVIEW);
2163         //    WriteEntity(MSG_ONE, self);            
2164         //makevectors(spectatee.v_angle);
2165         //setorigin(self, spectatee.origin - v_forward * 400 + v_up * 300);*/    
2166     }
2167 }
2168
2169 float SpectateUpdate() {
2170         if(!self.enemy)
2171             return 0;           
2172
2173         if (self == self.enemy)
2174                 return 0;
2175
2176         if(self.enemy.classname != "player")
2177                 return 0;
2178
2179         SpectateCopy(self.enemy);
2180
2181         return 1;
2182 }
2183
2184
2185 // Returns next available player to spectate if g_ca_spectate_enemies == 0
2186 entity CA_SpectateNext(entity start) {
2187         if (start.team == self.team) {
2188                 return start;
2189         }
2190         
2191         other = start;
2192         // continue from current player
2193         while(other && other.team != self.team) {
2194                 other = find(other, classname, "player");
2195         }
2196         
2197         if (!other) {
2198                 // restart from begining
2199                 other = find(other, classname, "player");
2200                 while(other && other.team != self.team) {
2201                         other = find(other, classname, "player");
2202                 }
2203         }
2204         
2205         return other;
2206 }
2207
2208 float SpectateNext(entity _prefer) {
2209         
2210         if(_prefer)
2211                 other = _prefer;        
2212         else
2213                 other = find(self.enemy, classname, "player");
2214         
2215         if (g_ca && !autocvar_g_ca_spectate_enemies && self.caplayer) {
2216                 // CA and ca players when spectating enemies is forbidden
2217                 other = CA_SpectateNext(other);
2218         } else {
2219                 // other modes and ca spectators or spectating enemies is allowed
2220                 if (!other)
2221                         other = find(other, classname, "player");
2222         }
2223         
2224         if (other)
2225                 self.enemy = other;
2226
2227         if(self.enemy.classname == "player") {
2228             /*if(self.enemy.vehicle)
2229             {      
2230             
2231             msg_entity = self;
2232             WriteByte(MSG_ONE, SVC_SETVIEW);
2233             WriteEntity(MSG_ONE, self.enemy);
2234             //stuffcmd(self, "set viewsize $tmpviewsize \n");
2235             
2236             self.movetype = MOVETYPE_NONE;
2237             accuracy_resend(self);
2238             }
2239             else 
2240             {*/         
2241             msg_entity = self;
2242             WriteByte(MSG_ONE, SVC_SETVIEW);
2243             WriteEntity(MSG_ONE, self.enemy);
2244             //stuffcmd(self, "set viewsize $tmpviewsize \n");
2245             self.movetype = MOVETYPE_NONE;
2246             accuracy_resend(self);
2247
2248             if(!SpectateUpdate())
2249                 PutObserverInServer();
2250         //}
2251         return 1;
2252         } else {
2253                 return 0;
2254         }
2255 }
2256
2257 /*
2258 =============
2259 ShowRespawnCountdown()
2260
2261 Update a respawn countdown display.
2262 =============
2263 */
2264 void ShowRespawnCountdown()
2265 {
2266         float number;
2267         if(self.deadflag == DEAD_NO) // just respawned?
2268                 return;
2269         else
2270         {
2271                 number = ceil(self.respawn_time - time);
2272                 if(number <= 0)
2273                         return;
2274                 if(number <= self.respawn_countdown)
2275                 {
2276                         self.respawn_countdown = number - 1;
2277                         if(ceil(self.respawn_time - (time + 0.5)) == number) // only say it if it is the same number even in 0.5s; to prevent overlapping sounds
2278                                 AnnounceTo(self, strcat(ftos(number), ""));
2279                 }
2280         }
2281 }
2282
2283 void LeaveSpectatorMode()
2284 {
2285         if(nJoinAllowed(self))
2286         {
2287                 if(!teamplay || autocvar_g_campaign || autocvar_g_balance_teams || (self.wasplayer && autocvar_g_changeteam_banned) || self.team_forced > 0)
2288                 {
2289                         self.classname = "player";
2290
2291                         if(autocvar_g_campaign || autocvar_g_balance_teams)
2292                                 { JoinBestTeam(self, FALSE, TRUE); }
2293
2294                         if(autocvar_g_campaign)
2295                                 { campaign_bots_may_start = 1; }
2296                         else
2297                                 { Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD); }
2298
2299                         Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_PREVENT_JOIN);
2300                         
2301                         PutClientInServer();
2302
2303                         if(IS_PLAYER(self)) { Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_JOIN_PLAY, self.netname); }
2304                 }
2305                 else if not(g_ca && self.caplayer) { stuffcmd(self, "menu_showteamselect\n"); }
2306         }
2307         else
2308         {
2309                 // Player may not join because g_maxplayers is set
2310                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_PREVENT_JOIN);
2311         }
2312 }
2313
2314 /**
2315  * Determines whether the player is allowed to join. This depends on cvar
2316  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
2317  * it checks whether the number of currently playing players exceeds g_maxplayers.
2318  * @return int number of free slots for players, 0 if none
2319  */
2320 float nJoinAllowed(entity ignore) {
2321         if(!ignore)
2322         // this is called that way when checking if anyone may be able to join (to build qcstatus)
2323         // so report 0 free slots if restricted
2324         {
2325                 if(autocvar_g_forced_team_otherwise == "spectate")
2326                         return 0;
2327                 if(autocvar_g_forced_team_otherwise == "spectator")
2328                         return 0;
2329         }
2330
2331         if(self.team_forced < 0)
2332                 return 0; // forced spectators can never join
2333
2334         // TODO simplify this
2335         entity e;
2336         float totalClients = 0;
2337         FOR_EACH_CLIENT(e)
2338                 if(e != ignore)
2339                         totalClients += 1;
2340
2341         if (!autocvar_g_maxplayers)
2342                 return maxclients - totalClients;
2343
2344         float currentlyPlaying = 0;
2345         FOR_EACH_REALPLAYER(e)
2346                 currentlyPlaying += 1;
2347
2348         if(currentlyPlaying < autocvar_g_maxplayers)
2349                 return min(maxclients - totalClients, autocvar_g_maxplayers - currentlyPlaying);
2350
2351         return 0;
2352 }
2353
2354 /**
2355  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2356  * g_maxplayers_spectator_blocktime seconds
2357  */
2358 void checkSpectatorBlock() {
2359         if(self.classname == "spectator" || self.classname == "observer") {
2360                 if( time > (self.spectatortime + autocvar_g_maxplayers_spectator_blocktime) ) {
2361                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_QUIT_KICK_SPECTATING);
2362                         dropclient(self);
2363                 }
2364         }
2365 }
2366
2367 .float motd_actived_time; // used for both motd and campaign_message
2368 void PrintWelcomeMessage()
2369 {
2370         if (self.motd_actived_time == 0) { // is there already a message showing?
2371                 if (autocvar_g_campaign) {
2372                         if ((self.classname == "player" && self.BUTTON_INFO) || (self.classname != "player")) {
2373                                 self.motd_actived_time = time;
2374                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, campaign_message);
2375                         }
2376                 } else {
2377                         if ((time - self.jointime > autocvar_welcome_message_time) && self.BUTTON_INFO) {
2378                                 self.motd_actived_time = time;
2379                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_MOTD, getwelcomemessage());
2380                         }
2381                 }
2382         } else { // showing MOTD or campaign message
2383                 if (autocvar_g_campaign) {
2384                         if (self.BUTTON_INFO)
2385                                 self.motd_actived_time = time;
2386                         else if ((time - self.motd_actived_time > 2) && self.classname == "player") { // hide it some seconds after BUTTON_INFO has been released
2387                                 self.motd_actived_time = 0;
2388                                 Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD);
2389                         }
2390                 } else {
2391                         if ((time - self.jointime) > autocvar_welcome_message_time) {
2392                                 if (self.BUTTON_INFO)
2393                                         self.motd_actived_time = time;
2394                                 else if (time - self.motd_actived_time > 2) { // hide it some seconds after BUTTON_INFO has been released
2395                                         self.motd_actived_time = 0;
2396                                         Kill_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER_CPID, CPID_MOTD);
2397                                 }
2398                         }
2399                 }
2400         }
2401 }
2402
2403 void ObserverThink()
2404 {
2405         float prefered_movetype;
2406         if (self.flags & FL_JUMPRELEASED) {
2407                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2408                         self.flags &~= FL_JUMPRELEASED;
2409                         self.flags |= FL_SPAWNING;
2410                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
2411                         self.flags &~= FL_JUMPRELEASED;
2412                         if(SpectateNext(world) == 1) {
2413                                 self.classname = "spectator";
2414                         }
2415                 } else {
2416                         prefered_movetype = ((!self.BUTTON_USE ? self.cvar_cl_clippedspectating : !self.cvar_cl_clippedspectating) ? MOVETYPE_FLY_WORLDONLY : MOVETYPE_NOCLIP);
2417                         if (self.movetype != prefered_movetype)
2418                                 self.movetype = prefered_movetype;
2419                 }
2420         } else {
2421                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
2422                         self.flags |= FL_JUMPRELEASED;
2423                         if(self.flags & FL_SPAWNING)
2424                         {
2425                                 self.flags &~= FL_SPAWNING;
2426                                 LeaveSpectatorMode();
2427                                 return;
2428                         }
2429                 }
2430         }
2431
2432         PrintWelcomeMessage();
2433 }
2434
2435 void SpectatorThink()
2436 {
2437         if (self.flags & FL_JUMPRELEASED) {
2438                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2439                         self.flags &~= FL_JUMPRELEASED;
2440                         self.flags |= FL_SPAWNING;
2441                 } else if(self.BUTTON_ATCK) {
2442                         self.flags &~= FL_JUMPRELEASED;
2443                         if(SpectateNext(world) == 1) {
2444                                 self.classname = "spectator";
2445                         } else {
2446                                 self.classname = "observer";
2447                                 PutClientInServer();
2448                         }
2449                 } else if (self.BUTTON_ATCK2) {
2450                         self.flags &~= FL_JUMPRELEASED;
2451                         self.classname = "observer";
2452                         PutClientInServer();
2453                 } else {
2454                         if(!SpectateUpdate())
2455                                 PutObserverInServer();
2456                 }
2457         } else {
2458                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
2459                         self.flags |= FL_JUMPRELEASED;
2460                         if(self.flags & FL_SPAWNING)
2461                         {
2462                                 self.flags &~= FL_SPAWNING;
2463                                 LeaveSpectatorMode();
2464                                 return;
2465                         }
2466                 }
2467                 if(!SpectateUpdate())
2468                         PutObserverInServer();
2469         }
2470
2471         PrintWelcomeMessage();
2472         self.flags |= FL_CLIENT | FL_NOTARGET;
2473 }
2474
2475 void PlayerUseKey()
2476 {
2477         if(self.classname != "player")
2478                 return;
2479
2480         if(self.vehicle)
2481         {
2482         vehicles_exit(VHEF_NORMAL);
2483         return;
2484         }
2485         
2486         // a use key was pressed; call handlers
2487         MUTATOR_CALLHOOK(PlayerUseKey);
2488 }
2489
2490 .float touchexplode_time;
2491
2492 /*
2493 =============
2494 PlayerPreThink
2495
2496 Called every frame for each client before the physics are run
2497 =============
2498 */
2499 .float usekeypressed;
2500 void() nexball_setstatus;
2501 .float items_added;
2502 void PlayerPreThink (void)
2503 {
2504         WarpZone_PlayerPhysics_FixVAngle();
2505
2506         self.stat_game_starttime = game_starttime;
2507         self.stat_allow_oldnexbeam = autocvar_g_allow_oldnexbeam;
2508         self.stat_leadlimit = autocvar_leadlimit;
2509
2510         if(g_arena || (g_ca && !allowed_to_spawn))
2511                 self.stat_respawn_time = 0;
2512         else
2513                 self.stat_respawn_time = self.respawn_time;
2514
2515         if(frametime)
2516         {
2517                 // physics frames: update anticheat stuff
2518                 anticheat_prethink();
2519         }
2520
2521         if(blockSpectators && frametime)
2522                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2523                 checkSpectatorBlock();
2524
2525         zoomstate_set = 0;
2526
2527         if(self.netname_previous != self.netname)
2528         {
2529                 if(autocvar_sv_eventlog)
2530                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2531                 if(self.netname_previous)
2532                         strunzone(self.netname_previous);
2533                 self.netname_previous = strzone(self.netname);
2534         }
2535
2536         // version nagging
2537         if(self.version_nagtime)
2538                 if(self.cvar_g_xonoticversion)
2539                         if(time > self.version_nagtime)
2540                         {
2541                                 // don't notify git users
2542                                 if(strstr(self.cvar_g_xonoticversion, "git", 0) < 0 && strstr(self.cvar_g_xonoticversion, "autobuild", 0) < 0)
2543                                 {
2544                                         if(strstr(autocvar_g_xonoticversion, "git", 0) >= 0 || strstr(autocvar_g_xonoticversion, "autobuild", 0) >= 0)
2545                                         {
2546                                                 // notify release users if connecting to git
2547                                                 dprint("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Xonotic ", autocvar_g_xonoticversion, " (beta)^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n");
2548                                                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_BETA, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2549                                         }
2550                                         else
2551                                         {
2552                                                 float r;
2553                                                 r = vercmp(self.cvar_g_xonoticversion, autocvar_g_xonoticversion);
2554                                                 if(r < 0)
2555                                                 {
2556                                                         // give users new version
2557                                                         dprint("^1NOTE^7 to ", self.netname, "^7 - ^3Xonotic ", autocvar_g_xonoticversion, "^7 is out, and you still have ^3Xonotic ", self.cvar_g_xonoticversion, "^1 - get the update from ^4http://www.xonotic.org/^1!\n");
2558                                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_OUTDATED, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2559                                                 }
2560                                                 else if(r > 0)
2561                                                 {
2562                                                         // notify users about old server version
2563                                                         print("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Xonotic ", autocvar_g_xonoticversion, "^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n");
2564                                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_VERSION_OLD, autocvar_g_xonoticversion, self.cvar_g_xonoticversion);
2565                                                 }
2566                                         }
2567                                 }
2568                                 self.version_nagtime = 0;
2569                         }
2570
2571         // GOD MODE info
2572         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2573         {
2574                 Send_Notification(NOTIF_ONE_ONLY, self, MSG_INFO, INFO_GODMODE_OFF, self.max_armorvalue);
2575                 self.max_armorvalue = 0;
2576         }
2577
2578 #ifdef TETRIS
2579         if (TetrisPreFrame())
2580                 return;
2581 #endif
2582
2583         MUTATOR_CALLHOOK(PlayerPreThink);
2584
2585         if(!self.cvar_cl_newusekeysupported) // FIXME remove this - it was a stupid idea to begin with, we can JUST use the button
2586         {
2587                 if(self.BUTTON_USE && !self.usekeypressed)
2588                         PlayerUseKey();
2589                 self.usekeypressed = self.BUTTON_USE;
2590         }
2591
2592         PrintWelcomeMessage();
2593
2594         if(self.classname == "player") {
2595 //              if(self.netname == "Wazat")
2596 //                      bprint(self.classname, "\n");
2597
2598                 CheckRules_Player();
2599
2600                 if (intermission_running)
2601                 {
2602                         IntermissionThink ();   // otherwise a button could be missed between
2603                         return;                                 // the think tics
2604                 }
2605
2606                 //don't allow the player to turn around while game is paused!
2607                 if(timeout_status == TIMEOUT_ACTIVE) {
2608                         // FIXME turn this into CSQC stuff
2609                         self.v_angle = self.lastV_angle;
2610                         self.angles = self.lastV_angle;
2611                         self.fixangle = TRUE;
2612                 }
2613
2614                 if(frametime)
2615                 {
2616                         if(self.weapon == WEP_NEX && autocvar_g_balance_nex_charge)
2617                         {
2618                                 self.weaponentity_glowmod_x = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_red_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2619                                 self.weaponentity_glowmod_y = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_green_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2620                                 self.weaponentity_glowmod_z = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_blue_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2621
2622                                 if(self.nex_charge > autocvar_g_balance_nex_charge_animlimit)
2623                                 {
2624                                         self.weaponentity_glowmod_x = self.weaponentity_glowmod_x + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_red_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2625                                         self.weaponentity_glowmod_y = self.weaponentity_glowmod_y + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_green_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2626                                         self.weaponentity_glowmod_z = self.weaponentity_glowmod_z + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_blue_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2627                                 }
2628                         }
2629                         else
2630                                 self.weaponentity_glowmod = colormapPaletteColor(self.clientcolors & 0x0F, TRUE) * 2;
2631
2632                         player_powerups();
2633                 }
2634
2635                 if (g_minstagib)
2636                         minstagib_ammocheck();
2637
2638                 if (self.deadflag != DEAD_NO)
2639                 {
2640                         float button_pressed, force_respawn;
2641                         if(self.personal && g_race_qualifying)
2642                         {
2643                                 if(time > self.respawn_time)
2644                                 {
2645                                         self.respawn_time = time + 1; // only retry once a second
2646                                         respawn();
2647                                         self.impulse = 141;
2648                                 }
2649                         }
2650                         else
2651                         {
2652                                 if(frametime)
2653                                         player_anim();
2654                                 button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2655                                 force_respawn = (g_lms || g_ca || g_cts || autocvar_g_forced_respawn);
2656                                 if (self.deadflag == DEAD_DYING)
2657                                 {
2658                                         if(force_respawn)
2659                                                 self.deadflag = DEAD_RESPAWNING;
2660                                         else if(!button_pressed)
2661                                                 self.deadflag = DEAD_DEAD;
2662                                 }
2663                                 else if (self.deadflag == DEAD_DEAD)
2664                                 {
2665                                         if(button_pressed)
2666                                                 self.deadflag = DEAD_RESPAWNABLE;
2667                                 }
2668                                 else if (self.deadflag == DEAD_RESPAWNABLE)
2669                                 {
2670                                         if(!button_pressed)
2671                                                 self.deadflag = DEAD_RESPAWNING;
2672                                 }
2673                                 else if (self.deadflag == DEAD_RESPAWNING)
2674                                 {
2675                                         if(time > self.respawn_time)
2676                                         {
2677                                                 self.respawn_time = time + 1; // only retry once a second
2678                                                 respawn();
2679                                         }
2680                                 }
2681                                 ShowRespawnCountdown();
2682                         }
2683
2684                         // if respawning, invert stat_respawn_time to indicate this, the client translates it
2685                         if(self.deadflag == DEAD_RESPAWNING && self.stat_respawn_time > 0)
2686                                 self.stat_respawn_time *= -1;
2687
2688                         return;
2689                 }
2690                 // FIXME from now on self.deadflag is always 0 (and self.health is never < 1)
2691                 // so (self.deadflag == DEAD_NO) is always true in the code below
2692
2693                 if(g_touchexplode)
2694                 if(time > self.touchexplode_time)
2695                 if(self.classname == "player")
2696                 if(self.deadflag == DEAD_NO)
2697                 if not(IS_INDEPENDENT_PLAYER(self))
2698                 FOR_EACH_PLAYER(other) if(self != other)
2699                 {
2700                         if(time > other.touchexplode_time)
2701                         if(other.deadflag == DEAD_NO)
2702                         if not(IS_INDEPENDENT_PLAYER(other))
2703                         if(boxesoverlap(self.absmin, self.absmax, other.absmin, other.absmax))
2704                         {
2705                                 PlayerTouchExplode(self, other);
2706                                 self.touchexplode_time = other.touchexplode_time = time + 0.2;
2707                         }
2708                 }
2709
2710                 if(g_lms && !self.deadflag && autocvar_g_lms_campcheck_interval)
2711                 {
2712                         vector dist;
2713
2714                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2715                         dist = self.prevorigin - self.origin;
2716                         dist_z = 0;
2717                         self.lms_traveled_distance += fabs(vlen(dist));
2718
2719                         if((autocvar_g_campaign && !campaign_bots_may_start) || (time < game_starttime))
2720                         {
2721                                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval*2;
2722                                 self.lms_traveled_distance = 0;
2723                         }
2724
2725                         if(time > self.lms_nextcheck)
2726                         {
2727                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2728                                 if(self.lms_traveled_distance < autocvar_g_lms_campcheck_distance)
2729                                 {
2730                                         Send_Notification(NOTIF_ONE, self, MSG_CENTER, CENTER_LMS_CAMPCHECK);
2731                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2732                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2733                                         Damage(self, self, self, bound(0, autocvar_g_lms_campcheck_damage, self.health + self.armorvalue * autocvar_g_balance_armor_blockpercent + 5), DEATH_CAMP, self.origin, '0 0 0');
2734                                 }
2735                                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval;
2736                                 self.lms_traveled_distance = 0;
2737                         }
2738                 }
2739
2740                 self.prevorigin = self.origin;
2741
2742                 float do_crouch = self.BUTTON_CROUCH;
2743                 if(self.hook.state)
2744                         do_crouch = 0;
2745                 if(self.health <= g_bloodloss)
2746                         do_crouch = 1;
2747                 if(self.vehicle)
2748                         do_crouch = 0;
2749                 if(self.freezetag_frozen)
2750                         do_crouch = 0;
2751                 if(self.weapon == WEP_SHOTGUN && self.weaponentity.wframe == WFRAME_FIRE2 && time < self.weapon_nextthink)
2752                         do_crouch = 0;
2753
2754                 if (do_crouch)
2755                 {
2756                         if (!self.crouch)
2757                         {
2758                                 self.crouch = TRUE;
2759                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2760                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2761                                 // setanim(self, self.anim_duck, FALSE, TRUE, TRUE); // this anim is BROKEN anyway
2762                         }
2763                 }
2764                 else
2765                 {
2766                         if (self.crouch)
2767                         {
2768                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2769                                 if (!trace_startsolid)
2770                                 {
2771                                         self.crouch = FALSE;
2772                                         self.view_ofs = PL_VIEW_OFS;
2773                                         setsize (self, PL_MIN, PL_MAX);
2774                                 }
2775                         }
2776                 }
2777
2778                 if(self.health <= g_bloodloss && self.deadflag == DEAD_NO)
2779                 {
2780                         if(self.bloodloss_timer < time)
2781                         {
2782                                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
2783                                 self.bloodloss_timer = time + 0.5 + random() * 0.5;
2784                         }
2785                 }
2786
2787                 FixPlayermodel();
2788
2789                 GrapplingHookFrame();
2790
2791                 // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2792                 //if(frametime)
2793                 {
2794                         self.items &~= self.items_added;
2795
2796                         W_WeaponFrame();
2797
2798                         self.items_added = 0;
2799                         if(self.items & IT_JETPACK)
2800                                 if(self.items & IT_FUEL_REGEN || self.ammo_fuel >= 0.01)
2801                                         self.items_added |= IT_FUEL;
2802
2803                         self.items |= self.items_added;
2804                 }
2805
2806                 player_regen();
2807
2808                 // rot nex charge to the charge limit
2809                 if(autocvar_g_balance_nex_charge_rot_rate && self.nex_charge > autocvar_g_balance_nex_charge_limit && self.nex_charge_rottime < time)
2810                         self.nex_charge = bound(autocvar_g_balance_nex_charge_limit, self.nex_charge - autocvar_g_balance_nex_charge_rot_rate * frametime / W_TICSPERFRAME, 1);
2811
2812                 if(frametime)
2813                         player_anim();
2814
2815                 if(g_nexball)
2816                         nexball_setstatus();
2817                 
2818                 // secret status
2819                 secrets_setstatus();
2820                 
2821                 self.dmg_team = max(0, self.dmg_team - autocvar_g_teamdamage_resetspeed * frametime);
2822
2823                 //self.angles_y=self.v_angle_y + 90;   // temp
2824         } else if(gameover) {
2825                 if (intermission_running)
2826                         IntermissionThink ();   // otherwise a button could be missed between
2827                 return;
2828         } else if(self.classname == "observer") {
2829                 ObserverThink();
2830         } else if(self.classname == "spectator") {
2831                 SpectatorThink();
2832         }
2833
2834         if(!zoomstate_set)
2835                 SetZoomState(self.BUTTON_ZOOM || self.BUTTON_ZOOMSCRIPT || (self.BUTTON_ATCK2 && self.weapon == WEP_NEX) || (self.BUTTON_ATCK2 && self.weapon == WEP_RIFLE && autocvar_g_balance_rifle_secondary == 0));
2836
2837         float oldspectatee_status;
2838         oldspectatee_status = self.spectatee_status;
2839         if(self.classname == "spectator")
2840                 self.spectatee_status = num_for_edict(self.enemy);
2841         else if(self.classname == "observer")
2842                 self.spectatee_status = num_for_edict(self);
2843         else
2844                 self.spectatee_status = 0;
2845         if(self.spectatee_status != oldspectatee_status)
2846         {
2847                 ClientData_Touch(self);
2848                 if(g_race || g_cts)
2849                         race_InitSpectator();
2850         }
2851
2852         if(self.teamkill_soundtime)
2853         if(time > self.teamkill_soundtime)
2854         {
2855                 self.teamkill_soundtime = 0;
2856
2857                 entity oldpusher, oldself;
2858
2859                 oldself = self; self = self.teamkill_soundsource;
2860                 oldpusher = self.pusher; self.pusher = oldself;
2861
2862                 PlayerSound(playersound_teamshoot, CH_VOICE, VOICETYPE_LASTATTACKER_ONLY);
2863
2864                 self.pusher = oldpusher;
2865                 self = oldself;
2866         }
2867
2868         if(self.taunt_soundtime)
2869         if(time > self.taunt_soundtime)
2870         {
2871                 self.taunt_soundtime = 0;
2872                 PlayerSound(playersound_taunt, CH_VOICE, VOICETYPE_AUTOTAUNT);
2873         }
2874
2875         target_voicescript_next(self);
2876
2877         // if a player goes unarmed after holding a loaded weapon, empty his clip size and remove the crosshair ammo ring
2878         if(!self.weapon)
2879                 self.clip_load = self.clip_size = 0;
2880 }
2881
2882 float isInvisibleString(string s)
2883 {
2884         float i, n, c;
2885         s = strdecolorize(s);
2886         for((i = 0), (n = strlen(s)); i < n; ++i)
2887         {
2888                 c = str2chr(s, i);
2889                 switch(c)
2890                 {
2891                         case 0:
2892                         case 32: // space
2893                                 break;
2894                         case 192: // charmap space
2895                                 if (!autocvar_utf8_enable)
2896                                         break;
2897                                 return FALSE;
2898                         case 160: // space in unicode fonts
2899                         case 0xE000 + 192: // utf8 charmap space
2900                                 if (autocvar_utf8_enable)
2901                                         break;
2902                         default:
2903                                 return FALSE;
2904                 }
2905         }
2906         return TRUE;
2907 }
2908
2909 /*
2910 =============
2911 PlayerPostThink
2912
2913 Called every frame for each client after the physics are run
2914 =============
2915 */
2916 .float idlekick_lasttimeleft;
2917 void PlayerPostThink (void)
2918 {
2919         // Savage: Check for nameless players
2920         if (isInvisibleString(self.netname)) {
2921                 self.netname = "Player";
2922                 stuffcmd(self, strcat("name ", self.netname, substring(ftos(random()), 2, -1), "\n"));
2923         }
2924
2925         if(sv_maxidle && frametime) // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2926         {
2927                 if (time - self.parm_idlesince < 1) // instead of (time == self.parm_idlesince) to support sv_maxidle <= 10
2928                 {
2929                         if(self.idlekick_lasttimeleft) { self.idlekick_lasttimeleft = 0; }
2930                 }
2931                 else
2932                 {
2933                         float timeleft;
2934                         timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2935                         if(timeleft == min(10, sv_maxidle - 1)) // - 1 to support sv_maxidle <= 10
2936                         {
2937                                 if(!self.idlekick_lasttimeleft)
2938                                         Send_Notification(NOTIF_ONE_ONLY, self, MSG_CENTER, CENTER_DISCONNECT_IDLING, timeleft);
2939                         }
2940                         if(timeleft <= 0)
2941                         {
2942                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_QUIT_KICK_IDLING, self.netname);
2943                                 dropclient(self);
2944                                 return;
2945                         }
2946                         else if(timeleft <= 10)
2947                         {
2948                                 if(timeleft != self.idlekick_lasttimeleft)
2949                                         AnnounceTo(self, ftos(timeleft));
2950                                 self.idlekick_lasttimeleft = timeleft;
2951                         }
2952                 }
2953         }
2954
2955 #ifdef TETRIS
2956         if(self.impulse == 100)
2957                 ImpulseCommands();
2958         if (!TetrisPostFrame())
2959         {
2960 #endif
2961
2962         CheatFrame();
2963
2964         //CheckPlayerJump();
2965
2966         if(self.classname == "player") {
2967                 CheckRules_Player();
2968                 UpdateChatBubble();
2969                 if (self.impulse)
2970                         ImpulseCommands();
2971                 if (intermission_running)
2972                         return;         // intermission or finale
2973                 GetPressedKeys();
2974         }
2975         
2976 #ifdef TETRIS
2977         }
2978 #endif
2979
2980         /*
2981         float i;
2982         for(i = 0; i < 1000; ++i)
2983         {
2984                 vector end;
2985                 end = self.origin + '0 0 1024' + 512 * randomvec();
2986                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
2987                 if(trace_fraction < 1)
2988                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
2989                 {
2990                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
2991                         break;
2992                 }
2993         }
2994         */
2995
2996         //pointparticles(particleeffectnum("machinegun_impact"), self.origin + self.view_ofs + '0 0 7', '0 0 0', 1);
2997
2998         if(self.waypointsprite_attachedforcarrier)
2999                 WaypointSprite_UpdateHealth(self.waypointsprite_attachedforcarrier, '1 0 0' * healtharmor_maxdamage(self.health, self.armorvalue, autocvar_g_balance_armor_blockpercent));
3000
3001         playerdemo_write();
3002
3003         if((g_cts || g_race) && self.cvar_cl_allow_uidtracking == 1 && self.cvar_cl_allow_uid2name == 1)
3004         {
3005                 if not(self.stored_netname)
3006                         self.stored_netname = strzone(uid2name(self.crypto_idfp));
3007                 if(self.stored_netname != self.netname)
3008                 {
3009                         db_put(ServerProgsDB, strcat("/uid2name/", self.crypto_idfp), self.netname);
3010                         strunzone(self.stored_netname);
3011                         self.stored_netname = strzone(self.netname);
3012                 }
3013         }
3014
3015         /*
3016         if(g_race)
3017                 dprint(sprintf("%f %.6f\n", time, race_GetFractionalLapCount(self)));
3018         */
3019
3020         CSQCMODEL_AUTOUPDATE();
3021 }