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