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