]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/client.qc
Merge branch 'z411/hide_invalid_ranks' into 'master'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / client.qc
1 #include "client.qh"
2
3 #include <common/csqcmodel_settings.qh>
4 #include <common/deathtypes/all.qh>
5 #include <common/effects/all.qh>
6 #include <common/effects/qc/globalsound.qh>
7 #include <common/ent_cs.qh>
8 #include <common/gamemodes/_mod.qh>
9 #include <common/gamemodes/gamemode/nexball/sv_nexball.qh>
10 #include <common/items/_mod.qh>
11 #include <common/items/inventory.qh>
12 #include <common/mapobjects/func/conveyor.qh>
13 #include <common/mapobjects/func/ladder.qh>
14 #include <common/mapobjects/subs.qh>
15 #include <common/mapobjects/target/spawnpoint.qh>
16 #include <common/mapobjects/teleporters.qh>
17 #include <common/mapobjects/trigger/counter.qh>
18 #include <common/mapobjects/trigger/secret.qh>
19 #include <common/mapobjects/trigger/swamp.qh>
20 #include <common/mapobjects/triggers.qh>
21 #include <common/minigames/sv_minigames.qh>
22 #include <common/monsters/sv_monsters.qh>
23 #include <common/mutators/mutator/instagib/sv_instagib.qh>
24 #include <common/mutators/mutator/nades/nades.qh>
25 #include <common/mutators/mutator/overkill/oknex.qh>
26 #include <common/mutators/mutator/status_effects/_mod.qh>
27 #include <common/mutators/mutator/waypoints/all.qh>
28 #include <common/net_linked.qh>
29 #include <common/net_notice.qh>
30 #include <common/notifications/all.qh>
31 #include <common/physics/player.qh>
32 #include <common/playerstats.qh>
33 #include <common/resources/sv_resources.qh>
34 #include <common/state.qh>
35 #include <common/stats.qh>
36 #include <common/vehicles/all.qh>
37 #include <common/vehicles/sv_vehicles.qh>
38 #include <common/viewloc.qh>
39 #include <common/weapons/_all.qh>
40 #include <common/weapons/weapon/vortex.qh>
41 #include <common/wepent.qh>
42 #include <lib/csqcmodel/sv_model.qh>
43 #include <lib/warpzone/common.qh>
44 #include <lib/warpzone/server.qh>
45 #include <server/anticheat.qh>
46 #include <server/antilag.qh>
47 #include <server/bot/api.qh>
48 #include <server/bot/default/cvars.qh>
49 #include <server/campaign.qh>
50 #include <server/chat.qh>
51 #include <server/cheats.qh>
52 #include <server/clientkill.qh>
53 #include <server/command/common.qh>
54 #include <server/command/common.qh>
55 #include <server/command/vote.qh>
56 #include <server/compat/quake3.qh>
57 #include <server/damage.qh>
58 #include <server/gamelog.qh>
59 #include <server/handicap.qh>
60 #include <server/hook.qh>
61 #include <server/impulse.qh>
62 #include <server/intermission.qh>
63 #include <server/ipban.qh>
64 #include <server/main.qh>
65 #include <server/mutators/_mod.qh>
66 #include <server/player.qh>
67 #include <server/portals.qh>
68 #include <server/race.qh>
69 #include <server/scores.qh>
70 #include <server/scores_rules.qh>
71 #include <server/spawnpoints.qh>
72 #include <server/teamplay.qh>
73 #include <server/weapons/accuracy.qh>
74 #include <server/weapons/common.qh>
75 #include <server/weapons/hitplot.qh>
76 #include <server/weapons/selection.qh>
77 #include <server/weapons/tracing.qh>
78 #include <server/weapons/weaponsystem.qh>
79 #include <server/world.qh>
80
81 STATIC_METHOD(Client, Add, void(Client this, int _team))
82 {
83     ClientConnect(this);
84     TRANSMUTE(Player, this);
85     this.frame = 12; // 7
86     this.team = _team;
87     PutClientInServer(this);
88 }
89
90 STATIC_METHOD(Client, Remove, void(Client this))
91 {
92     TRANSMUTE(Observer, this);
93     PutClientInServer(this);
94     ClientDisconnect(this);
95 }
96
97 void send_CSQC_teamnagger() {
98         WriteHeader(MSG_BROADCAST, TE_CSQC_TEAMNAGGER);
99 }
100
101 int CountSpectators(entity player, entity to)
102 {
103         if(!player) { return 0; } // not sure how, but best to be safe
104
105         int spec_count = 0;
106
107         FOREACH_CLIENT(IS_REAL_CLIENT(it) && IS_SPEC(it) && it != to && it.enemy == player,
108         {
109                 spec_count++;
110         });
111
112         return spec_count;
113 }
114
115 void WriteSpectators(entity player, entity to)
116 {
117         if(!player) { return; } // not sure how, but best to be safe
118
119         int spec_count = 0;
120         FOREACH_CLIENT(IS_REAL_CLIENT(it) && IS_SPEC(it) && it != to && it.enemy == player,
121         {
122                 if(spec_count >= MAX_SPECTATORS)
123                         break;
124                 WriteByte(MSG_ENTITY, num_for_edict(it));
125                 ++spec_count;
126         });
127 }
128
129 bool ClientData_Send(entity this, entity to, int sf)
130 {
131         assert(to == this.owner, return false);
132
133         entity e = to;
134         if (IS_SPEC(e)) e = e.enemy;
135
136         sf = 0;
137         if (CS(e).race_completed)       sf |= BIT(0); // forced scoreboard
138         if (CS(to).spectatee_status)    sf |= BIT(1); // spectator ent number follows
139         if (CS(e).zoomstate)            sf |= BIT(2); // zoomed
140         if (autocvar_sv_showspectators) sf |= BIT(4); // show spectators
141
142         WriteHeader(MSG_ENTITY, ENT_CLIENT_CLIENTDATA);
143         WriteByte(MSG_ENTITY, sf);
144
145         if (sf & BIT(1))
146                 WriteByte(MSG_ENTITY, CS(to).spectatee_status);
147
148         if(sf & BIT(4))
149         {
150                 float specs = CountSpectators(e, to);
151                 WriteByte(MSG_ENTITY, specs);
152                 WriteSpectators(e, to);
153         }
154
155         return true;
156 }
157
158 void ClientData_Attach(entity this)
159 {
160         Net_LinkEntity(CS(this).clientdata = new_pure(clientdata), false, 0, ClientData_Send);
161         CS(this).clientdata.drawonlytoclient = this;
162         CS(this).clientdata.owner = this;
163 }
164
165 void ClientData_Detach(entity this)
166 {
167         delete(CS(this).clientdata);
168         CS(this).clientdata = NULL;
169 }
170
171 void ClientData_Touch(entity e)
172 {
173         entity cd = CS(e).clientdata;
174         if (cd) { cd.SendFlags = 1; }
175
176         // make it spectatable
177         FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != e && IS_SPEC(it) && it.enemy == e,
178         {
179                 entity cd = CS(it).clientdata;
180                 if (cd) { cd.SendFlags = 1; }
181         });
182 }
183
184
185 /*
186 =============
187 CheckPlayerModel
188
189 Checks if the argument string can be a valid playermodel.
190 Returns a valid one in doubt.
191 =============
192 */
193 string FallbackPlayerModel;
194 string CheckPlayerModel(string plyermodel) {
195         if(FallbackPlayerModel != cvar_defstring("_cl_playermodel"))
196         {
197                 // note: we cannot summon Don Strunzone here, some player may
198                 // still have the model string set. In case anyone manages how
199                 // to change a cvar default, we'll have a small leak here.
200                 FallbackPlayerModel = strzone(cvar_defstring("_cl_playermodel"));
201         }
202         // only in right path
203         if(substring(plyermodel, 0, 14) != "models/player/")
204                 return FallbackPlayerModel;
205         // only good file extensions
206         if(substring(plyermodel, -4, 4) != ".iqm"
207                 && substring(plyermodel, -4, 4) != ".zym"
208                 && substring(plyermodel, -4, 4) != ".dpm"
209                 && substring(plyermodel, -4, 4) != ".md3"
210                 && substring(plyermodel, -4, 4) != ".psk")
211         {
212                 return FallbackPlayerModel;
213         }
214         // forbid the LOD models
215         if(substring(plyermodel, -9, 5) == "_lod1" || substring(plyermodel, -9, 5) == "_lod2")
216                 return FallbackPlayerModel;
217         if(plyermodel != strtolower(plyermodel))
218                 return FallbackPlayerModel;
219         // also, restrict to server models
220         if(autocvar_sv_servermodelsonly)
221         {
222                 if(!fexists(plyermodel))
223                         return FallbackPlayerModel;
224         }
225         return plyermodel;
226 }
227
228 void setplayermodel(entity e, string modelname)
229 {
230         precache_model(modelname);
231         _setmodel(e, modelname);
232         player_setupanimsformodel(e);
233         if(!autocvar_g_debug_globalsounds)
234                 UpdatePlayerSounds(e);
235 }
236
237 /** putting a client as observer in the server */
238 void PutObserverInServer(entity this, bool is_forced, bool use_spawnpoint)
239 {
240         bool mutator_returnvalue = MUTATOR_CALLHOOK(MakePlayerObserver, this, is_forced);
241         PlayerState_detach(this);
242
243         if (IS_PLAYER(this))
244         {
245                 if(GetResource(this, RES_HEALTH) >= 1)
246                 {
247                         // despawn effect
248                         Send_Effect(EFFECT_SPAWN_NEUTRAL, this.origin, '0 0 0', 1);
249                 }
250
251                 // was a player, recount votes and ready status
252                 if(IS_REAL_CLIENT(this))
253                 {
254                         if (vote_called) { VoteCount(false); }
255                         ReadyCount();
256                 }
257                 entcs_update_players(this);
258         }
259
260         if (use_spawnpoint)
261         {
262                 entity spot = SelectSpawnPoint(this, true);
263                 if (!spot) LOG_FATAL("No spawnpoints for observers?!?");
264                 this.angles = vec2(spot.angles);
265                 // offset it so that the spectator spawns higher off the ground, looks better this way
266                 setorigin(this, spot.origin + STAT(PL_VIEW_OFS, this));
267         }
268         else // change origin to restore previous view origin
269                 setorigin(this, this.origin + STAT(PL_VIEW_OFS, this) - STAT(PL_CROUCH_VIEW_OFS, this));
270         this.fixangle = true;
271
272         if (IS_REAL_CLIENT(this))
273         {
274                 msg_entity = this;
275                 WriteByte(MSG_ONE, SVC_SETVIEW);
276                 WriteEntity(MSG_ONE, this);
277         }
278         // give the spectator some space between walls for MOVETYPE_FLY_WORLDONLY
279         // so that your view doesn't go into the ceiling with MOVETYPE_FLY_WORLDONLY, previously "PL_VIEW_OFS"
280         if(!autocvar_g_debug_globalsounds)
281         {
282                 // needed for player sounds
283                 this.model = "";
284                 FixPlayermodel(this);
285         }
286         setmodel(this, MDL_Null);
287         setsize(this, STAT(PL_CROUCH_MIN, this), STAT(PL_CROUCH_MAX, this));
288         this.view_ofs = '0 0 0';
289
290         RemoveGrapplingHooks(this);
291         Portal_ClearAll(this);
292         Unfreeze(this, false);
293         SetSpectatee(this, NULL);
294
295         if (this.alivetime)
296         {
297                 if (!warmup_stage)
298                         PlayerStats_GameReport_Event_Player(this, PLAYERSTATS_ALIVETIME, time - this.alivetime);
299                 this.alivetime = 0;
300         }
301
302         if (this.vehicle) vehicles_exit(this.vehicle, VHEF_RELEASE);
303
304         WaypointSprite_PlayerDead(this);
305
306         if (CS(this).killcount != FRAGS_SPECTATOR && !game_stopped && CHAT_NOSPECTATORS())
307                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_CHAT_NOSPECTATORS);
308
309         accuracy_resend(this);
310
311         CS(this).spectatortime = time;
312         if(this.bot_attack)
313                 IL_REMOVE(g_bot_targets, this);
314         this.bot_attack = false;
315         if(this.monster_attack)
316                 IL_REMOVE(g_monster_targets, this);
317         this.monster_attack = false;
318         STAT(HUD, this) = HUD_NORMAL;
319         TRANSMUTE(Observer, this);
320         this.iscreature = false;
321         this.teleportable = TELEPORT_SIMPLE;
322         if(this.damagedbycontents)
323                 IL_REMOVE(g_damagedbycontents, this);
324         this.damagedbycontents = false;
325         SetResourceExplicit(this, RES_HEALTH, FRAGS_SPECTATOR);
326         SetSpectatee_status(this, etof(this));
327         this.takedamage = DAMAGE_NO;
328         this.solid = SOLID_NOT;
329         set_movetype(this, MOVETYPE_FLY_WORLDONLY); // user preference is controlled by playerprethink
330         this.flags = FL_CLIENT | FL_NOTARGET;
331         this.effects = 0;
332         SetResourceExplicit(this, RES_ARMOR, autocvar_g_balance_armor_start); // was 666?!
333         this.pauserotarmor_finished = 0;
334         this.pauserothealth_finished = 0;
335         this.pauseregen_finished = 0;
336         this.damageforcescale = 0;
337         this.death_time = 0;
338         this.respawn_flags = 0;
339         this.respawn_time = 0;
340         STAT(RESPAWN_TIME, this) = 0;
341         this.alpha = 0;
342         this.scale = 0;
343         this.fade_time = 0;
344         this.pain_finished = 0;
345         STAT(AIR_FINISHED, this) = 0;
346         //this.dphitcontentsmask = 0;
347         this.dphitcontentsmask = DPCONTENTS_SOLID;
348         if (autocvar_g_playerclip_collisions)
349                 this.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
350         this.pushltime = 0;
351         this.istypefrag = 0;
352         setthink(this, func_null);
353         this.nextthink = 0;
354         this.deadflag = DEAD_NO;
355         UNSET_DUCKED(this);
356         STAT(REVIVE_PROGRESS, this) = 0;
357         this.revival_time = 0;
358         this.draggable = drag_undraggable;
359
360         this.items = 0;
361         STAT(WEAPONS, this) = '0 0 0';
362         this.drawonlytoclient = this;
363
364         this.viewloc = NULL;
365
366         //this.spawnpoint_targ = NULL; // keep it so they can return to where they were?
367
368         this.weaponmodel = "";
369         for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
370         {
371                 this.weaponentities[slot] = NULL;
372         }
373         this.exteriorweaponentity = NULL;
374         CS(this).killcount = FRAGS_SPECTATOR;
375         this.velocity = '0 0 0';
376         this.avelocity = '0 0 0';
377         this.punchangle = '0 0 0';
378         this.punchvector = '0 0 0';
379         this.oldvelocity = this.velocity;
380         this.event_damage = func_null;
381         this.event_heal = func_null;
382
383         for(int slot = 0; slot < MAX_AXH; ++slot)
384         {
385                 entity axh = this.(AuxiliaryXhair[slot]);
386                 this.(AuxiliaryXhair[slot]) = NULL;
387
388                 if(axh.owner == this && axh != NULL && !wasfreed(axh))
389                         delete(axh);
390         }
391
392         if (mutator_returnvalue)
393         {
394                 // mutator prevents resetting teams+score
395         }
396         else
397         {
398                 SetPlayerTeam(this, -1, TEAM_CHANGE_SPECTATOR);
399                 this.frags = FRAGS_SPECTATOR;
400         }
401
402         bot_relinkplayerlist();
403
404         if (CS(this).just_joined)
405                 CS(this).just_joined = false;
406 }
407
408 int player_getspecies(entity this)
409 {
410         get_model_parameters(this.model, this.skin);
411         int s = get_model_parameters_species;
412         get_model_parameters(string_null, 0);
413         if (s < 0) return SPECIES_HUMAN;
414         return s;
415 }
416
417 .float model_randomizer;
418 void FixPlayermodel(entity player)
419 {
420         string defaultmodel = "";
421         int defaultskin = 0;
422         if(autocvar_sv_defaultcharacter)
423         {
424                 if(teamplay)
425                 {
426                         switch(player.team)
427                         {
428                                 case NUM_TEAM_1: defaultmodel = autocvar_sv_defaultplayermodel_red; defaultskin = autocvar_sv_defaultplayerskin_red; break;
429                                 case NUM_TEAM_2: defaultmodel = autocvar_sv_defaultplayermodel_blue; defaultskin = autocvar_sv_defaultplayerskin_blue; break;
430                                 case NUM_TEAM_3: defaultmodel = autocvar_sv_defaultplayermodel_yellow; defaultskin = autocvar_sv_defaultplayerskin_yellow; break;
431                                 case NUM_TEAM_4: defaultmodel = autocvar_sv_defaultplayermodel_pink; defaultskin = autocvar_sv_defaultplayerskin_pink; break;
432                         }
433                 }
434
435                 if(defaultmodel == "")
436                 {
437                         defaultmodel = autocvar_sv_defaultplayermodel;
438                         defaultskin = autocvar_sv_defaultplayerskin;
439                 }
440
441                 int n = tokenize_console(defaultmodel);
442                 if(n > 0)
443                 {
444                         defaultmodel = argv(floor(n * CS(player).model_randomizer));
445                         // However, do NOT randomize if the player-selected model is in the list.
446                         for (int i = 0; i < n; ++i)
447                                 if ((argv(i) == player.playermodel && defaultskin == stof(player.playerskin)) || argv(i) == strcat(player.playermodel, ":", player.playerskin))
448                                         defaultmodel = argv(i);
449                 }
450
451                 int i = strstrofs(defaultmodel, ":", 0);
452                 if(i >= 0)
453                 {
454                         defaultskin = stof(substring(defaultmodel, i+1, -1));
455                         defaultmodel = substring(defaultmodel, 0, i);
456                 }
457         }
458         if(autocvar_sv_defaultcharacterskin && !defaultskin)
459         {
460                 if(teamplay)
461                 {
462                         switch(player.team)
463                         {
464                                 case NUM_TEAM_1: defaultskin = autocvar_sv_defaultplayerskin_red; break;
465                                 case NUM_TEAM_2: defaultskin = autocvar_sv_defaultplayerskin_blue; break;
466                                 case NUM_TEAM_3: defaultskin = autocvar_sv_defaultplayerskin_yellow; break;
467                                 case NUM_TEAM_4: defaultskin = autocvar_sv_defaultplayerskin_pink; break;
468                         }
469                 }
470
471                 if(!defaultskin)
472                         defaultskin = autocvar_sv_defaultplayerskin;
473         }
474
475         MUTATOR_CALLHOOK(FixPlayermodel, defaultmodel, defaultskin, player);
476         defaultmodel = M_ARGV(0, string);
477         defaultskin = M_ARGV(1, int);
478
479         bool chmdl = false;
480         int oldskin;
481         if(defaultmodel != "")
482         {
483                 if (defaultmodel != player.model)
484                 {
485                         vector m1 = player.mins;
486                         vector m2 = player.maxs;
487                         setplayermodel (player, defaultmodel);
488                         setsize (player, m1, m2);
489                         chmdl = true;
490                 }
491
492                 oldskin = player.skin;
493                 player.skin = defaultskin;
494         } else {
495                 if (player.playermodel != player.model || player.playermodel == "")
496                 {
497                         player.playermodel = CheckPlayerModel(player.playermodel); // this is never "", so no endless loop
498                         vector m1 = player.mins;
499                         vector m2 = player.maxs;
500                         setplayermodel (player, player.playermodel);
501                         setsize (player, m1, m2);
502                         chmdl = true;
503                 }
504
505                 if(!autocvar_sv_defaultcharacterskin)
506                 {
507                         oldskin = player.skin;
508                         player.skin = stof(player.playerskin);
509                 }
510                 else
511                 {
512                         oldskin = player.skin;
513                         player.skin = defaultskin;
514                 }
515         }
516
517         if(chmdl || oldskin != player.skin) // model or skin has changed
518         {
519                 player.species = player_getspecies(player); // update species
520                 if(!autocvar_g_debug_globalsounds)
521                         UpdatePlayerSounds(player); // update skin sounds
522         }
523
524         if(!teamplay)
525                 if(strlen(autocvar_sv_defaultplayercolors))
526                         if(player.clientcolors != stof(autocvar_sv_defaultplayercolors))
527                                 setcolor(player, stof(autocvar_sv_defaultplayercolors));
528 }
529
530 void PutPlayerInServer(entity this)
531 {
532         if (this.vehicle) vehicles_exit(this.vehicle, VHEF_RELEASE);
533
534         PlayerState_attach(this);
535         accuracy_resend(this);
536
537         if (this.team < 0)
538                 TeamBalance_JoinBestTeam(this);
539
540         entity spot = SelectSpawnPoint(this, false);
541         if (!spot) {
542                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_JOIN_NOSPAWNS);
543                 return; // spawn failed
544         }
545
546         TRANSMUTE(Player, this);
547
548         CS(this).wasplayer = true;
549         this.iscreature = true;
550         this.teleportable = TELEPORT_NORMAL;
551         if(!this.damagedbycontents)
552                 IL_PUSH(g_damagedbycontents, this);
553         this.damagedbycontents = true;
554         set_movetype(this, MOVETYPE_WALK);
555         this.solid = SOLID_SLIDEBOX;
556         this.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_SOLID;
557         if (autocvar_g_playerclip_collisions)
558                 this.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
559         if (IS_BOT_CLIENT(this) && autocvar_g_botclip_collisions)
560                 this.dphitcontentsmask |= DPCONTENTS_BOTCLIP;
561         this.frags = FRAGS_PLAYER;
562         if (INDEPENDENT_PLAYERS) MAKE_INDEPENDENT_PLAYER(this);
563         this.flags = FL_CLIENT | FL_PICKUPITEMS;
564         if (autocvar__notarget)
565                 this.flags |= FL_NOTARGET;
566         this.takedamage = DAMAGE_AIM;
567         this.effects = EF_TELEPORT_BIT | EF_RESTARTANIM_BIT;
568
569         if (warmup_stage) {
570                 SetResource(this, RES_SHELLS, warmup_start_ammo_shells);
571                 SetResource(this, RES_BULLETS, warmup_start_ammo_nails);
572                 SetResource(this, RES_ROCKETS, warmup_start_ammo_rockets);
573                 SetResource(this, RES_CELLS, warmup_start_ammo_cells);
574                 SetResource(this, RES_PLASMA, warmup_start_ammo_plasma);
575                 SetResource(this, RES_FUEL, warmup_start_ammo_fuel);
576                 SetResource(this, RES_HEALTH, warmup_start_health);
577                 SetResource(this, RES_ARMOR, warmup_start_armorvalue);
578                 STAT(WEAPONS, this) = WARMUP_START_WEAPONS;
579         } else {
580                 SetResource(this, RES_SHELLS, start_ammo_shells);
581                 SetResource(this, RES_BULLETS, start_ammo_nails);
582                 SetResource(this, RES_ROCKETS, start_ammo_rockets);
583                 SetResource(this, RES_CELLS, start_ammo_cells);
584                 SetResource(this, RES_PLASMA, start_ammo_plasma);
585                 SetResource(this, RES_FUEL, start_ammo_fuel);
586                 SetResource(this, RES_HEALTH, start_health);
587                 SetResource(this, RES_ARMOR, start_armorvalue);
588                 STAT(WEAPONS, this) = start_weapons;
589                 if (MUTATOR_CALLHOOK(ForbidRandomStartWeapons, this) == false)
590                 {
591                         GiveRandomWeapons(this, random_start_weapons_count,
592                                 autocvar_g_random_start_weapons, random_start_ammo);
593                 }
594         }
595         SetSpectatee_status(this, 0);
596
597         PS(this).dual_weapons = '0 0 0';
598
599         if(STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS)
600                 StatusEffects_apply(STATUSEFFECT_Superweapons, this, time + autocvar_g_balance_superweapons_time, 0);
601
602         this.items = start_items;
603
604         float shieldtime = time + autocvar_g_spawnshieldtime;
605
606         this.pauserotarmor_finished = time + autocvar_g_balance_pause_armor_rot_spawn;
607         this.pauserothealth_finished = time + autocvar_g_balance_pause_health_rot_spawn;
608         this.pauserotfuel_finished = time + autocvar_g_balance_pause_fuel_rot_spawn;
609         this.pauseregen_finished = time + autocvar_g_balance_pause_health_regen_spawn;
610         if (!sv_ready_restart_after_countdown && time < game_starttime)
611         {
612                 float f = game_starttime - time;
613                 shieldtime += f;
614                 this.pauserotarmor_finished += f;
615                 this.pauserothealth_finished += f;
616                 this.pauseregen_finished += f;
617         }
618
619         StatusEffects_apply(STATUSEFFECT_SpawnShield, this, shieldtime, 0);
620
621         this.damageforcescale = autocvar_g_player_damageforcescale;
622         this.death_time = 0;
623         this.respawn_flags = 0;
624         this.respawn_time = 0;
625         STAT(RESPAWN_TIME, this) = 0;
626         this.scale = ((q3compat && autocvar_sv_q3compat_changehitbox) ? 0.9 : autocvar_sv_player_scale);
627         this.fade_time = 0;
628         this.pain_finished = 0;
629         this.pushltime = 0;
630         setthink(this, func_null); // players have no think function
631         this.nextthink = 0;
632         this.dmg_team = 0;
633         PS(this).ballistics_density = autocvar_g_ballistics_density_player;
634
635         this.deadflag = DEAD_NO;
636
637         this.angles = spot.angles;
638         this.angles_z = 0; // never spawn tilted even if the spot says to
639         if (IS_BOT_CLIENT(this))
640         {
641                 this.v_angle = this.angles;
642                 bot_aim_reset(this);
643         }
644         this.fixangle = true; // turn this way immediately
645         this.oldvelocity = this.velocity = '0 0 0';
646         this.avelocity = '0 0 0';
647         this.punchangle = '0 0 0';
648         this.punchvector = '0 0 0';
649
650         STAT(REVIVE_PROGRESS, this) = 0;
651         this.revival_time = 0;
652
653         STAT(AIR_FINISHED, this) = 0;
654         this.waterlevel = WATERLEVEL_NONE;
655         this.watertype = CONTENT_EMPTY;
656
657         entity spawnevent = new_pure(spawnevent);
658         spawnevent.owner = this;
659         Net_LinkEntity(spawnevent, false, 0.5, SpawnEvent_Send);
660
661         // Cut off any still running player sounds.
662         stopsound(this, CH_PLAYER_SINGLE);
663
664         this.model = "";
665         FixPlayermodel(this);
666         this.drawonlytoclient = NULL;
667
668         this.viewloc = NULL;
669
670         for(int slot = 0; slot < MAX_AXH; ++slot)
671         {
672                 entity axh = this.(AuxiliaryXhair[slot]);
673                 this.(AuxiliaryXhair[slot]) = NULL;
674
675                 if(axh.owner == this && axh != NULL && !wasfreed(axh))
676                         delete(axh);
677         }
678
679         this.spawnpoint_targ = NULL;
680
681         UNSET_DUCKED(this);
682         this.view_ofs = STAT(PL_VIEW_OFS, this);
683         setsize(this, STAT(PL_MIN, this), STAT(PL_MAX, this));
684         this.spawnorigin = spot.origin;
685         setorigin(this, spot.origin + '0 0 1' * (1 - this.mins.z - 24));
686         // don't reset back to last position, even if new position is stuck in solid
687         this.oldorigin = this.origin;
688         if(this.conveyor)
689                 IL_REMOVE(g_conveyed, this);
690         this.conveyor = NULL; // prevent conveyors at the previous location from moving a freshly spawned player
691         if(this.swampslug)
692                 IL_REMOVE(g_swamped, this);
693         this.swampslug = NULL;
694         this.swamp_interval = 0;
695         if(this.ladder_entity)
696                 IL_REMOVE(g_ladderents, this);
697         this.ladder_entity = NULL;
698         IL_EACH(g_counters, it.realowner == this,
699         {
700                 delete(it);
701         });
702         STAT(HUD, this) = HUD_NORMAL;
703
704         this.event_damage = PlayerDamage;
705         this.event_heal = PlayerHeal;
706
707         this.draggable = func_null;
708
709         if(!this.bot_attack)
710                 IL_PUSH(g_bot_targets, this);
711         this.bot_attack = true;
712         if(!this.monster_attack)
713                 IL_PUSH(g_monster_targets, this);
714         this.monster_attack = true;
715         navigation_dynamicgoal_init(this, false);
716
717         PHYS_INPUT_BUTTON_ATCK(this) = PHYS_INPUT_BUTTON_JUMP(this) = PHYS_INPUT_BUTTON_ATCK2(this) = false;
718
719         // player was spectator
720         if (CS(this).killcount == FRAGS_SPECTATOR) {
721                 PlayerScore_Clear(this);
722                 CS(this).killcount = 0;
723                 CS(this).startplaytime = time;
724         }
725
726         for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
727         {
728                 .entity weaponentity = weaponentities[slot];
729                 CL_SpawnWeaponentity(this, weaponentity);
730         }
731         this.alpha = default_player_alpha;
732         this.colormod = '1 1 1' * autocvar_g_player_brightness;
733         this.exteriorweaponentity.alpha = default_weapon_alpha;
734
735         this.speedrunning = false;
736
737         this.counter_cnt = 0;
738         this.fragsfilter_cnt = 0;
739
740         target_voicescript_clear(this);
741
742         // reset fields the weapons may use
743         FOREACH(Weapons, true, {
744                 it.wr_resetplayer(it, this);
745                         // reload all reloadable weapons
746                 if (it.spawnflags & WEP_FLAG_RELOADABLE) {
747                         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
748                         {
749                                 .entity weaponentity = weaponentities[slot];
750                                 this.(weaponentity).weapon_load[it.m_id] = it.reloading_ammo;
751                         }
752                 }
753         });
754
755         Unfreeze(this, false);
756
757         MUTATOR_CALLHOOK(PlayerSpawn, this, spot);
758
759         {
760                 string s = spot.target;
761                 if(g_assault || g_race) // TODO: make targeting work in assault & race without this hack
762                         spot.target = string_null;
763                 SUB_UseTargets(spot, this, NULL);
764                 if(g_assault || g_race)
765                         spot.target = s;
766         }
767
768         if (autocvar_spawn_debug)
769         {
770                 sprint(this, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
771                 delete(spot); // usefull for checking if there are spawnpoints, that let drop through the floor
772         }
773
774         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
775         {
776                 .entity weaponentity = weaponentities[slot];
777                 entity w_ent = this.(weaponentity);
778                 if(slot == 0 || autocvar_g_weaponswitch_debug == 1)
779                         w_ent.m_switchweapon = w_getbestweapon(this, weaponentity);
780                 else
781                         w_ent.m_switchweapon = WEP_Null;
782                 w_ent.m_weapon = WEP_Null;
783                 w_ent.weaponname = "";
784                 w_ent.m_switchingweapon = WEP_Null;
785                 w_ent.cnt = -1;
786         }
787
788         MUTATOR_CALLHOOK(PlayerWeaponSelect, this);
789
790         if (CS(this).impulse) ImpulseCommands(this);
791
792         W_ResetGunAlign(this, CS_CVAR(this).cvar_cl_gunalign);
793         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
794         {
795                 .entity weaponentity = weaponentities[slot];
796                 W_WeaponFrame(this, weaponentity);
797         }
798
799         if (!warmup_stage && !this.alivetime)
800                 this.alivetime = time;
801
802         antilag_clear(this, CS(this));
803 }
804
805 /** Called when a client spawns in the server */
806 void PutClientInServer(entity this)
807 {
808         if (IS_BOT_CLIENT(this)) {
809                 TRANSMUTE(Player, this);
810         } else if (IS_REAL_CLIENT(this)) {
811                 msg_entity = this;
812                 WriteByte(MSG_ONE, SVC_SETVIEW);
813                 WriteEntity(MSG_ONE, this);
814         }
815         if (game_stopped)
816                 TRANSMUTE(Observer, this);
817
818         bool use_spawnpoint = (!this.enemy); // check this.enemy here since SetSpectatee will clear it
819         SetSpectatee(this, NULL);
820
821         // reset player keys
822         if(PS(this))
823                 PS(this).itemkeys = 0;
824
825         MUTATOR_CALLHOOK(PutClientInServer, this);
826
827         if (IS_OBSERVER(this)) {
828                 PutObserverInServer(this, false, use_spawnpoint);
829         } else if (IS_PLAYER(this)) {
830                 PutPlayerInServer(this);
831         }
832
833         bot_relinkplayerlist();
834 }
835
836 // TODO do we need all these fields, or should we stop autodetecting runtime
837 // changes and just have a console command to update this?
838 bool ClientInit_SendEntity(entity this, entity to, int sf)
839 {
840         WriteHeader(MSG_ENTITY, _ENT_CLIENT_INIT);
841         return = true;
842         msg_entity = to;
843         // MSG_INIT replacement
844         // TODO: make easier to use
845         Registry_send_all();
846         W_PROP_reload(MSG_ONE, to);
847         ClientInit_misc(this);
848         MUTATOR_CALLHOOK(Ent_Init);
849 }
850 void ClientInit_misc(entity this)
851 {
852         int channel = MSG_ONE;
853         WriteHeader(channel, ENT_CLIENT_INIT);
854         WriteByte(channel, g_nexball_meter_period * 32);
855         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[0]));
856         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[1]));
857         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[2]));
858         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[3]));
859         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[0]));
860         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[1]));
861         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[2]));
862         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[3]));
863
864         if(autocvar_sv_foginterval && world.fog != "")
865                 WriteString(channel, world.fog);
866         else
867                 WriteString(channel, "");
868         WriteByte(channel, this.count * 255.0); // g_balance_armor_blockpercent
869         WriteByte(channel, this.cnt * 255.0); // g_balance_damagepush_speedfactor
870         WriteByte(channel, serverflags);
871         WriteCoord(channel, autocvar_g_trueaim_minrange);
872 }
873
874 void ClientInit_CheckUpdate(entity this)
875 {
876         this.nextthink = time;
877         if(this.count != autocvar_g_balance_armor_blockpercent)
878         {
879                 this.count = autocvar_g_balance_armor_blockpercent;
880                 this.SendFlags |= 1;
881         }
882         if(this.cnt != autocvar_g_balance_damagepush_speedfactor)
883         {
884                 this.cnt = autocvar_g_balance_damagepush_speedfactor;
885                 this.SendFlags |= 1;
886         }
887 }
888
889 void ClientInit_Spawn()
890 {
891         entity e = new_pure(clientinit);
892         setthink(e, ClientInit_CheckUpdate);
893         Net_LinkEntity(e, false, 0, ClientInit_SendEntity);
894
895         ClientInit_CheckUpdate(e);
896 }
897
898 /*
899 =============
900 SetNewParms
901 =============
902 */
903 void SetNewParms ()
904 {
905         // initialize parms for a new player
906         parm1 = -(86400 * 366);
907
908         MUTATOR_CALLHOOK(SetNewParms);
909 }
910
911 /*
912 =============
913 SetChangeParms
914 =============
915 */
916 void SetChangeParms (entity this)
917 {
918         // save parms for level change
919         parm1 = CS(this).parm_idlesince - time;
920
921         MUTATOR_CALLHOOK(SetChangeParms);
922 }
923
924 /*
925 =============
926 DecodeLevelParms
927 =============
928 */
929 void DecodeLevelParms(entity this)
930 {
931         // load parms
932         CS(this).parm_idlesince = parm1;
933         if (CS(this).parm_idlesince == -(86400 * 366))
934                 CS(this).parm_idlesince = time;
935
936         // whatever happens, allow 60 seconds of idling directly after connect for map loading
937         CS(this).parm_idlesince = max(CS(this).parm_idlesince, time - autocvar_sv_maxidle + 60);
938
939         MUTATOR_CALLHOOK(DecodeLevelParms);
940 }
941
942 void FixClientCvars(entity e)
943 {
944         // send prediction settings to the client
945         if(autocvar_g_antilag == 3) // client side hitscan
946                 stuffcmd(e, "cl_cmd settemp cl_prydoncursor_notrace 0\n");
947         if(autocvar_sv_gentle)
948                 stuffcmd(e, "cl_cmd settemp cl_gentle 1\n");
949
950         stuffcmd(e, sprintf("\ncl_jumpspeedcap_min \"%s\"\n", autocvar_sv_jumpspeedcap_min));
951         stuffcmd(e, sprintf("\ncl_jumpspeedcap_max \"%s\"\n", autocvar_sv_jumpspeedcap_max));
952
953         stuffcmd(e, sprintf("\ncl_shootfromfixedorigin \"%s\"\n", autocvar_g_shootfromfixedorigin));
954
955         MUTATOR_CALLHOOK(FixClientCvars, e);
956 }
957
958 bool findinlist_abbrev(string tofind, string list)
959 {
960         if(list == "" || tofind == "")
961                 return false; // empty list or search, just return
962
963         // this function allows abbreviated strings!
964         FOREACH_WORD(list, it == substring(tofind, 0, strlen(it)),
965         {
966                 return true;
967         });
968
969         return false;
970 }
971
972 bool PlayerInIPList(entity p, string iplist)
973 {
974         // some safety checks (never allow local?)
975         if(p.netaddress == "local" || p.netaddress == "" || !IS_REAL_CLIENT(p))
976                 return false;
977
978         return findinlist_abbrev(p.netaddress, iplist);
979 }
980
981 bool PlayerInIDList(entity p, string idlist)
982 {
983         // NOTE: we do NOT check crypto_idfp_signed here, an unsigned ID is fine too for this
984         if(!p.crypto_idfp)
985                 return false;
986
987         return findinlist_abbrev(p.crypto_idfp, idlist);
988 }
989
990 bool PlayerInList(entity player, string list)
991 {
992         return boolean(PlayerInIDList(player, list) || PlayerInIPList(player, list));
993 }
994
995 #ifdef DP_EXT_PRECONNECT
996 /*
997 =============
998 ClientPreConnect
999
1000 Called once (not at each match start) when a client begins a connection to the server
1001 =============
1002 */
1003 void ClientPreConnect(entity this)
1004 {
1005         if(autocvar_sv_eventlog)
1006         {
1007                 GameLogEcho(sprintf(":connect:%d:%d:%s",
1008                         this.playerid,
1009                         etof(this),
1010                         ((IS_REAL_CLIENT(this)) ? this.netaddress : "bot")
1011                 ));
1012         }
1013 }
1014 #endif
1015
1016 string GetClientVersionMessage(entity this)
1017 {
1018         if (CS(this).version_mismatch) {
1019                 if(CS(this).version < autocvar_gameversion) {
1020                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
1021                                 "\n^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8");
1022                 } else {
1023                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
1024                                 "\n^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8");
1025                 }
1026         } else {
1027                 return strcat("Welcome to Xonotic ", autocvar_g_xonoticversion);
1028         }
1029 }
1030
1031 string getwelcomemessage(entity this)
1032 {
1033         MUTATOR_CALLHOOK(BuildMutatorsPrettyString, "");
1034         string modifications = M_ARGV(0, string);
1035
1036         if(g_weaponarena)
1037         {
1038                 if(g_weaponarena_random)
1039                         modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
1040                 else
1041                         modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
1042         }
1043         else if(cvar("g_balance_blaster_weaponstartoverride") == 0)
1044                 modifications = strcat(modifications, ", No start weapons");
1045         if(cvar("sv_gravity") < stof(cvar_defstring("sv_gravity")))
1046                 modifications = strcat(modifications, ", Low gravity");
1047         if(g_weapon_stay && !g_cts)
1048                 modifications = strcat(modifications, ", Weapons stay");
1049         if(autocvar_g_jetpack)
1050                 modifications = strcat(modifications, ", Jet pack");
1051         modifications = substring(modifications, 2, strlen(modifications) - 2);
1052
1053         string versionmessage = GetClientVersionMessage(this);
1054         string s = strcat(versionmessage, "^8\n^8\nserver is ^9", autocvar_hostname, "^8\n");
1055
1056         s = strcat(s, "^8\nmatch type is ^1", gamemode_name, "^8\n");
1057
1058         if(modifications != "")
1059                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
1060
1061         if(cache_lastmutatormsg != autocvar_g_mutatormsg)
1062         {
1063                 strcpy(cache_lastmutatormsg, autocvar_g_mutatormsg);
1064                 strcpy(cache_mutatormsg, cache_lastmutatormsg);
1065         }
1066
1067         if (cache_mutatormsg != "") {
1068                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
1069         }
1070
1071         string mutator_msg = "";
1072         MUTATOR_CALLHOOK(BuildGameplayTipsString, mutator_msg);
1073         mutator_msg = M_ARGV(0, string);
1074
1075         s = strcat(s, mutator_msg); // trust that the mutator will do proper formatting
1076
1077         string motd = autocvar_sv_motd;
1078         if (motd != "") {
1079                 s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
1080         }
1081         return s;
1082 }
1083
1084 /**
1085 =============
1086 ClientConnect
1087
1088 Called when a client connects to the server
1089 =============
1090 */
1091 void ClientConnect(entity this)
1092 {
1093         if (Ban_MaybeEnforceBanOnce(this)) return;
1094         assert(!IS_CLIENT(this), return);
1095         this.flags |= FL_CLIENT;
1096         assert(player_count >= 0, player_count = 0);
1097
1098         TRANSMUTE(Client, this);
1099         CS(this).version_nagtime = time + 10 + random() * 10;
1100
1101         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_JOIN_CONNECT, this.netname);
1102
1103         bot_clientconnect(this);
1104
1105         Player_DetermineForcedTeam(this);
1106
1107         TRANSMUTE(Observer, this);
1108
1109         PlayerStats_GameReport_AddEvent(sprintf("kills-%d", this.playerid));
1110
1111         // always track bots, don't ask for cl_allow_uidtracking
1112         if (IS_BOT_CLIENT(this))
1113                 PlayerStats_GameReport_AddPlayer(this);
1114         else
1115                 CS(this).allowed_timeouts = autocvar_sv_timeout_number;
1116
1117         if (autocvar_sv_eventlog)
1118                 GameLogEcho(strcat(":join:", ftos(this.playerid), ":", ftos(etof(this)), ":", ((IS_REAL_CLIENT(this)) ? GameLog_ProcessIP(this.netaddress) : "bot"), ":", playername(this.netname, this.team, false)));
1119
1120         CS(this).just_joined = true;  // stop spamming the eventlog with additional lines when the client connects
1121
1122         stuffcmd(this, clientstuff, "\n");
1123         stuffcmd(this, "cl_particles_reloadeffects\n"); // TODO do we still need this?
1124
1125         FixClientCvars(this);
1126
1127         // get version info from player
1128         stuffcmd(this, "cmd clientversion $gameversion\n");
1129
1130         // notify about available teams
1131         if (teamplay)
1132         {
1133                 entity balance = TeamBalance_CheckAllowedTeams(this);
1134                 int t = TeamBalance_GetAllowedTeams(balance);
1135                 TeamBalance_Destroy(balance);
1136                 stuffcmd(this, sprintf("set _teams_available %d\n", t));
1137         }
1138         else
1139         {
1140                 stuffcmd(this, "set _teams_available 0\n");
1141         }
1142
1143         bot_relinkplayerlist();
1144
1145         CS(this).spectatortime = time;
1146         if (blockSpectators)
1147         {
1148                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
1149         }
1150
1151         CS(this).jointime = time;
1152
1153         if (IS_REAL_CLIENT(this))
1154         {
1155                 if (g_weaponarena_weapons == WEPSET(TUBA))
1156                         stuffcmd(this, "cl_cmd settemp chase_active 1\n");
1157         }
1158
1159         if (!autocvar_sv_foginterval && world.fog != "")
1160                 stuffcmd(this, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1161
1162         if (autocvar_sv_teamnagger && !(autocvar_bot_vs_human && AvailableTeams() == 2))
1163                 if(!MUTATOR_CALLHOOK(HideTeamNagger, this))
1164                         send_CSQC_teamnagger();
1165
1166         CSQCMODEL_AUTOINIT(this);
1167
1168         CS(this).model_randomizer = random();
1169
1170         if (IS_REAL_CLIENT(this))
1171                 sv_notice_join(this);
1172
1173         this.move_qcphysics = autocvar_sv_qcphysics;
1174
1175         // update physics stats (players can spawn before physics runs)
1176         Physics_UpdateStats(this);
1177
1178         IL_EACH(g_initforplayer, it.init_for_player, {
1179                 it.init_for_player(it, this);
1180         });
1181
1182         Handicap_Initialize(this);
1183
1184         MUTATOR_CALLHOOK(ClientConnect, this);
1185
1186         if (IS_REAL_CLIENT(this))
1187         {
1188                 if (!autocvar_g_campaign && !IS_PLAYER(this))
1189                 {
1190                         CS(this).motd_actived_time = -1;
1191                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_MOTD, getwelcomemessage(this));
1192                 }
1193         }
1194 }
1195 /*
1196 =============
1197 ClientDisconnect
1198
1199 Called when a client disconnects from the server
1200 =============
1201 */
1202 .entity chatbubbleentity;
1203 void player_powerups_remove_all(entity this);
1204
1205 void ClientDisconnect(entity this)
1206 {
1207         assert(IS_CLIENT(this), return);
1208
1209         PlayerStats_GameReport_FinalizePlayer(this);
1210         if (this.vehicle) vehicles_exit(this.vehicle, VHEF_RELEASE);
1211         if (CS(this).active_minigame) part_minigame(this);
1212         if (IS_PLAYER(this)) Send_Effect(EFFECT_SPAWN_NEUTRAL, this.origin, '0 0 0', 1);
1213
1214         if (autocvar_sv_eventlog)
1215                 GameLogEcho(strcat(":part:", ftos(this.playerid)));
1216
1217         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_DISCONNECT, this.netname);
1218
1219         if(IS_SPEC(this))
1220                 SetSpectatee(this, NULL);
1221
1222         MUTATOR_CALLHOOK(ClientDisconnect, this);
1223
1224         strfree(CS(this).netname_previous); // needs to be before the CS entity is removed!
1225         strfree(CS_CVAR(this).weaponorder_byimpulse);
1226         ClientState_detach(this);
1227
1228         Portal_ClearAll(this);
1229
1230         Unfreeze(this, false);
1231
1232         RemoveGrapplingHooks(this);
1233
1234         // Here, everything has been done that requires this player to be a client.
1235
1236         this.flags &= ~FL_CLIENT;
1237
1238         if (this.chatbubbleentity) delete(this.chatbubbleentity);
1239         if (this.killindicator) delete(this.killindicator);
1240
1241         IL_EACH(g_counters, it.realowner == this,
1242         {
1243                 delete(it);
1244         });
1245
1246         WaypointSprite_PlayerGone(this);
1247
1248         bot_relinkplayerlist();
1249
1250         strfree(this.clientstatus);
1251         if (this.personal) delete(this.personal);
1252
1253         this.playerid = 0;
1254         ReadyCount();
1255         if (vote_called && IS_REAL_CLIENT(this)) VoteCount(false);
1256
1257         player_powerups_remove_all(this); // stop powerup sound
1258
1259         ONREMOVE(this);
1260 }
1261
1262 void ChatBubbleThink(entity this)
1263 {
1264         this.nextthink = time;
1265         if ((this.owner.alpha < 0) || this.owner.chatbubbleentity != this)
1266         {
1267                 if(this.owner) // but why can that ever be NULL?
1268                         this.owner.chatbubbleentity = NULL;
1269                 delete(this);
1270                 return;
1271         }
1272
1273         this.mdl = "";
1274
1275         if ( !IS_DEAD(this.owner) && IS_PLAYER(this.owner) )
1276         {
1277                 if ( CS(this.owner).active_minigame && PHYS_INPUT_BUTTON_MINIGAME(this.owner) )
1278                         this.mdl = "models/sprites/minigame_busy.iqm";
1279                 else if (PHYS_INPUT_BUTTON_CHAT(this.owner))
1280                         this.mdl = "models/misc/chatbubble.spr";
1281         }
1282
1283         if ( this.model != this.mdl )
1284                 _setmodel(this, this.mdl);
1285
1286 }
1287
1288 void UpdateChatBubble(entity this)
1289 {
1290         if (this.alpha < 0)
1291                 return;
1292         // spawn a chatbubble entity if needed
1293         if (!this.chatbubbleentity)
1294         {
1295                 this.chatbubbleentity = new(chatbubbleentity);
1296                 this.chatbubbleentity.owner = this;
1297                 this.chatbubbleentity.exteriormodeltoclient = this;
1298                 setthink(this.chatbubbleentity, ChatBubbleThink);
1299                 this.chatbubbleentity.nextthink = time;
1300                 setmodel(this.chatbubbleentity, MDL_CHAT); // precision set below
1301                 //setorigin(this.chatbubbleentity, this.origin + '0 0 15' + this.maxs_z * '0 0 1');
1302                 setorigin(this.chatbubbleentity, '0 0 15' + this.maxs_z * '0 0 1');
1303                 setattachment(this.chatbubbleentity, this, "");  // sticks to moving player better, also conserves bandwidth
1304                 this.chatbubbleentity.mdl = this.chatbubbleentity.model;
1305                 //this.chatbubbleentity.model = "";
1306                 this.chatbubbleentity.effects = EF_LOWPRECISION;
1307         }
1308 }
1309
1310 void calculate_player_respawn_time(entity this)
1311 {
1312         if(MUTATOR_CALLHOOK(CalculateRespawnTime, this))
1313                 return;
1314
1315         float gametype_setting_tmp;
1316         float sdelay_max = GAMETYPE_DEFAULTED_SETTING(respawn_delay_max);
1317         float sdelay_small = GAMETYPE_DEFAULTED_SETTING(respawn_delay_small);
1318         float sdelay_large = GAMETYPE_DEFAULTED_SETTING(respawn_delay_large);
1319         float sdelay_small_count = GAMETYPE_DEFAULTED_SETTING(respawn_delay_small_count);
1320         float sdelay_large_count = GAMETYPE_DEFAULTED_SETTING(respawn_delay_large_count);
1321         float waves = GAMETYPE_DEFAULTED_SETTING(respawn_waves);
1322
1323         float pcount = 1;  // Include myself whether or not team is already set right and I'm a "player".
1324         if (teamplay)
1325         {
1326                 FOREACH_CLIENT(IS_PLAYER(it) && it != this, {
1327                         if(it.team == this.team)
1328                                 ++pcount;
1329                 });
1330                 if (sdelay_small_count == 0)
1331                         sdelay_small_count = 1;
1332                 if (sdelay_large_count == 0)
1333                         sdelay_large_count = 1;
1334         }
1335         else
1336         {
1337                 FOREACH_CLIENT(IS_PLAYER(it) && it != this, {
1338                         ++pcount;
1339                 });
1340                 if (sdelay_small_count == 0)
1341                 {
1342                         if (IS_INDEPENDENT_PLAYER(this))
1343                         {
1344                                 // Players play independently. No point in requiring enemies.
1345                                 sdelay_small_count = 1;
1346                         }
1347                         else
1348                         {
1349                                 // Players play AGAINST each other. Enemies required.
1350                                 sdelay_small_count = 2;
1351                         }
1352                 }
1353                 if (sdelay_large_count == 0)
1354                 {
1355                         if (IS_INDEPENDENT_PLAYER(this))
1356                         {
1357                                 // Players play independently. No point in requiring enemies.
1358                                 sdelay_large_count = 1;
1359                         }
1360                         else
1361                         {
1362                                 // Players play AGAINST each other. Enemies required.
1363                                 sdelay_large_count = 2;
1364                         }
1365                 }
1366         }
1367
1368         float sdelay;
1369
1370         if (pcount <= sdelay_small_count)
1371                 sdelay = sdelay_small;
1372         else if (pcount >= sdelay_large_count)
1373                 sdelay = sdelay_large;
1374         else  // NOTE: this case implies sdelay_large_count > sdelay_small_count.
1375                 sdelay = sdelay_small + (sdelay_large - sdelay_small) * (pcount - sdelay_small_count) / (sdelay_large_count - sdelay_small_count);
1376
1377         if(waves)
1378                 this.respawn_time = ceil((time + sdelay) / waves) * waves;
1379         else
1380                 this.respawn_time = time + sdelay;
1381
1382         if(sdelay < sdelay_max)
1383                 this.respawn_time_max = time + sdelay_max;
1384         else
1385                 this.respawn_time_max = this.respawn_time;
1386
1387         if((sdelay + waves >= 5.0) && (this.respawn_time - time > 1.75))
1388                 this.respawn_countdown = 10; // first number to count down from is 10
1389         else
1390                 this.respawn_countdown = -1; // do not count down
1391
1392         if(autocvar_g_forced_respawn)
1393                 this.respawn_flags = this.respawn_flags | RESPAWN_FORCE;
1394 }
1395
1396 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1397 // added to the model skins
1398 /*void UpdateColorModHack()
1399 {
1400         float c;
1401         c = this.clientcolors & 15;
1402         // LordHavoc: only bothering to support white, green, red, yellow, blue
1403              if (!teamplay) this.colormod = '0 0 0';
1404         else if (c ==  0) this.colormod = '1.00 1.00 1.00';
1405         else if (c ==  3) this.colormod = '0.10 1.73 0.10';
1406         else if (c ==  4) this.colormod = '1.73 0.10 0.10';
1407         else if (c == 12) this.colormod = '1.22 1.22 0.10';
1408         else if (c == 13) this.colormod = '0.10 0.10 1.73';
1409         else this.colormod = '1 1 1';
1410 }*/
1411
1412 void respawn(entity this)
1413 {
1414         bool damagedbycontents_prev = this.damagedbycontents;
1415         if(this.alpha >= 0)
1416         {
1417                 if(autocvar_g_respawn_ghosts)
1418                 {
1419                         this.solid = SOLID_NOT;
1420                         this.takedamage = DAMAGE_NO;
1421                         this.damagedbycontents = false;
1422                         set_movetype(this, MOVETYPE_FLY);
1423                         this.velocity = '0 0 1' * autocvar_g_respawn_ghosts_speed;
1424                         this.avelocity = randomvec() * autocvar_g_respawn_ghosts_speed * 3 - randomvec() * autocvar_g_respawn_ghosts_speed * 3;
1425                         this.effects |= CSQCMODEL_EF_RESPAWNGHOST;
1426                         this.alpha = min(this.alpha, autocvar_g_respawn_ghosts_alpha);
1427                         Send_Effect(EFFECT_RESPAWN_GHOST, this.origin, '0 0 0', 1);
1428                         if(autocvar_g_respawn_ghosts_time > 0)
1429                                 SUB_SetFade(this, time + autocvar_g_respawn_ghosts_time, autocvar_g_respawn_ghosts_fadetime);
1430                 }
1431                 else
1432                         SUB_SetFade (this, time, 1); // fade out the corpse immediately
1433         }
1434
1435         CopyBody(this, 1);
1436         this.damagedbycontents = damagedbycontents_prev;
1437
1438         this.effects |= EF_NODRAW; // prevent another CopyBody
1439         PutClientInServer(this);
1440 }
1441
1442 void play_countdown(entity this, float finished, Sound samp)
1443 {
1444         TC(Sound, samp);
1445         if(IS_REAL_CLIENT(this))
1446                 if(floor(finished - time - frametime) != floor(finished - time))
1447                         if(finished - time < 6)
1448                                 sound (this, CH_INFO, samp, VOL_BASE, ATTEN_NORM);
1449 }
1450
1451 void player_powerups_remove_all(entity this)
1452 {
1453         if (this.items & IT_SUPERWEAPON)
1454         {
1455                 // don't play the poweroff sound when the game restarts or the player disconnects
1456                 if (time > game_starttime + 1 && IS_CLIENT(this))
1457                         sound(this, CH_INFO, SND_POWEROFF, VOL_BASE, ATTEN_NORM);
1458                 stopsound(this, CH_TRIGGER_SINGLE); // get rid of the pickup sound
1459                 this.items -= (this.items & IT_SUPERWEAPON);
1460         }
1461 }
1462
1463 void player_powerups(entity this)
1464 {
1465         if((this.items & IT_USING_JETPACK) && !IS_DEAD(this) && !game_stopped)
1466                 this.modelflags |= MF_ROCKET;
1467         else
1468                 this.modelflags &= ~MF_ROCKET;
1469
1470         this.effects &= ~EF_NODEPTHTEST;
1471
1472         if (IS_DEAD(this))
1473                 player_powerups_remove_all(this);
1474
1475         if((this.alpha < 0 || IS_DEAD(this)) && !this.vehicle) // don't apply the flags if the player is gibbed
1476                 return;
1477
1478         // add a way to see what the items were BEFORE all of these checks for the mutator hook
1479         int items_prev = this.items;
1480
1481         if (!MUTATOR_IS_ENABLED(mutator_instagib))
1482         {
1483                 // NOTE: superweapons are a special case and as such are handled here instead of the status effects system
1484                 if (this.items & IT_SUPERWEAPON)
1485                 {
1486                         if (!(STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS))
1487                         {
1488                                 StatusEffects_remove(STATUSEFFECT_Superweapons, this, STATUSEFFECT_REMOVE_NORMAL);
1489                                 this.items = this.items - (this.items & IT_SUPERWEAPON);
1490                                 //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_LOST, this.netname);
1491                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_LOST);
1492                         }
1493                         else if (this.items & IT_UNLIMITED_SUPERWEAPONS)
1494                         {
1495                                 // don't let them run out
1496                         }
1497                         else
1498                         {
1499                                 play_countdown(this, StatusEffects_gettime(STATUSEFFECT_Superweapons, this), SND_POWEROFF);
1500                                 if (time > StatusEffects_gettime(STATUSEFFECT_Superweapons, this))
1501                                 {
1502                                         this.items = this.items - (this.items & IT_SUPERWEAPON);
1503                                         STAT(WEAPONS, this) &= ~WEPSET_SUPERWEAPONS;
1504                                         //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_BROKEN, this.netname);
1505                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_BROKEN);
1506                                 }
1507                         }
1508                 }
1509                 else if(STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS)
1510                 {
1511                         if (time < StatusEffects_gettime(STATUSEFFECT_Superweapons, this) || (this.items & IT_UNLIMITED_SUPERWEAPONS))
1512                         {
1513                                 this.items = this.items | IT_SUPERWEAPON;
1514                                 if(!(this.items & IT_UNLIMITED_SUPERWEAPONS))
1515                                 {
1516                                         if(!g_cts)
1517                                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_PICKUP, this.netname);
1518                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_PICKUP);
1519                                 }
1520                         }
1521                         else
1522                         {
1523                                 if(StatusEffects_active(STATUSEFFECT_Superweapons, this))
1524                                         StatusEffects_remove(STATUSEFFECT_Superweapons, this, STATUSEFFECT_REMOVE_TIMEOUT);
1525                                 STAT(WEAPONS, this) &= ~WEPSET_SUPERWEAPONS;
1526                         }
1527                 }
1528                 else if(StatusEffects_active(STATUSEFFECT_Superweapons, this)) // cheaper to check than to update each frame!
1529                 {
1530                         StatusEffects_remove(STATUSEFFECT_Superweapons, this, STATUSEFFECT_REMOVE_CLEAR);
1531                 }
1532         }
1533
1534         if(autocvar_g_nodepthtestplayers)
1535                 this.effects = this.effects | EF_NODEPTHTEST;
1536
1537         if(autocvar_g_fullbrightplayers)
1538                 this.effects = this.effects | EF_FULLBRIGHT;
1539
1540         MUTATOR_CALLHOOK(PlayerPowerups, this, items_prev);
1541 }
1542
1543 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1544 {
1545         if(current > stable)
1546                 return current;
1547         else if(current > stable - 0.25) // when close enough, "snap"
1548                 return stable;
1549         else
1550                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1551 }
1552
1553 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1554 {
1555         if(current < stable)
1556                 return current;
1557         else if(current < stable + 0.25) // when close enough, "snap"
1558                 return stable;
1559         else
1560                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1561 }
1562
1563 void RotRegen(entity this, Resource res, float limit_mod,
1564         float regenstable, float regenfactor, float regenlinear, float regenframetime,
1565         float rotstable, float rotfactor, float rotlinear, float rotframetime)
1566 {
1567         float old = GetResource(this, res);
1568         float current = old;
1569         if(current > rotstable)
1570         {
1571                 if(rotframetime > 0)
1572                 {
1573                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1574                         current = max(rotstable, current - rotlinear * rotframetime);
1575                 }
1576         }
1577         else if(current < regenstable)
1578         {
1579                 if(regenframetime > 0)
1580                 {
1581                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1582                         current = min(regenstable, current + regenlinear * regenframetime);
1583                 }
1584         }
1585
1586         float limit = GetResourceLimit(this, res) * limit_mod;
1587         if(current > limit)
1588                 current = limit;
1589
1590         if (current != old)
1591                 SetResource(this, res, current);
1592 }
1593
1594 void player_regen(entity this)
1595 {
1596         float max_mod, regen_mod, rot_mod, limit_mod;
1597         max_mod = regen_mod = rot_mod = limit_mod = 1;
1598
1599         float regen_health = autocvar_g_balance_health_regen;
1600         float regen_health_linear = autocvar_g_balance_health_regenlinear;
1601         float regen_health_rot = autocvar_g_balance_health_rot;
1602         float regen_health_rotlinear = autocvar_g_balance_health_rotlinear;
1603         float regen_health_stable = autocvar_g_balance_health_regenstable;
1604         float regen_health_rotstable = autocvar_g_balance_health_rotstable;
1605         bool mutator_returnvalue = MUTATOR_CALLHOOK(PlayerRegen, this, max_mod, regen_mod, rot_mod, limit_mod, regen_health, regen_health_linear, regen_health_rot,
1606                 regen_health_rotlinear, regen_health_stable, regen_health_rotstable);
1607         max_mod = M_ARGV(1, float);
1608         regen_mod = M_ARGV(2, float);
1609         rot_mod = M_ARGV(3, float);
1610         limit_mod = M_ARGV(4, float);
1611         regen_health = M_ARGV(5, float);
1612         regen_health_linear = M_ARGV(6, float);
1613         regen_health_rot = M_ARGV(7, float);
1614         regen_health_rotlinear = M_ARGV(8, float);
1615         regen_health_stable = M_ARGV(9, float);
1616         regen_health_rotstable = M_ARGV(10, float);
1617
1618         float rotstable, regenstable, rotframetime, regenframetime;
1619
1620         if(!mutator_returnvalue)
1621         if(!STAT(FROZEN, this))
1622         {
1623                 regenstable = autocvar_g_balance_armor_regenstable;
1624                 rotstable = autocvar_g_balance_armor_rotstable;
1625                 regenframetime = (time > this.pauseregen_finished) ? (regen_mod * frametime) : 0;
1626                 rotframetime = (time > this.pauserotarmor_finished) ? (rot_mod * frametime) : 0;
1627                 RotRegen(this, RES_ARMOR, limit_mod,
1628                         regenstable, autocvar_g_balance_armor_regen, autocvar_g_balance_armor_regenlinear, regenframetime,
1629                         rotstable, autocvar_g_balance_armor_rot, autocvar_g_balance_armor_rotlinear, rotframetime);
1630
1631                 // NOTE: max_mod is only applied to health
1632                 regenstable = regen_health_stable * max_mod;
1633                 rotstable = regen_health_rotstable * max_mod;
1634                 regenframetime = (time > this.pauseregen_finished) ? (regen_mod * frametime) : 0;
1635                 rotframetime = (time > this.pauserothealth_finished) ? (rot_mod * frametime) : 0;
1636                 RotRegen(this, RES_HEALTH, limit_mod,
1637                         regenstable, regen_health, regen_health_linear, regenframetime,
1638                         rotstable, regen_health_rot, regen_health_rotlinear, rotframetime);
1639         }
1640
1641         // if player rotted to death...  die!
1642         // check this outside above checks, as player may still be able to rot to death
1643         if(GetResource(this, RES_HEALTH) < 1)
1644         {
1645                 if(this.vehicle)
1646                         vehicles_exit(this.vehicle, VHEF_RELEASE);
1647                 if(this.event_damage)
1648                         this.event_damage(this, this, this, 1, DEATH_ROT.m_id, DMG_NOWEP, this.origin, '0 0 0');
1649         }
1650
1651         if (!(this.items & IT_UNLIMITED_AMMO))
1652         {
1653                 regenstable = autocvar_g_balance_fuel_regenstable;
1654                 rotstable = autocvar_g_balance_fuel_rotstable;
1655                 regenframetime = ((time > this.pauseregen_finished) && (this.items & ITEM_JetpackRegen.m_itemid)) ? frametime : 0;
1656                 rotframetime = (time > this.pauserotfuel_finished) ? frametime : 0;
1657                 RotRegen(this, RES_FUEL, 1,
1658                         regenstable, autocvar_g_balance_fuel_regen, autocvar_g_balance_fuel_regenlinear, regenframetime,
1659                         rotstable, autocvar_g_balance_fuel_rot, autocvar_g_balance_fuel_rotlinear, rotframetime);
1660         }
1661 }
1662
1663 bool zoomstate_set;
1664 void SetZoomState(entity this, float newzoom)
1665 {
1666         if(newzoom != CS(this).zoomstate)
1667         {
1668                 CS(this).zoomstate = newzoom;
1669                 ClientData_Touch(this);
1670         }
1671         zoomstate_set = true;
1672 }
1673
1674 void GetPressedKeys(entity this)
1675 {
1676         MUTATOR_CALLHOOK(GetPressedKeys, this);
1677         if (game_stopped)
1678         {
1679                 CS(this).pressedkeys = 0;
1680                 STAT(PRESSED_KEYS, this) = 0;
1681                 return;
1682         }
1683
1684         // NOTE: GetPressedKeys and PM_dodging_GetPressedKeys use similar code
1685         int keys = STAT(PRESSED_KEYS, this);
1686         keys = BITSET(keys, KEY_FORWARD,        CS(this).movement.x > 0);
1687         keys = BITSET(keys, KEY_BACKWARD,       CS(this).movement.x < 0);
1688         keys = BITSET(keys, KEY_RIGHT,          CS(this).movement.y > 0);
1689         keys = BITSET(keys, KEY_LEFT,           CS(this).movement.y < 0);
1690
1691         keys = BITSET(keys, KEY_JUMP,           PHYS_INPUT_BUTTON_JUMP(this));
1692         keys = BITSET(keys, KEY_CROUCH,         IS_DUCKED(this)); // workaround: player can't un-crouch until their path is clear, so we keep the button held here
1693         keys = BITSET(keys, KEY_ATCK,           PHYS_INPUT_BUTTON_ATCK(this));
1694         keys = BITSET(keys, KEY_ATCK2,          PHYS_INPUT_BUTTON_ATCK2(this));
1695         CS(this).pressedkeys = keys; // store for other users
1696
1697         STAT(PRESSED_KEYS, this) = keys;
1698 }
1699
1700 /*
1701 ======================
1702 spectate mode routines
1703 ======================
1704 */
1705
1706 void SpectateCopy(entity this, entity spectatee)
1707 {
1708         TC(Client, this); TC(Client, spectatee);
1709
1710         MUTATOR_CALLHOOK(SpectateCopy, spectatee, this);
1711         PS(this) = PS(spectatee);
1712         this.armortype = spectatee.armortype;
1713         SetResourceExplicit(this, RES_ARMOR, GetResource(spectatee, RES_ARMOR));
1714         SetResourceExplicit(this, RES_CELLS, GetResource(spectatee, RES_CELLS));
1715         SetResourceExplicit(this, RES_PLASMA, GetResource(spectatee, RES_PLASMA));
1716         SetResourceExplicit(this, RES_SHELLS, GetResource(spectatee, RES_SHELLS));
1717         SetResourceExplicit(this, RES_BULLETS, GetResource(spectatee, RES_BULLETS));
1718         SetResourceExplicit(this, RES_ROCKETS, GetResource(spectatee, RES_ROCKETS));
1719         SetResourceExplicit(this, RES_FUEL, GetResource(spectatee, RES_FUEL));
1720         this.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
1721         SetResourceExplicit(this, RES_HEALTH, GetResource(spectatee, RES_HEALTH));
1722         CS(this).impulse = 0;
1723         this.disableclientprediction = 1; // no need to run prediction on a spectator
1724         this.items = spectatee.items;
1725         STAT(LAST_PICKUP, this) = STAT(LAST_PICKUP, spectatee);
1726         STAT(HIT_TIME, this) = STAT(HIT_TIME, spectatee);
1727         STAT(AIR_FINISHED, this) = STAT(AIR_FINISHED, spectatee);
1728         STAT(PRESSED_KEYS, this) = STAT(PRESSED_KEYS, spectatee);
1729         STAT(WEAPONS, this) = STAT(WEAPONS, spectatee);
1730         this.punchangle = spectatee.punchangle;
1731         this.view_ofs = spectatee.view_ofs;
1732         this.velocity = spectatee.velocity;
1733         this.dmg_take = spectatee.dmg_take;
1734         this.dmg_save = spectatee.dmg_save;
1735         this.dmg_inflictor = spectatee.dmg_inflictor;
1736         this.v_angle = spectatee.v_angle;
1737         this.angles = spectatee.v_angle;
1738         STAT(FROZEN, this) = STAT(FROZEN, spectatee);
1739         STAT(REVIVE_PROGRESS, this) = STAT(REVIVE_PROGRESS, spectatee);
1740         this.viewloc = spectatee.viewloc;
1741         if(!PHYS_INPUT_BUTTON_USE(this) && STAT(CAMERA_SPECTATOR, this) != 2)
1742                 this.fixangle = true;
1743         setorigin(this, spectatee.origin);
1744         setsize(this, spectatee.mins, spectatee.maxs);
1745         SetZoomState(this, CS(spectatee).zoomstate);
1746
1747     anticheat_spectatecopy(this, spectatee);
1748         STAT(HUD, this) = STAT(HUD, spectatee);
1749         if(spectatee.vehicle)
1750     {
1751         this.angles = spectatee.v_angle;
1752
1753         //this.fixangle = false;
1754         //this.velocity = spectatee.vehicle.velocity;
1755         this.vehicle_health = spectatee.vehicle_health;
1756         this.vehicle_shield = spectatee.vehicle_shield;
1757         this.vehicle_energy = spectatee.vehicle_energy;
1758         this.vehicle_ammo1 = spectatee.vehicle_ammo1;
1759         this.vehicle_ammo2 = spectatee.vehicle_ammo2;
1760         this.vehicle_reload1 = spectatee.vehicle_reload1;
1761         this.vehicle_reload2 = spectatee.vehicle_reload2;
1762
1763         //msg_entity = this;
1764
1765        // WriteByte (MSG_ONE, SVC_SETVIEWANGLES);
1766             //WriteAngle(MSG_ONE,  spectatee.v_angle.x);
1767            // WriteAngle(MSG_ONE,  spectatee.v_angle.y);
1768            // WriteAngle(MSG_ONE,  spectatee.v_angle.z);
1769
1770         //WriteByte (MSG_ONE, SVC_SETVIEW);
1771         //    WriteEntity(MSG_ONE, this);
1772         //makevectors(spectatee.v_angle);
1773         //setorigin(this, spectatee.origin - v_forward * 400 + v_up * 300);*/
1774     }
1775 }
1776
1777 bool SpectateUpdate(entity this)
1778 {
1779         if(!this.enemy)
1780                 return false;
1781
1782         if(!IS_PLAYER(this.enemy) || this == this.enemy)
1783         {
1784                 SetSpectatee(this, NULL);
1785                 return false;
1786         }
1787
1788         SpectateCopy(this, this.enemy);
1789
1790         return true;
1791 }
1792
1793 bool SpectateSet(entity this)
1794 {
1795         if(!IS_PLAYER(this.enemy))
1796                 return false;
1797
1798         ClientData_Touch(this.enemy);
1799
1800         msg_entity = this;
1801         WriteByte(MSG_ONE, SVC_SETVIEW);
1802         WriteEntity(MSG_ONE, this.enemy);
1803         set_movetype(this, MOVETYPE_NONE);
1804         accuracy_resend(this);
1805
1806         if(!SpectateUpdate(this))
1807                 PutObserverInServer(this, false, true);
1808
1809         return true;
1810 }
1811
1812 void SetSpectatee_status(entity this, int spectatee_num)
1813 {
1814         int oldspectatee_status = CS(this).spectatee_status;
1815         CS(this).spectatee_status = spectatee_num;
1816
1817         if (CS(this).spectatee_status != oldspectatee_status)
1818         {
1819                 if (STAT(PRESSED_KEYS, this))
1820                 {
1821                         CS(this).pressedkeys = 0;
1822                         STAT(PRESSED_KEYS, this) = 0;
1823                 }
1824                 ClientData_Touch(this);
1825                 if (g_race || g_cts) race_InitSpectator();
1826         }
1827 }
1828
1829 void SetSpectatee(entity this, entity spectatee)
1830 {
1831         if(IS_BOT_CLIENT(this))
1832                 return; // bots abuse .enemy, this code is useless to them
1833
1834         entity old_spectatee = this.enemy;
1835
1836         this.enemy = spectatee;
1837
1838         // WEAPONTODO
1839         // these are required to fix the spectator bug with arc
1840         if(old_spectatee)
1841         {
1842                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1843                 {
1844                         .entity weaponentity = weaponentities[slot];
1845                         if(old_spectatee.(weaponentity).arc_beam)
1846                                 old_spectatee.(weaponentity).arc_beam.SendFlags |= ARC_SF_SETTINGS;
1847                 }
1848         }
1849         if(spectatee)
1850         {
1851                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1852                 {
1853                         .entity weaponentity = weaponentities[slot];
1854                         if(spectatee.(weaponentity).arc_beam)
1855                                 spectatee.(weaponentity).arc_beam.SendFlags |= ARC_SF_SETTINGS;
1856                 }
1857         }
1858
1859         if (spectatee)
1860                 SetSpectatee_status(this, etof(spectatee));
1861
1862         // needed to update spectator list
1863         if(old_spectatee) { ClientData_Touch(old_spectatee); }
1864 }
1865
1866 bool Spectate(entity this, entity pl)
1867 {
1868         if(MUTATOR_CALLHOOK(SpectateSet, this, pl))
1869                 return false;
1870         pl = M_ARGV(1, entity);
1871
1872         SetSpectatee(this, pl);
1873         return SpectateSet(this);
1874 }
1875
1876 bool SpectateNext(entity this)
1877 {
1878         entity ent = find(this.enemy, classname, STR_PLAYER);
1879
1880         if (MUTATOR_CALLHOOK(SpectateNext, this, ent))
1881                 ent = M_ARGV(1, entity);
1882         else if (!ent)
1883                 ent = find(ent, classname, STR_PLAYER);
1884
1885         if(ent) { SetSpectatee(this, ent); }
1886
1887         return SpectateSet(this);
1888 }
1889
1890 bool SpectatePrev(entity this)
1891 {
1892         // NOTE: chain order is from the highest to the lower entnum (unlike find)
1893         entity ent = findchain(classname, STR_PLAYER);
1894         if (!ent) // no player
1895                 return false;
1896
1897         entity first = ent;
1898         // skip players until current spectated player
1899         if(this.enemy)
1900         while(ent && ent != this.enemy)
1901                 ent = ent.chain;
1902
1903         switch (MUTATOR_CALLHOOK(SpectatePrev, this, ent, first))
1904         {
1905                 case MUT_SPECPREV_FOUND:
1906                         ent = M_ARGV(1, entity);
1907                         break;
1908                 case MUT_SPECPREV_RETURN:
1909                         return true;
1910                 case MUT_SPECPREV_CONTINUE:
1911                 default:
1912                 {
1913                         if(ent.chain)
1914                                 ent = ent.chain;
1915                         else
1916                                 ent = first;
1917                         break;
1918                 }
1919         }
1920
1921         SetSpectatee(this, ent);
1922         return SpectateSet(this);
1923 }
1924
1925 /*
1926 =============
1927 ShowRespawnCountdown()
1928
1929 Update a respawn countdown display.
1930 =============
1931 */
1932 void ShowRespawnCountdown(entity this)
1933 {
1934         float number;
1935         if(!IS_DEAD(this)) // just respawned?
1936                 return;
1937         else
1938         {
1939                 number = ceil(this.respawn_time - time);
1940                 if(number <= 0)
1941                         return;
1942                 if(number <= this.respawn_countdown)
1943                 {
1944                         this.respawn_countdown = number - 1;
1945                         if(ceil(this.respawn_time - (time + 0.5)) == number) // only say it if it is the same number even in 0.5s; to prevent overlapping sounds
1946                                 { Send_Notification(NOTIF_ONE, this, MSG_ANNCE, Announcer_PickNumber(CNT_RESPAWN, number)); }
1947                 }
1948         }
1949 }
1950
1951 .bool team_selected;
1952 bool ShowTeamSelection(entity this)
1953 {
1954         if (!teamplay || autocvar_g_campaign || autocvar_g_balance_teams || this.team_selected || (CS(this).wasplayer && autocvar_g_changeteam_banned) || Player_HasRealForcedTeam(this))
1955                 return false;
1956         stuffcmd(this, "menu_showteamselect\n");
1957         return true;
1958 }
1959 void Join(entity this)
1960 {
1961         TRANSMUTE(Player, this);
1962
1963         if(!this.team_selected)
1964         if(autocvar_g_campaign || autocvar_g_balance_teams)
1965                 TeamBalance_JoinBestTeam(this);
1966
1967         if(autocvar_g_campaign)
1968                 campaign_bots_may_start = true;
1969
1970         Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_PREVENT_JOIN);
1971
1972         PutClientInServer(this);
1973
1974         if(IS_PLAYER(this))
1975         if(teamplay && this.team != -1)
1976         {
1977         }
1978         else
1979                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_JOIN_PLAY, this.netname);
1980         this.team_selected = false;
1981 }
1982
1983 int GetPlayerLimit()
1984 {
1985         if(g_duel)
1986                 return 2; // TODO: this workaround is needed since the mutator hook from duel can't be activated before the gametype is loaded (e.g. switching modes via gametype vote screen)
1987         int player_limit = autocvar_g_maxplayers;
1988         MUTATOR_CALLHOOK(GetPlayerLimit, player_limit);
1989         player_limit = M_ARGV(0, int);
1990         return player_limit;
1991 }
1992
1993 /**
1994  * Determines whether the player is allowed to join. This depends on cvar
1995  * g_maxplayers, if it isn't used this function always return true, otherwise
1996  * it checks whether the number of currently playing players exceeds g_maxplayers.
1997  * @return int number of free slots for players, 0 if none
1998  */
1999 int nJoinAllowed(entity this, entity ignore)
2000 {
2001         if(!ignore)
2002         // this is called that way when checking if anyone may be able to join (to build qcstatus)
2003         // so report 0 free slots if restricted
2004         {
2005                 if(autocvar_g_forced_team_otherwise == "spectate")
2006                         return 0;
2007                 if(autocvar_g_forced_team_otherwise == "spectator")
2008                         return 0;
2009         }
2010
2011         if(this && (Player_GetForcedTeamIndex(this) == TEAM_FORCE_SPECTATOR))
2012                 return 0; // forced spectators can never join
2013
2014         // TODO simplify this
2015         int totalClients = 0;
2016         int currentlyPlaying = 0;
2017         FOREACH_CLIENT(true, {
2018                 if(it != ignore)
2019                         ++totalClients;
2020                 if(IS_REAL_CLIENT(it) && (IS_PLAYER(it) || INGAME(it)))
2021                         ++currentlyPlaying;
2022         });
2023
2024         int player_limit = GetPlayerLimit();
2025
2026         int free_slots = 0;
2027         if (!player_limit)
2028                 free_slots = maxclients - totalClients;
2029         else if(player_limit > 0 && currentlyPlaying < player_limit)
2030                 free_slots = min(maxclients - totalClients, player_limit - currentlyPlaying);
2031
2032         static float msg_time = 0;
2033         if(this && !INGAME(this) && ignore && !free_slots && time > msg_time)
2034         {
2035                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_JOIN_PREVENT);
2036                 msg_time = time + 0.5;
2037         }
2038
2039         return free_slots;
2040 }
2041
2042 void PrintWelcomeMessage(entity this)
2043 {
2044         if(CS(this).motd_actived_time == 0)
2045         {
2046                 if (autocvar_g_campaign) {
2047                         if ((IS_PLAYER(this) && PHYS_INPUT_BUTTON_INFO(this)) || (!IS_PLAYER(this))) {
2048                                 CS(this).motd_actived_time = time;
2049                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_CAMPAIGN_MESSAGE, Campaign_GetMessage(), Campaign_GetLevelNum());
2050                         }
2051                 } else {
2052                         if (PHYS_INPUT_BUTTON_INFO(this)) {
2053                                 CS(this).motd_actived_time = time;
2054                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_MOTD, getwelcomemessage(this));
2055                         }
2056                 }
2057         }
2058         else if(CS(this).motd_actived_time > 0) // showing MOTD or campaign message
2059         {
2060                 if (autocvar_g_campaign) {
2061                         if (PHYS_INPUT_BUTTON_INFO(this))
2062                                 CS(this).motd_actived_time = time;
2063                         else if ((time - CS(this).motd_actived_time > 2) && IS_PLAYER(this)) { // hide it some seconds after BUTTON_INFO has been released
2064                                 CS(this).motd_actived_time = 0;
2065                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_CAMPAIGN_MESSAGE);
2066                         }
2067                 } else {
2068                         if (PHYS_INPUT_BUTTON_INFO(this))
2069                                 CS(this).motd_actived_time = time;
2070                         else if (time - CS(this).motd_actived_time > 2) { // hide it some seconds after BUTTON_INFO has been released
2071                                 CS(this).motd_actived_time = 0;
2072                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_MOTD);
2073                         }
2074                 }
2075         }
2076         else //if(CS(this).motd_actived_time < 0) // just connected, motd is active
2077         {
2078                 if(PHYS_INPUT_BUTTON_INFO(this)) // BUTTON_INFO hides initial MOTD
2079                         CS(this).motd_actived_time = -2; // wait until BUTTON_INFO gets released
2080                 else if (CS(this).motd_actived_time == -2)
2081                 {
2082                         // instantly hide MOTD
2083                         CS(this).motd_actived_time = 0;
2084                         if (autocvar_g_campaign)
2085                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_CAMPAIGN_MESSAGE);
2086                         else
2087                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_MOTD);
2088                 }
2089                 else if (IS_PLAYER(this) || IS_SPEC(this))
2090                 {
2091                         // FIXME occasionally for some reason MOTD never goes away
2092                         // delay MOTD removal a little bit in the hope it fixes this bug
2093                         if (CS(this).motd_actived_time == -1) // MOTD marked to fade away as soon as client becomes player or spectator
2094                                 CS(this).motd_actived_time = -(5 + floor(random() * 10)); // add small delay
2095                         else //if (CS(this).motd_actived_time < -2)
2096                                 CS(this).motd_actived_time++;
2097                 }
2098         }
2099 }
2100
2101 bool joinAllowed(entity this)
2102 {
2103         if (CS(this).version_mismatch) return false;
2104         if (time < CS(this).jointime + MIN_SPEC_TIME) return false;
2105         if (!nJoinAllowed(this, this)) return false;
2106         if (teamplay && lockteams) return false;
2107         if (MUTATOR_CALLHOOK(ForbidSpawn, this)) return false;
2108         if (ShowTeamSelection(this)) return false;
2109         return true;
2110 }
2111
2112 .string shootfromfixedorigin;
2113 .bool dualwielding_prev;
2114 bool PlayerThink(entity this)
2115 {
2116         if (game_stopped || intermission_running) {
2117                 this.modelflags &= ~MF_ROCKET;
2118                 if(intermission_running)
2119                         IntermissionThink(this);
2120                 return false;
2121         }
2122
2123         if (timeout_status == TIMEOUT_ACTIVE) {
2124                 // don't allow the player to turn around while game is paused
2125                 // FIXME turn this into CSQC stuff
2126                 this.v_angle = this.lastV_angle;
2127                 this.angles = this.lastV_angle;
2128                 this.fixangle = true;
2129         }
2130
2131         if (frametime) player_powerups(this);
2132
2133         if (IS_DEAD(this)) {
2134                 if (this.personal && g_race_qualifying) {
2135                         if (time > this.respawn_time) {
2136                                 STAT(RESPAWN_TIME, this) = this.respawn_time = time + 1; // only retry once a second
2137                                 respawn(this);
2138                                 CS(this).impulse = CHIMPULSE_SPEEDRUN.impulse;
2139                         }
2140                 } else {
2141                         if (frametime) player_anim(this);
2142
2143                         if (this.respawn_flags & RESPAWN_DENY)
2144                         {
2145                                 STAT(RESPAWN_TIME, this) = 0;
2146                                 return false;
2147                         }
2148
2149                         bool button_pressed = (PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this) || PHYS_INPUT_BUTTON_ATCK2(this) || PHYS_INPUT_BUTTON_HOOK(this) || PHYS_INPUT_BUTTON_USE(this));
2150
2151                         switch(this.deadflag)
2152                         {
2153                                 case DEAD_DYING:
2154                                 {
2155                                         if ((this.respawn_flags & RESPAWN_FORCE) && !(this.respawn_time < this.respawn_time_max))
2156                                                 this.deadflag = DEAD_RESPAWNING;
2157                                         else if (!button_pressed || (time >= this.respawn_time_max && (this.respawn_flags & RESPAWN_FORCE)))
2158                                                 this.deadflag = DEAD_DEAD;
2159                                         break;
2160                                 }
2161                                 case DEAD_DEAD:
2162                                 {
2163                                         if (button_pressed)
2164                                                 this.deadflag = DEAD_RESPAWNABLE;
2165                                         else if (time >= this.respawn_time_max && (this.respawn_flags & RESPAWN_FORCE))
2166                                                 this.deadflag = DEAD_RESPAWNING;
2167                                         break;
2168                                 }
2169                                 case DEAD_RESPAWNABLE:
2170                                 {
2171                                         if (!button_pressed || (this.respawn_flags & RESPAWN_FORCE))
2172                                                 this.deadflag = DEAD_RESPAWNING;
2173                                         break;
2174                                 }
2175                                 case DEAD_RESPAWNING:
2176                                 {
2177                                         if (time > this.respawn_time)
2178                                         {
2179                                                 this.respawn_time = time + 1; // only retry once a second
2180                                                 this.respawn_time_max = this.respawn_time;
2181                                                 respawn(this);
2182                                         }
2183                                         break;
2184                                 }
2185                         }
2186
2187                         ShowRespawnCountdown(this);
2188
2189                         if (this.respawn_flags & RESPAWN_SILENT)
2190                                 STAT(RESPAWN_TIME, this) = 0;
2191                         else if ((this.respawn_flags & RESPAWN_FORCE) && this.respawn_time < this.respawn_time_max)
2192                         {
2193                                 if (time < this.respawn_time)
2194                                         STAT(RESPAWN_TIME, this) = this.respawn_time;
2195                                 else if (this.deadflag != DEAD_RESPAWNING)
2196                                         STAT(RESPAWN_TIME, this) = -this.respawn_time_max;
2197                         }
2198                         else
2199                                 STAT(RESPAWN_TIME, this) = this.respawn_time;
2200                 }
2201
2202                 // if respawning, invert stat_respawn_time to indicate this, the client translates it
2203                 if (this.deadflag == DEAD_RESPAWNING && STAT(RESPAWN_TIME, this) > 0)
2204                         STAT(RESPAWN_TIME, this) *= -1;
2205
2206                 return false;
2207         }
2208
2209         FixPlayermodel(this);
2210
2211         if (this.shootfromfixedorigin != autocvar_g_shootfromfixedorigin) {
2212                 this.shootfromfixedorigin = autocvar_g_shootfromfixedorigin;
2213                 stuffcmd(this, sprintf("\ncl_shootfromfixedorigin \"%s\"\n", autocvar_g_shootfromfixedorigin));
2214         }
2215
2216         // reset gun alignment when dual wielding status changes
2217         // to ensure guns are always aligned right and left
2218         bool dualwielding = W_DualWielding(this);
2219         if(this.dualwielding_prev != dualwielding)
2220         {
2221                 W_ResetGunAlign(this, CS_CVAR(this).cvar_cl_gunalign);
2222                 this.dualwielding_prev = dualwielding;
2223         }
2224
2225         // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2226         //if(frametime)
2227         {
2228                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2229                 {
2230                         .entity weaponentity = weaponentities[slot];
2231                         if(WEP_CVAR(vortex, charge_always))
2232                                 W_Vortex_Charge(this, weaponentity, frametime);
2233                         W_WeaponFrame(this, weaponentity);
2234                 }
2235         }
2236
2237         if (frametime)
2238         {
2239                 // WEAPONTODO: Add a weapon request for this
2240                 // rot vortex charge to the charge limit
2241                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2242                 {
2243                         .entity weaponentity = weaponentities[slot];
2244                         if (WEP_CVAR(vortex, charge_rot_rate) && this.(weaponentity).vortex_charge > WEP_CVAR(vortex, charge_limit) && this.(weaponentity).vortex_charge_rottime < time)
2245                                 this.(weaponentity).vortex_charge = bound(WEP_CVAR(vortex, charge_limit), this.(weaponentity).vortex_charge - WEP_CVAR(vortex, charge_rot_rate) * frametime / W_TICSPERFRAME, 1);
2246                 }
2247
2248                 player_regen(this);
2249                 player_anim(this);
2250                 this.dmg_team = max(0, this.dmg_team - autocvar_g_teamdamage_resetspeed * frametime);
2251         }
2252
2253         monsters_setstatus(this);
2254
2255         return true;
2256 }
2257
2258 .bool would_spectate;
2259 // merged SpectatorThink and ObserverThink (old names are here so you can grep for them)
2260 void ObserverOrSpectatorThink(entity this)
2261 {
2262         bool is_spec = IS_SPEC(this);
2263         if ( CS(this).impulse )
2264         {
2265                 int r = MinigameImpulse(this, CS(this).impulse);
2266                 if (!is_spec || r)
2267                         CS(this).impulse = 0;
2268
2269                 if (is_spec && CS(this).impulse == IMP_weapon_drop.impulse)
2270                 {
2271                         STAT(CAMERA_SPECTATOR, this) = (STAT(CAMERA_SPECTATOR, this) + 1) % 3;
2272                         CS(this).impulse = 0;
2273                         return;
2274                 }
2275         }
2276
2277         if (this.flags & FL_JUMPRELEASED) {
2278                 if (PHYS_INPUT_BUTTON_JUMP(this) && (joinAllowed(this) || time < CS(this).jointime + MIN_SPEC_TIME)) {
2279                         this.flags &= ~FL_JUMPRELEASED;
2280                         this.flags |= FL_SPAWNING;
2281                 } else if((is_spec && (PHYS_INPUT_BUTTON_ATCK(this) || CS(this).impulse == 10 || CS(this).impulse == 15 || CS(this).impulse == 18 || (CS(this).impulse >= 200 && CS(this).impulse <= 209)))
2282                         || (!is_spec && ((PHYS_INPUT_BUTTON_ATCK(this) && !CS(this).version_mismatch) || this.would_spectate))) {
2283                         this.flags &= ~FL_JUMPRELEASED;
2284                         if(SpectateNext(this)) {
2285                                 TRANSMUTE(Spectator, this);
2286                         } else if (is_spec) {
2287                                 TRANSMUTE(Observer, this);
2288                                 PutClientInServer(this);
2289                         }
2290                         else
2291                                 this.would_spectate = false; // unable to spectate anyone
2292                         if (is_spec)
2293                                 CS(this).impulse = 0;
2294                 } else if (is_spec) {
2295                         if(CS(this).impulse == 12 || CS(this).impulse == 16  || CS(this).impulse == 19 || (CS(this).impulse >= 220 && CS(this).impulse <= 229)) {
2296                                 this.flags &= ~FL_JUMPRELEASED;
2297                                 if(SpectatePrev(this)) {
2298                                         TRANSMUTE(Spectator, this);
2299                                 } else {
2300                                         TRANSMUTE(Observer, this);
2301                                         PutClientInServer(this);
2302                                 }
2303                                 CS(this).impulse = 0;
2304                         } else if(PHYS_INPUT_BUTTON_ATCK2(this)) {
2305                                 this.would_spectate = false;
2306                                 this.flags &= ~FL_JUMPRELEASED;
2307                                 TRANSMUTE(Observer, this);
2308                                 PutClientInServer(this);
2309                         } else if(!SpectateUpdate(this) && !SpectateNext(this)) {
2310                                 PutObserverInServer(this, false, true);
2311                                 this.would_spectate = true;
2312                         }
2313                 }
2314                 else {
2315                         bool wouldclip = CS_CVAR(this).cvar_cl_clippedspectating;
2316                         if (PHYS_INPUT_BUTTON_USE(this))
2317                                 wouldclip = !wouldclip;
2318                         int preferred_movetype = (wouldclip ? MOVETYPE_FLY_WORLDONLY : MOVETYPE_NOCLIP);
2319                         set_movetype(this, preferred_movetype);
2320                 }
2321         } else { // jump pressed
2322                 if ((is_spec && !(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_ATCK2(this)))
2323                         || (!is_spec && !(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this)))) {
2324                         this.flags |= FL_JUMPRELEASED;
2325                         if(this.flags & FL_SPAWNING)
2326                         {
2327                                 this.flags &= ~FL_SPAWNING;
2328                                 if(joinAllowed(this))
2329                                         Join(this);
2330                                 else if(time < CS(this).jointime + MIN_SPEC_TIME)
2331                                         CS(this).autojoin_checked = -1;
2332                                 return;
2333                         }
2334                 }
2335                 if(is_spec && !SpectateUpdate(this))
2336                         PutObserverInServer(this, false, true);
2337         }
2338         if (is_spec)
2339                 this.flags |= FL_CLIENT | FL_NOTARGET;
2340 }
2341
2342 void PlayerUseKey(entity this)
2343 {
2344         if (!IS_PLAYER(this))
2345                 return;
2346
2347         if(this.vehicle)
2348         {
2349                 if(!game_stopped)
2350                 {
2351                         vehicles_exit(this.vehicle, VHEF_NORMAL);
2352                         return;
2353                 }
2354         }
2355         else if(autocvar_g_vehicles_enter)
2356         {
2357                 if(!game_stopped && !STAT(FROZEN, this) && !IS_DEAD(this) && !IS_INDEPENDENT_PLAYER(this))
2358                 {
2359                         entity head, closest_target = NULL;
2360                         head = WarpZone_FindRadius(this.origin, autocvar_g_vehicles_enter_radius, true);
2361
2362                         while(head) // find the closest acceptable target to enter
2363                         {
2364                                 if(IS_VEHICLE(head) && !IS_DEAD(head) && head.takedamage != DAMAGE_NO)
2365                                 if(!head.owner || ((head.vehicle_flags & VHF_MULTISLOT) && SAME_TEAM(head.owner, this)))
2366                                 {
2367                                         if(closest_target)
2368                                         {
2369                                                 if(vlen2(this.origin - head.origin) < vlen2(this.origin - closest_target.origin))
2370                                                 { closest_target = head; }
2371                                         }
2372                                         else { closest_target = head; }
2373                                 }
2374
2375                                 head = head.chain;
2376                         }
2377
2378                         if(closest_target) { vehicles_enter(this, closest_target); return; }
2379                 }
2380         }
2381
2382         // a use key was pressed; call handlers
2383         MUTATOR_CALLHOOK(PlayerUseKey, this);
2384 }
2385
2386
2387 /*
2388 =============
2389 PlayerPreThink
2390
2391 Called every frame for each client before the physics are run
2392 =============
2393 */
2394 .float last_vehiclecheck;
2395 void PlayerPreThink (entity this)
2396 {
2397         STAT(GUNALIGN, this) = CS_CVAR(this).cvar_cl_gunalign; // TODO
2398         STAT(MOVEVARS_CL_TRACK_CANJUMP, this) = CS_CVAR(this).cvar_cl_movement_track_canjump;
2399
2400         WarpZone_PlayerPhysics_FixVAngle(this);
2401
2402         if (frametime) {
2403                 // physics frames: update anticheat stuff
2404                 anticheat_prethink(this);
2405
2406                 // WORKAROUND: only use dropclient in server frames (frametime set).
2407                 // Never use it in cl_movement frames (frametime zero).
2408                 if (blockSpectators && IS_REAL_CLIENT(this)
2409                         && (IS_SPEC(this) || IS_OBSERVER(this)) && !INGAME(this)
2410                         && time > (CS(this).spectatortime + autocvar_g_maxplayers_spectator_blocktime))
2411                 {
2412                         if (dropclient_schedule(this))
2413                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_QUIT_KICK_SPECTATING);
2414                 }
2415         }
2416
2417         zoomstate_set = false;
2418
2419         // Check for nameless players
2420         if (this.netname == "" || this.netname != CS(this).netname_previous)
2421         {
2422                 bool assume_unchanged = (CS(this).netname_previous == "");
2423                 if (autocvar_sv_name_maxlength > 0 && strlennocol(this.netname) > autocvar_sv_name_maxlength)
2424                 {
2425                         int new_length = textLengthUpToLength(this.netname, autocvar_sv_name_maxlength, strlennocol);
2426                         this.netname = strzone(strcat(substring(this.netname, 0, new_length), "^7"));
2427                         sprint(this, sprintf("Warning: your name is longer than %d characters, it has been truncated.\n", autocvar_sv_name_maxlength));
2428                         assume_unchanged = false;
2429                         // stuffcmd(this, strcat("name ", this.netname, "\n")); // maybe?
2430                 }
2431                 if (isInvisibleString(this.netname))
2432                 {
2433                         this.netname = strzone(sprintf("Player#%d", this.playerid));
2434                         sprint(this, "Warning: invisible names are not allowed.\n");
2435                         assume_unchanged = false;
2436                         // stuffcmd(this, strcat("name ", this.netname, "\n")); // maybe?
2437                 }
2438                 if (!assume_unchanged && autocvar_sv_eventlog)
2439                         GameLogEcho(strcat(":name:", ftos(this.playerid), ":", playername(this.netname, this.team, false)));
2440                 strcpy(CS(this).netname_previous, this.netname);
2441         }
2442
2443         // version nagging
2444         if (CS(this).version_nagtime && CS_CVAR(this).cvar_g_xonoticversion && time > CS(this).version_nagtime) {
2445         CS(this).version_nagtime = 0;
2446         if (strstrofs(CS_CVAR(this).cvar_g_xonoticversion, "git", 0) >= 0 || strstrofs(CS_CVAR(this).cvar_g_xonoticversion, "autobuild", 0) >= 0) {
2447             // git client
2448         } else if (strstrofs(autocvar_g_xonoticversion, "git", 0) >= 0 || strstrofs(autocvar_g_xonoticversion, "autobuild", 0) >= 0) {
2449             // git server
2450             Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_BETA, autocvar_g_xonoticversion, CS_CVAR(this).cvar_g_xonoticversion);
2451         } else {
2452             int r = vercmp(CS_CVAR(this).cvar_g_xonoticversion, autocvar_g_xonoticversion);
2453             if (r < 0) { // old client
2454                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_OUTDATED, autocvar_g_xonoticversion, CS_CVAR(this).cvar_g_xonoticversion);
2455             } else if (r > 0) { // old server
2456                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_OLD, autocvar_g_xonoticversion, CS_CVAR(this).cvar_g_xonoticversion);
2457             }
2458         }
2459     }
2460
2461         // GOD MODE info
2462         if (!(this.flags & FL_GODMODE) && this.max_armorvalue)
2463         {
2464                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_GODMODE_OFF, this.max_armorvalue);
2465                 this.max_armorvalue = 0;
2466         }
2467
2468         if (frametime && IS_PLAYER(this) && time >= game_starttime)
2469         {
2470                 if (STAT(FROZEN, this) == FROZEN_TEMP_REVIVING)
2471                 {
2472                         STAT(REVIVE_PROGRESS, this) = bound(0, STAT(REVIVE_PROGRESS, this) + frametime * this.revive_speed, 1);
2473                         SetResourceExplicit(this, RES_HEALTH, max(1, STAT(REVIVE_PROGRESS, this) * start_health));
2474                         if (this.iceblock)
2475                                 this.iceblock.alpha = bound(0.2, 1 - STAT(REVIVE_PROGRESS, this), 1);
2476
2477                         if (STAT(REVIVE_PROGRESS, this) >= 1)
2478                                 Unfreeze(this, false);
2479                 }
2480                 else if (STAT(FROZEN, this) == FROZEN_TEMP_DYING)
2481                 {
2482                         STAT(REVIVE_PROGRESS, this) = bound(0, STAT(REVIVE_PROGRESS, this) - frametime * this.revive_speed, 1);
2483                         SetResourceExplicit(this, RES_HEALTH, max(0, autocvar_g_nades_ice_health + (start_health-autocvar_g_nades_ice_health) * STAT(REVIVE_PROGRESS, this)));
2484
2485                         if (GetResource(this, RES_HEALTH) < 1)
2486                         {
2487                                 if (this.vehicle)
2488                                         vehicles_exit(this.vehicle, VHEF_RELEASE);
2489                                 if(this.event_damage)
2490                                         this.event_damage(this, this, this.frozen_by, 1, DEATH_NADE_ICE_FREEZE.m_id, DMG_NOWEP, this.origin, '0 0 0');
2491                         }
2492                         else if (STAT(REVIVE_PROGRESS, this) <= 0)
2493                                 Unfreeze(this, false);
2494                 }
2495         }
2496
2497         MUTATOR_CALLHOOK(PlayerPreThink, this);
2498
2499         if(autocvar_g_vehicles_enter && (time > this.last_vehiclecheck) && !game_stopped && !this.vehicle)
2500         if(IS_PLAYER(this) && !STAT(FROZEN, this) && !IS_DEAD(this) && !IS_INDEPENDENT_PLAYER(this))
2501         {
2502                 FOREACH_ENTITY_RADIUS(this.origin, autocvar_g_vehicles_enter_radius, IS_VEHICLE(it) && !IS_DEAD(it) && it.takedamage != DAMAGE_NO,
2503                 {
2504                         if(!it.owner)
2505                         {
2506                                 if(!it.team || SAME_TEAM(this, it))
2507                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER);
2508                                 else if(autocvar_g_vehicles_steal)
2509                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER_STEAL);
2510                         }
2511                         else if((it.vehicle_flags & VHF_MULTISLOT) && SAME_TEAM(it.owner, this))
2512                         {
2513                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER_GUNNER);
2514                         }
2515                 });
2516
2517                 this.last_vehiclecheck = time + 1;
2518         }
2519
2520         if(PHYS_INPUT_BUTTON_USE(this) && !CS(this).usekeypressed)
2521                 PlayerUseKey(this);
2522         CS(this).usekeypressed = PHYS_INPUT_BUTTON_USE(this);
2523
2524         if (IS_REAL_CLIENT(this))
2525                 PrintWelcomeMessage(this);
2526
2527         if (IS_PLAYER(this)) {
2528                 if (IS_REAL_CLIENT(this) && time < CS(this).jointime + MIN_SPEC_TIME)
2529                         error("Client can't be spawned as player on connection!");
2530                 if(!PlayerThink(this))
2531                         return;
2532         }
2533         else if (game_stopped || intermission_running) {
2534                 if(intermission_running)
2535                         IntermissionThink(this);
2536                 return;
2537         }
2538         else if (IS_REAL_CLIENT(this) && CS(this).autojoin_checked <= 0 && time >= CS(this).jointime + MIN_SPEC_TIME)
2539         {
2540                 bool early_join_requested = (CS(this).autojoin_checked < 0);
2541                 CS(this).autojoin_checked = 1;
2542                 // don't do this in ClientConnect
2543                 // many things can go wrong if a client is spawned as player on connection
2544                 if (early_join_requested || MUTATOR_CALLHOOK(AutoJoinOnConnection, this)
2545                         || (!(autocvar_sv_spectate || autocvar_g_campaign || (Player_GetForcedTeamIndex(this) == TEAM_FORCE_SPECTATOR))
2546                                 && (!teamplay || autocvar_g_balance_teams)))
2547                 {
2548                         campaign_bots_may_start = true;
2549                         if(joinAllowed(this))
2550                                 Join(this);
2551                         return;
2552                 }
2553         }
2554         else if (IS_OBSERVER(this) || IS_SPEC(this)) {
2555                 ObserverOrSpectatorThink(this);
2556         }
2557
2558         // WEAPONTODO: Add weapon request for this
2559         if (!zoomstate_set) {
2560                 bool wep_zoomed = false;
2561                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2562                 {
2563                         .entity weaponentity = weaponentities[slot];
2564                         Weapon thiswep = this.(weaponentity).m_weapon;
2565                         if(thiswep != WEP_Null && thiswep.wr_zoom)
2566                                 wep_zoomed += thiswep.wr_zoom(thiswep, this);
2567                 }
2568                 SetZoomState(this, PHYS_INPUT_BUTTON_ZOOM(this) || PHYS_INPUT_BUTTON_ZOOMSCRIPT(this) || wep_zoomed);
2569         }
2570
2571         if (CS(this).teamkill_soundtime && time > CS(this).teamkill_soundtime)
2572         {
2573                 CS(this).teamkill_soundtime = 0;
2574
2575                 entity e = CS(this).teamkill_soundsource;
2576                 entity oldpusher = e.pusher;
2577                 e.pusher = this;
2578                 PlayerSound(e, playersound_teamshoot, CH_VOICE, VOL_BASEVOICE, VOICETYPE_LASTATTACKER_ONLY);
2579                 e.pusher = oldpusher;
2580         }
2581
2582         if (CS(this).taunt_soundtime && time > CS(this).taunt_soundtime) {
2583                 CS(this).taunt_soundtime = 0;
2584                 PlayerSound(this, playersound_taunt, CH_VOICE, VOL_BASEVOICE, VOICETYPE_AUTOTAUNT);
2585         }
2586
2587         target_voicescript_next(this);
2588 }
2589
2590 void DrownPlayer(entity this)
2591 {
2592         if(IS_DEAD(this) || game_stopped || time < game_starttime || this.vehicle
2593                 || STAT(FROZEN, this) || this.watertype != CONTENT_WATER)
2594         {
2595                 STAT(AIR_FINISHED, this) = 0;
2596                 return;
2597         }
2598
2599         if (this.waterlevel != WATERLEVEL_SUBMERGED)
2600         {
2601                 if(STAT(AIR_FINISHED, this) && STAT(AIR_FINISHED, this) < time)
2602                         PlayerSound(this, playersound_gasp, CH_PLAYER, VOL_BASE, VOICETYPE_PLAYERSOUND);
2603                 STAT(AIR_FINISHED, this) = 0;
2604         }
2605         else
2606         {
2607                 if (!STAT(AIR_FINISHED, this))
2608                         STAT(AIR_FINISHED, this) = time + autocvar_g_balance_contents_drowndelay;
2609                 if (STAT(AIR_FINISHED, this) < time)
2610                 {       // drown!
2611                         if (this.pain_finished < time)
2612                         {
2613                                 Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_drowning * autocvar_g_balance_contents_damagerate, DEATH_DROWN.m_id, DMG_NOWEP, this.origin, '0 0 0');
2614                                 this.pain_finished = time + 0.5;
2615                         }
2616                 }
2617         }
2618 }
2619
2620 .bool move_qcphysics;
2621
2622 void Player_Physics(entity this)
2623 {
2624         this.movetype = (this.move_qcphysics) ? MOVETYPE_QCPLAYER : this.move_movetype;
2625
2626         if(!this.move_qcphysics)
2627                 return;
2628
2629         if(!frametime && !CS(this).pm_frametime)
2630                 return;
2631
2632         Movetype_Physics_NoMatchTicrate(this, CS(this).pm_frametime, true);
2633
2634         CS(this).pm_frametime = 0;
2635 }
2636
2637 /*
2638 =============
2639 PlayerPostThink
2640
2641 Called every frame for each client after the physics are run
2642 =============
2643 */
2644 void PlayerPostThink (entity this)
2645 {
2646         Player_Physics(this);
2647
2648         if (autocvar_sv_maxidle > 0 || (IS_PLAYER(this) && autocvar_sv_maxidle_playertospectator > 0))
2649         if (frametime) // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2650         if (IS_REAL_CLIENT(this))
2651         if (IS_PLAYER(this) || autocvar_sv_maxidle_alsokickspectators)
2652         if (!intermission_running) // NextLevel() kills all centerprints after setting this true
2653         {
2654                 int totalClients = 0;
2655                 if(autocvar_sv_maxidle > 0 && autocvar_sv_maxidle_slots > 0)
2656                 {
2657                         // maxidle disabled in local matches by not counting clients (totalClients 0)
2658                         if (server_is_dedicated)
2659                         {
2660                                 FOREACH_CLIENT(IS_REAL_CLIENT(it) || autocvar_sv_maxidle_slots_countbots,
2661                                 {
2662                                         ++totalClients;
2663                                 });
2664                                 if (maxclients - totalClients > autocvar_sv_maxidle_slots)
2665                                         totalClients = 0;
2666                         }
2667                 }
2668                 else if (IS_PLAYER(this) && autocvar_sv_maxidle_playertospectator > 0)
2669                 {
2670                         FOREACH_CLIENT(IS_REAL_CLIENT(it),
2671                         {
2672                                 ++totalClients;
2673                         });
2674                 }
2675
2676                 if (totalClients < autocvar_sv_maxidle_minplayers)
2677                 {
2678                         // idle kick disabled
2679                         CS(this).parm_idlesince = time;
2680                 }
2681                 else if (time - CS(this).parm_idlesince < 1) // instead of (time == this.parm_idlesince) to support sv_maxidle <= 10
2682                 {
2683                         if (CS(this).idlekick_lasttimeleft)
2684                         {
2685                                 CS(this).idlekick_lasttimeleft = 0;
2686                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_IDLING);
2687                         }
2688                 }
2689                 else
2690                 {
2691                         float maxidle_time = autocvar_sv_maxidle;
2692                         if (IS_PLAYER(this) && autocvar_sv_maxidle_playertospectator > 0)
2693                                 maxidle_time = autocvar_sv_maxidle_playertospectator;
2694                         float timeleft = ceil(maxidle_time - (time - CS(this).parm_idlesince));
2695                         float countdown_time = max(min(10, maxidle_time - 1), ceil(maxidle_time * 0.33)); // - 1 to support maxidle_time <= 10
2696                         if (timeleft == countdown_time && !CS(this).idlekick_lasttimeleft)
2697                         {
2698                                 if (IS_PLAYER(this) && autocvar_sv_maxidle_playertospectator > 0)
2699                                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_MOVETOSPEC_IDLING, timeleft);
2700                                 else
2701                                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_DISCONNECT_IDLING, timeleft);
2702                         }
2703                         if (timeleft <= 0) {
2704                                 if (IS_PLAYER(this) && autocvar_sv_maxidle_playertospectator > 0)
2705                                 {
2706                                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_MOVETOSPEC_IDLING, this.netname, maxidle_time);
2707                                         PutObserverInServer(this, true, true);
2708                                 }
2709                                 else
2710                                 {
2711                                         if (dropclient_schedule(this))
2712                                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_KICK_IDLING, this.netname, maxidle_time);
2713                                 }
2714                                 return;
2715                         }
2716                         else if (timeleft <= countdown_time) {
2717                                 if (timeleft != CS(this).idlekick_lasttimeleft)
2718                                         play2(this, SND(TALK2));
2719                                 CS(this).idlekick_lasttimeleft = timeleft;
2720                         }
2721                 }
2722         }
2723
2724         CheatFrame(this);
2725
2726         if (game_stopped)
2727         {
2728                 this.solid = SOLID_NOT;
2729                 this.takedamage = DAMAGE_NO;
2730                 set_movetype(this, MOVETYPE_NONE);
2731                 CS(this).teamkill_complain = 0;
2732                 CS(this).teamkill_soundtime = 0;
2733                 CS(this).teamkill_soundsource = NULL;
2734         }
2735
2736         if (IS_PLAYER(this)) {
2737                 if(this.death_time == time && IS_DEAD(this))
2738                 {
2739                         // player's bbox gets resized now, instead of in the damage event that killed the player,
2740                         // once all the damage events of this frame have been processed with normal size
2741                         this.maxs.z = 5;
2742                         setsize(this, this.mins, this.maxs);
2743                 }
2744                 DrownPlayer(this);
2745                 UpdateChatBubble(this);
2746                 if (CS(this).impulse) ImpulseCommands(this);
2747                 GetPressedKeys(this);
2748                 if (game_stopped)
2749                 {
2750                         CSQCMODEL_AUTOUPDATE(this);
2751                         return;
2752                 }
2753         }
2754         else if (IS_OBSERVER(this) && STAT(PRESSED_KEYS, this))
2755         {
2756                 CS(this).pressedkeys = 0;
2757                 STAT(PRESSED_KEYS, this) = 0;
2758         }
2759
2760         if (this.waypointsprite_attachedforcarrier) {
2761                 float hp = healtharmor_maxdamage(GetResource(this, RES_HEALTH), GetResource(this, RES_ARMOR), autocvar_g_balance_armor_blockpercent, DEATH_WEAPON.m_id).x;
2762                 WaypointSprite_UpdateHealth(this.waypointsprite_attachedforcarrier, hp);
2763         }
2764
2765         CSQCMODEL_AUTOUPDATE(this);
2766 }
2767
2768 // hack to copy the button fields from the client entity to the Client State
2769 void PM_UpdateButtons(entity this, entity store)
2770 {
2771         if(this.impulse)
2772                 store.impulse = this.impulse;
2773         this.impulse = 0;
2774
2775         bool typing = this.buttonchat || this.button12;
2776
2777         store.button0 = (typing) ? 0 : this.button0;
2778         //button1?!
2779         store.button2 = (typing) ? 0 : this.button2;
2780         store.button3 = (typing) ? 0 : this.button3;
2781         store.button4 = this.button4;
2782         store.button5 = (typing) ? 0 : this.button5;
2783         store.button6 = this.button6;
2784         store.button7 = this.button7;
2785         store.button8 = this.button8;
2786         store.button9 = this.button9;
2787         store.button10 = this.button10;
2788         store.button11 = this.button11;
2789         store.button12 = this.button12;
2790         store.button13 = this.button13;
2791         store.button14 = this.button14;
2792         store.button15 = this.button15;
2793         store.button16 = this.button16;
2794         store.buttonuse = this.buttonuse;
2795         store.buttonchat = this.buttonchat;
2796
2797         store.cursor_active = this.cursor_active;
2798         store.cursor_screen = this.cursor_screen;
2799         store.cursor_trace_start = this.cursor_trace_start;
2800         store.cursor_trace_endpos = this.cursor_trace_endpos;
2801         store.cursor_trace_ent = this.cursor_trace_ent;
2802
2803         store.ping = this.ping;
2804         store.ping_packetloss = this.ping_packetloss;
2805         store.ping_movementloss = this.ping_movementloss;
2806
2807         store.v_angle = this.v_angle;
2808         store.movement = this.movement;
2809 }
2810
2811 NET_HANDLE(fpsreport, bool)
2812 {
2813         int fps = ReadShort();
2814         PlayerScore_Set(sender, SP_FPS, fps);
2815         return true;
2816 }