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