g_world.qc 60.3 KB
Newer Older
TimePath's avatar
TimePath committed
1
#include "g_world.qh"
TimePath's avatar
TimePath committed
2
#include "_all.qh"
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

#include "anticheat.qh"
#include "antilag.qh"
#include "bot/bot.qh"
#include "campaign.qh"
#include "cheats.qh"
#include "cl_client.qh"
#include "command/common.qh"
#include "command/getreplies.qh"
#include "command/sv_cmd.qh"
#include "command/vote.qh"
#include "g_hook.qh"
#include "ipban.qh"
#include "mapvoting.qh"
#include "mutators/mutators_include.qh"
#include "race.qh"
#include "scores.qh"
#include "teamplay.qh"
#include "waypointsprites.qh"
#include "weapons/weaponstats.qh"
TimePath's avatar
TimePath committed
23
#include "../common/buffs.qh"
24 25 26
#include "../common/constants.qh"
#include "../common/deathtypes.qh"
#include "../common/mapinfo.qh"
27
#include "../common/monsters/all.qh"
28 29 30 31 32 33
#include "../common/monsters/sv_monsters.qh"
#include "../common/notifications.qh"
#include "../common/playerstats.qh"
#include "../common/stats.qh"
#include "../common/teams.qh"
#include "../common/util.qh"
TimePath's avatar
TimePath committed
34
#include "../common/items/all.qh"
35
#include "../common/weapons/all.qh"
TimePath's avatar
TimePath committed
36

37
const float LATENCY_THINKRATE = 10;
38 39 40
.float latency_sum;
.float latency_cnt;
.float latency_time;
41
entity pingplreport;
42 43 44 45 46 47 48 49 50 51 52
void PingPLReport_Think()
{
	float delta;
	entity e;

	delta = 3 / maxclients;
	if(delta < sys_frametime)
		delta = 0;
	self.nextthink = time + delta;

	e = edict_num(self.cnt + 1);
53
	if(IS_REAL_CLIENT(e))
54 55 56 57 58 59 60
	{
		WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
		WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
		WriteByte(MSG_BROADCAST, self.cnt);
		WriteShort(MSG_BROADCAST, max(1, e.ping));
		WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
		WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
61 62 63 64 65 66 67 68 69

		// record latency times for clients throughout the match so we can report it to playerstats
		if(time > (e.latency_time + LATENCY_THINKRATE))
		{
			e.latency_sum += e.ping;
			e.latency_cnt += 1;
			e.latency_time = time;
			//print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
		}
70 71 72 73 74 75 76 77 78 79
	}
	else
	{
		WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
		WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
		WriteByte(MSG_BROADCAST, self.cnt);
		WriteShort(MSG_BROADCAST, 0);
		WriteByte(MSG_BROADCAST, 0);
		WriteByte(MSG_BROADCAST, 0);
	}
80
	self.cnt = (self.cnt + 1) % maxclients;
81 82 83 84 85 86 87 88 89
}
void PingPLReport_Spawn()
{
	pingplreport = spawn();
	pingplreport.classname = "pingplreport";
	pingplreport.think = PingPLReport_Think;
	pingplreport.nextthink = time;
}

90
const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
91 92 93 94
string redirection_target;
float world_initialized;

string GetGametype();
Rudolf Polzer's avatar
Rudolf Polzer committed
95
void ShuffleMaplist();
96 97 98

void SetDefaultAlpha()
{
99
	if(autocvar_g_running_guns)
100 101 102 103 104 105
	{
		default_player_alpha = -1;
		default_weapon_alpha = +1;
	}
	else if(g_cloaked)
	{
106
		default_player_alpha = autocvar_g_balance_cloaked_alpha;
107 108 109 110
		default_weapon_alpha = default_player_alpha;
	}
	else
	{
111
		default_player_alpha = autocvar_g_player_alpha;
112 113 114 115 116 117 118 119 120
		if(default_player_alpha == 0)
			default_player_alpha = 1;
		default_weapon_alpha = default_player_alpha;
	}
}

void GotoFirstMap()
{
	float n;
121
	if(autocvar__sv_init)
122 123 124 125 126
	{
		// cvar_set("_sv_init", "0");
		// we do NOT set this to 0 any more, so someone "accidentally" changing
		// to this "init" map on a dedicated server will cause no permanent
		// harm
127
		if(autocvar_g_maplist_shuffle)
128
			ShuffleMaplist();
129
		n = tokenizebyseparator(autocvar_g_maplist, " ");
130 131 132 133 134
		cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap

		MapInfo_Enumerate();
		MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);

135 136
		if(!DoNextMapOverride(1))
			GotoNextMap(1);
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

		return;
	}

	if(time < 5)
	{
		self.nextthink = time;
	}
	else
	{
		self.nextthink = time + 1;
		print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
	}
}

void cvar_changes_init()
{
	float h;
	string k, v, d;
156
	float n, i, adding, pureadding;
157 158 159 160

	if(cvar_changes)
		strunzone(cvar_changes);
	cvar_changes = string_null;
161 162 163 164
	if(cvar_purechanges)
		strunzone(cvar_purechanges);
	cvar_purechanges = string_null;
	cvar_purechanges_count = 0;
165 166 167 168 169

	h = buf_create();
	buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
	n = buf_getsize(h);

TimePath's avatar
TimePath committed
170 171
	adding = true;
	pureadding = true;
172

173 174 175 176 177
	for(i = 0; i < n; ++i)
	{
		k = bufstr_get(h, i);

#define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
178
#define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
179
#define BADCVAR(p) if(k == p) continue
180 181 182 183

		// general excludes and namespaces for server admin used cvars
		BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT

184 185 186 187 188 189 190
		// internal
		BADPREFIX("csqc_");
		BADPREFIX("cvar_check_");
		BADCVAR("gamecfg");
		BADCVAR("g_configversion");
		BADCVAR("g_maplist_index");
		BADCVAR("halflifebsp");
191
		BADCVAR("sv_mapformat_is_quake2");
192
		BADCVAR("sv_mapformat_is_quake3");
Rudolf Polzer's avatar
Rudolf Polzer committed
193
		BADPREFIX("sv_world");
194 195

		// client
Rudolf Polzer's avatar
Rudolf Polzer committed
196
		BADPREFIX("chase_");
197 198
		BADPREFIX("cl_");
		BADPREFIX("con_");
Rudolf Polzer's avatar
Rudolf Polzer committed
199
		BADPREFIX("scoreboard_");
200
		BADPREFIX("g_campaign");
201
		BADPREFIX("g_waypointsprite_");
202 203
		BADPREFIX("gl_");
		BADPREFIX("joy");
Rudolf Polzer's avatar
Rudolf Polzer committed
204
		BADPREFIX("hud_");
205
		BADPREFIX("m_");
206 207 208 209 210
		BADPREFIX("menu_");
		BADPREFIX("net_slist_");
		BADPREFIX("r_");
		BADPREFIX("sbar_");
		BADPREFIX("scr_");
211
		BADPREFIX("snd_");
212 213
		BADPREFIX("show");
		BADPREFIX("sensitivity");
214 215 216 217 218 219
		BADPREFIX("userbind");
		BADPREFIX("v_");
		BADPREFIX("vid_");
		BADPREFIX("crosshair");
		BADCVAR("mod_q3bsp_lightmapmergepower");
		BADCVAR("mod_q3bsp_nolightmaps");
220 221 222 223
		BADCVAR("fov");
		BADCVAR("mastervolume");
		BADCVAR("volume");
		BADCVAR("bgmvolume");
224 225

		// private
Rudolf Polzer's avatar
Rudolf Polzer committed
226 227 228 229 230 231
		BADCVAR("developer");
		BADCVAR("log_dest_udp");
		BADCVAR("net_address");
		BADCVAR("net_address_ipv6");
		BADCVAR("port");
		BADCVAR("savedgamecfg");
232
		BADCVAR("serverconfig");
233
		BADCVAR("sv_autoscreenshot");
Rudolf Polzer's avatar
Rudolf Polzer committed
234 235 236 237
		BADCVAR("sv_heartbeatperiod");
		BADCVAR("sv_vote_master_password");
		BADCVAR("sys_colortranslation");
		BADCVAR("sys_specialcharactertranslation");
238
		BADCVAR("timeformat");
Rudolf Polzer's avatar
Rudolf Polzer committed
239 240
		BADCVAR("timestamps");
		BADPREFIX("developer_");
241
		BADPREFIX("g_ban_");
242
		BADPREFIX("g_banned_list");
243
		BADPREFIX("g_chat_flood_");
244
		BADPREFIX("g_ghost_items");
Rudolf Polzer's avatar
Rudolf Polzer committed
245
		BADPREFIX("g_playerstats_");
246
		BADPREFIX("g_respawn_ghosts");
247
		BADPREFIX("g_voice_flood_");
Mario's avatar
Mario committed
248
		BADPREFIX("log_file");
249
		BADPREFIX("rcon_");
250
		BADPREFIX("sv_allowdownloads");
251 252 253 254 255
		BADPREFIX("sv_autodemo");
		BADPREFIX("sv_curl_");
		BADPREFIX("sv_eventlog");
		BADPREFIX("sv_logscores_");
		BADPREFIX("sv_master");
256
		BADPREFIX("sv_weaponstats_");
257
		BADPREFIX("sv_waypointsprite_");
Rudolf Polzer's avatar
Rudolf Polzer committed
258
		BADCVAR("rescan_pending");
259

260
		// these can contain player IDs, so better hide
Rudolf Polzer's avatar
Rudolf Polzer committed
261
		BADPREFIX("g_forced_team_");
262

263 264 265
		// mapinfo
		BADCVAR("fraglimit");
		BADCVAR("g_assault");
266
		BADCVAR("g_ca");
267
		BADCVAR("g_ca_teams");
268
		BADCVAR("g_ctf");
269
		BADCVAR("g_cts");
270 271
		BADCVAR("g_dm");
		BADCVAR("g_domination");
272
		BADCVAR("g_domination_default_teams");
Rudolf Polzer's avatar
Rudolf Polzer committed
273
		BADCVAR("g_freezetag");
274
		BADCVAR("g_freezetag_teams");
275
		BADCVAR("g_invasion_teams");
276
		BADCVAR("g_keepaway");
277 278
		BADCVAR("g_keyhunt");
		BADCVAR("g_keyhunt_teams");
279 280
		BADCVAR("g_lms");
		BADCVAR("g_nexball");
281 282
		BADCVAR("g_onslaught");
		BADCVAR("g_race");
283
		BADCVAR("g_race_qualifying_timelimit");
284
		BADCVAR("g_tdm");
285 286 287
		BADCVAR("g_tdm_teams");
		BADCVAR("leadlimit");
		BADCVAR("nextmap");
288
		BADCVAR("teamplay");
289
		BADCVAR("timelimit");
290 291 292 293 294 295 296 297 298

		// long
		BADCVAR("hostname");
		BADCVAR("g_maplist");
		BADCVAR("g_maplist_mostrecent");
		BADCVAR("sv_motd");

		v = cvar_string(k);
		d = cvar_defstring(k);
299 300 301 302
		if(v == d)
			continue;

		if(adding)
303 304 305 306 307
		{
			cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
			if(strlen(cvar_changes) > 16384)
			{
				cvar_changes = "// too many settings have been changed to show them here\n";
308 309 310 311 312 313 314
				adding = 0;
			}
		}

		// now check if the changes are actually gameplay relevant

		// does nothing visible
315
		BADCVAR("captureleadlimit_override");
Rudolf Polzer's avatar
Rudolf Polzer committed
316
		BADCVAR("g_balance_kill_delay");
Mario's avatar
Mario committed
317
		BADCVAR("g_ca_point_limit");
318
		BADCVAR("g_ca_point_leadlimit");
Rudolf Polzer's avatar
Rudolf Polzer committed
319 320
		BADCVAR("g_ctf_captimerecord_always");
		BADCVAR("g_ctf_flag_glowtrails");
Samual's avatar
Samual committed
321
		BADCVAR("g_ctf_flag_pickup_verbosename");
322
		BADCVAR("g_domination_point_leadlimit");
Rudolf Polzer's avatar
Rudolf Polzer committed
323
		BADCVAR("g_forced_respawn");
Mario's avatar
Mario committed
324 325
		BADCVAR("g_freezetag_point_limit");
		BADCVAR("g_freezetag_point_leadlimit");
326
		BADCVAR("g_keyhunt_point_leadlimit");
327
		BADPREFIX("g_mod_");
Mario's avatar
Mario committed
328
		BADCVAR("g_invasion_point_limit");
329
		BADCVAR("g_nexball_goalleadlimit");
Mario's avatar
Mario committed
330 331
		BADCVAR("g_tdm_point_limit");
		BADCVAR("g_tdm_point_leadlimit");
332 333
		BADCVAR("leadlimit_and_fraglimit");
		BADCVAR("leadlimit_override");
334
		BADCVAR("pausable");
335
		BADCVAR("sv_allow_fullbright");
Rudolf Polzer's avatar
Rudolf Polzer committed
336
		BADCVAR("sv_checkforpacketsduringsleep");
Samual's avatar
Samual committed
337
		BADCVAR("sv_fraginfo");
338
		BADCVAR("sv_timeout");
339
		BADPREFIX("sv_timeout_");
340
		BADPREFIX("crypto_");
341
		BADPREFIX("g_chat_");
Rudolf Polzer's avatar
Rudolf Polzer committed
342 343
		BADPREFIX("g_ctf_captimerecord_");
		BADPREFIX("g_maplist_votable_");
344
		BADPREFIX("net_");
345
		BADPREFIX("prvm_");
Rudolf Polzer's avatar
Rudolf Polzer committed
346
		BADPREFIX("skill_");
347
		BADPREFIX("sv_cullentities_");
348
		BADPREFIX("sv_fraginfo_");
Rudolf Polzer's avatar
Rudolf Polzer committed
349
		BADPREFIX("sv_maxidle_");
350 351
		BADPREFIX("sv_vote_");
		BADPREFIX("timelimit_");
Rudolf Polzer's avatar
Rudolf Polzer committed
352 353
		BADCVAR("gameversion");
		BADPREFIX("gameversion_");
Rudolf Polzer's avatar
Rudolf Polzer committed
354
		BADCVAR("sv_namechangetimer");
355 356 357

		// allowed changes to server admins (please sync this to server.cfg)
		// vi commands:
358
		//   :/"impure"/,$d
359 360 361 362
		//   :g!,^\/\/[^ /],d
		//   :%s,//\([^ ]*\).*,BADCVAR("\1");,
		//   :%!sort
		// yes, this does contain some redundant stuff, don't really care
363
		BADCVAR("bot_config_file");
364 365 366 367 368 369 370 371
		BADCVAR("bot_number");
		BADCVAR("bot_prefix");
		BADCVAR("bot_suffix");
		BADCVAR("capturelimit_override");
		BADCVAR("fraglimit_override");
		BADCVAR("gametype");
		BADCVAR("g_antilag");
		BADCVAR("g_balance_teams");
372 373
		BADCVAR("g_balance_teams_prevent_imbalance");
		BADCVAR("g_balance_teams_scorefactor");
374 375
		BADCVAR("g_ban_sync_trusted_servers");
		BADCVAR("g_ban_sync_uri");
376
		BADCVAR("g_ca_teams_override");
377 378
		BADCVAR("g_ctf_ignore_frags");
		BADCVAR("g_domination_point_limit");
379
		BADCVAR("g_domination_teams_override");
380
		BADCVAR("g_freezetag_teams_override");
Rudolf Polzer's avatar
Rudolf Polzer committed
381
		BADCVAR("g_friendlyfire");
382 383 384 385 386 387 388 389 390 391 392 393 394
		BADCVAR("g_fullbrightitems");
		BADCVAR("g_fullbrightplayers");
		BADCVAR("g_keyhunt_point_limit");
		BADCVAR("g_keyhunt_teams_override");
		BADCVAR("g_lms_lives_override");
		BADCVAR("g_maplist");
		BADCVAR("g_maplist_check_waypoints");
		BADCVAR("g_maplist_mostrecent_count");
		BADCVAR("g_maplist_shuffle");
		BADCVAR("g_maplist_votable");
		BADCVAR("g_maplist_votable_abstain");
		BADCVAR("g_maplist_votable_nodetail");
		BADCVAR("g_maplist_votable_suggestions");
Rudolf Polzer's avatar
Rudolf Polzer committed
395 396
		BADCVAR("g_maxplayers");
		BADCVAR("g_mirrordamage");
397
		BADCVAR("g_nexball_goallimit");
398
		BADCVAR("g_powerups");
Rudolf Polzer's avatar
Rudolf Polzer committed
399
		BADCVAR("g_start_delay");
400
		BADCVAR("g_tdm_teams_override");
Rudolf Polzer's avatar
Rudolf Polzer committed
401
		BADCVAR("g_warmup");
402
		BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
403 404 405 406 407 408 409 410 411 412
		BADCVAR("hostname");
		BADCVAR("log_file");
		BADCVAR("maxplayers");
		BADCVAR("minplayers");
		BADCVAR("net_address");
		BADCVAR("port");
		BADCVAR("rcon_password");
		BADCVAR("rcon_restricted_commands");
		BADCVAR("rcon_restricted_password");
		BADCVAR("skill");
413
		BADCVAR("sv_adminnick");
414
		BADCVAR("sv_autoscreenshot");
Rudolf Polzer's avatar
Rudolf Polzer committed
415
		BADCVAR("sv_autotaunt");
416
		BADCVAR("sv_curl_defaulturl");
Rudolf Polzer's avatar
Rudolf Polzer committed
417 418 419 420
		BADCVAR("sv_defaultcharacter");
		BADCVAR("sv_defaultplayercolors");
		BADCVAR("sv_defaultplayermodel");
		BADCVAR("sv_defaultplayerskin");
Rudolf Polzer's avatar
Rudolf Polzer committed
421
		BADCVAR("sv_maxidle");
422
		BADCVAR("sv_maxrate");
423 424 425 426
		BADCVAR("sv_motd");
		BADCVAR("sv_public");
		BADCVAR("sv_ready_restart");
		BADCVAR("sv_status_privacy");
427
		BADCVAR("sv_taunt");
428 429 430 431 432 433 434
		BADCVAR("sv_vote_call");
		BADCVAR("sv_vote_commands");
		BADCVAR("sv_vote_majority_factor");
		BADCVAR("sv_vote_master");
		BADCVAR("sv_vote_master_commands");
		BADCVAR("sv_vote_master_password");
		BADCVAR("sv_vote_simple_majority_factor");
Rudolf Polzer's avatar
Rudolf Polzer committed
435
		BADCVAR("teamplay_mode");
436
		BADCVAR("timelimit_override");
437
		BADCVAR("g_spawnshieldtime");
Rudolf Polzer's avatar
Rudolf Polzer committed
438
		BADPREFIX("g_warmup_");
Rudolf Polzer's avatar
Rudolf Polzer committed
439
		BADPREFIX("sv_ready_restart_");
440

441
		// mutators that announce themselves properly to the server browser
Mario's avatar
Mario committed
442
		BADCVAR("g_instagib");
443 444
		BADCVAR("g_new_toys");
		BADCVAR("g_nix");
Mario's avatar
Mario committed
445 446
		BADCVAR("g_grappling_hook");
		BADCVAR("g_jetpack");
447

448 449 450 451 452 453 454 455 456 457
#undef BADPREFIX
#undef BADCVAR

		if(pureadding)
		{
			cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
			if(strlen(cvar_purechanges) > 16384)
			{
				cvar_purechanges = "// too many settings have been changed to show them here\n";
				pureadding = 0;
458 459
			}
		}
460
		++cvar_purechanges_count;
Rudolf Polzer's avatar
Rudolf Polzer committed
461 462 463 464 465 466
		// WARNING: this variable is used for the server list
		// NEVER dare to skip this code!
		// Hacks to intentionally appearing as "pure server" even though you DO have
		// modified settings may be punished by removal from the server list.
		// You can do to the variables cvar_changes and cvar_purechanges all you want,
		// though.
467 468 469
	}
	buf_del(h);
	if(cvar_changes == "")
470
		cvar_changes = "// this server runs at default server settings\n";
471
	else
472
		cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
473
	cvar_changes = strzone(cvar_changes);
474 475 476 477 478
	if(cvar_purechanges == "")
		cvar_purechanges = "// this server runs at default gameplay settings\n";
	else
		cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
	cvar_purechanges = strzone(cvar_purechanges);
479 480 481 482 483 484 485 486
}

void detect_maptype()
{
#if 0
	vector o, v;
	float i;

TimePath's avatar
TimePath committed
487
	for (;;)
488 489
	{
		o = world.mins;
490 491 492
		o.x += random() * (world.maxs.x - world.mins.x);
		o.y += random() * (world.maxs.y - world.mins.y);
		o.z += random() * (world.maxs.z - world.mins.z);
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

		tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
		if(trace_fraction == 1)
			continue;

		v = trace_endpos;

		for(i = 0; i < 64; i += 4)
		{
			tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
	if(trace_fraction == 1)
		continue;
			print(ftos(i), " -> ", vtos(trace_endpos), "\n");
		}

		break;
	}
#endif
}

entity randomseed;
Mario's avatar
Mario committed
514
float RandomSeed_Send(entity to, int sf)
515 516 517
{
	WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
	WriteShort(MSG_ENTITY, self.cnt);
TimePath's avatar
TimePath committed
518
	return true;
519 520 521 522 523 524 525 526 527 528 529 530
}
void RandomSeed_Think()
{
	self.cnt = bound(0, floor(random() * 65536), 65535);
	self.nextthink = time + 5;

	self.SendFlags |= 1;
}
void RandomSeed_Spawn()
{
	randomseed = spawn();
	randomseed.think = RandomSeed_Think;
TimePath's avatar
TimePath committed
531
	Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

	entity oldself;
	oldself = self;
	self = randomseed;
	self.think(); // sets random seed and nextthink
	self = oldself;
}

void spawnfunc___init_dedicated_server(void)
{
	// handler for _init/_init map (only for dedicated server initialization)

	world_initialized = -1; // don't complain
	cvar = cvar_normal;
	cvar_string = cvar_string_normal;
	cvar_set = cvar_set_normal;

	remove = remove_unsafely;

	entity e;
	e = spawn();
	e.think = GotoFirstMap;
	e.nextthink = time; // this is usually 1 at this point

	e = spawn();
	e.classname = "info_player_deathmatch"; // safeguard against player joining

	self.classname = "worldspawn"; // safeguard against various stuff ;)

561
	// needs to be done so early because of the constants they create
TimePath's avatar
TimePath committed
562
	static_init();
563
	CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
564
	CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
565
	CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
Samual's avatar
Samual committed
566 567
	CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
	CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
568
	CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
569

570 571 572 573 574 575 576
	MapInfo_Enumerate();
	MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
}

void Map_MarkAsRecent(string m);
float world_already_spawned;
void Nagger_Init();
577
void Item_ItemsTime_Init();
578 579 580
void ClientInit_Spawn();
void WeaponStats_Init();
void WeaponStats_Shutdown();
581
void Physics_AddStats();
582 583
void spawnfunc_worldspawn (void)
{
TimePath's avatar
TimePath committed
584
	float fd, l, j, n;
585
	string s;
586 587 588 589 590 591 592

	cvar = cvar_normal;
	cvar_string = cvar_string_normal;
	cvar_set = cvar_set_normal;

	if(world_already_spawned)
		error("world already spawned - you may have EXACTLY ONE worldspawn!");
TimePath's avatar
TimePath committed
593
	world_already_spawned = true;
594 595 596

	remove = remove_safely; // during spawning, watch what you remove!

597 598
	cvar_changes_init(); // do this very early now so it REALLY matches the server config

599 600
	compressShortVector_init();

601
	entity head;
602 603 604 605 606 607 608 609
	head = nextent(world);
	maxclients = 0;
	while(head)
	{
		++maxclients;
		head = nextent(head);
	}

TimePath's avatar
TimePath committed
610
	server_is_dedicated = (stof(cvar_defstring("is_dedicated")) ? true : false);
611

612
	// needs to be done so early because of the constants they create
TimePath's avatar
TimePath committed
613
	static_init();
614
	CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
615
	CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
616
	CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
Samual's avatar
Samual committed
617 618
	CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
	CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
619
	CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
620

621
	ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

	TemporaryDB = db_create();

	// 0 normal
	lightstyle(0, "m");

	// 1 FLICKER (first variety)
	lightstyle(1, "mmnmmommommnonmmonqnmmo");

	// 2 SLOW STRONG PULSE
	lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");

	// 3 CANDLE (first variety)
	lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");

	// 4 FAST STROBE
	lightstyle(4, "mamamamamama");

	// 5 GENTLE PULSE 1
	lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");

	// 6 FLICKER (second variety)
	lightstyle(6, "nmonqnmomnmomomno");

	// 7 CANDLE (second variety)
	lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");

	// 8 CANDLE (third variety)
	lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");

	// 9 SLOW STROBE (fourth variety)
	lightstyle(9, "aaaaaaaazzzzzzzz");

	// 10 FLUORESCENT FLICKER
	lightstyle(10, "mmamammmmammamamaaamammma");

	// 11 SLOW PULSE NOT FADE TO BLACK
	lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");

	// styles 32-62 are assigned by the spawnfunc_light program for switchable lights

	// 63 testing
	lightstyle(63, "a");

666
	if(autocvar_g_campaign)
667 668 669 670
		CampaignPreInit();

	Map_MarkAsRecent(mapname);

671
	PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
672

673 674 675 676 677 678
	precache_model ("null"); // we need this one before InitGameplayMode
	InitGameplayMode();
	readlevelcvars();
	GrappleHookInit();

	player_count = 0;
679
	bot_waypoints_for_items = autocvar_g_waypoints_for_items;
680 681 682 683 684 685 686 687 688
	if(bot_waypoints_for_items == 1)
		if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
			bot_waypoints_for_items = 0;

	precache();

	WaypointSprite_Init();

	GameLogInit(); // prepare everything
689 690 691 692
	// NOTE for matchid:
	// changing the logic generating it is okay. But:
	// it HAS to stay <= 64 chars
	// character set: ASCII 33-126 without the following characters: : ; ' " \ $
693
	if(autocvar_sv_eventlog)
694
	{
695
		s = sprintf("%d.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
696 697 698 699
		matchid = strzone(s);

		GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
		s = ":gameinfo:mutators:LIST";
700 701 702 703 704

		ret_string = s;
		MUTATOR_CALLHOOK(BuildMutatorsString);
		s = ret_string;

705
		// simple, probably not good in the mutator system
706
		if(autocvar_g_grappling_hook)
707
			s = strcat(s, ":grappling_hook");
708 709

		// initialiation stuff, not good in the mutator system
710
		if(!autocvar_g_use_ammunition)
711
			s = strcat(s, ":no_use_ammunition");
712 713

		// initialiation stuff, not good in the mutator system
714
		if(autocvar_g_pickup_items == 0)
715
			s = strcat(s, ":no_pickup_items");
716 717
		if(autocvar_g_pickup_items > 0)
			s = strcat(s, ":pickup_items");
718 719

		// initialiation stuff, not good in the mutator system
720 721
		if(autocvar_g_weaponarena != "0")
			s = strcat(s, ":", autocvar_g_weaponarena, " arena");
722 723

		// TODO to mutator system
724
		if(autocvar_g_norecoil)
725
			s = strcat(s, ":norecoil");
726

727
		// TODO to mutator system
728
		if(autocvar_g_powerups == 0)
729
			s = strcat(s, ":no_powerups");
730 731
		if(autocvar_g_powerups > 0)
			s = strcat(s, ":powerups");
732

733 734 735 736 737 738 739 740 741 742
		GameLogEcho(s);
		GameLogEcho(":gameinfo:end");
	}
	else
		matchid = strzone(ftos(random()));

	cvar_set("nextmap", "");

	SetDefaultAlpha();

743
	if(autocvar_g_campaign)
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
		CampaignPostInit();

	Ban_LoadBans();

	MapInfo_Enumerate();
	MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);

	if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
	{
		fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
		if(fd != -1)
		{
			while((s = fgets(fd)))
			{
				l = tokenize_console(s);
				if(l < 2)
					continue;
				if(argv(0) == "cd")
				{
763
					print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
764 765 766 767
					print("  cdtrack ", argv(2), "\n");
				}
				else if(argv(0) == "fog")
				{
768
					print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
769 770 771 772
					print("  \"fog\" \"", s, "\"\n");
				}
				else if(argv(0) == "set")
				{
773
					print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
774 775 776 777
					print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
				}
				else if(argv(0) != "//")
				{
778
					print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
779 780 781 782 783 784 785 786 787
					print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
				}
			}
			fclose(fd);
		}
	}

	WeaponStats_Init();

788
	WepSet_AddStat();
789
	WepSet_AddStat_InMap();
790
	addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
791
	addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
792
	addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
793
	addstat(STAT_ROUNDSTARTTIME, AS_FLOAT, stat_round_starttime);
Mario's avatar
Mario committed
794
	addstat(STAT_ALLOW_OLDVORTEXBEAM, AS_INT, stat_allow_oldvortexbeam);
795 796 797 798
	Nagger_Init();

	addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
	addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
799
	addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
800 801
	addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
	addstat(STAT_FUEL, AS_INT, ammo_fuel);
Mario's avatar
Mario committed
802
	addstat(STAT_PLASMA, AS_INT, ammo_plasma);
803 804
	addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
	addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
Mircea Kitsune's avatar
Mircea Kitsune committed
805 806
	addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
	addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
807
	addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
808
	addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
809
	addstat(STAT_DAMAGE_DEALT_TOTAL, AS_INT, damage_dealt_total);
Rudolf Polzer's avatar
Rudolf Polzer committed
810
	addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
811
	addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
812

Mario's avatar
Mario committed
813 814
	addstat(STAT_VORTEX_CHARGE, AS_FLOAT, vortex_charge);
	addstat(STAT_VORTEX_CHARGEPOOL, AS_FLOAT, vortex_chargepool_ammo);
815

816
	addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
TimePath's avatar
TimePath committed
817

Mario's avatar
Mario committed
818
	addstat(STAT_ARC_HEAT, AS_FLOAT, arc_heat_percent);
819

820
	// items time
821 822 823 824
	addstat(STAT_ARMOR_LARGE_TIME, AS_FLOAT, item_armor_large_time);
	addstat(STAT_HEALTH_MEGA_TIME, AS_FLOAT, item_health_mega_time);
	addstat(STAT_INVISIBLE_TIME, AS_FLOAT, item_invisible_time);
	addstat(STAT_SPEED_TIME, AS_FLOAT, item_speed_time);
825 826
	addstat(STAT_EXTRALIFE_TIME, AS_FLOAT, item_extralife_time);
	addstat(STAT_STRENGTH_TIME, AS_FLOAT, item_strength_time);
827 828 829
	addstat(STAT_SHIELD_TIME, AS_FLOAT, item_shield_time);
	addstat(STAT_FUELREGEN_TIME, AS_FLOAT, item_fuelregen_time);
	addstat(STAT_JETPACK_TIME, AS_FLOAT, item_jetpack_time);
830
	addstat(STAT_SUPERWEAPONS_TIME, AS_FLOAT, item_superweapons_time);
831
	Item_ItemsTime_Init();
832

833 834 835
	// freeze attacks
	addstat(STAT_FROZEN, AS_INT, frozen);
	addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, revive_progress);
836

837 838
	// physics
	Physics_AddStats();
839

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	// new properties
	addstat(STAT_MOVEVARS_JUMPVELOCITY, AS_FLOAT, stat_sv_jumpvelocity);
	addstat(STAT_MOVEVARS_AIRACCEL_QW_STRETCHFACTOR, AS_FLOAT, stat_sv_airaccel_qw_stretchfactor);
	addstat(STAT_MOVEVARS_MAXAIRSTRAFESPEED, AS_FLOAT, stat_sv_maxairstrafespeed);
	addstat(STAT_MOVEVARS_MAXAIRSPEED, AS_FLOAT, stat_sv_maxairspeed);
	addstat(STAT_MOVEVARS_AIRSTRAFEACCELERATE, AS_FLOAT, stat_sv_airstrafeaccelerate);
	addstat(STAT_MOVEVARS_WARSOWBUNNY_TURNACCEL, AS_FLOAT, stat_sv_warsowbunny_turnaccel);
	addstat(STAT_MOVEVARS_AIRACCEL_SIDEWAYS_FRICTION, AS_FLOAT, stat_sv_airaccel_sideways_friction);
	addstat(STAT_MOVEVARS_AIRCONTROL, AS_FLOAT, stat_sv_aircontrol);
	addstat(STAT_MOVEVARS_AIRCONTROL_POWER, AS_FLOAT, stat_sv_aircontrol_power);
	addstat(STAT_MOVEVARS_AIRCONTROL_PENALTY, AS_FLOAT, stat_sv_aircontrol_penalty);
	addstat(STAT_MOVEVARS_WARSOWBUNNY_AIRFORWARDACCEL, AS_FLOAT, stat_sv_warsowbunny_airforwardaccel);
	addstat(STAT_MOVEVARS_WARSOWBUNNY_TOPSPEED, AS_FLOAT, stat_sv_warsowbunny_topspeed);
	addstat(STAT_MOVEVARS_WARSOWBUNNY_ACCEL, AS_FLOAT, stat_sv_warsowbunny_accel);
	addstat(STAT_MOVEVARS_WARSOWBUNNY_BACKTOSIDERATIO, AS_FLOAT, stat_sv_warsowbunny_backtosideratio);
	addstat(STAT_MOVEVARS_FRICTION, AS_FLOAT, stat_sv_friction);
	addstat(STAT_MOVEVARS_ACCELERATE, AS_FLOAT, stat_sv_accelerate);
	addstat(STAT_MOVEVARS_STOPSPEED, AS_FLOAT, stat_sv_stopspeed);
	addstat(STAT_MOVEVARS_AIRACCELERATE, AS_FLOAT, stat_sv_airaccelerate);
	addstat(STAT_MOVEVARS_AIRSTOPACCELERATE, AS_FLOAT, stat_sv_airstopaccelerate);
860

861 862 863
	// secrets
	addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
	addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
864

Mario's avatar
Mario committed
865 866 867
	// monsters
	addstat(STAT_MONSTERS_TOTAL, AS_FLOAT, stat_monsters_total);
	addstat(STAT_MONSTERS_KILLED, AS_FLOAT, stat_monsters_killed);
868 869

	// misc
Mircea Kitsune's avatar
Mircea Kitsune committed
870
	addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
871

872 873 874
	next_pingtime = time + 5;

	detect_maptype();
875

876
	// set up information replies for clients and server to use
877
	maplist_reply = strzone(getmaplist());
878
	lsmaps_reply = strzone(getlsmaps());
879
	monsterlist_reply = strzone(getmonsterlist());
TimePath's avatar
TimePath committed
880
	for(int i = 0; i < 10; ++i)
881
	{
882 883 884
		s = getrecords(i);
		if (s)
			records_reply[i] = strzone(s);
885
	}
886
	ladder_reply = strzone(getladder());
887 888
	rankings_reply = strzone(getrankings());

889
	// begin other init
890 891 892 893 894 895
	ClientInit_Spawn();
	RandomSeed_Spawn();
	PingPLReport_Spawn();

	CheatInit();

896
	localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
897

898
	// fill sv_curl_serverpackages from .serverpackage files
899
	if(autocvar_sv_curl_serverpackages_auto)
900 901
	{
		s = "";
Rudolf Polzer's avatar
Rudolf Polzer committed
902
		n = tokenize_console(cvar_string("sv_curl_serverpackages"));
TimePath's avatar
TimePath committed
903
		for(int i = 0; i < n; ++i)
904
			if(substring(argv(i), -18, -1) != "-serverpackage.txt")
905
			if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
906
				s = strcat(s, " ", argv(i));
TimePath's avatar
TimePath committed
907
		fd = search_begin("*-serverpackage.txt", true, false);
908 909 910
		if(fd >= 0)
		{
			j = search_getsize(fd);
TimePath's avatar
TimePath committed
911
			for(int i = 0; i < j; ++i)
912 913 914
				s = strcat(s, " ", search_getfilename(fd, i));
			search_end(fd);
		}
TimePath's avatar
TimePath committed
915
		fd = search_begin("*.serverpackage", true, false);
Rudolf Polzer's avatar
Rudolf Polzer committed
916 917 918
		if(fd >= 0)
		{
			j = search_getsize(fd);
TimePath's avatar
TimePath committed
919
			for(int i = 0; i < j; ++i)
Rudolf Polzer's avatar
Rudolf Polzer committed
920 921 922
				s = strcat(s, " ", search_getfilename(fd, i));
			search_end(fd);
		}
923 924 925
		cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
	}

926
	// MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
927 928 929 930 931 932 933 934
	modname = "Xonotic";
	// physics/balance/config changes that count as mod
	if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
		modname = cvar_string("g_mod_physics");
	if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
		modname = cvar_string("g_mod_balance");
	if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
		modname = cvar_string("g_mod_config");
935 936
	// extra mutators that deserve to count as mod
	MUTATOR_CALLHOOK(SetModname);
937

938
	// save it for later
939 940
	modname = strzone(modname);

941 942
	WinningConditionHelper(); // set worldstatus

943 944 945 946 947 948 949 950 951 952 953
	world_initialized = 1;
}

void spawnfunc_light (void)
{
	//makestatic (self); // Who the f___ did that?
	remove(self);
}

string GetGametype()
{
954
	return MapInfo_Type_ToString(MapInfo_LoadedGametype);
955 956 957 958 959 960 961 962 963 964
}

string GetMapname()
{
	return mapname;
}

float Map_Count, Map_Current;
string Map_Current_Name;

965
// NOTE: this now expects the map list to be already tokenized and the count in Map_Count
966 967 968 969 970 971
float GetMaplistPosition()
{
	float pos, idx;
	string map;

	map = GetMapname();
972
	idx = autocvar_g_maplist_index;
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

	if(idx >= 0)
		if(idx < Map_Count)
			if(map == argv(idx))
				return idx;

	for(pos = 0; pos < Map_Count; ++pos)
		if(map == argv(pos))
			return pos;

	// resume normal maplist rotation if current map is not in g_maplist
	return idx;
}

float MapHasRightSize(string map)
{
	float fh;
990 991
	if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
	if(autocvar_g_maplist_check_waypoints)
992 993
	{
		dprint("checkwp "); dprint(map);
994
		if(!fexists(strcat("maps/", map, ".waypoints")))
995 996
		{
			dprint(": no waypoints\n");
TimePath's avatar
TimePath committed
997
			return false;
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
		}
		dprint(": has waypoints\n");
	}

	// open map size restriction file
	dprint("opensize "); dprint(map);
	fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
	if(fh >= 0)
	{
		float mapmin, mapmax;
		dprint(": ok, ");
		mapmin = stof(fgets(fh));
		mapmax = stof(fgets(fh));
		fclose(fh);
		if(player_count < mapmin)
		{
			dprint("not enough\n");
TimePath's avatar
TimePath committed
1015
			return false;
1016 1017 1018 1019
		}
		if(player_count > mapmax)
		{
			dprint("too many\n");
TimePath's avatar
TimePath committed
1020
			return false;
1021 1022
		}
		dprint("right size\n");
TimePath's avatar
TimePath committed
1023
		return true;
1024 1025
	}
	dprint(": not found\n");
TimePath's avatar
TimePath committed
1026
	return true;
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
}

string Map_Filename(float position)
{
	return strcat("maps/", argv(position), ".bsp");
}

string strwords(string s, float w)
{
	float endpos;
	for(endpos = 0; w && endpos >= 0; --w)
		endpos = strstrofs(s, " ", endpos + 1);
	if(endpos < 0)
		return s;
	else
		return substring(s, 0, endpos);
}

float strhasword(string s, string w)
{
	return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
}

void Map_MarkAsRecent(string m)
{
1052
	cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1053 1054 1055 1056
}

float Map_IsRecent(string m)
{
1057
	return strhasword(autocvar_g_maplist_mostrecent, m);
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
}

float Map_Check(float position, float pass)
{
	string filename;
	string map_next;
	map_next = argv(position);
	if(pass <= 1)
	{
		if(Map_IsRecent(map_next))
			return 0;
	}
	filename = Map_Filename(position);
	if(MapInfo_CheckMap(map_next))
	{
		if(pass == 2)
			return 1;
		if(MapHasRightSize(map_next))
			return 1;
		return 0;
	}
	else
		dprint( "Couldn't select '", filename, "'..\n" );

	return 0;
}

void Map_Goto_SetStr(string nextmapname)
{
	if(getmapname_stored != "")
		strunzone(getmapname_stored);
	if(nextmapname == "")
		getmapname_stored = "";
	else
		getmapname_stored = strzone(nextmapname);
}

void Map_Goto_SetFloat(float position)
{
	cvar_set("g_maplist_index", ftos(position));
	Map_Goto_SetStr(argv(position));
}

1101
void Map_Goto(float reinit)
1102
{
1103
	MapInfo_LoadMap(getmapname_stored, reinit);
1104 1105 1106 1107 1108 1109 1110 1111 1112
}

// return codes of map selectors:
//   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
//   -2 = permanent failure
float() MaplistMethod_Iterate = // usual method
{
	float pass, i;

1113 1114
	dprint("Trying MaplistMethod_Iterate\n");

1115 1116 1117 1118 1119
	for(pass = 1; pass <= 2; ++pass)
	{
		for(i = 1; i < Map_Count; ++i)
		{
			float mapindex;
1120
			mapindex = (i + Map_Current) % Map_Count;
1121 1122 1123 1124 1125 1126 1127 1128 1129
			if(Map_Check(mapindex, pass))
				return mapindex;
		}
	}
	return -1;
}

float() MaplistMethod_Repeat = // fallback method
{
1130 1131
	dprint("Trying MaplistMethod_Repeat\n");

1132 1133 1134 1135 1136 1137 1138 1139 1140
	if(Map_Check(Map_Current, 2))
		return Map_Current;
	return -2;
}

float() MaplistMethod_Random = // random map selection
{
	float i, imax;

1141 1142
	dprint("Trying MaplistMethod_Random\n");

1143 1144 1145 1146 1147
	imax = 42;

	for(i = 0; i <= imax; ++i)
	{
		float mapindex;
1148
		mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
		if(Map_Check(mapindex, 1))
			return mapindex;
	}
	return -1;
}

float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
// the exponent sets a bias on the map selection:
// the higher the exponent, the less likely "shortly repeated" same maps are
{
	float i, j, imax, insertpos;

1161 1162
	dprint("Trying MaplistMethod_Shuffle\n");

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
	imax = 42;

	for(i = 0; i <= imax; ++i)
	{
		string newlist;

		// now reinsert this at another position
		insertpos = pow(random(), 1 / exponent);       // ]0, 1]
		insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
		insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
		dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");

		// insert the current map there
		newlist = "";
		for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
			newlist = strcat(newlist, " ", argv(j));
		newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
		for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
			newlist = strcat(newlist, " ", argv(j));
		newlist = substring(newlist, 1, strlen(newlist) - 1);
		cvar_set("g_maplist", newlist);
1184
		Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195

		// NOTE: the selected map has just been inserted at (insertpos-1)th position
		Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
		if(Map_Check(Map_Current, 1))
			return Map_Current;
	}
	return -1;
}

void Maplist_Init()
{
1196
	Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1197 1198 1199 1200 1201
	float i;
	for (i = 0; i < Map_Count; ++i)
		if (Map_Check(i, 2))
			break;
	if (i == Map_Count)
1202
	{
1203 1204
		bprint( "Maplist contains no usable maps!  Resetting it to default map list.\n" );
		cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1205
		if(autocvar_g_maplist_shuffle)
1206 1207
			ShuffleMaplist();
		localcmd("\nmenu_cmd sync\n");
1208
		Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
	}
	if(Map_Count == 0)
		error("empty maplist, cannot select a new map");
	Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);

	if(Map_Current_Name)
		strunzone(Map_Current_Name);
	Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
	// this may or may not be correct, but who cares, in the worst case a map
	// isn't chosen in the first pass that should have been
}

string GetNextMap()
{
	float nextMap;

	Maplist_Init();
	nextMap = -1;

	if(nextMap == -1)
1229 1230
		if(autocvar_g_maplist_shuffle > 0)
			nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1231 1232

	if(nextMap == -1)
1233
		if(autocvar_g_maplist_selectrandom)
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
			nextMap = MaplistMethod_Random();

	if(nextMap == -1)
		nextMap = MaplistMethod_Iterate();

	if(nextMap == -1)
		nextMap = MaplistMethod_Repeat();

	if(nextMap >= 0)
	{
		Map_Goto_SetFloat(nextMap);
		return getmapname_stored;
	}

	return "";
1249
}
1250

1251
float DoNextMapOverride(float reinit)
1252
{
1253
	if(autocvar_g_campaign)
1254 1255
	{
		CampaignPostIntermission();
TimePath's avatar
TimePath committed
1256 1257
		alreadychangedlevel = true;
		return true;
1258
	}
1259
	if(autocvar_quit_when_empty)
1260 1261 1262 1263
	{
		if(player_count <= currentbots)
		{
			localcmd("quit\n");
TimePath's avatar
TimePath committed
1264 1265
			alreadychangedlevel = true;
			return true;
1266 1267
		}
	}
1268
	if(autocvar_quit_and_redirect != "")
1269
	{
1270
		redirection_target = strzone(autocvar_quit_and_redirect);
TimePath's avatar
TimePath committed
1271 1272
		alreadychangedlevel = true;
		return true;
1273
	}
1274
	if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1275 1276
	{
		localcmd("restart\n");
TimePath's avatar
TimePath committed
1277 1278
		alreadychangedlevel = true;
		return true;
1279
	}
1280
	if(autocvar_nextmap != "")
1281 1282 1283 1284
	{
		string m;
		m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
		cvar_set("nextmap",m);
TimePath's avatar
TimePath committed
1285

1286
		if(!m || gametypevote)
TimePath's avatar
TimePath committed
1287
			return false;
1288
		if(autocvar_sv_vote_gametype)
1289
		{
1290
			Map_Goto_SetStr(m);
TimePath's avatar
TimePath committed
1291
			return false;
1292
		}
TimePath's avatar
TimePath committed
1293

1294
		if(MapInfo_CheckMap(m))
1295
		{
1296
			Map_Goto_SetStr(m);
1297
			Map_Goto(reinit);
TimePath's avatar
TimePath committed
1298 1299
			alreadychangedlevel = true;
			return true;
1300
		}
1301
	}
1302
	if(!reinit && autocvar_lastlevel)
1303
	{
1304 1305
		cvar_settemp_restore();
		localcmd("set lastlevel 0\ntogglemenu 1\n");
TimePath's avatar
TimePath committed
1306 1307
		alreadychangedlevel = true;
		return true;
1308
	}
TimePath's avatar
TimePath committed
1309
	return false;
1310
}
1311

1312
void GotoNextMap(float reinit)
1313
{
1314 1315 1316
	//string nextmap;
	//float n, nummaps;
	//string s;
1317 1318
	if (alreadychangedlevel)
		return;
TimePath's avatar
TimePath committed
1319
	alreadychangedlevel = true;
1320

1321
	string nextMap;
1322

1323 1324 1325
	nextMap = GetNextMap();
	if(nextMap == "")
		error("Everything is broken - cannot find a next map. Please report this to the developers.");
1326
	Map_Goto(reinit);
1327
}
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340


/*
============
IntermissionThink

When the player presses attack or jump, change to the next level
============
*/
.float autoscreenshot;
void IntermissionThink()
{
	FixIntermissionClient(self);
1341

1342 1343
	float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
	float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1344

1345
	if( (server_screenshot || client_screenshot)
1346
		&& ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1347 1348
	{
		self.autoscreenshot = -1;
TimePath's avatar
TimePath committed
1349
		if(IS_REAL_CLIENT(self)) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(false, "%s"))); }
1350 1351 1352 1353 1354 1355 1356
		return;
	}

	if (time < intermission_exittime)
		return;

	if(!mapvote_initialized)
Rudolf Polzer's avatar
Rudolf Polzer committed
1357
		if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1358 1359 1360
			return;

	MapVote_Start();
1361
}
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407

/*
============
FindIntermission

Returns the entity to view from
============
*/
/*
entity FindIntermission()
{
	local	entity spot;
	local	float cyc;

// look for info_intermission first
	spot = find (world, classname, "info_intermission");
	if (spot)
	{	// pick a random one
		cyc = random() * 4;
		while (cyc > 1)
		{
			spot = find (spot, classname, "info_intermission");
			if (!spot)
				spot = find (spot, classname, "info_intermission");
			cyc = cyc - 1;
		}
		return spot;
	}

// then look for the start position
	spot = find (world, classname, "info_player_start");
	if (spot)
		return spot;

// testinfo_player_start is only found in regioned levels
	spot = find (world, classname, "testplayerstart");
	if (spot)
		return spot;

// then look for the start position
	spot = find (world, classname, "info_player_deathmatch");
	if (spot)
		return spot;

	//objerror ("FindIntermission: no spot");
	return world;
1408
}
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
*/

/*
===============================================================================

RULES

===============================================================================
*/

void DumpStats(float final)
{
1421 1422 1423 1424 1425 1426
	float file;
	string s;
	float to_console;
	float to_eventlog;
	float to_file;
	float i;
1427

1428 1429 1430
	to_console = autocvar_sv_logscores_console;
	to_eventlog = autocvar_sv_eventlog;
	to_file = autocvar_sv_logscores_file;
1431 1432 1433

	if(!final)
	{
TimePath's avatar
TimePath committed
1434 1435
		to_console = true; // always print printstats replies
		to_eventlog = false; // but never print them to the event log
1436 1437 1438
	}

	if(to_eventlog)
1439
		if(autocvar_sv_eventlog_console)
TimePath's avatar
TimePath committed
1440
			to_console = false; // otherwise we get the output twice
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451

	if(final)
		s = ":scores:";
	else
		s = ":status:";
	s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));

	if(to_console)
		print(s, "\n");
	if(to_eventlog)
		GameLogEcho(s);
1452 1453

	file = -1;
1454 1455
	if(to_file)
	{
1456
		file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1457
		if(file == -1)
TimePath's avatar
TimePath committed
1458
			to_file = false;
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
		else
			fputs(file, strcat(s, "\n"));
	}

	s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
	if(to_console)
		print(s, "\n");
	if(to_eventlog)
		GameLogEcho(s);
	if(to_file)
		fputs(file, strcat(s, "\n"));

	FOR_EACH_CLIENT(other)
	{
1473
		if ((IS_REAL_CLIENT(other)) || (IS_BOT_CLIENT(other) && autocvar_sv_logscores_bots))
1474 1475 1476
		{
			s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
			s = strcat(s, ftos(rint(time - other.jointime)), ":");
Mario's avatar
Mario committed
1477
			if(IS_PLAYER(other) || other.caplayer == 1 || g_lms)
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
				s = strcat(s, ftos(other.team), ":");
			else
				s = strcat(s, "spectator:");

			if(to_console)
				print(s, other.netname, "\n");
			if(to_eventlog)
				GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
			if(to_file)
				fputs(file, strcat(s, other.netname, "\n"));
		}
	}

1491
	if(teamplay)
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
	{
		s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
		if(to_console)
			print(s, "\n");
		if(to_eventlog)
			GameLogEcho(s);
		if(to_file)
			fputs(file, strcat(s, "\n"));

		for(i = 1; i < 16; ++i)
		{
			s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
			s = strcat(s, ":", ftos(i));
			if(to_console)
				print(s, "\n");
			if(to_eventlog)
				GameLogEcho(s);
			if(to_file)
				fputs(file, strcat(s, "\n"));
		}
	}

	if(to_console)
		print(":end\n");
	if(to_eventlog)
		GameLogEcho(":end");
	if(to_file)
	{
		fputs(file, ":end\n");
		fclose(file);
	}
}

void FixIntermissionClient(entity e)
{
	string s;
	if(!e.autoscreenshot) // initial call
	{
		e.autoscreenshot = time + 0.8;	// used for autoscreenshot
		e.health = -2342;
		// first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
		e.solid = SOLID_NOT;
		e.movetype = MOVETYPE_NONE;
		e.takedamage = DAMAGE_NO;
		if(e.weaponentity)
		{
			e.weaponentity.effects = EF_NODRAW;
			if (e.weaponentity.weaponentity)
				e.weaponentity.weaponentity.effects = EF_NODRAW;
		}
1542
		if(IS_REAL_CLIENT(e))
1543 1544
		{
			stuffcmd(e, "\nscr_printspeed 1000000\n");
1545
			s = autocvar_sv_intermission_cdtrack;
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
			if(s != "")
				stuffcmd(e, strcat("\ncd loop ", s, "\n"));
			msg_entity = e;
			WriteByte(MSG_ONE, SVC_INTERMISSION);
		}
	}
}

/*
go to the next level for deathmatch
only called if a time or frag limit has expired
*/
void NextLevel()
{
TimePath's avatar
TimePath committed
1560
	gameover = true;
1561 1562 1563 1564 1565

	intermission_running = 1;

// enforce a wait time before allowing changelevel
	if(player_count > 0)
1566
		intermission_exittime = time + autocvar_sv_mapchange_delay;
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
	else
		intermission_exittime = -1;

	/*
	WriteByte (MSG_ALL, SVC_CDTRACK);
	WriteByte (MSG_ALL, 3);
	WriteByte (MSG_ALL, 3);
	// done in FixIntermission
	*/

	//pos = FindIntermission ();

	VoteReset();

TimePath's avatar
TimePath committed
1581
	DumpStats(true);
1582 1583

	// send statistics
TimePath's avatar
TimePath committed
1584
	PlayerStats_GameReport(true);
1585
	WeaponStats_Shutdown();
1586

Samual's avatar
Samual committed
1587
	Kill_Notification(NOTIF_ALL, world, MSG_CENTER, 0); // kill all centerprints now
1588

1589
	if(autocvar_sv_eventlog)
1590 1591 1592 1593
		GameLogEcho(":gameover");

	GameLogClose();

Rudolf Polzer's avatar
Rudolf Polzer committed
1594 1595 1596 1597
	FOR_EACH_PLAYER(other) {
		FixIntermissionClient(other);
		if(other.winning)
			bprint(other.netname, " ^7wins.\n");
1598 1599
	}

1600
	if(autocvar_g_campaign)
1601 1602
		CampaignPreIntermission();

1603 1604
	MUTATOR_CALLHOOK(MatchEnd);

1605
	localcmd("\nsv_hook_gameend\n");
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
}

/*
============
CheckRules_Player

Exit deathmatch games upon conditions
============
*/
void CheckRules_Player()
{
	if (gameover)	// someone else quit the game already