From: Lyberta Date: Sun, 10 Jun 2018 08:35:27 +0000 (+0300) Subject: Merge branch 'master' into Lyberta/TeamplayOverhaul X-Git-Tag: xonotic-v0.8.5~1953^2~12 X-Git-Url: https://git.rm.cloudns.org/?a=commitdiff_plain;h=76de60deecae125795551ba1a4576a265d7ae7de;p=xonotic%2Fxonotic-data.pk3dir.git Merge branch 'master' into Lyberta/TeamplayOverhaul --- 76de60deecae125795551ba1a4576a265d7ae7de diff --cc qcsrc/common/gamemodes/gamemode/assault/assault.qc index 000000000,ba3d996d1..1dc5c3f9c mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/assault/assault.qc +++ b/qcsrc/common/gamemodes/gamemode/assault/assault.qc @@@ -1,0 -1,628 +1,628 @@@ + #include "assault.qh" + + // TODO: split into sv_assault + #ifdef SVQC + .entity sprite; + #define AS_ROUND_DELAY 5 + + IntrusiveList g_assault_destructibles; + IntrusiveList g_assault_objectivedecreasers; + IntrusiveList g_assault_objectives; + STATIC_INIT(g_assault) + { + g_assault_destructibles = IL_NEW(); + g_assault_objectivedecreasers = IL_NEW(); + g_assault_objectives = IL_NEW(); + } + + // random functions + void assault_objective_use(entity this, entity actor, entity trigger) + { + // activate objective + this.health = 100; + //print("^2Activated objective ", this.targetname, "=", etos(this), "\n"); + //print("Activator is ", actor.classname, "\n"); + + IL_EACH(g_assault_objectivedecreasers, it.target == this.targetname, + { + target_objective_decrease_activate(it); + }); + } + + vector target_objective_spawn_evalfunc(entity this, entity player, entity spot, vector current) + { + if(this.health < 0 || this.health >= ASSAULT_VALUE_INACTIVE) + return '-1 0 0'; + return current; + } + + // reset this objective. Used when spawning an objective + // and when a new round starts + void assault_objective_reset(entity this) + { + this.health = ASSAULT_VALUE_INACTIVE; + } + + // decrease the health of targeted objectives + void assault_objective_decrease_use(entity this, entity actor, entity trigger) + { + if(actor.team != assault_attacker_team) + { + // wrong team triggered decrease + return; + } + + if(trigger.assault_sprite) + { + WaypointSprite_Disown(trigger.assault_sprite, waypointsprite_deadlifetime); + if(trigger.classname == "func_assault_destructible") + trigger.sprite = NULL; // TODO: just unsetting it?! + } + else + return; // already activated! cannot activate again! + + if(this.enemy.health < ASSAULT_VALUE_INACTIVE) + { + if(this.enemy.health - this.dmg > 0.5) + { + GameRules_scoring_add_team(actor, SCORE, this.dmg); + this.enemy.health = this.enemy.health - this.dmg; + } + else + { + GameRules_scoring_add_team(actor, SCORE, this.enemy.health); + GameRules_scoring_add_team(actor, ASSAULT_OBJECTIVES, 1); + this.enemy.health = -1; + + if(this.enemy.message) + FOREACH_CLIENT(IS_PLAYER(it), { centerprint(it, this.enemy.message); }); + + SUB_UseTargets(this.enemy, this, trigger); + } + } + } + + void assault_setenemytoobjective(entity this) + { + IL_EACH(g_assault_objectives, it.targetname == this.target, + { + if(this.enemy == NULL) + this.enemy = it; + else + objerror(this, "more than one objective as target - fix the map!"); + break; + }); + + if(this.enemy == NULL) + objerror(this, "no objective as target - fix the map!"); + } + + bool assault_decreaser_sprite_visible(entity this, entity player, entity view) + { + if(this.assault_decreaser.enemy.health >= ASSAULT_VALUE_INACTIVE) + return false; + + return true; + } + + void target_objective_decrease_activate(entity this) + { + entity spr; + this.owner = NULL; + FOREACH_ENTITY_STRING(target, this.targetname, + { + if(it.assault_sprite != NULL) + { + WaypointSprite_Disown(it.assault_sprite, waypointsprite_deadlifetime); + if(it.classname == "func_assault_destructible") + it.sprite = NULL; // TODO: just unsetting it?! + } + + spr = WaypointSprite_SpawnFixed(WP_AssaultDefend, 0.5 * (it.absmin + it.absmax), it, assault_sprite, RADARICON_OBJECTIVE); + spr.assault_decreaser = this; + spr.waypointsprite_visible_for_player = assault_decreaser_sprite_visible; + spr.classname = "sprite_waypoint"; + WaypointSprite_UpdateRule(spr, assault_attacker_team, SPRITERULE_TEAMPLAY); + if(it.classname == "func_assault_destructible") + { + WaypointSprite_UpdateSprites(spr, WP_AssaultDefend, WP_AssaultDestroy, WP_AssaultDestroy); + WaypointSprite_UpdateMaxHealth(spr, it.max_health); + WaypointSprite_UpdateHealth(spr, it.health); + it.sprite = spr; + } + else + WaypointSprite_UpdateSprites(spr, WP_AssaultDefend, WP_AssaultPush, WP_AssaultPush); + }); + } + + void target_objective_decrease_findtarget(entity this) + { + assault_setenemytoobjective(this); + } + + void target_assault_roundend_reset(entity this) + { + //print("round end reset\n"); + ++this.cnt; // up round counter + this.winning = false; // up round + } + + void target_assault_roundend_use(entity this, entity actor, entity trigger) + { + this.winning = 1; // round has been won by attackers + } + + void assault_roundstart_use(entity this, entity actor, entity trigger) + { + SUB_UseTargets(this, this, trigger); + + //(Re)spawn all turrets + IL_EACH(g_turrets, true, + { + // Swap turret teams + if(it.team == NUM_TEAM_1) + it.team = NUM_TEAM_2; + else + it.team = NUM_TEAM_1; + + // Doubles as teamchange + turret_respawn(it); + }); + } + void assault_roundstart_use_this(entity this) + { + assault_roundstart_use(this, NULL, NULL); + } + + void assault_wall_think(entity this) + { + if(this.enemy.health < 0) + { + this.model = ""; + this.solid = SOLID_NOT; + } + else + { + this.model = this.mdl; + this.solid = SOLID_BSP; + } + + this.nextthink = time + 0.2; + } + + // trigger new round + // reset objectives, toggle spawnpoints, reset triggers, ... + void assault_new_round(entity this) + { + //bprint("ASSAULT: new round\n"); + + // up round counter + this.winning = this.winning + 1; + + // swap attacker/defender roles + if(assault_attacker_team == NUM_TEAM_1) + assault_attacker_team = NUM_TEAM_2; + else + assault_attacker_team = NUM_TEAM_1; + + IL_EACH(g_saved_team, !IS_CLIENT(it), + { + if(it.team_saved == NUM_TEAM_1) + it.team_saved = NUM_TEAM_2; + else if(it.team_saved == NUM_TEAM_2) + it.team_saved = NUM_TEAM_1; + }); + + // reset the level with a countdown + cvar_set("timelimit", ftos(ceil(time - AS_ROUND_DELAY - game_starttime) / 60)); + ReadyRestart_force(); // sets game_starttime + } + + entity as_round; + .entity ent_winning; + void as_round_think() + { + game_stopped = false; + assault_new_round(as_round.ent_winning); + delete(as_round); + as_round = NULL; + } + + // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives) + // they win. Otherwise the defending team wins once the timelimit passes. + int WinningCondition_Assault() + { + if(as_round) + return WINNING_NO; + + WinningConditionHelper(NULL); // set worldstatus + + int status = WINNING_NO; + // as the timelimit has not yet passed just assume the defending team will win + if(assault_attacker_team == NUM_TEAM_1) + { + SetWinners(team, NUM_TEAM_2); + } + else + { + SetWinners(team, NUM_TEAM_1); + } + + entity ent; + ent = find(NULL, classname, "target_assault_roundend"); + if(ent) + { + if(ent.winning) // round end has been triggered by attacking team + { + bprint("Assault: round completed.\n"); + SetWinners(team, assault_attacker_team); + + TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0)); + + if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round + { + status = WINNING_YES; + } + else + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ASSAULT_OBJ_DESTROYED, ceil(time - game_starttime)); + as_round = new(as_round); + as_round.think = as_round_think; + as_round.ent_winning = ent; + as_round.nextthink = time + AS_ROUND_DELAY; + game_stopped = true; + + // make sure timelimit isn't hit while the game is blocked + if(autocvar_timelimit > 0) + if(time + AS_ROUND_DELAY >= game_starttime + autocvar_timelimit * 60) + cvar_set("timelimit", ftos(autocvar_timelimit + AS_ROUND_DELAY / 60)); + } + } + } + + return status; + } + + // spawnfuncs + spawnfunc(info_player_attacker) + { + if (!g_assault) { delete(this); return; } + + this.team = NUM_TEAM_1; // red, gets swapped every round + spawnfunc_info_player_deathmatch(this); + } + + spawnfunc(info_player_defender) + { + if (!g_assault) { delete(this); return; } + + this.team = NUM_TEAM_2; // blue, gets swapped every round + spawnfunc_info_player_deathmatch(this); + } + + spawnfunc(target_objective) + { + if (!g_assault) { delete(this); return; } + + this.classname = "target_objective"; + IL_PUSH(g_assault_objectives, this); + this.use = assault_objective_use; + this.reset = assault_objective_reset; + this.reset(this); + this.spawn_evalfunc = target_objective_spawn_evalfunc; + } + + spawnfunc(target_objective_decrease) + { + if (!g_assault) { delete(this); return; } + + this.classname = "target_objective_decrease"; + IL_PUSH(g_assault_objectivedecreasers, this); + + if(!this.dmg) + this.dmg = 101; + + this.use = assault_objective_decrease_use; + this.health = ASSAULT_VALUE_INACTIVE; + this.max_health = ASSAULT_VALUE_INACTIVE; + this.enemy = NULL; + + InitializeEntity(this, target_objective_decrease_findtarget, INITPRIO_FINDTARGET); + } + + // destructible walls that can be used to trigger target_objective_decrease + spawnfunc(func_breakable); + spawnfunc(func_assault_destructible) + { + if (!g_assault) { delete(this); return; } + + this.spawnflags = 3; + this.classname = "func_assault_destructible"; + IL_PUSH(g_assault_destructibles, this); + + if(assault_attacker_team == NUM_TEAM_1) + this.team = NUM_TEAM_2; + else + this.team = NUM_TEAM_1; + + spawnfunc_func_breakable(this); + } + + spawnfunc(func_assault_wall) + { + if (!g_assault) { delete(this); return; } + + this.classname = "func_assault_wall"; + this.mdl = this.model; + _setmodel(this, this.mdl); + this.solid = SOLID_BSP; + setthink(this, assault_wall_think); + this.nextthink = time; + InitializeEntity(this, assault_setenemytoobjective, INITPRIO_FINDTARGET); + } + + spawnfunc(target_assault_roundend) + { + if (!g_assault) { delete(this); return; } + + this.winning = 0; // round not yet won by attackers + this.classname = "target_assault_roundend"; + this.use = target_assault_roundend_use; + this.cnt = 0; // first round + this.reset = target_assault_roundend_reset; + } + + spawnfunc(target_assault_roundstart) + { + if (!g_assault) { delete(this); return; } + + assault_attacker_team = NUM_TEAM_1; + this.classname = "target_assault_roundstart"; + this.use = assault_roundstart_use; + this.reset2 = assault_roundstart_use_this; + InitializeEntity(this, assault_roundstart_use_this, INITPRIO_FINDTARGET); + } + + // legacy bot code + void havocbot_goalrating_ast_targets(entity this, float ratingscale) + { + IL_EACH(g_assault_destructibles, it.bot_attack, + { + if (it.target == "") + continue; + + bool found = false; + entity destr = it; + IL_EACH(g_assault_objectivedecreasers, it.targetname == destr.target, + { + if(it.enemy.health > 0 && it.enemy.health < ASSAULT_VALUE_INACTIVE) + { + found = true; + break; + } + }); + + if(!found) + continue; + + vector p = 0.5 * (it.absmin + it.absmax); + + // Find and rate waypoints around it + found = false; + entity best = NULL; + float bestvalue = 99999999999; + entity des = it; + for(float radius = 0; radius < 1500 && !found; radius += 500) + { + FOREACH_ENTITY_RADIUS(p, radius, it.classname == "waypoint" && !(it.wpflags & WAYPOINTFLAG_GENERATED), + { + if(checkpvs(it.origin, des)) + { + found = true; + if(it.cnt < bestvalue) + { + best = it; + bestvalue = it.cnt; + } + } + }); + } + + if(best) + { + /// dprint("waypoints around target were found\n"); + // te_lightning2(NULL, '0 0 0', best.origin); + // te_knightspike(best.origin); + + navigation_routerating(this, best, ratingscale, 4000); + best.cnt += 1; + + this.havocbot_attack_time = 0; + + if(checkpvs(this.origin + this.view_ofs, it)) + if(checkpvs(this.origin + this.view_ofs, best)) + { + // dprint("increasing attack time for this target\n"); + this.havocbot_attack_time = time + 2; + } + } + }); + } + + void havocbot_role_ast_offense(entity this) + { + if(IS_DEAD(this)) + { + this.havocbot_attack_time = 0; + havocbot_ast_reset_role(this); + return; + } + + // Set the role timeout if necessary + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + 120; + + if (time > this.havocbot_role_timeout) + { + havocbot_ast_reset_role(this); + return; + } + + if(this.havocbot_attack_time>time) + return; + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + havocbot_goalrating_enemyplayers(this, 20000, this.origin, 650); + havocbot_goalrating_ast_targets(this, 20000); + havocbot_goalrating_items(this, 15000, this.origin, 10000); + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_ast_defense(entity this) + { + if(IS_DEAD(this)) + { + this.havocbot_attack_time = 0; + havocbot_ast_reset_role(this); + return; + } + + // Set the role timeout if necessary + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + 120; + + if (time > this.havocbot_role_timeout) + { + havocbot_ast_reset_role(this); + return; + } + + if(this.havocbot_attack_time>time) + return; + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + havocbot_goalrating_enemyplayers(this, 20000, this.origin, 3000); + havocbot_goalrating_ast_targets(this, 20000); + havocbot_goalrating_items(this, 15000, this.origin, 10000); + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_ast_setrole(entity this, float role) + { + switch(role) + { + case HAVOCBOT_AST_ROLE_DEFENSE: + this.havocbot_role = havocbot_role_ast_defense; + this.havocbot_role_flags = HAVOCBOT_AST_ROLE_DEFENSE; + this.havocbot_role_timeout = 0; + break; + case HAVOCBOT_AST_ROLE_OFFENSE: + this.havocbot_role = havocbot_role_ast_offense; + this.havocbot_role_flags = HAVOCBOT_AST_ROLE_OFFENSE; + this.havocbot_role_timeout = 0; + break; + } + } + + void havocbot_ast_reset_role(entity this) + { + if(IS_DEAD(this)) + return; + + if(this.team == assault_attacker_team) + havocbot_role_ast_setrole(this, HAVOCBOT_AST_ROLE_OFFENSE); + else + havocbot_role_ast_setrole(this, HAVOCBOT_AST_ROLE_DEFENSE); + } + + // mutator hooks + MUTATOR_HOOKFUNCTION(as, PlayerSpawn) + { + entity player = M_ARGV(0, entity); + + if(player.team == assault_attacker_team) + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ASSAULT_ATTACKING); + else + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ASSAULT_DEFENDING); + } + + MUTATOR_HOOKFUNCTION(as, TurretSpawn) + { + entity turret = M_ARGV(0, entity); + + if(!turret.team || turret.team == FLOAT_MAX) + turret.team = 5; // this gets reversed when match starts? + } + + MUTATOR_HOOKFUNCTION(as, VehicleInit) + { + entity veh = M_ARGV(0, entity); + + veh.nextthink = time + 0.5; + } + + MUTATOR_HOOKFUNCTION(as, HavocBot_ChooseRole) + { + entity bot = M_ARGV(0, entity); + + havocbot_ast_reset_role(bot); + return true; + } + + MUTATOR_HOOKFUNCTION(as, PlayHitsound) + { + entity frag_victim = M_ARGV(0, entity); + + return (frag_victim.classname == "func_assault_destructible"); + } + -MUTATOR_HOOKFUNCTION(as, CheckAllowedTeams) ++MUTATOR_HOOKFUNCTION(as, TeamBalance_CheckAllowedTeams) + { + // assault always has 2 teams - c1 = c2 = 0; ++ M_ARGV(0, float) = BIT(0) | BIT(1); + return true; + } + + MUTATOR_HOOKFUNCTION(as, CheckRules_World) + { + M_ARGV(0, float) = WinningCondition_Assault(); + return true; + } + + MUTATOR_HOOKFUNCTION(as, ReadLevelCvars) + { + // incompatible + warmup_stage = 0; + sv_ready_restart_after_countdown = 0; + } + + MUTATOR_HOOKFUNCTION(as, OnEntityPreSpawn) + { + entity ent = M_ARGV(0, entity); + + switch(ent.classname) + { + case "info_player_team1": + case "info_player_team2": + case "info_player_team3": + case "info_player_team4": + return true; + } + } + + MUTATOR_HOOKFUNCTION(as, ReadyRestart_Deny) + { + // readyrestart not supported (yet) + return true; + } + #endif diff --cc qcsrc/common/gamemodes/gamemode/clanarena/clanarena.qc index 000000000,561129c7d..9b5457136 mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/clanarena/clanarena.qc +++ b/qcsrc/common/gamemodes/gamemode/clanarena/clanarena.qc @@@ -1,0 -1,491 +1,505 @@@ + #include "clanarena.qh" + + // TODO: split into sv_clanarena + #ifdef SVQC + float autocvar_g_ca_damage2score_multiplier; + bool autocvar_g_ca_spectate_enemies; + + void CA_count_alive_players() + { - total_players = redalive = bluealive = yellowalive = pinkalive = 0; - FOREACH_CLIENT(IS_PLAYER(it), { - switch(it.team) ++ total_players = 0; ++ for (int i = 1; i <= NUM_TEAMS; ++i) ++ { ++ Team_SetNumberOfAlivePlayers(Team_GetTeamFromIndex(i), 0); ++ } ++ FOREACH_CLIENT(IS_PLAYER(it) && Entity_HasValidTeam(it), ++ { ++ ++total_players; ++ if (IS_DEAD(it)) + { - case NUM_TEAM_1: ++total_players; if(!IS_DEAD(it)) ++redalive; break; - case NUM_TEAM_2: ++total_players; if(!IS_DEAD(it)) ++bluealive; break; - case NUM_TEAM_3: ++total_players; if(!IS_DEAD(it)) ++yellowalive; break; - case NUM_TEAM_4: ++total_players; if(!IS_DEAD(it)) ++pinkalive; break; ++ continue; + } ++ entity team_ = Entity_GetTeam(it); ++ int num_alive = Team_GetNumberOfAlivePlayers(team_); ++ ++num_alive; ++ Team_SetNumberOfAlivePlayers(team_, num_alive); + }); - FOREACH_CLIENT(IS_REAL_CLIENT(it), { - STAT(REDALIVE, it) = redalive; - STAT(BLUEALIVE, it) = bluealive; - STAT(YELLOWALIVE, it) = yellowalive; - STAT(PINKALIVE, it) = pinkalive; ++ FOREACH_CLIENT(IS_REAL_CLIENT(it), ++ { ++ STAT(REDALIVE, it) = Team_GetNumberOfAlivePlayers(Team_GetTeamFromIndex( ++ 1)); ++ STAT(BLUEALIVE, it) = Team_GetNumberOfAlivePlayers( ++ Team_GetTeamFromIndex(2)); ++ STAT(YELLOWALIVE, it) = Team_GetNumberOfAlivePlayers( ++ Team_GetTeamFromIndex(3)); ++ STAT(PINKALIVE, it) = Team_GetNumberOfAlivePlayers( ++ Team_GetTeamFromIndex(4)); + }); + } + -float CA_GetWinnerTeam() ++int CA_GetWinnerTeam() + { - float winner_team = 0; - if(redalive >= 1) - winner_team = NUM_TEAM_1; - if(bluealive >= 1) ++ int winner_team = 0; ++ if (Team_GetNumberOfAlivePlayers(Team_GetTeamFromIndex(1)) >= 1) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_2; ++ winner_team = NUM_TEAM_1; + } - if(yellowalive >= 1) ++ for (int i = 2; i <= NUM_TEAMS; ++i) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_3; ++ if (Team_GetNumberOfAlivePlayers(Team_GetTeamFromIndex(i)) >= 1) ++ { ++ if (winner_team != 0) ++ { ++ return 0; ++ } ++ winner_team = Team_IndexToTeam(i); ++ } + } - if(pinkalive >= 1) ++ if (winner_team) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_4; - } - if(winner_team) + return winner_team; ++ } + return -1; // no player left + } + + void nades_Clear(entity player); + -#define CA_ALIVE_TEAMS() ((redalive > 0) + (bluealive > 0) + (yellowalive > 0) + (pinkalive > 0)) -#define CA_ALIVE_TEAMS_OK() (CA_ALIVE_TEAMS() == NumTeams(ca_teams)) ++#define CA_ALIVE_TEAMS_OK() (Team_GetNumberOfAliveTeams() == NumTeams(ca_teams)) + float CA_CheckWinner() + { + if(round_handler_GetEndTime() > 0 && round_handler_GetEndTime() - time <= 0) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_OVER); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_OVER); + FOREACH_CLIENT(IS_PLAYER(it), { nades_Clear(it); }); + + allowed_to_spawn = false; + game_stopped = true; + round_handler_Init(5, autocvar_g_ca_warmup, autocvar_g_ca_round_timelimit); + return 1; + } + + CA_count_alive_players(); - if(CA_ALIVE_TEAMS() > 1) ++ if (Team_GetNumberOfAliveTeams() > 1) ++ { + return 0; ++ } + + int winner_team = CA_GetWinnerTeam(); + if(winner_team > 0) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(winner_team, CENTER_ROUND_TEAM_WIN)); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(winner_team, INFO_ROUND_TEAM_WIN)); + TeamScore_AddToTeam(winner_team, ST_CA_ROUNDS, +1); + } + else if(winner_team == -1) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_TIED); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_TIED); + } + + allowed_to_spawn = false; + game_stopped = true; + round_handler_Init(5, autocvar_g_ca_warmup, autocvar_g_ca_round_timelimit); + + FOREACH_CLIENT(IS_PLAYER(it), { nades_Clear(it); }); + + return 1; + } + + void CA_RoundStart() + { + allowed_to_spawn = boolean(warmup_stage); + } + + bool CA_CheckTeams() + { + static int prev_missing_teams_mask; + allowed_to_spawn = true; + CA_count_alive_players(); + if(CA_ALIVE_TEAMS_OK()) + { + if(prev_missing_teams_mask > 0) + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS); + prev_missing_teams_mask = -1; + return true; + } + if(total_players == 0) + { + if(prev_missing_teams_mask > 0) + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS); + prev_missing_teams_mask = -1; + return false; + } + int missing_teams_mask = 0; - if(ca_teams & BIT(0)) - missing_teams_mask += (!redalive) * 1; - if(ca_teams & BIT(1)) - missing_teams_mask += (!bluealive) * 2; - if(ca_teams & BIT(2)) - missing_teams_mask += (!yellowalive) * 4; - if(ca_teams & BIT(3)) - missing_teams_mask += (!pinkalive) * 8; ++ for (int i = 1; i <= NUM_TEAMS; ++i) ++ { ++ if ((ca_teams & Team_IndexToBit(i)) && ++ (Team_GetNumberOfAlivePlayers(Team_GetTeamFromIndex(i)) == 0)) ++ { ++ missing_teams_mask |= Team_IndexToBit(i); ++ } ++ } + if(prev_missing_teams_mask != missing_teams_mask) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_MISSING_TEAMS, missing_teams_mask); + prev_missing_teams_mask = missing_teams_mask; + } + return false; + } + + bool ca_isEliminated(entity e) + { + if(e.caplayer == 1 && (IS_DEAD(e) || e.frags == FRAGS_LMS_LOSER)) + return true; + if(e.caplayer == 0.5) + return true; + return false; + } + + /** Returns next available player to spectate if g_ca_spectate_enemies == 0 */ + entity CA_SpectateNext(entity player, entity start) + { + if (SAME_TEAM(start, player)) return start; + // continue from current player + for (entity e = start; (e = find(e, classname, STR_PLAYER)); ) + { + if (SAME_TEAM(player, e)) return e; + } + // restart from begining + for (entity e = NULL; (e = find(e, classname, STR_PLAYER)); ) + { + if (SAME_TEAM(player, e)) return e; + } + return start; + } + + + MUTATOR_HOOKFUNCTION(ca, PlayerSpawn) + { + entity player = M_ARGV(0, entity); + + player.caplayer = 1; + if (!warmup_stage) + eliminatedPlayers.SendFlags |= 1; + } + + MUTATOR_HOOKFUNCTION(ca, ForbidSpawn) + { + entity player = M_ARGV(0, entity); + + // spectators / observers that weren't playing can join; they are + // immediately forced to observe in the PutClientInServer hook + // this way they are put in a team and can play in the next round + if (!allowed_to_spawn && player.caplayer) + return true; + return false; + } + + MUTATOR_HOOKFUNCTION(ca, PutClientInServer) + { + entity player = M_ARGV(0, entity); + + if (!allowed_to_spawn && IS_PLAYER(player)) // this is true even when player is trying to join + { + TRANSMUTE(Observer, player); + if (CS(player).jointime != time && !player.caplayer) // not when connecting + { + player.caplayer = 0.5; + Send_Notification(NOTIF_ONE_ONLY, player, MSG_INFO, INFO_CA_JOIN_LATE); + } + } + } + + MUTATOR_HOOKFUNCTION(ca, reset_map_players) + { + FOREACH_CLIENT(true, { + CS(it).killcount = 0; + if (!it.caplayer && IS_BOT_CLIENT(it)) + { + it.team = -1; + it.caplayer = 1; + } + if (it.caplayer) + { + TRANSMUTE(Player, it); + it.caplayer = 1; + PutClientInServer(it); + } + }); + bot_relinkplayerlist(); + return true; + } + + MUTATOR_HOOKFUNCTION(ca, ClientConnect) + { + entity player = M_ARGV(0, entity); + + TRANSMUTE(Observer, player); + return true; + } + + MUTATOR_HOOKFUNCTION(ca, reset_map_global) + { + allowed_to_spawn = true; + return true; + } + -MUTATOR_HOOKFUNCTION(ca, CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) ++MUTATOR_HOOKFUNCTION(ca, TeamBalance_CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) + { + M_ARGV(0, float) = ca_teams; ++ return true; + } + + entity ca_LastPlayerForTeam(entity this) + { + entity last_pl = NULL; + FOREACH_CLIENT(IS_PLAYER(it) && it != this, { + if (!IS_DEAD(it)) + if (SAME_TEAM(this, it)) + if (!last_pl) + last_pl = it; + else + return NULL; + }); + return last_pl; + } + + void ca_LastPlayerForTeam_Notify(entity this) + { + if (round_handler_IsActive()) + if (round_handler_IsRoundStarted()) + { + entity pl = ca_LastPlayerForTeam(this); + if (pl) + Send_Notification(NOTIF_ONE, pl, MSG_CENTER, CENTER_ALONE); + } + } + + MUTATOR_HOOKFUNCTION(ca, PlayerDies) + { + entity frag_target = M_ARGV(2, entity); + + ca_LastPlayerForTeam_Notify(frag_target); + if (!allowed_to_spawn) + { + frag_target.respawn_flags = RESPAWN_SILENT; + // prevent unwanted sudden rejoin as spectator and movement of spectator camera + frag_target.respawn_time = time + 2; + } + frag_target.respawn_flags |= RESPAWN_FORCE; + if (!warmup_stage) + eliminatedPlayers.SendFlags |= 1; + if(IS_BOT_CLIENT(frag_target)) + bot_clear(frag_target); + return true; + } + + MUTATOR_HOOKFUNCTION(ca, ClientDisconnect) + { + entity player = M_ARGV(0, entity); + + if (player.caplayer == 1) + ca_LastPlayerForTeam_Notify(player); + return true; + } + + MUTATOR_HOOKFUNCTION(ca, MakePlayerObserver) + { + entity player = M_ARGV(0, entity); + + if (!IS_DEAD(player)) + ca_LastPlayerForTeam_Notify(player); + if (player.killindicator_teamchange == -2) // player wants to spectate + player.caplayer = 0; + if (player.caplayer) + player.frags = FRAGS_LMS_LOSER; + if (!warmup_stage) + eliminatedPlayers.SendFlags |= 1; + if (!player.caplayer) + return false; // allow team reset + return true; // prevent team reset + } + + MUTATOR_HOOKFUNCTION(ca, ForbidThrowCurrentWeapon) + { + return true; + } + + MUTATOR_HOOKFUNCTION(ca, GiveFragsForKill, CBC_ORDER_FIRST) + { + M_ARGV(2, float) = 0; // score will be given to the winner team when the round ends + return true; + } + + MUTATOR_HOOKFUNCTION(ca, SetStartItems) + { + start_items &= ~IT_UNLIMITED_AMMO; + start_health = warmup_start_health = cvar("g_lms_start_health"); + start_armorvalue = warmup_start_armorvalue = cvar("g_lms_start_armor"); + start_ammo_shells = warmup_start_ammo_shells = cvar("g_lms_start_ammo_shells"); + start_ammo_nails = warmup_start_ammo_nails = cvar("g_lms_start_ammo_nails"); + start_ammo_rockets = warmup_start_ammo_rockets = cvar("g_lms_start_ammo_rockets"); + start_ammo_cells = warmup_start_ammo_cells = cvar("g_lms_start_ammo_cells"); + start_ammo_plasma = warmup_start_ammo_plasma = cvar("g_lms_start_ammo_plasma"); + start_ammo_fuel = warmup_start_ammo_fuel = cvar("g_lms_start_ammo_fuel"); + } + + MUTATOR_HOOKFUNCTION(ca, Damage_Calculate) + { + entity frag_attacker = M_ARGV(1, entity); + entity frag_target = M_ARGV(2, entity); + float frag_deathtype = M_ARGV(3, float); + float frag_damage = M_ARGV(4, float); + float frag_mirrordamage = M_ARGV(5, float); + + if (IS_PLAYER(frag_target)) + if (!IS_DEAD(frag_target)) + if (frag_target == frag_attacker || SAME_TEAM(frag_target, frag_attacker) || frag_deathtype == DEATH_FALL.m_id) + frag_damage = 0; + + frag_mirrordamage = 0; + + M_ARGV(4, float) = frag_damage; + M_ARGV(5, float) = frag_mirrordamage; + } + + MUTATOR_HOOKFUNCTION(ca, FilterItem) + { + entity item = M_ARGV(0, entity); + + if (autocvar_g_powerups <= 0) + if (item.flags & FL_POWERUP) + return true; + + if (autocvar_g_pickup_items <= 0) + return true; + } + + MUTATOR_HOOKFUNCTION(ca, PlayerDamage_SplitHealthArmor) + { + entity frag_attacker = M_ARGV(1, entity); + entity frag_target = M_ARGV(2, entity); + float frag_damage = M_ARGV(7, float); + float damage_take = M_ARGV(4, float); + float damage_save = M_ARGV(5, float); + + float excess = max(0, frag_damage - damage_take - damage_save); + + if (frag_target != frag_attacker && IS_PLAYER(frag_attacker)) + GameRules_scoring_add_team(frag_attacker, SCORE, (frag_damage - excess) * autocvar_g_ca_damage2score_multiplier); + } + + MUTATOR_HOOKFUNCTION(ca, CalculateRespawnTime) + { + // no respawn calculations needed, player is forced to spectate anyway + return true; + } + + MUTATOR_HOOKFUNCTION(ca, PlayerRegen) + { + // no regeneration in CA + return true; + } + + MUTATOR_HOOKFUNCTION(ca, Scores_CountFragsRemaining) + { + // announce remaining frags + return true; + } + + MUTATOR_HOOKFUNCTION(ca, SpectateSet) + { + entity client = M_ARGV(0, entity); + entity targ = M_ARGV(1, entity); + + if (!autocvar_g_ca_spectate_enemies && client.caplayer) + if (DIFF_TEAM(targ, client)) + return true; + } + + MUTATOR_HOOKFUNCTION(ca, SpectateNext) + { + entity client = M_ARGV(0, entity); + + if (!autocvar_g_ca_spectate_enemies && client.caplayer) + { + entity targ = M_ARGV(1, entity); + M_ARGV(1, entity) = CA_SpectateNext(client, targ); + return true; + } + } + + MUTATOR_HOOKFUNCTION(ca, SpectatePrev) + { + entity client = M_ARGV(0, entity); + entity targ = M_ARGV(1, entity); + entity first = M_ARGV(2, entity); + + if (!autocvar_g_ca_spectate_enemies && client.caplayer) + { + do { targ = targ.chain; } + while(targ && DIFF_TEAM(targ, client)); + + if (!targ) + { + for (targ = first; targ && DIFF_TEAM(targ, client); targ = targ.chain); + + if (targ == client.enemy) + return MUT_SPECPREV_RETURN; + } + } + + M_ARGV(1, entity) = targ; + + return MUT_SPECPREV_FOUND; + } + + MUTATOR_HOOKFUNCTION(ca, Bot_FixCount, CBC_ORDER_EXCLUSIVE) + { + FOREACH_CLIENT(IS_REAL_CLIENT(it), { + if (IS_PLAYER(it) || it.caplayer == 1) + ++M_ARGV(0, int); + ++M_ARGV(1, int); + }); + return true; + } + + MUTATOR_HOOKFUNCTION(ca, ClientCommand_Spectate) + { + entity player = M_ARGV(0, entity); + + if (player.caplayer) + { + // they're going to spec, we can do other checks + if (autocvar_sv_spectate && (IS_SPEC(player) || IS_OBSERVER(player))) + Send_Notification(NOTIF_ONE_ONLY, player, MSG_INFO, INFO_CA_LEAVE); + return MUT_SPECCMD_FORCE; + } + + return MUT_SPECCMD_CONTINUE; + } + + MUTATOR_HOOKFUNCTION(ca, WantWeapon) + { + M_ARGV(2, bool) = true; // all weapons + } + + MUTATOR_HOOKFUNCTION(ca, HideTeamNagger) + { + return true; // doesn't work well with the whole spectator as player thing + } + + MUTATOR_HOOKFUNCTION(ca, GetPlayerStatus) + { + entity player = M_ARGV(0, entity); + + return player.caplayer == 1; + } + + MUTATOR_HOOKFUNCTION(ca, SetWeaponArena) + { + // most weapons arena + if (M_ARGV(0, string) == "0" || M_ARGV(0, string) == "") M_ARGV(0, string) = "most"; + } + #endif diff --cc qcsrc/common/gamemodes/gamemode/ctf/ctf.qc index 000000000,9382c9d8d..0fdbf3ab2 mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/ctf/ctf.qc +++ b/qcsrc/common/gamemodes/gamemode/ctf/ctf.qc @@@ -1,0 -1,2779 +1,2777 @@@ + #include "ctf.qh" + + // TODO: split into sv_ctf + #ifdef SVQC + #include + #include + #include + + #include + + bool autocvar_g_ctf_allow_vehicle_carry; + bool autocvar_g_ctf_allow_vehicle_touch; + bool autocvar_g_ctf_allow_monster_touch; + bool autocvar_g_ctf_throw; + float autocvar_g_ctf_throw_angle_max; + float autocvar_g_ctf_throw_angle_min; + int autocvar_g_ctf_throw_punish_count; + float autocvar_g_ctf_throw_punish_delay; + float autocvar_g_ctf_throw_punish_time; + float autocvar_g_ctf_throw_strengthmultiplier; + float autocvar_g_ctf_throw_velocity_forward; + float autocvar_g_ctf_throw_velocity_up; + float autocvar_g_ctf_drop_velocity_up; + float autocvar_g_ctf_drop_velocity_side; + bool autocvar_g_ctf_oneflag_reverse; + bool autocvar_g_ctf_portalteleport; + bool autocvar_g_ctf_pass; + float autocvar_g_ctf_pass_arc; + float autocvar_g_ctf_pass_arc_max; + float autocvar_g_ctf_pass_directional_max; + float autocvar_g_ctf_pass_directional_min; + float autocvar_g_ctf_pass_radius; + float autocvar_g_ctf_pass_wait; + bool autocvar_g_ctf_pass_request; + float autocvar_g_ctf_pass_turnrate; + float autocvar_g_ctf_pass_timelimit; + float autocvar_g_ctf_pass_velocity; + bool autocvar_g_ctf_dynamiclights; + float autocvar_g_ctf_flag_collect_delay; + float autocvar_g_ctf_flag_damageforcescale; + bool autocvar_g_ctf_flag_dropped_waypoint; + bool autocvar_g_ctf_flag_dropped_floatinwater; + bool autocvar_g_ctf_flag_glowtrails; + int autocvar_g_ctf_flag_health; + bool autocvar_g_ctf_flag_return; + bool autocvar_g_ctf_flag_return_carrying; + float autocvar_g_ctf_flag_return_carried_radius; + float autocvar_g_ctf_flag_return_time; + bool autocvar_g_ctf_flag_return_when_unreachable; + float autocvar_g_ctf_flag_return_damage; + float autocvar_g_ctf_flag_return_damage_delay; + float autocvar_g_ctf_flag_return_dropped; + float autocvar_g_ctf_flagcarrier_auto_helpme_damage; + float autocvar_g_ctf_flagcarrier_auto_helpme_time; + float autocvar_g_ctf_flagcarrier_selfdamagefactor; + float autocvar_g_ctf_flagcarrier_selfforcefactor; + float autocvar_g_ctf_flagcarrier_damagefactor; + float autocvar_g_ctf_flagcarrier_forcefactor; + //float autocvar_g_ctf_flagcarrier_waypointforenemy_spotting; + bool autocvar_g_ctf_fullbrightflags; + bool autocvar_g_ctf_ignore_frags; + bool autocvar_g_ctf_score_ignore_fields; + int autocvar_g_ctf_score_capture; + int autocvar_g_ctf_score_capture_assist; + int autocvar_g_ctf_score_kill; + int autocvar_g_ctf_score_penalty_drop; + int autocvar_g_ctf_score_penalty_returned; + int autocvar_g_ctf_score_pickup_base; + int autocvar_g_ctf_score_pickup_dropped_early; + int autocvar_g_ctf_score_pickup_dropped_late; + int autocvar_g_ctf_score_return; + float autocvar_g_ctf_shield_force; + float autocvar_g_ctf_shield_max_ratio; + int autocvar_g_ctf_shield_min_negscore; + bool autocvar_g_ctf_stalemate; + int autocvar_g_ctf_stalemate_endcondition; + float autocvar_g_ctf_stalemate_time; + bool autocvar_g_ctf_reverse; + float autocvar_g_ctf_dropped_capture_delay; + float autocvar_g_ctf_dropped_capture_radius; + + void ctf_FakeTimeLimit(entity e, float t) + { + msg_entity = e; + WriteByte(MSG_ONE, 3); // svc_updatestat + WriteByte(MSG_ONE, 236); // STAT_TIMELIMIT + if(t < 0) + WriteCoord(MSG_ONE, autocvar_timelimit); + else + WriteCoord(MSG_ONE, (t + 1) / 60); + } + + void ctf_EventLog(string mode, int flagteam, entity actor) // use an alias for easy changing and quick editing later + { + if(autocvar_sv_eventlog) + GameLogEcho(sprintf(":ctf:%s:%d:%d:%s", mode, flagteam, actor.team, ((actor != NULL) ? ftos(actor.playerid) : ""))); + //GameLogEcho(strcat(":ctf:", mode, ":", ftos(flagteam), ((actor != NULL) ? (strcat(":", ftos(actor.playerid))) : ""))); + } + + void ctf_CaptureRecord(entity flag, entity player) + { + float cap_record = ctf_captimerecord; + float cap_time = (time - flag.ctf_pickuptime); + string refername = db_get(ServerProgsDB, strcat(GetMapname(), "/captimerecord/netname")); + + // notify about shit + if(ctf_oneflag) + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_CTF_CAPTURE_NEUTRAL, player.netname); + else if(!ctf_captimerecord) + Send_Notification(NOTIF_ALL, NULL, MSG_CHOICE, APP_TEAM_NUM(flag.team, CHOICE_CTF_CAPTURE_TIME), player.netname, TIME_ENCODE(cap_time)); + else if(cap_time < cap_record) + Send_Notification(NOTIF_ALL, NULL, MSG_CHOICE, APP_TEAM_NUM(flag.team, CHOICE_CTF_CAPTURE_BROKEN), player.netname, refername, TIME_ENCODE(cap_time), TIME_ENCODE(cap_record)); + else + Send_Notification(NOTIF_ALL, NULL, MSG_CHOICE, APP_TEAM_NUM(flag.team, CHOICE_CTF_CAPTURE_UNBROKEN), player.netname, refername, TIME_ENCODE(cap_time), TIME_ENCODE(cap_record)); + + // write that shit in the database + if(!ctf_oneflag) // but not in 1-flag mode + if((!ctf_captimerecord) || (cap_time < cap_record)) + { + ctf_captimerecord = cap_time; + db_put(ServerProgsDB, strcat(GetMapname(), "/captimerecord/time"), ftos(cap_time)); + db_put(ServerProgsDB, strcat(GetMapname(), "/captimerecord/netname"), player.netname); + write_recordmarker(player, flag.ctf_pickuptime, cap_time); + } + + if(autocvar_g_ctf_leaderboard && !ctf_oneflag) + race_setTime(GetMapname(), TIME_ENCODE(cap_time), player.crypto_idfp, player.netname, player, false); + } + + bool ctf_Immediate_Return_Allowed(entity flag, entity toucher) + { + int num_perteam = 0; + FOREACH_CLIENT(IS_PLAYER(it) && SAME_TEAM(toucher, it), { ++num_perteam; }); + + // automatically return if there's only 1 player on the team + return ((autocvar_g_ctf_flag_return || num_perteam <= 1 || (autocvar_g_ctf_flag_return_carrying && toucher.flagcarried)) + && flag.team); + } + + bool ctf_Return_Customize(entity this, entity client) + { + // only to the carrier + return boolean(client == this.owner); + } + + void ctf_FlagcarrierWaypoints(entity player) + { + WaypointSprite_Spawn(WP_FlagCarrier, 0, 0, player, FLAG_WAYPOINT_OFFSET, NULL, player.team, player, wps_flagcarrier, true, RADARICON_FLAG); + WaypointSprite_UpdateMaxHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(start_health, start_armorvalue, autocvar_g_balance_armor_blockpercent, DEATH_WEAPON.m_id) * 2); + WaypointSprite_UpdateHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(player.health, player.armorvalue, autocvar_g_balance_armor_blockpercent, DEATH_WEAPON.m_id)); + WaypointSprite_UpdateTeamRadar(player.wps_flagcarrier, RADARICON_FLAGCARRIER, WPCOLOR_FLAGCARRIER(player.team)); + + if(player.flagcarried && CTF_SAMETEAM(player, player.flagcarried)) + { + if(!player.wps_enemyflagcarrier) + { + entity wp = WaypointSprite_Spawn(((ctf_oneflag) ? WP_FlagCarrier : WP_FlagCarrierEnemy), 0, 0, player, FLAG_WAYPOINT_OFFSET, NULL, 0, player, wps_enemyflagcarrier, true, RADARICON_FLAG); + wp.colormod = WPCOLOR_ENEMYFC(player.team); + setcefc(wp, ctf_Stalemate_Customize); + + if(IS_REAL_CLIENT(player) && !ctf_stalemate) + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_CTF_PICKUP_VISIBLE); + } + + if(!player.wps_flagreturn) + { + entity owp = WaypointSprite_SpawnFixed(WP_FlagReturn, player.flagcarried.ctf_spawnorigin + FLAG_WAYPOINT_OFFSET, player, wps_flagreturn, RADARICON_FLAG); + owp.colormod = '0 0.8 0.8'; + //WaypointSprite_UpdateTeamRadar(player.wps_flagreturn, RADARICON_FLAG, ((player.team) ? colormapPaletteColor(player.team - 1, false) : '1 1 1')); + setcefc(owp, ctf_Return_Customize); + } + } + } + + void ctf_CalculatePassVelocity(entity flag, vector to, vector from, float turnrate) + { + float current_distance = vlen((('1 0 0' * to.x) + ('0 1 0' * to.y)) - (('1 0 0' * from.x) + ('0 1 0' * from.y))); // for the sake of this check, exclude Z axis + float initial_height = min(autocvar_g_ctf_pass_arc_max, (flag.pass_distance * tanh(autocvar_g_ctf_pass_arc))); + float current_height = (initial_height * min(1, (current_distance / flag.pass_distance))); + //print("current_height = ", ftos(current_height), ", initial_height = ", ftos(initial_height), ".\n"); + + vector targpos; + if(current_height) // make sure we can actually do this arcing path + { + targpos = (to + ('0 0 1' * current_height)); + WarpZone_TraceLine(flag.origin, targpos, MOVE_NOMONSTERS, flag); + if(trace_fraction < 1) + { + //print("normal arc line failed, trying to find new pos..."); + WarpZone_TraceLine(to, targpos, MOVE_NOMONSTERS, flag); + targpos = (trace_endpos + FLAG_PASS_ARC_OFFSET); + WarpZone_TraceLine(flag.origin, targpos, MOVE_NOMONSTERS, flag); + if(trace_fraction < 1) { targpos = to; /* print(" ^1FAILURE^7, reverting to original direction.\n"); */ } + /*else { print(" ^3SUCCESS^7, using new arc line.\n"); } */ + } + } + else { targpos = to; } + + //flag.angles = normalize(('0 1 0' * to_y) - ('0 1 0' * from_y)); + + vector desired_direction = normalize(targpos - from); + if(turnrate) { flag.velocity = (normalize(normalize(flag.velocity) + (desired_direction * autocvar_g_ctf_pass_turnrate)) * autocvar_g_ctf_pass_velocity); } + else { flag.velocity = (desired_direction * autocvar_g_ctf_pass_velocity); } + } + + bool ctf_CheckPassDirection(vector head_center, vector passer_center, vector passer_angle, vector nearest_to_passer) + { + if(autocvar_g_ctf_pass_directional_max || autocvar_g_ctf_pass_directional_min) + { + // directional tracing only + float spreadlimit; + makevectors(passer_angle); + + // find the closest point on the enemy to the center of the attack + float h; // hypotenuse, which is the distance between attacker to head + float a; // adjacent side, which is the distance between attacker and the point on w_shotdir that is closest to head.origin + + h = vlen(head_center - passer_center); + a = h * (normalize(head_center - passer_center) * v_forward); + + vector nearest_on_line = (passer_center + a * v_forward); + float distance_from_line = vlen(nearest_to_passer - nearest_on_line); + + spreadlimit = (autocvar_g_ctf_pass_radius ? min(1, (vlen(passer_center - nearest_on_line) / autocvar_g_ctf_pass_radius)) : 1); + spreadlimit = (autocvar_g_ctf_pass_directional_min * (1 - spreadlimit) + autocvar_g_ctf_pass_directional_max * spreadlimit); + + if(spreadlimit && (distance_from_line <= spreadlimit) && ((vlen(normalize(head_center - passer_center) - v_forward) * RAD2DEG) <= 90)) + { return true; } + else + { return false; } + } + else { return true; } + } + + + // ======================= + // CaptureShield Functions + // ======================= + + bool ctf_CaptureShield_CheckStatus(entity p) + { + int s, s2, s3, s4, se, se2, se3, se4, sr, ser; + int players_worseeq, players_total; + + if(ctf_captureshield_max_ratio <= 0) + return false; + + s = GameRules_scoring_add(p, CTF_CAPS, 0); + s2 = GameRules_scoring_add(p, CTF_PICKUPS, 0); + s3 = GameRules_scoring_add(p, CTF_RETURNS, 0); + s4 = GameRules_scoring_add(p, CTF_FCKILLS, 0); + + sr = ((s - s2) + (s3 + s4)); + + if(sr >= -ctf_captureshield_min_negscore) + return false; + + players_total = players_worseeq = 0; + FOREACH_CLIENT(IS_PLAYER(it), { + if(DIFF_TEAM(it, p)) + continue; + se = GameRules_scoring_add(it, CTF_CAPS, 0); + se2 = GameRules_scoring_add(it, CTF_PICKUPS, 0); + se3 = GameRules_scoring_add(it, CTF_RETURNS, 0); + se4 = GameRules_scoring_add(it, CTF_FCKILLS, 0); + + ser = ((se - se2) + (se3 + se4)); + + if(ser <= sr) + ++players_worseeq; + ++players_total; + }); + + // player is in the worse half, if >= half the players are better than him, or consequently, if < half of the players are worse + // use this rule here + + if(players_worseeq >= players_total * ctf_captureshield_max_ratio) + return false; + + return true; + } + + void ctf_CaptureShield_Update(entity player, bool wanted_status) + { + bool updated_status = ctf_CaptureShield_CheckStatus(player); + if((wanted_status == player.ctf_captureshielded) && (updated_status != wanted_status)) // 0: shield only, 1: unshield only + { + Send_Notification(NOTIF_ONE, player, MSG_CENTER, ((updated_status) ? CENTER_CTF_CAPTURESHIELD_SHIELDED : CENTER_CTF_CAPTURESHIELD_FREE)); + player.ctf_captureshielded = updated_status; + } + } + + bool ctf_CaptureShield_Customize(entity this, entity client) + { + if(!client.ctf_captureshielded) { return false; } + if(CTF_SAMETEAM(this, client)) { return false; } + + return true; + } + + void ctf_CaptureShield_Touch(entity this, entity toucher) + { + if(!toucher.ctf_captureshielded) { return; } + if(CTF_SAMETEAM(this, toucher)) { return; } + + vector mymid = (this.absmin + this.absmax) * 0.5; + vector theirmid = (toucher.absmin + toucher.absmax) * 0.5; + + Damage(toucher, this, this, 0, DEATH_HURTTRIGGER.m_id, DMG_NOWEP, mymid, normalize(theirmid - mymid) * ctf_captureshield_force); + if(IS_REAL_CLIENT(toucher)) { Send_Notification(NOTIF_ONE, toucher, MSG_CENTER, CENTER_CTF_CAPTURESHIELD_SHIELDED); } + } + + void ctf_CaptureShield_Spawn(entity flag) + { + entity shield = new(ctf_captureshield); + + shield.enemy = flag; + shield.team = flag.team; + settouch(shield, ctf_CaptureShield_Touch); + setcefc(shield, ctf_CaptureShield_Customize); + shield.effects = EF_ADDITIVE; + set_movetype(shield, MOVETYPE_NOCLIP); + shield.solid = SOLID_TRIGGER; + shield.avelocity = '7 0 11'; + shield.scale = 0.5; + + setorigin(shield, flag.origin); + setmodel(shield, MDL_CTF_SHIELD); + setsize(shield, shield.scale * shield.mins, shield.scale * shield.maxs); + } + + + // ==================== + // Drop/Pass/Throw Code + // ==================== + + void ctf_Handle_Drop(entity flag, entity player, int droptype) + { + // declarations + player = (player ? player : flag.pass_sender); + + // main + set_movetype(flag, MOVETYPE_TOSS); + flag.takedamage = DAMAGE_YES; + flag.angles = '0 0 0'; + flag.health = flag.max_flag_health; + flag.ctf_droptime = time; + flag.ctf_dropper = player; + flag.ctf_status = FLAG_DROPPED; + + // messages and sounds + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_NUM(flag.team, INFO_CTF_LOST), player.netname); + _sound(flag, CH_TRIGGER, flag.snd_flag_dropped, VOL_BASE, ATTEN_NONE); + ctf_EventLog("dropped", player.team, player); + + // scoring + GameRules_scoring_add_team(player, SCORE, -((flag.score_drop) ? flag.score_drop : autocvar_g_ctf_score_penalty_drop)); + GameRules_scoring_add(player, CTF_DROPS, 1); + + // waypoints + if(autocvar_g_ctf_flag_dropped_waypoint) { + entity wp = WaypointSprite_Spawn(WP_FlagDropped, 0, 0, flag, FLAG_WAYPOINT_OFFSET, NULL, ((autocvar_g_ctf_flag_dropped_waypoint == 2) ? 0 : player.team), flag, wps_flagdropped, true, RADARICON_FLAG); + wp.colormod = WPCOLOR_DROPPEDFLAG(flag.team); + } + + if(autocvar_g_ctf_flag_return_time || (autocvar_g_ctf_flag_return_damage && autocvar_g_ctf_flag_health)) + { + WaypointSprite_UpdateMaxHealth(flag.wps_flagdropped, flag.max_flag_health); + WaypointSprite_UpdateHealth(flag.wps_flagdropped, flag.health); + } + + player.throw_antispam = time + autocvar_g_ctf_pass_wait; + + if(droptype == DROP_PASS) + { + flag.pass_distance = 0; + flag.pass_sender = NULL; + flag.pass_target = NULL; + } + } + + void ctf_Handle_Retrieve(entity flag, entity player) + { + entity sender = flag.pass_sender; + + // transfer flag to player + flag.owner = player; + flag.owner.flagcarried = flag; + GameRules_scoring_vip(player, true); + + // reset flag + if(player.vehicle) + { + setattachment(flag, player.vehicle, ""); + setorigin(flag, VEHICLE_FLAG_OFFSET); + flag.scale = VEHICLE_FLAG_SCALE; + } + else + { + setattachment(flag, player, ""); + setorigin(flag, FLAG_CARRY_OFFSET); + } + set_movetype(flag, MOVETYPE_NONE); + flag.takedamage = DAMAGE_NO; + flag.solid = SOLID_NOT; + flag.angles = '0 0 0'; + flag.ctf_status = FLAG_CARRY; + + // messages and sounds + _sound(player, CH_TRIGGER, flag.snd_flag_pass, VOL_BASE, ATTEN_NORM); + ctf_EventLog("receive", flag.team, player); + + FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it), { + if(it == sender) + Send_Notification(NOTIF_ONE, it, MSG_CENTER, APP_NUM(flag.team, CENTER_CTF_PASS_SENT), player.netname); + else if(it == player) + Send_Notification(NOTIF_ONE, it, MSG_CENTER, APP_NUM(flag.team, CENTER_CTF_PASS_RECEIVED), sender.netname); + else if(SAME_TEAM(it, sender)) + Send_Notification(NOTIF_ONE, it, MSG_CENTER, APP_NUM(flag.team, CENTER_CTF_PASS_OTHER), sender.netname, player.netname); + }); + + // create new waypoint + ctf_FlagcarrierWaypoints(player); + + sender.throw_antispam = time + autocvar_g_ctf_pass_wait; + player.throw_antispam = sender.throw_antispam; + + flag.pass_distance = 0; + flag.pass_sender = NULL; + flag.pass_target = NULL; + } + + void ctf_Handle_Throw(entity player, entity receiver, int droptype) + { + entity flag = player.flagcarried; + vector targ_origin, flag_velocity; + + if(!flag) { return; } + if((droptype == DROP_PASS) && !receiver) { return; } + + if(flag.speedrunning) { ctf_RespawnFlag(flag); return; } + + // reset the flag + setattachment(flag, NULL, ""); + setorigin(flag, player.origin + FLAG_DROP_OFFSET); + flag.owner.flagcarried = NULL; + GameRules_scoring_vip(flag.owner, false); + flag.owner = NULL; + flag.solid = SOLID_TRIGGER; + flag.ctf_dropper = player; + flag.ctf_droptime = time; + navigation_dynamicgoal_set(flag); + + flag.flags = FL_ITEM | FL_NOTARGET; // clear FL_ONGROUND for MOVETYPE_TOSS + + switch(droptype) + { + case DROP_PASS: + { + // warpzone support: + // for the examples, we assume player -> wz1 -> ... -> wzn -> receiver + // findradius has already put wzn ... wz1 into receiver's warpzone parameters! + WarpZone_RefSys_Copy(flag, receiver); + WarpZone_RefSys_AddInverse(flag, receiver); // wz1^-1 ... wzn^-1 receiver + targ_origin = WarpZone_RefSys_TransformOrigin(receiver, flag, (0.5 * (receiver.absmin + receiver.absmax))); // this is target origin as seen by the flag + + flag.pass_distance = vlen((('1 0 0' * targ_origin.x) + ('0 1 0' * targ_origin.y)) - (('1 0 0' * player.origin.x) + ('0 1 0' * player.origin.y))); // for the sake of this check, exclude Z axis + ctf_CalculatePassVelocity(flag, targ_origin, player.origin, false); + + // main + set_movetype(flag, MOVETYPE_FLY); + flag.takedamage = DAMAGE_NO; + flag.pass_sender = player; + flag.pass_target = receiver; + flag.ctf_status = FLAG_PASSING; + + // other + _sound(player, CH_TRIGGER, flag.snd_flag_touch, VOL_BASE, ATTEN_NORM); + WarpZone_TrailParticles(NULL, _particleeffectnum(flag.passeffect), player.origin, targ_origin); + ctf_EventLog("pass", flag.team, player); + break; + } + + case DROP_THROW: + { + makevectors((player.v_angle.y * '0 1 0') + (bound(autocvar_g_ctf_throw_angle_min, player.v_angle.x, autocvar_g_ctf_throw_angle_max) * '1 0 0')); + + flag_velocity = (('0 0 1' * autocvar_g_ctf_throw_velocity_up) + ((v_forward * autocvar_g_ctf_throw_velocity_forward) * ((player.items & ITEM_Strength.m_itemid) ? autocvar_g_ctf_throw_strengthmultiplier : 1))); + flag.velocity = W_CalculateProjectileVelocity(player, player.velocity, flag_velocity, false); + ctf_Handle_Drop(flag, player, droptype); + break; + } + + case DROP_RESET: + { + flag.velocity = '0 0 0'; // do nothing + break; + } + + default: + case DROP_NORMAL: + { + flag.velocity = W_CalculateProjectileVelocity(player, player.velocity, (('0 0 1' * autocvar_g_ctf_drop_velocity_up) + ((('0 1 0' * crandom()) + ('1 0 0' * crandom())) * autocvar_g_ctf_drop_velocity_side)), false); + ctf_Handle_Drop(flag, player, droptype); + break; + } + } + + // kill old waypointsprite + WaypointSprite_Ping(player.wps_flagcarrier); + WaypointSprite_Kill(player.wps_flagcarrier); + + if(player.wps_enemyflagcarrier) + WaypointSprite_Kill(player.wps_enemyflagcarrier); + + if(player.wps_flagreturn) + WaypointSprite_Kill(player.wps_flagreturn); + + // captureshield + ctf_CaptureShield_Update(player, 0); // shield player from picking up flag + } + + void shockwave_spawn(string m, vector org, float sz, float t1, float t2) + { + return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2); + } + + // ============== + // Event Handlers + // ============== + + void nades_GiveBonus(entity player, float score); + + void ctf_Handle_Capture(entity flag, entity toucher, int capturetype) + { + entity enemy_flag = ((capturetype == CAPTURE_NORMAL) ? toucher.flagcarried : toucher); + entity player = ((capturetype == CAPTURE_NORMAL) ? toucher : enemy_flag.ctf_dropper); + entity player_team_flag = NULL, tmp_entity; + float old_time, new_time; + + if(!player) { return; } // without someone to give the reward to, we can't possibly cap + if(CTF_DIFFTEAM(player, flag)) { return; } + if((flag.cnt || enemy_flag.cnt) && flag.cnt != enemy_flag.cnt) { return; } // this should catch some edge cases (capturing grouped flag at ungrouped flag disallowed etc) + + if (toucher.goalentity == flag.bot_basewaypoint) + toucher.goalentity_lock_timeout = 0; + + if(ctf_oneflag) + for(tmp_entity = ctf_worldflaglist; tmp_entity; tmp_entity = tmp_entity.ctf_worldflagnext) + if(SAME_TEAM(tmp_entity, player)) + { + player_team_flag = tmp_entity; + break; + } + + nades_GiveBonus(player, autocvar_g_nades_bonus_score_high ); + + player.throw_prevtime = time; + player.throw_count = 0; + + // messages and sounds + Send_Notification(NOTIF_ONE, player, MSG_CENTER, APP_NUM(enemy_flag.team, CENTER_CTF_CAPTURE)); + ctf_CaptureRecord(enemy_flag, player); + _sound(player, CH_TRIGGER, ((ctf_oneflag) ? player_team_flag.snd_flag_capture : ((DIFF_TEAM(player, flag)) ? enemy_flag.snd_flag_capture : flag.snd_flag_capture)), VOL_BASE, ATTEN_NONE); + + switch(capturetype) + { + case CAPTURE_NORMAL: ctf_EventLog("capture", enemy_flag.team, player); break; + case CAPTURE_DROPPED: ctf_EventLog("droppedcapture", enemy_flag.team, player); break; + default: break; + } + + // scoring + float pscore = 0; + if(enemy_flag.score_capture || flag.score_capture) + pscore = floor((max(1, enemy_flag.score_capture) + max(1, flag.score_capture)) * 0.5); + GameRules_scoring_add_team(player, SCORE, ((pscore) ? pscore : autocvar_g_ctf_score_capture)); + float capscore = 0; + if(enemy_flag.score_team_capture || flag.score_team_capture) + capscore = floor((max(1, enemy_flag.score_team_capture) + max(1, flag.score_team_capture)) * 0.5); + GameRules_scoring_add_team(player, CTF_CAPS, ((capscore) ? capscore : 1)); + + old_time = GameRules_scoring_add(player, CTF_CAPTIME, 0); + new_time = TIME_ENCODE(time - enemy_flag.ctf_pickuptime); + if(!old_time || new_time < old_time) + GameRules_scoring_add(player, CTF_CAPTIME, new_time - old_time); + + // effects + Send_Effect_(flag.capeffect, flag.origin, '0 0 0', 1); + //shockwave_spawn("models/ctf/shockwavetransring.md3", flag.origin - '0 0 15', -0.8, 0, 1); + + // other + if(capturetype == CAPTURE_NORMAL) + { + WaypointSprite_Kill(player.wps_flagcarrier); + if(flag.speedrunning) { ctf_FakeTimeLimit(player, -1); } + + if((enemy_flag.ctf_dropper) && (player != enemy_flag.ctf_dropper)) + { GameRules_scoring_add_team(enemy_flag.ctf_dropper, SCORE, ((enemy_flag.score_assist) ? enemy_flag.score_assist : autocvar_g_ctf_score_capture_assist)); } + } + + flag.enemy = toucher; + + // reset the flag + player.next_take_time = time + autocvar_g_ctf_flag_collect_delay; + ctf_RespawnFlag(enemy_flag); + } + + void ctf_Handle_Return(entity flag, entity player) + { + // messages and sounds + if(IS_MONSTER(player)) + { + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(flag.team, INFO_CTF_RETURN_MONSTER), player.monster_name); + } + else if(flag.team) + { + Send_Notification(NOTIF_ONE, player, MSG_CENTER, APP_TEAM_NUM(flag.team, CENTER_CTF_RETURN)); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(flag.team, INFO_CTF_RETURN), player.netname); + } + _sound(player, CH_TRIGGER, flag.snd_flag_returned, VOL_BASE, ATTEN_NONE); + ctf_EventLog("return", flag.team, player); + + // scoring + if(IS_PLAYER(player)) + { + GameRules_scoring_add_team(player, SCORE, ((flag.score_return) ? flag.score_return : autocvar_g_ctf_score_return)); // reward for return + GameRules_scoring_add(player, CTF_RETURNS, 1); // add to count of returns + + nades_GiveBonus(player,autocvar_g_nades_bonus_score_medium); + } + + TeamScore_AddToTeam(flag.team, ST_SCORE, -autocvar_g_ctf_score_penalty_returned); // punish the team who was last carrying it + + if(flag.ctf_dropper) + { + GameRules_scoring_add(flag.ctf_dropper, SCORE, -autocvar_g_ctf_score_penalty_returned); // punish the player who dropped the flag + ctf_CaptureShield_Update(flag.ctf_dropper, 0); // shield player from picking up flag + flag.ctf_dropper.next_take_time = time + autocvar_g_ctf_flag_collect_delay; // set next take time + } + + // other + if(player.flagcarried == flag) + WaypointSprite_Kill(player.wps_flagcarrier); + + flag.enemy = player; + + // reset the flag + ctf_RespawnFlag(flag); + } + + void ctf_Handle_Pickup(entity flag, entity player, int pickuptype) + { + // declarations + float pickup_dropped_score; // used to calculate dropped pickup score + + // attach the flag to the player + flag.owner = player; + player.flagcarried = flag; + GameRules_scoring_vip(player, true); + if(player.vehicle) + { + setattachment(flag, player.vehicle, ""); + setorigin(flag, VEHICLE_FLAG_OFFSET); + flag.scale = VEHICLE_FLAG_SCALE; + } + else + { + setattachment(flag, player, ""); + setorigin(flag, FLAG_CARRY_OFFSET); + } + + // flag setup + set_movetype(flag, MOVETYPE_NONE); + flag.takedamage = DAMAGE_NO; + flag.solid = SOLID_NOT; + flag.angles = '0 0 0'; + flag.ctf_status = FLAG_CARRY; + + switch(pickuptype) + { + case PICKUP_BASE: flag.ctf_pickuptime = time; break; // used for timing runs + case PICKUP_DROPPED: flag.health = flag.max_flag_health; break; // reset health/return timelimit + default: break; + } + + // messages and sounds + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_NUM(flag.team, INFO_CTF_PICKUP), player.netname); + if(ctf_stalemate) + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_CTF_STALEMATE_CARRIER); + if(!flag.team) + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_CTF_PICKUP_NEUTRAL); + else if(CTF_DIFFTEAM(player, flag)) + Send_Notification(NOTIF_ONE, player, MSG_CENTER, APP_TEAM_NUM(flag.team, CENTER_CTF_PICKUP)); + else + Send_Notification(NOTIF_ONE, player, MSG_CENTER, ((SAME_TEAM(player, flag)) ? CENTER_CTF_PICKUP_RETURN : CENTER_CTF_PICKUP_RETURN_ENEMY), Team_ColorCode(flag.team)); + + Send_Notification(NOTIF_TEAM_EXCEPT, player, MSG_CHOICE, APP_NUM(flag.team, CHOICE_CTF_PICKUP_TEAM), Team_ColorCode(player.team), player.netname); + + if(!flag.team) + FOREACH_CLIENT(IS_PLAYER(it) && it != player && DIFF_TEAM(it, player), { Send_Notification(NOTIF_ONE, it, MSG_CHOICE, CHOICE_CTF_PICKUP_ENEMY_NEUTRAL, Team_ColorCode(player.team), player.netname); }); + + if(flag.team) + FOREACH_CLIENT(IS_PLAYER(it) && it != player, { + if(CTF_SAMETEAM(flag, it)) + if(SAME_TEAM(player, it)) + Send_Notification(NOTIF_ONE, it, MSG_CHOICE, APP_TEAM_NUM(flag.team, CHOICE_CTF_PICKUP_TEAM), Team_ColorCode(player.team), player.netname); + else + Send_Notification(NOTIF_ONE, it, MSG_CHOICE, ((SAME_TEAM(flag, player)) ? CHOICE_CTF_PICKUP_ENEMY_TEAM : CHOICE_CTF_PICKUP_ENEMY), Team_ColorCode(player.team), player.netname); + }); + + _sound(player, CH_TRIGGER, flag.snd_flag_taken, VOL_BASE, ATTEN_NONE); + + // scoring + GameRules_scoring_add(player, CTF_PICKUPS, 1); + nades_GiveBonus(player, autocvar_g_nades_bonus_score_minor); + switch(pickuptype) + { + case PICKUP_BASE: + { + GameRules_scoring_add_team(player, SCORE, ((flag.score_pickup) ? flag.score_pickup : autocvar_g_ctf_score_pickup_base)); + ctf_EventLog("steal", flag.team, player); + break; + } + + case PICKUP_DROPPED: + { + pickup_dropped_score = (autocvar_g_ctf_flag_return_time ? bound(0, ((flag.ctf_droptime + autocvar_g_ctf_flag_return_time) - time) / autocvar_g_ctf_flag_return_time, 1) : 1); + pickup_dropped_score = floor((autocvar_g_ctf_score_pickup_dropped_late * (1 - pickup_dropped_score) + autocvar_g_ctf_score_pickup_dropped_early * pickup_dropped_score) + 0.5); + LOG_TRACE("pickup_dropped_score is ", ftos(pickup_dropped_score)); + GameRules_scoring_add_team(player, SCORE, pickup_dropped_score); + ctf_EventLog("pickup", flag.team, player); + break; + } + + default: break; + } + + // speedrunning + if(pickuptype == PICKUP_BASE) + { + flag.speedrunning = player.speedrunning; // if speedrunning, flag will flag-return and teleport the owner back after the record + if((player.speedrunning) && (ctf_captimerecord)) + ctf_FakeTimeLimit(player, time + ctf_captimerecord); + } + + // effects + Send_Effect_(flag.toucheffect, player.origin, '0 0 0', 1); + + // waypoints + if(pickuptype == PICKUP_DROPPED) { WaypointSprite_Kill(flag.wps_flagdropped); } + ctf_FlagcarrierWaypoints(player); + WaypointSprite_Ping(player.wps_flagcarrier); + } + + + // =================== + // Main Flag Functions + // =================== + + void ctf_CheckFlagReturn(entity flag, int returntype) + { + if((flag.ctf_status == FLAG_DROPPED) || (flag.ctf_status == FLAG_PASSING)) + { + if(flag.wps_flagdropped) { WaypointSprite_UpdateHealth(flag.wps_flagdropped, flag.health); } + + if((flag.health <= 0) || (time >= flag.ctf_droptime + autocvar_g_ctf_flag_return_time)) + { + switch(returntype) + { + case RETURN_DROPPED: + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_NUM(flag.team, INFO_CTF_FLAGRETURN_DROPPED)); break; + case RETURN_DAMAGE: + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_NUM(flag.team, INFO_CTF_FLAGRETURN_DAMAGED)); break; + case RETURN_SPEEDRUN: + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_NUM(flag.team, INFO_CTF_FLAGRETURN_SPEEDRUN), TIME_ENCODE(ctf_captimerecord)); break; + case RETURN_NEEDKILL: + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_NUM(flag.team, INFO_CTF_FLAGRETURN_NEEDKILL)); break; + default: + case RETURN_TIMEOUT: + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_NUM(flag.team, INFO_CTF_FLAGRETURN_TIMEOUT)); break; + } + _sound(flag, CH_TRIGGER, flag.snd_flag_respawn, VOL_BASE, ATTEN_NONE); + ctf_EventLog("returned", flag.team, NULL); + flag.enemy = NULL; + ctf_RespawnFlag(flag); + } + } + } + + bool ctf_Stalemate_Customize(entity this, entity client) + { + // make spectators see what the player would see + entity e = WaypointSprite_getviewentity(client); + entity wp_owner = this.owner; + + // team waypoints + //if(CTF_SAMETEAM(wp_owner.flagcarried, wp_owner)) { return false; } + if(SAME_TEAM(wp_owner, e)) { return false; } + if(!IS_PLAYER(e)) { return false; } + + return true; + } + + void ctf_CheckStalemate() + { + // declarations + int stale_flags = 0, stale_red_flags = 0, stale_blue_flags = 0, stale_yellow_flags = 0, stale_pink_flags = 0, stale_neutral_flags = 0; + entity tmp_entity; + + entity ctf_staleflaglist = NULL; // reset the list, we need to build the list each time this function runs + + // build list of stale flags + for(tmp_entity = ctf_worldflaglist; tmp_entity; tmp_entity = tmp_entity.ctf_worldflagnext) + { + if(autocvar_g_ctf_stalemate) + if(tmp_entity.ctf_status != FLAG_BASE) + if(time >= tmp_entity.ctf_pickuptime + autocvar_g_ctf_stalemate_time || !tmp_entity.team) // instant stalemate in oneflag + { + tmp_entity.ctf_staleflagnext = ctf_staleflaglist; // link flag into staleflaglist + ctf_staleflaglist = tmp_entity; + + switch(tmp_entity.team) + { + case NUM_TEAM_1: ++stale_red_flags; break; + case NUM_TEAM_2: ++stale_blue_flags; break; + case NUM_TEAM_3: ++stale_yellow_flags; break; + case NUM_TEAM_4: ++stale_pink_flags; break; + default: ++stale_neutral_flags; break; + } + } + } + + if(ctf_oneflag) + stale_flags = (stale_neutral_flags >= 1); + else + stale_flags = (stale_red_flags >= 1) + (stale_blue_flags >= 1) + (stale_yellow_flags >= 1) + (stale_pink_flags >= 1); + + if(ctf_oneflag && stale_flags == 1) + ctf_stalemate = true; + else if(stale_flags >= 2) + ctf_stalemate = true; + else if(stale_flags == 0 && autocvar_g_ctf_stalemate_endcondition == 2) + { ctf_stalemate = false; wpforenemy_announced = false; } + else if(stale_flags < 2 && autocvar_g_ctf_stalemate_endcondition == 1) + { ctf_stalemate = false; wpforenemy_announced = false; } + + // if sufficient stalemate, then set up the waypointsprite and announce the stalemate if necessary + if(ctf_stalemate) + { + for(tmp_entity = ctf_staleflaglist; tmp_entity; tmp_entity = tmp_entity.ctf_staleflagnext) + { + if((tmp_entity.owner) && (!tmp_entity.owner.wps_enemyflagcarrier)) + { + entity wp = WaypointSprite_Spawn(((ctf_oneflag) ? WP_FlagCarrier : WP_FlagCarrierEnemy), 0, 0, tmp_entity.owner, FLAG_WAYPOINT_OFFSET, NULL, 0, tmp_entity.owner, wps_enemyflagcarrier, true, RADARICON_FLAG); + wp.colormod = WPCOLOR_ENEMYFC(tmp_entity.owner.team); + setcefc(tmp_entity.owner.wps_enemyflagcarrier, ctf_Stalemate_Customize); + } + } + + if (!wpforenemy_announced) + { + FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it), { Send_Notification(NOTIF_ONE, it, MSG_CENTER, ((it.flagcarried) ? CENTER_CTF_STALEMATE_CARRIER : CENTER_CTF_STALEMATE_OTHER)); }); + + wpforenemy_announced = true; + } + } + } + + void ctf_FlagDamage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force) + { + if(ITEM_DAMAGE_NEEDKILL(deathtype)) + { + if(autocvar_g_ctf_flag_return_damage_delay) + this.ctf_flagdamaged_byworld = true; + else + { + this.health = 0; + ctf_CheckFlagReturn(this, RETURN_NEEDKILL); + } + return; + } + if(autocvar_g_ctf_flag_return_damage) + { + // reduce health and check if it should be returned + this.health = this.health - damage; + ctf_CheckFlagReturn(this, RETURN_DAMAGE); + return; + } + } + + void ctf_FlagThink(entity this) + { + // declarations + entity tmp_entity; + + this.nextthink = time + FLAG_THINKRATE; // only 5 fps, more is unnecessary. + + // captureshield + if(this == ctf_worldflaglist) // only for the first flag + FOREACH_CLIENT(true, { ctf_CaptureShield_Update(it, 1); }); // release shield only + + // sanity checks + if(this.mins != this.m_mins || this.maxs != this.m_maxs) { // reset the flag boundaries in case it got squished + LOG_TRACE("wtf the flag got squashed?"); + tracebox(this.origin, this.m_mins, this.m_maxs, this.origin, MOVE_NOMONSTERS, this); + if(!trace_startsolid || this.noalign) // can we resize it without getting stuck? + setsize(this, this.m_mins, this.m_maxs); + } + + // main think method + switch(this.ctf_status) + { + case FLAG_BASE: + { + if(autocvar_g_ctf_dropped_capture_radius) + { + for(tmp_entity = ctf_worldflaglist; tmp_entity; tmp_entity = tmp_entity.ctf_worldflagnext) + if(tmp_entity.ctf_status == FLAG_DROPPED) + if(vdist(this.origin - tmp_entity.origin, <, autocvar_g_ctf_dropped_capture_radius)) + if(time > tmp_entity.ctf_droptime + autocvar_g_ctf_dropped_capture_delay) + ctf_Handle_Capture(this, tmp_entity, CAPTURE_DROPPED); + } + return; + } + + case FLAG_DROPPED: + { + this.angles = '0 0 0'; // reset flag angles in case warpzones adjust it + + if(autocvar_g_ctf_flag_dropped_floatinwater) + { + vector midpoint = ((this.absmin + this.absmax) * 0.5); + if(pointcontents(midpoint) == CONTENT_WATER) + { + this.velocity = this.velocity * 0.5; + + if(pointcontents(midpoint + FLAG_FLOAT_OFFSET) == CONTENT_WATER) + { this.velocity_z = autocvar_g_ctf_flag_dropped_floatinwater; } + else + { set_movetype(this, MOVETYPE_FLY); } + } + else if(this.move_movetype == MOVETYPE_FLY) { set_movetype(this, MOVETYPE_TOSS); } + } + if(autocvar_g_ctf_flag_return_dropped) + { + if((vdist(this.origin - this.ctf_spawnorigin, <=, autocvar_g_ctf_flag_return_dropped)) || (autocvar_g_ctf_flag_return_dropped == -1)) + { + this.health = 0; + ctf_CheckFlagReturn(this, RETURN_DROPPED); + return; + } + } + if(this.ctf_flagdamaged_byworld) + { + this.health -= ((this.max_flag_health / autocvar_g_ctf_flag_return_damage_delay) * FLAG_THINKRATE); + ctf_CheckFlagReturn(this, RETURN_NEEDKILL); + return; + } + else if(autocvar_g_ctf_flag_return_time) + { + this.health -= ((this.max_flag_health / autocvar_g_ctf_flag_return_time) * FLAG_THINKRATE); + ctf_CheckFlagReturn(this, RETURN_TIMEOUT); + return; + } + return; + } + + case FLAG_CARRY: + { + if(this.speedrunning && ctf_captimerecord && (time >= this.ctf_pickuptime + ctf_captimerecord)) + { + this.health = 0; + ctf_CheckFlagReturn(this, RETURN_SPEEDRUN); + + CS(this.owner).impulse = CHIMPULSE_SPEEDRUN.impulse; // move the player back to the waypoint they set + ImpulseCommands(this.owner); + } + if(autocvar_g_ctf_stalemate) + { + if(time >= wpforenemy_nextthink) + { + ctf_CheckStalemate(); + wpforenemy_nextthink = time + WPFE_THINKRATE; // waypoint for enemy think rate (to reduce unnecessary spam of this check) + } + } + if(CTF_SAMETEAM(this, this.owner) && this.team) + { + if(autocvar_g_ctf_flag_return) // drop the flag if reverse status has changed + ctf_Handle_Throw(this.owner, NULL, DROP_THROW); + else if(vdist(this.owner.origin - this.ctf_spawnorigin, <=, autocvar_g_ctf_flag_return_carried_radius)) + ctf_Handle_Return(this, this.owner); + } + return; + } + + case FLAG_PASSING: + { + vector targ_origin = ((this.pass_target.absmin + this.pass_target.absmax) * 0.5); + targ_origin = WarpZone_RefSys_TransformOrigin(this.pass_target, this, targ_origin); // origin of target as seen by the flag (us) + WarpZone_TraceLine(this.origin, targ_origin, MOVE_NOMONSTERS, this); + + if((this.pass_target == NULL) + || (IS_DEAD(this.pass_target)) + || (this.pass_target.flagcarried) + || (vdist(this.origin - targ_origin, >, autocvar_g_ctf_pass_radius)) + || ((trace_fraction < 1) && (trace_ent != this.pass_target)) + || (time > this.ctf_droptime + autocvar_g_ctf_pass_timelimit)) + { + // give up, pass failed + ctf_Handle_Drop(this, NULL, DROP_PASS); + } + else + { + // still a viable target, go for it + ctf_CalculatePassVelocity(this, targ_origin, this.origin, true); + } + return; + } + + default: // this should never happen + { + LOG_TRACE("ctf_FlagThink(): Flag exists with no status?"); + return; + } + } + } + + METHOD(Flag, giveTo, bool(Flag this, entity flag, entity toucher)) + { + return = false; + if(game_stopped) return; + if(trace_dphitcontents & (DPCONTENTS_PLAYERCLIP | DPCONTENTS_MONSTERCLIP)) { return; } + + bool is_not_monster = (!IS_MONSTER(toucher)); + + // automatically kill the flag and return it if it touched lava/slime/nodrop surfaces + if(ITEM_TOUCH_NEEDKILL()) + { + if(!autocvar_g_ctf_flag_return_damage_delay) + { + flag.health = 0; + ctf_CheckFlagReturn(flag, RETURN_NEEDKILL); + } + if(!flag.ctf_flagdamaged_byworld) { return; } + } + + // special touch behaviors + if(STAT(FROZEN, toucher)) { return; } + else if(IS_VEHICLE(toucher)) + { + if(autocvar_g_ctf_allow_vehicle_touch && toucher.owner) + toucher = toucher.owner; // the player is actually the vehicle owner, not other + else + return; // do nothing + } + else if(IS_MONSTER(toucher)) + { + if(!autocvar_g_ctf_allow_monster_touch) + return; // do nothing + } + else if (!IS_PLAYER(toucher)) // The flag just touched an object, most likely the world + { + if(time > flag.wait) // if we haven't in a while, play a sound/effect + { + Send_Effect_(flag.toucheffect, flag.origin, '0 0 0', 1); + _sound(flag, CH_TRIGGER, flag.snd_flag_touch, VOL_BASE, ATTEN_NORM); + flag.wait = time + FLAG_TOUCHRATE; + } + return; + } + else if(IS_DEAD(toucher)) { return; } + + switch(flag.ctf_status) + { + case FLAG_BASE: + { + if(ctf_oneflag) + { + if(CTF_SAMETEAM(toucher, flag) && (toucher.flagcarried) && !toucher.flagcarried.team && is_not_monster) + ctf_Handle_Capture(flag, toucher, CAPTURE_NORMAL); // toucher just captured the neutral flag to enemy base + else if(!flag.team && (!toucher.flagcarried) && (!toucher.ctf_captureshielded) && (time > toucher.next_take_time) && is_not_monster) + ctf_Handle_Pickup(flag, toucher, PICKUP_BASE); // toucher just stole the neutral flag + } + else if(CTF_SAMETEAM(toucher, flag) && (toucher.flagcarried) && DIFF_TEAM(toucher.flagcarried, flag) && is_not_monster) + ctf_Handle_Capture(flag, toucher, CAPTURE_NORMAL); // toucher just captured the enemies flag to his base + else if(CTF_DIFFTEAM(toucher, flag) && (toucher.flagcarried) && CTF_SAMETEAM(toucher.flagcarried, toucher) && (!toucher.ctf_captureshielded) && autocvar_g_ctf_flag_return_carrying && (time > toucher.next_take_time) && is_not_monster) + { + ctf_Handle_Return(toucher.flagcarried, toucher); // return their current flag + ctf_Handle_Pickup(flag, toucher, PICKUP_BASE); // now pickup the flag + } + else if(CTF_DIFFTEAM(toucher, flag) && (!toucher.flagcarried) && (!toucher.ctf_captureshielded) && (time > toucher.next_take_time) && is_not_monster) + ctf_Handle_Pickup(flag, toucher, PICKUP_BASE); // toucher just stole the enemies flag + break; + } + + case FLAG_DROPPED: + { + if(CTF_SAMETEAM(toucher, flag) && ctf_Immediate_Return_Allowed(flag, toucher)) + ctf_Handle_Return(flag, toucher); // toucher just returned his own flag + else if(is_not_monster && (!toucher.flagcarried) && ((toucher != flag.ctf_dropper) || (time > flag.ctf_droptime + autocvar_g_ctf_flag_collect_delay))) + ctf_Handle_Pickup(flag, toucher, PICKUP_DROPPED); // toucher just picked up a dropped enemy flag + break; + } + + case FLAG_CARRY: + { + LOG_TRACE("Someone touched a flag even though it was being carried?"); + break; + } + + case FLAG_PASSING: + { + if((IS_PLAYER(toucher)) && !IS_DEAD(toucher) && (toucher != flag.pass_sender)) + { + if(DIFF_TEAM(toucher, flag.pass_sender)) + { + if(ctf_Immediate_Return_Allowed(flag, toucher)) + ctf_Handle_Return(flag, toucher); + else if(is_not_monster && (!toucher.flagcarried)) + ctf_Handle_Pickup(flag, toucher, PICKUP_DROPPED); + } + else if(!toucher.flagcarried) + ctf_Handle_Retrieve(flag, toucher); + } + break; + } + } + } + + .float last_respawn; + void ctf_RespawnFlag(entity flag) + { + // check for flag respawn being called twice in a row + if(flag.last_respawn > time - 0.5) + { backtrace("flag respawn called twice quickly! please notify Samual about this..."); } + + flag.last_respawn = time; + + // reset the player (if there is one) + if((flag.owner) && (flag.owner.flagcarried == flag)) + { + WaypointSprite_Kill(flag.owner.wps_enemyflagcarrier); + WaypointSprite_Kill(flag.owner.wps_flagreturn); + WaypointSprite_Kill(flag.wps_flagcarrier); + + flag.owner.flagcarried = NULL; + GameRules_scoring_vip(flag.owner, false); + + if(flag.speedrunning) + ctf_FakeTimeLimit(flag.owner, -1); + } + + if((flag.owner) && (flag.owner.vehicle)) + flag.scale = FLAG_SCALE; + + if(flag.ctf_status == FLAG_DROPPED) + { WaypointSprite_Kill(flag.wps_flagdropped); } + + // reset the flag + setattachment(flag, NULL, ""); + setorigin(flag, flag.ctf_spawnorigin); + + set_movetype(flag, ((flag.noalign) ? MOVETYPE_NONE : MOVETYPE_TOSS)); + flag.takedamage = DAMAGE_NO; + flag.health = flag.max_flag_health; + flag.solid = SOLID_TRIGGER; + flag.velocity = '0 0 0'; + flag.angles = flag.mangle; + flag.flags = FL_ITEM | FL_NOTARGET; + + flag.ctf_status = FLAG_BASE; + flag.owner = NULL; + flag.pass_distance = 0; + flag.pass_sender = NULL; + flag.pass_target = NULL; + flag.ctf_dropper = NULL; + flag.ctf_pickuptime = 0; + flag.ctf_droptime = 0; + flag.ctf_flagdamaged_byworld = false; + navigation_dynamicgoal_unset(flag); + + ctf_CheckStalemate(); + } + + void ctf_Reset(entity this) + { + if(this.owner && IS_PLAYER(this.owner)) + ctf_Handle_Throw(this.owner, NULL, DROP_RESET); + + this.enemy = NULL; + ctf_RespawnFlag(this); + } + + bool ctf_FlagBase_Customize(entity this, entity client) + { + entity e = WaypointSprite_getviewentity(client); + entity wp_owner = this.owner; + entity flag = e.flagcarried; + if(flag && CTF_SAMETEAM(e, flag)) + return false; + if(flag && (flag.cnt || wp_owner.cnt) && wp_owner.cnt != flag.cnt) + return false; + return true; + } + + void ctf_DelayedFlagSetup(entity this) // called after a flag is placed on a map by ctf_FlagSetup() + { + // bot waypoints + waypoint_spawnforitem_force(this, this.origin); + navigation_dynamicgoal_init(this, true); + + // waypointsprites + entity basename; + switch (this.team) + { + case NUM_TEAM_1: basename = WP_FlagBaseRed; break; + case NUM_TEAM_2: basename = WP_FlagBaseBlue; break; + case NUM_TEAM_3: basename = WP_FlagBaseYellow; break; + case NUM_TEAM_4: basename = WP_FlagBasePink; break; + default: basename = WP_FlagBaseNeutral; break; + } + + entity wp = WaypointSprite_SpawnFixed(basename, this.origin + FLAG_WAYPOINT_OFFSET, this, wps_flagbase, RADARICON_FLAG); + wp.colormod = ((this.team) ? Team_ColorRGB(this.team) : '1 1 1'); + WaypointSprite_UpdateTeamRadar(this.wps_flagbase, RADARICON_FLAG, ((this.team) ? colormapPaletteColor(this.team - 1, false) : '1 1 1')); + setcefc(wp, ctf_FlagBase_Customize); + + // captureshield setup + ctf_CaptureShield_Spawn(this); + } + + .bool pushable; + + void ctf_FlagSetup(int teamnumber, entity flag) // called when spawning a flag entity on the map as a spawnfunc + { + // main setup + flag.ctf_worldflagnext = ctf_worldflaglist; // link flag into ctf_worldflaglist + ctf_worldflaglist = flag; + + setattachment(flag, NULL, ""); + + flag.netname = strzone(sprintf("%s%s^7 flag", Team_ColorCode(teamnumber), Team_ColorName_Upper(teamnumber))); + flag.team = teamnumber; + flag.classname = "item_flag_team"; + flag.target = "###item###"; // wut? + flag.flags = FL_ITEM | FL_NOTARGET; + IL_PUSH(g_items, flag); + flag.solid = SOLID_TRIGGER; + flag.takedamage = DAMAGE_NO; + flag.damageforcescale = autocvar_g_ctf_flag_damageforcescale; + flag.max_flag_health = ((autocvar_g_ctf_flag_return_damage && autocvar_g_ctf_flag_health) ? autocvar_g_ctf_flag_health : 100); + flag.health = flag.max_flag_health; + flag.event_damage = ctf_FlagDamage; + flag.pushable = true; + flag.teleportable = TELEPORT_NORMAL; + flag.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_PLAYERCLIP; + flag.damagedbytriggers = autocvar_g_ctf_flag_return_when_unreachable; + flag.damagedbycontents = autocvar_g_ctf_flag_return_when_unreachable; + if(flag.damagedbycontents) + IL_PUSH(g_damagedbycontents, flag); + flag.velocity = '0 0 0'; + flag.mangle = flag.angles; + flag.reset = ctf_Reset; + settouch(flag, ctf_FlagTouch); + setthink(flag, ctf_FlagThink); + flag.nextthink = time + FLAG_THINKRATE; + flag.ctf_status = FLAG_BASE; + + // crudely force them all to 0 + if(autocvar_g_ctf_score_ignore_fields) + flag.cnt = flag.score_assist = flag.score_team_capture = flag.score_capture = flag.score_drop = flag.score_pickup = flag.score_return = 0; + + string teamname = Static_Team_ColorName_Lower(teamnumber); + // appearence + if(!flag.scale) { flag.scale = FLAG_SCALE; } + if(flag.skin == 0) { flag.skin = cvar(sprintf("g_ctf_flag_%s_skin", teamname)); } + if(flag.model == "") { flag.model = cvar_string(sprintf("g_ctf_flag_%s_model", teamname)); } + if (flag.toucheffect == "") { flag.toucheffect = EFFECT_FLAG_TOUCH(teamnumber).eent_eff_name; } + if (flag.passeffect == "") { flag.passeffect = EFFECT_PASS(teamnumber).eent_eff_name; } + if (flag.capeffect == "") { flag.capeffect = EFFECT_CAP(teamnumber).eent_eff_name; } + + // sounds + #define X(s,b) \ + if(flag.s == "") flag.s = b; \ + precache_sound(flag.s); + + X(snd_flag_taken, strzone(SND(CTF_TAKEN(teamnumber)))) + X(snd_flag_returned, strzone(SND(CTF_RETURNED(teamnumber)))) + X(snd_flag_capture, strzone(SND(CTF_CAPTURE(teamnumber)))) + X(snd_flag_dropped, strzone(SND(CTF_DROPPED(teamnumber)))) + X(snd_flag_respawn, strzone(SND(CTF_RESPAWN))) + X(snd_flag_touch, strzone(SND(CTF_TOUCH))) + X(snd_flag_pass, strzone(SND(CTF_PASS))) + #undef X + + // precache + precache_model(flag.model); + + // appearence + _setmodel(flag, flag.model); // precision set below + setsize(flag, CTF_FLAG.m_mins * flag.scale, CTF_FLAG.m_maxs * flag.scale); + flag.m_mins = flag.mins; // store these for squash checks + flag.m_maxs = flag.maxs; + setorigin(flag, (flag.origin + FLAG_SPAWN_OFFSET)); + + if(autocvar_g_ctf_flag_glowtrails) + { + switch(teamnumber) + { + case NUM_TEAM_1: flag.glow_color = 251; break; + case NUM_TEAM_2: flag.glow_color = 210; break; + case NUM_TEAM_3: flag.glow_color = 110; break; + case NUM_TEAM_4: flag.glow_color = 145; break; + default: flag.glow_color = 254; break; + } + flag.glow_size = 25; + flag.glow_trail = 1; + } + + flag.effects |= EF_LOWPRECISION; + if(autocvar_g_ctf_fullbrightflags) { flag.effects |= EF_FULLBRIGHT; } + if(autocvar_g_ctf_dynamiclights) + { + switch(teamnumber) + { + case NUM_TEAM_1: flag.effects |= EF_RED; break; + case NUM_TEAM_2: flag.effects |= EF_BLUE; break; + case NUM_TEAM_3: flag.effects |= EF_DIMLIGHT; break; + case NUM_TEAM_4: flag.effects |= EF_RED; break; + default: flag.effects |= EF_DIMLIGHT; break; + } + } + + // flag placement + if((flag.spawnflags & 1) || flag.noalign) // don't drop to floor, just stay at fixed location + { + flag.dropped_origin = flag.origin; + flag.noalign = true; + set_movetype(flag, MOVETYPE_NONE); + } + else // drop to floor, automatically find a platform and set that as spawn origin + { + flag.noalign = false; + droptofloor(flag); + set_movetype(flag, MOVETYPE_NONE); + } + + InitializeEntity(flag, ctf_DelayedFlagSetup, INITPRIO_SETLOCATION); + } + + + // ================ + // Bot player logic + // ================ + + // NOTE: LEGACY CODE, needs to be re-written! + + void havocbot_ctf_calculate_middlepoint() + { + entity f; + vector s = '0 0 0'; + vector fo = '0 0 0'; + int n = 0; + + f = ctf_worldflaglist; + while (f) + { + fo = f.origin; + s = s + fo; + f = f.ctf_worldflagnext; + n++; + } + if(!n) + return; + + havocbot_middlepoint = s / n; + havocbot_middlepoint_radius = vlen(fo - havocbot_middlepoint); + + havocbot_symmetryaxis_equation = '0 0 0'; + if(n == 2) + { + // for symmetrical editing of waypoints + entity f1 = ctf_worldflaglist; + entity f2 = f1.ctf_worldflagnext; + float m = -(f1.origin.y - f2.origin.y) / (f1.origin.x - f2.origin.x); + float q = havocbot_middlepoint.y - m * havocbot_middlepoint.x; + havocbot_symmetryaxis_equation.x = m; + havocbot_symmetryaxis_equation.y = q; + } + // store number of flags in this otherwise unused vector component + havocbot_symmetryaxis_equation.z = n; + } + + + entity havocbot_ctf_find_flag(entity bot) + { + entity f; + f = ctf_worldflaglist; + while (f) + { + if (CTF_SAMETEAM(bot, f)) + return f; + f = f.ctf_worldflagnext; + } + return NULL; + } + + entity havocbot_ctf_find_enemy_flag(entity bot) + { + entity f; + f = ctf_worldflaglist; + while (f) + { + if(ctf_oneflag) + { + if(CTF_DIFFTEAM(bot, f)) + { + if(f.team) + { + if(bot.flagcarried) + return f; + } + else if(!bot.flagcarried) + return f; + } + } + else if (CTF_DIFFTEAM(bot, f)) + return f; + f = f.ctf_worldflagnext; + } + return NULL; + } + + int havocbot_ctf_teamcount(entity bot, vector org, float tc_radius) + { + if (!teamplay) + return 0; + + int c = 0; + + FOREACH_CLIENT(IS_PLAYER(it), { + if(DIFF_TEAM(it, bot) || IS_DEAD(it) || it == bot) + continue; + + if(vdist(it.origin - org, <, tc_radius)) + ++c; + }); + + return c; + } + + // unused + #if 0 + void havocbot_goalrating_ctf_ourflag(entity this, float ratingscale) + { + entity head; + head = ctf_worldflaglist; + while (head) + { + if (CTF_SAMETEAM(this, head)) + break; + head = head.ctf_worldflagnext; + } + if (head) + navigation_routerating(this, head, ratingscale, 10000); + } + #endif + + void havocbot_goalrating_ctf_ourbase(entity this, float ratingscale) + { + entity head; + head = ctf_worldflaglist; + while (head) + { + if (CTF_SAMETEAM(this, head)) + { + if (this.flagcarried) + if ((this.flagcarried.cnt || head.cnt) && this.flagcarried.cnt != head.cnt) + { + head = head.ctf_worldflagnext; // skip base if it has a different group + continue; + } + break; + } + head = head.ctf_worldflagnext; + } + if (!head) + return; + + navigation_routerating(this, head.bot_basewaypoint, ratingscale, 10000); + } + + void havocbot_goalrating_ctf_enemyflag(entity this, float ratingscale) + { + entity head; + head = ctf_worldflaglist; + while (head) + { + if(ctf_oneflag) + { + if(CTF_DIFFTEAM(this, head)) + { + if(head.team) + { + if(this.flagcarried) + break; + } + else if(!this.flagcarried) + break; + } + } + else if(CTF_DIFFTEAM(this, head)) + break; + head = head.ctf_worldflagnext; + } + if (head) + navigation_routerating(this, head, ratingscale, 10000); + } + + void havocbot_goalrating_ctf_enemybase(entity this, float ratingscale) + { + if (!bot_waypoints_for_items) + { + havocbot_goalrating_ctf_enemyflag(this, ratingscale); + return; + } + + entity head; + + head = havocbot_ctf_find_enemy_flag(this); + + if (!head) + return; + + navigation_routerating(this, head.bot_basewaypoint, ratingscale, 10000); + } + + void havocbot_goalrating_ctf_ourstolenflag(entity this, float ratingscale) + { + entity mf; + + mf = havocbot_ctf_find_flag(this); + + if(mf.ctf_status == FLAG_BASE) + return; + + if(mf.tag_entity) + navigation_routerating(this, mf.tag_entity, ratingscale, 10000); + } + + void havocbot_goalrating_ctf_droppedflags(entity this, float ratingscale, vector org, float df_radius) + { + entity head; + head = ctf_worldflaglist; + while (head) + { + // flag is out in the field + if(head.ctf_status != FLAG_BASE) + if(head.tag_entity==NULL) // dropped + { + if(df_radius) + { + if(vdist(org - head.origin, <, df_radius)) + navigation_routerating(this, head, ratingscale, 10000); + } + else + navigation_routerating(this, head, ratingscale, 10000); + } + + head = head.ctf_worldflagnext; + } + } + + void havocbot_goalrating_ctf_carrieritems(entity this, float ratingscale, vector org, float sradius) + { + IL_EACH(g_items, it.bot_pickup, + { + // gather health and armor only + if (it.solid) + if (it.health || it.armorvalue) + if (vdist(it.origin - org, <, sradius)) + { + // get the value of the item + float t = it.bot_pickupevalfunc(this, it) * 0.0001; + if (t > 0) + navigation_routerating(this, it, t * ratingscale, 500); + } + }); + } + + void havocbot_ctf_reset_role(entity this) + { + float cdefense, cmiddle, coffense; + entity mf, ef; + float c; + + if(IS_DEAD(this)) + return; + + // Check ctf flags + if (this.flagcarried) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_CARRIER); + return; + } + + mf = havocbot_ctf_find_flag(this); + ef = havocbot_ctf_find_enemy_flag(this); + + // Retrieve stolen flag + if(mf.ctf_status!=FLAG_BASE) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_RETRIEVER); + return; + } + + // If enemy flag is taken go to the middle to intercept pursuers + if(ef.ctf_status!=FLAG_BASE) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_MIDDLE); + return; + } + + // if there is only me on the team switch to offense + c = 0; + FOREACH_CLIENT(IS_PLAYER(it) && SAME_TEAM(it, this), { ++c; }); + + if(c==1) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_OFFENSE); + return; + } + + // Evaluate best position to take + // Count mates on middle position + cmiddle = havocbot_ctf_teamcount(this, havocbot_middlepoint, havocbot_middlepoint_radius * 0.5); + + // Count mates on defense position + cdefense = havocbot_ctf_teamcount(this, mf.dropped_origin, havocbot_middlepoint_radius * 0.5); + + // Count mates on offense position + coffense = havocbot_ctf_teamcount(this, ef.dropped_origin, havocbot_middlepoint_radius); + + if(cdefense<=coffense) + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_DEFENSE); + else if(coffense<=cmiddle) + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_OFFENSE); + else + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_MIDDLE); + } + + void havocbot_role_ctf_carrier(entity this) + { + if(IS_DEAD(this)) + { + havocbot_ctf_reset_role(this); + return; + } + + if (this.flagcarried == NULL) + { + havocbot_ctf_reset_role(this); + return; + } + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + + if(ctf_oneflag) + havocbot_goalrating_ctf_enemybase(this, 50000); + else + havocbot_goalrating_ctf_ourbase(this, 50000); + + if(this.health<100) + havocbot_goalrating_ctf_carrieritems(this, 1000, this.origin, 1000); + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + + entity head = ctf_worldflaglist; + while (head) + { + if (this.goalentity == head.bot_basewaypoint) + { + this.goalentity_lock_timeout = time + 5; + break; + } + head = head.ctf_worldflagnext; + } + + if (this.goalentity) + this.havocbot_cantfindflag = time + 10; + else if (time > this.havocbot_cantfindflag) + { + // Can't navigate to my own base, suicide! + // TODO: drop it and wander around + Damage(this, this, this, 100000, DEATH_KILL.m_id, DMG_NOWEP, this.origin, '0 0 0'); + return; + } + } + } + + void havocbot_role_ctf_escort(entity this) + { + entity mf, ef; + + if(IS_DEAD(this)) + { + havocbot_ctf_reset_role(this); + return; + } + + if (this.flagcarried) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_CARRIER); + return; + } + + // If enemy flag is back on the base switch to previous role + ef = havocbot_ctf_find_enemy_flag(this); + if(ef.ctf_status==FLAG_BASE) + { + this.havocbot_role = this.havocbot_previous_role; + this.havocbot_role_timeout = 0; + return; + } + + // If the flag carrier reached the base switch to defense + mf = havocbot_ctf_find_flag(this); + if(mf.ctf_status!=FLAG_BASE) + if(vdist(ef.origin - mf.dropped_origin, <, 300)) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_DEFENSE); + return; + } + + // Set the role timeout if necessary + if (!this.havocbot_role_timeout) + { + this.havocbot_role_timeout = time + random() * 30 + 60; + } + + // If nothing happened just switch to previous role + if (time > this.havocbot_role_timeout) + { + this.havocbot_role = this.havocbot_previous_role; + this.havocbot_role_timeout = 0; + return; + } + + // Chase the flag carrier + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + + havocbot_goalrating_ctf_enemyflag(this, 30000); + havocbot_goalrating_ctf_ourstolenflag(this, 40000); + havocbot_goalrating_items(this, 10000, this.origin, 10000); + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_ctf_offense(entity this) + { + entity mf, ef; + vector pos; + + if(IS_DEAD(this)) + { + havocbot_ctf_reset_role(this); + return; + } + + if (this.flagcarried) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_CARRIER); + return; + } + + // Check flags + mf = havocbot_ctf_find_flag(this); + ef = havocbot_ctf_find_enemy_flag(this); + + // Own flag stolen + if(mf.ctf_status!=FLAG_BASE) + { + if(mf.tag_entity) + pos = mf.tag_entity.origin; + else + pos = mf.origin; + + // Try to get it if closer than the enemy base + if(vlen2(this.origin-ef.dropped_origin)>vlen2(this.origin-pos)) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_RETRIEVER); + return; + } + } + + // Escort flag carrier + if(ef.ctf_status!=FLAG_BASE) + { + if(ef.tag_entity) + pos = ef.tag_entity.origin; + else + pos = ef.origin; + + if(vdist(pos - mf.dropped_origin, >, 700)) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_ESCORT); + return; + } + } + + // About to fail, switch to middlefield + if(this.health<50) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_MIDDLE); + return; + } + + // Set the role timeout if necessary + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + 120; + + if (time > this.havocbot_role_timeout) + { + havocbot_ctf_reset_role(this); + return; + } + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + + havocbot_goalrating_ctf_ourstolenflag(this, 50000); + havocbot_goalrating_ctf_enemybase(this, 20000); + havocbot_goalrating_items(this, 5000, this.origin, 1000); + havocbot_goalrating_items(this, 1000, this.origin, 10000); + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + // Retriever (temporary role): + void havocbot_role_ctf_retriever(entity this) + { + entity mf; + + if(IS_DEAD(this)) + { + havocbot_ctf_reset_role(this); + return; + } + + if (this.flagcarried) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_CARRIER); + return; + } + + // If flag is back on the base switch to previous role + mf = havocbot_ctf_find_flag(this); + if(mf.ctf_status==FLAG_BASE) + { + if (mf.enemy == this) // did this bot return the flag? + navigation_goalrating_timeout_force(this); + havocbot_ctf_reset_role(this); + return; + } + + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + 20; + + if (time > this.havocbot_role_timeout) + { + havocbot_ctf_reset_role(this); + return; + } + + if (navigation_goalrating_timeout(this)) + { + float rt_radius; + rt_radius = 10000; + + navigation_goalrating_start(this); + + havocbot_goalrating_ctf_ourstolenflag(this, 50000); + havocbot_goalrating_ctf_droppedflags(this, 40000, this.origin, rt_radius); + havocbot_goalrating_ctf_enemybase(this, 30000); + havocbot_goalrating_items(this, 500, this.origin, rt_radius); + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_ctf_middle(entity this) + { + entity mf; + + if(IS_DEAD(this)) + { + havocbot_ctf_reset_role(this); + return; + } + + if (this.flagcarried) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_CARRIER); + return; + } + + mf = havocbot_ctf_find_flag(this); + if(mf.ctf_status!=FLAG_BASE) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_RETRIEVER); + return; + } + + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + 10; + + if (time > this.havocbot_role_timeout) + { + havocbot_ctf_reset_role(this); + return; + } + + if (navigation_goalrating_timeout(this)) + { + vector org; + + org = havocbot_middlepoint; + org.z = this.origin.z; + + navigation_goalrating_start(this); + + havocbot_goalrating_ctf_ourstolenflag(this, 50000); + havocbot_goalrating_ctf_droppedflags(this, 30000, this.origin, 10000); + havocbot_goalrating_enemyplayers(this, 10000, org, havocbot_middlepoint_radius * 0.5); + havocbot_goalrating_items(this, 5000, org, havocbot_middlepoint_radius * 0.5); + havocbot_goalrating_items(this, 2500, this.origin, 10000); + havocbot_goalrating_ctf_enemybase(this, 2500); + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_ctf_defense(entity this) + { + entity mf; + + if(IS_DEAD(this)) + { + havocbot_ctf_reset_role(this); + return; + } + + if (this.flagcarried) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_CARRIER); + return; + } + + // If own flag was captured + mf = havocbot_ctf_find_flag(this); + if(mf.ctf_status!=FLAG_BASE) + { + havocbot_role_ctf_setrole(this, HAVOCBOT_CTF_ROLE_RETRIEVER); + return; + } + + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + 30; + + if (time > this.havocbot_role_timeout) + { + havocbot_ctf_reset_role(this); + return; + } + if (navigation_goalrating_timeout(this)) + { + vector org = mf.dropped_origin; + + navigation_goalrating_start(this); + + // if enemies are closer to our base, go there + entity closestplayer = NULL; + float distance, bestdistance = 10000; + FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it), { + distance = vlen(org - it.origin); + if(distance, 1000)) + if(checkpvs(this.origin,closestplayer)||random()<0.5) + havocbot_goalrating_ctf_ourbase(this, 30000); + + havocbot_goalrating_ctf_ourstolenflag(this, 20000); + havocbot_goalrating_ctf_droppedflags(this, 20000, org, havocbot_middlepoint_radius); + havocbot_goalrating_enemyplayers(this, 15000, org, havocbot_middlepoint_radius); + havocbot_goalrating_items(this, 10000, org, havocbot_middlepoint_radius); + havocbot_goalrating_items(this, 5000, this.origin, 10000); + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_ctf_setrole(entity bot, int role) + { + string s = "(null)"; + switch(role) + { + case HAVOCBOT_CTF_ROLE_CARRIER: + s = "carrier"; + bot.havocbot_role = havocbot_role_ctf_carrier; + bot.havocbot_role_timeout = 0; + bot.havocbot_cantfindflag = time + 10; + if (bot.havocbot_previous_role != bot.havocbot_role) + navigation_goalrating_timeout_force(bot); + break; + case HAVOCBOT_CTF_ROLE_DEFENSE: + s = "defense"; + bot.havocbot_role = havocbot_role_ctf_defense; + bot.havocbot_role_timeout = 0; + break; + case HAVOCBOT_CTF_ROLE_MIDDLE: + s = "middle"; + bot.havocbot_role = havocbot_role_ctf_middle; + bot.havocbot_role_timeout = 0; + break; + case HAVOCBOT_CTF_ROLE_OFFENSE: + s = "offense"; + bot.havocbot_role = havocbot_role_ctf_offense; + bot.havocbot_role_timeout = 0; + break; + case HAVOCBOT_CTF_ROLE_RETRIEVER: + s = "retriever"; + bot.havocbot_previous_role = bot.havocbot_role; + bot.havocbot_role = havocbot_role_ctf_retriever; + bot.havocbot_role_timeout = time + 10; + if (bot.havocbot_previous_role != bot.havocbot_role) + navigation_goalrating_timeout_expire(bot, 2); + break; + case HAVOCBOT_CTF_ROLE_ESCORT: + s = "escort"; + bot.havocbot_previous_role = bot.havocbot_role; + bot.havocbot_role = havocbot_role_ctf_escort; + bot.havocbot_role_timeout = time + 30; + if (bot.havocbot_previous_role != bot.havocbot_role) + navigation_goalrating_timeout_expire(bot, 2); + break; + } + LOG_TRACE(bot.netname, " switched to ", s); + } + + + // ============== + // Hook Functions + // ============== + + MUTATOR_HOOKFUNCTION(ctf, PlayerPreThink) + { + entity player = M_ARGV(0, entity); + + int t = 0, t2 = 0, t3 = 0; + bool b1 = false, b2 = false, b3 = false, b4 = false, b5 = false; // TODO: kill this, we WANT to show the other flags, somehow! (note: also means you don't see if you're FC) + + // initially clear items so they can be set as necessary later. + STAT(CTF_FLAGSTATUS, player) &= ~(CTF_RED_FLAG_CARRYING | CTF_RED_FLAG_TAKEN | CTF_RED_FLAG_LOST + | CTF_BLUE_FLAG_CARRYING | CTF_BLUE_FLAG_TAKEN | CTF_BLUE_FLAG_LOST + | CTF_YELLOW_FLAG_CARRYING | CTF_YELLOW_FLAG_TAKEN | CTF_YELLOW_FLAG_LOST + | CTF_PINK_FLAG_CARRYING | CTF_PINK_FLAG_TAKEN | CTF_PINK_FLAG_LOST + | CTF_NEUTRAL_FLAG_CARRYING | CTF_NEUTRAL_FLAG_TAKEN | CTF_NEUTRAL_FLAG_LOST + | CTF_FLAG_NEUTRAL | CTF_SHIELDED | CTF_STALEMATE); + + // scan through all the flags and notify the client about them + for(entity flag = ctf_worldflaglist; flag; flag = flag.ctf_worldflagnext) + { + if(flag.team == NUM_TEAM_1 && !b1) { b1 = true; t = CTF_RED_FLAG_CARRYING; t2 = CTF_RED_FLAG_TAKEN; t3 = CTF_RED_FLAG_LOST; } + if(flag.team == NUM_TEAM_2 && !b2) { b2 = true; t = CTF_BLUE_FLAG_CARRYING; t2 = CTF_BLUE_FLAG_TAKEN; t3 = CTF_BLUE_FLAG_LOST; } + if(flag.team == NUM_TEAM_3 && !b3) { b3 = true; t = CTF_YELLOW_FLAG_CARRYING; t2 = CTF_YELLOW_FLAG_TAKEN; t3 = CTF_YELLOW_FLAG_LOST; } + if(flag.team == NUM_TEAM_4 && !b4) { b4 = true; t = CTF_PINK_FLAG_CARRYING; t2 = CTF_PINK_FLAG_TAKEN; t3 = CTF_PINK_FLAG_LOST; } + if(flag.team == 0 && !b5) { b5 = true; t = CTF_NEUTRAL_FLAG_CARRYING; t2 = CTF_NEUTRAL_FLAG_TAKEN; t3 = CTF_NEUTRAL_FLAG_LOST; STAT(CTF_FLAGSTATUS, player) |= CTF_FLAG_NEUTRAL; } + + switch(flag.ctf_status) + { + case FLAG_PASSING: + case FLAG_CARRY: + { + if((flag.owner == player) || (flag.pass_sender == player)) + STAT(CTF_FLAGSTATUS, player) |= t; // carrying: player is currently carrying the flag + else + STAT(CTF_FLAGSTATUS, player) |= t2; // taken: someone else is carrying the flag + break; + } + case FLAG_DROPPED: + { + STAT(CTF_FLAGSTATUS, player) |= t3; // lost: the flag is dropped somewhere on the map + break; + } + } + } + + // item for stopping players from capturing the flag too often + if(player.ctf_captureshielded) + STAT(CTF_FLAGSTATUS, player) |= CTF_SHIELDED; + + if(ctf_stalemate) + STAT(CTF_FLAGSTATUS, player) |= CTF_STALEMATE; + + // update the health of the flag carrier waypointsprite + if(player.wps_flagcarrier) + WaypointSprite_UpdateHealth(player.wps_flagcarrier, '1 0 0' * healtharmor_maxdamage(player.health, player.armorvalue, autocvar_g_balance_armor_blockpercent, DEATH_WEAPON.m_id)); + } + + MUTATOR_HOOKFUNCTION(ctf, Damage_Calculate) // for changing damage and force values that are applied to players in g_damage.qc + { + entity frag_attacker = M_ARGV(1, entity); + entity frag_target = M_ARGV(2, entity); + float frag_damage = M_ARGV(4, float); + vector frag_force = M_ARGV(6, vector); + + if(frag_attacker.flagcarried) // if the attacker is a flagcarrier + { + if(frag_target == frag_attacker) // damage done to yourself + { + frag_damage *= autocvar_g_ctf_flagcarrier_selfdamagefactor; + frag_force *= autocvar_g_ctf_flagcarrier_selfforcefactor; + } + else // damage done to everyone else + { + frag_damage *= autocvar_g_ctf_flagcarrier_damagefactor; + frag_force *= autocvar_g_ctf_flagcarrier_forcefactor; + } + + M_ARGV(4, float) = frag_damage; + M_ARGV(6, vector) = frag_force; + } + else if(frag_target.flagcarried && !IS_DEAD(frag_target) && CTF_DIFFTEAM(frag_target, frag_attacker)) // if the target is a flagcarrier + { + if(autocvar_g_ctf_flagcarrier_auto_helpme_damage > ('1 0 0' * healtharmor_maxdamage(frag_target.health, frag_target.armorvalue, autocvar_g_balance_armor_blockpercent, DEATH_WEAPON.m_id))) + if(time > frag_target.wps_helpme_time + autocvar_g_ctf_flagcarrier_auto_helpme_time) + { + frag_target.wps_helpme_time = time; + WaypointSprite_HelpMePing(frag_target.wps_flagcarrier); + } + // todo: add notification for when flag carrier needs help? + } + } + + MUTATOR_HOOKFUNCTION(ctf, PlayerDies) + { + entity frag_attacker = M_ARGV(1, entity); + entity frag_target = M_ARGV(2, entity); + + if((frag_attacker != frag_target) && (IS_PLAYER(frag_attacker)) && (frag_target.flagcarried)) + { + GameRules_scoring_add_team(frag_attacker, SCORE, ((SAME_TEAM(frag_attacker, frag_target)) ? -autocvar_g_ctf_score_kill : autocvar_g_ctf_score_kill)); + GameRules_scoring_add(frag_attacker, CTF_FCKILLS, 1); + } + + if(frag_target.flagcarried) + { + entity tmp_entity = frag_target.flagcarried; + ctf_Handle_Throw(frag_target, NULL, DROP_NORMAL); + tmp_entity.ctf_dropper = NULL; + } + } + + MUTATOR_HOOKFUNCTION(ctf, GiveFragsForKill) + { + M_ARGV(2, float) = 0; // frag score + return (autocvar_g_ctf_ignore_frags); // no frags counted in ctf if this is true + } + + void ctf_RemovePlayer(entity player) + { + if(player.flagcarried) + { ctf_Handle_Throw(player, NULL, DROP_NORMAL); } + + for(entity flag = ctf_worldflaglist; flag; flag = flag.ctf_worldflagnext) + { + if(flag.pass_sender == player) { flag.pass_sender = NULL; } + if(flag.pass_target == player) { flag.pass_target = NULL; } + if(flag.ctf_dropper == player) { flag.ctf_dropper = NULL; } + } + } + + MUTATOR_HOOKFUNCTION(ctf, MakePlayerObserver) + { + entity player = M_ARGV(0, entity); + + ctf_RemovePlayer(player); + } + + MUTATOR_HOOKFUNCTION(ctf, ClientDisconnect) + { + entity player = M_ARGV(0, entity); + + ctf_RemovePlayer(player); + } + + MUTATOR_HOOKFUNCTION(ctf, ClientConnect) + { + if(!autocvar_g_ctf_leaderboard) + return; + + entity player = M_ARGV(0, entity); + + if(IS_REAL_CLIENT(player)) + { + int m = min(RANKINGS_CNT, autocvar_g_cts_send_rankings_cnt); + race_send_rankings_cnt(MSG_ONE); + for (int i = 1; i <= m; ++i) + { + race_SendRankings(i, 0, 0, MSG_ONE); + } + } + } + + MUTATOR_HOOKFUNCTION(ctf, GetPressedKeys) + { + if(!autocvar_g_ctf_leaderboard) + return; + + entity player = M_ARGV(0, entity); + + if(CS(player).cvar_cl_allow_uidtracking == 1 && CS(player).cvar_cl_allow_uid2name == 1) + { + if (!player.stored_netname) + player.stored_netname = strzone(uid2name(player.crypto_idfp)); + if(player.stored_netname != player.netname) + { + db_put(ServerProgsDB, strcat("/uid2name/", player.crypto_idfp), player.netname); + strcpy(player.stored_netname, player.netname); + } + } + } + + MUTATOR_HOOKFUNCTION(ctf, PortalTeleport) + { + entity player = M_ARGV(0, entity); + + if(player.flagcarried) + if(!autocvar_g_ctf_portalteleport) + { ctf_Handle_Throw(player, NULL, DROP_NORMAL); } + } + + MUTATOR_HOOKFUNCTION(ctf, PlayerUseKey) + { + if(MUTATOR_RETURNVALUE || game_stopped) return; + + entity player = M_ARGV(0, entity); + + if((time > player.throw_antispam) && !IS_DEAD(player) && !player.speedrunning && (!player.vehicle || autocvar_g_ctf_allow_vehicle_touch)) + { + // pass the flag to a team mate + if(autocvar_g_ctf_pass) + { + entity head, closest_target = NULL; + head = WarpZone_FindRadius(player.origin, autocvar_g_ctf_pass_radius, true); + + while(head) // find the closest acceptable target to pass to + { + if(IS_PLAYER(head) && !IS_DEAD(head)) + if(head != player && SAME_TEAM(head, player)) + if(!head.speedrunning && !head.vehicle) + { + // if it's a player, use the view origin as reference (stolen from RadiusDamage functions in g_damage.qc) + vector head_center = WarpZone_UnTransformOrigin(head, CENTER_OR_VIEWOFS(head)); + vector passer_center = CENTER_OR_VIEWOFS(player); + + if(ctf_CheckPassDirection(head_center, passer_center, player.v_angle, head.WarpZone_findradius_nearest)) + { + if(autocvar_g_ctf_pass_request && !player.flagcarried && head.flagcarried) + { + if(IS_BOT_CLIENT(head)) + { + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_CTF_PASS_REQUESTING, head.netname); + ctf_Handle_Throw(head, player, DROP_PASS); + } + else + { + Send_Notification(NOTIF_ONE, head, MSG_CENTER, CENTER_CTF_PASS_REQUESTED, player.netname); + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_CTF_PASS_REQUESTING, head.netname); + } + player.throw_antispam = time + autocvar_g_ctf_pass_wait; + return true; + } + else if(player.flagcarried && !head.flagcarried) + { + if(closest_target) + { + vector closest_target_center = WarpZone_UnTransformOrigin(closest_target, CENTER_OR_VIEWOFS(closest_target)); + if(vlen2(passer_center - head_center) < vlen2(passer_center - closest_target_center)) + { closest_target = head; } + } + else { closest_target = head; } + } + } + } + head = head.chain; + } + + if(closest_target) { ctf_Handle_Throw(player, closest_target, DROP_PASS); return true; } + } + + // throw the flag in front of you + if(autocvar_g_ctf_throw && player.flagcarried) + { + if(player.throw_count == -1) + { + if(time > player.throw_prevtime + autocvar_g_ctf_throw_punish_delay) + { + player.throw_prevtime = time; + player.throw_count = 1; + ctf_Handle_Throw(player, NULL, DROP_THROW); + return true; + } + else + { + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_CTF_FLAG_THROW_PUNISH, rint((player.throw_prevtime + autocvar_g_ctf_throw_punish_delay) - time)); + return false; + } + } + else + { + if(time > player.throw_prevtime + autocvar_g_ctf_throw_punish_time) { player.throw_count = 1; } + else { player.throw_count += 1; } + if(player.throw_count >= autocvar_g_ctf_throw_punish_count) { player.throw_count = -1; } + + player.throw_prevtime = time; + ctf_Handle_Throw(player, NULL, DROP_THROW); + return true; + } + } + } + } + + MUTATOR_HOOKFUNCTION(ctf, HelpMePing) + { + entity player = M_ARGV(0, entity); + + if(player.wps_flagcarrier) // update the flagcarrier waypointsprite with "NEEDING HELP" notification + { + player.wps_helpme_time = time; + WaypointSprite_HelpMePing(player.wps_flagcarrier); + } + else // create a normal help me waypointsprite + { + WaypointSprite_Spawn(WP_Helpme, waypointsprite_deployed_lifetime, waypointsprite_limitedrange, player, FLAG_WAYPOINT_OFFSET, NULL, player.team, player, wps_helpme, false, RADARICON_HELPME); + WaypointSprite_Ping(player.wps_helpme); + } + + return true; + } + + MUTATOR_HOOKFUNCTION(ctf, VehicleEnter) + { + entity player = M_ARGV(0, entity); + entity veh = M_ARGV(1, entity); + + if(player.flagcarried) + { + if(!autocvar_g_ctf_allow_vehicle_carry && !autocvar_g_ctf_allow_vehicle_touch) + { + ctf_Handle_Throw(player, NULL, DROP_NORMAL); + } + else + { + player.flagcarried.nodrawtoclient = player; // hide the flag from the driver + setattachment(player.flagcarried, veh, ""); + setorigin(player.flagcarried, VEHICLE_FLAG_OFFSET); + player.flagcarried.scale = VEHICLE_FLAG_SCALE; + //player.flagcarried.angles = '0 0 0'; + } + return true; + } + } + + MUTATOR_HOOKFUNCTION(ctf, VehicleExit) + { + entity player = M_ARGV(0, entity); + + if(player.flagcarried) + { + setattachment(player.flagcarried, player, ""); + setorigin(player.flagcarried, FLAG_CARRY_OFFSET); + player.flagcarried.scale = FLAG_SCALE; + player.flagcarried.angles = '0 0 0'; + player.flagcarried.nodrawtoclient = NULL; + return true; + } + } + + MUTATOR_HOOKFUNCTION(ctf, AbortSpeedrun) + { + entity player = M_ARGV(0, entity); + + if(player.flagcarried) + { + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_NUM(player.flagcarried.team, INFO_CTF_FLAGRETURN_ABORTRUN)); + ctf_RespawnFlag(player.flagcarried); + return true; + } + } + + MUTATOR_HOOKFUNCTION(ctf, MatchEnd) + { + entity flag; // temporary entity for the search method + + for(flag = ctf_worldflaglist; flag; flag = flag.ctf_worldflagnext) + { + switch(flag.ctf_status) + { + case FLAG_DROPPED: + case FLAG_PASSING: + { + // lock the flag, game is over + set_movetype(flag, MOVETYPE_NONE); + flag.takedamage = DAMAGE_NO; + flag.solid = SOLID_NOT; + flag.nextthink = false; // stop thinking + + //dprint("stopping the ", flag.netname, " from moving.\n"); + break; + } + + default: + case FLAG_BASE: + case FLAG_CARRY: + { + // do nothing for these flags + break; + } + } + } + } + + MUTATOR_HOOKFUNCTION(ctf, HavocBot_ChooseRole) + { + entity bot = M_ARGV(0, entity); + + havocbot_ctf_reset_role(bot); + return true; + } + -MUTATOR_HOOKFUNCTION(ctf, CheckAllowedTeams) ++MUTATOR_HOOKFUNCTION(ctf, TeamBalance_CheckAllowedTeams) + { - //M_ARGV(0, float) = ctf_teams; + M_ARGV(1, string) = "ctf_team"; - return true; + } + + MUTATOR_HOOKFUNCTION(ctf, SpectateCopy) + { + entity spectatee = M_ARGV(0, entity); + entity client = M_ARGV(1, entity); + + STAT(CTF_FLAGSTATUS, client) = STAT(CTF_FLAGSTATUS, spectatee); + } + + MUTATOR_HOOKFUNCTION(ctf, GetRecords) + { + int record_page = M_ARGV(0, int); + string ret_string = M_ARGV(1, string); + + for(int i = record_page * 200; i < MapInfo_count && i < record_page * 200 + 200; ++i) + { + if (MapInfo_Get_ByID(i)) + { + float r = stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/time"))); + + if(!r) + continue; + + // TODO: uid2name + string h = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/netname")); + ret_string = strcat(ret_string, strpad(32, MapInfo_Map_bspname), " ", strpad(-6, ftos_decimals(r, 2)), " ", h, "\n"); + } + } + + M_ARGV(1, string) = ret_string; + } + + bool superspec_Spectate(entity this, entity targ); // TODO + void superspec_msg(string _center_title, string _con_title, entity _to, string _msg, float _spamlevel); // TODO + MUTATOR_HOOKFUNCTION(ctf, SV_ParseClientCommand) + { + entity player = M_ARGV(0, entity); + string cmd_name = M_ARGV(1, string); + int cmd_argc = M_ARGV(2, int); + + if(IS_PLAYER(player) || MUTATOR_RETURNVALUE || !cvar("g_superspectate")) { return false; } + + if(cmd_name == "followfc") + { + if(!g_ctf) + return true; + + int _team = 0; + bool found = false; + + if(cmd_argc == 2) + { + switch(argv(1)) + { + case "red": if(ctf_teams & BIT(0)) _team = NUM_TEAM_1; break; + case "blue": if(ctf_teams & BIT(1)) _team = NUM_TEAM_2; break; + case "yellow": if(ctf_teams & BIT(2)) _team = NUM_TEAM_3; break; + case "pink": if(ctf_teams & BIT(3)) _team = NUM_TEAM_4; break; + } + } + + FOREACH_CLIENT(IS_PLAYER(it), { + if(it.flagcarried && (it.team == _team || _team == 0)) + { + found = true; + if(_team == 0 && IS_SPEC(player) && player.enemy == it) + continue; // already spectating this fc, try another + return superspec_Spectate(player, it); + } + }); + + if(!found) + superspec_msg("", "", player, "No active flag carrier\n", 1); + return true; + } + } + + MUTATOR_HOOKFUNCTION(ctf, DropSpecialItems) + { + entity frag_target = M_ARGV(0, entity); + + if(frag_target.flagcarried) + ctf_Handle_Throw(frag_target, NULL, DROP_THROW); + } + + + // ========== + // Spawnfuncs + // ========== + + /*QUAKED spawnfunc_item_flag_team1 (0 0.5 0.8) (-48 -48 -37) (48 48 37) + CTF flag for team one (Red). + Keys: + "angle" Angle the flag will point (minus 90 degrees)... + "model" model to use, note this needs red and blue as skins 0 and 1... + "noise" sound played when flag is picked up... + "noise1" sound played when flag is returned by a teammate... + "noise2" sound played when flag is captured... + "noise3" sound played when flag is lost in the field and respawns itself... + "noise4" sound played when flag is dropped by a player... + "noise5" sound played when flag touches the ground... */ + spawnfunc(item_flag_team1) + { + if(!g_ctf) { delete(this); return; } + + ctf_FlagSetup(NUM_TEAM_1, this); + } + + /*QUAKED spawnfunc_item_flag_team2 (0 0.5 0.8) (-48 -48 -37) (48 48 37) + CTF flag for team two (Blue). + Keys: + "angle" Angle the flag will point (minus 90 degrees)... + "model" model to use, note this needs red and blue as skins 0 and 1... + "noise" sound played when flag is picked up... + "noise1" sound played when flag is returned by a teammate... + "noise2" sound played when flag is captured... + "noise3" sound played when flag is lost in the field and respawns itself... + "noise4" sound played when flag is dropped by a player... + "noise5" sound played when flag touches the ground... */ + spawnfunc(item_flag_team2) + { + if(!g_ctf) { delete(this); return; } + + ctf_FlagSetup(NUM_TEAM_2, this); + } + + /*QUAKED spawnfunc_item_flag_team3 (0 0.5 0.8) (-48 -48 -37) (48 48 37) + CTF flag for team three (Yellow). + Keys: + "angle" Angle the flag will point (minus 90 degrees)... + "model" model to use, note this needs red, blue yellow and pink as skins 0, 1, 2 and 3... + "noise" sound played when flag is picked up... + "noise1" sound played when flag is returned by a teammate... + "noise2" sound played when flag is captured... + "noise3" sound played when flag is lost in the field and respawns itself... + "noise4" sound played when flag is dropped by a player... + "noise5" sound played when flag touches the ground... */ + spawnfunc(item_flag_team3) + { + if(!g_ctf) { delete(this); return; } + + ctf_FlagSetup(NUM_TEAM_3, this); + } + + /*QUAKED spawnfunc_item_flag_team4 (0 0.5 0.8) (-48 -48 -37) (48 48 37) + CTF flag for team four (Pink). + Keys: + "angle" Angle the flag will point (minus 90 degrees)... + "model" model to use, note this needs red, blue yellow and pink as skins 0, 1, 2 and 3... + "noise" sound played when flag is picked up... + "noise1" sound played when flag is returned by a teammate... + "noise2" sound played when flag is captured... + "noise3" sound played when flag is lost in the field and respawns itself... + "noise4" sound played when flag is dropped by a player... + "noise5" sound played when flag touches the ground... */ + spawnfunc(item_flag_team4) + { + if(!g_ctf) { delete(this); return; } + + ctf_FlagSetup(NUM_TEAM_4, this); + } + + /*QUAKED spawnfunc_item_flag_neutral (0 0.5 0.8) (-48 -48 -37) (48 48 37) + CTF flag (Neutral). + Keys: + "angle" Angle the flag will point (minus 90 degrees)... + "model" model to use, note this needs red, blue yellow and pink as skins 0, 1, 2 and 3... + "noise" sound played when flag is picked up... + "noise1" sound played when flag is returned by a teammate... + "noise2" sound played when flag is captured... + "noise3" sound played when flag is lost in the field and respawns itself... + "noise4" sound played when flag is dropped by a player... + "noise5" sound played when flag touches the ground... */ + spawnfunc(item_flag_neutral) + { + if(!g_ctf) { delete(this); return; } + if(!cvar("g_ctf_oneflag")) { delete(this); return; } + + ctf_FlagSetup(0, this); + } + + /*QUAKED spawnfunc_ctf_team (0 .5 .8) (-16 -16 -24) (16 16 32) + Team declaration for CTF gameplay, this allows you to decide what team names and control point models are used in your map. + Note: If you use spawnfunc_ctf_team entities you must define at least 2! However, unlike domination, you don't need to make a blank one too. + Keys: + "netname" Name of the team (for example Red, Blue, Green, Yellow, Life, Death, Offense, Defense, etc)... + "cnt" Scoreboard color of the team (for example 4 is red and 13 is blue)... */ + spawnfunc(ctf_team) + { + if(!g_ctf) { delete(this); return; } + + this.classname = "ctf_team"; + this.team = this.cnt + 1; + } + + // compatibility for quake maps + spawnfunc(team_CTF_redflag) { spawnfunc_item_flag_team1(this); } + spawnfunc(team_CTF_blueflag) { spawnfunc_item_flag_team2(this); } + spawnfunc(info_player_team1); + spawnfunc(team_CTF_redplayer) { spawnfunc_info_player_team1(this); } + spawnfunc(team_CTF_redspawn) { spawnfunc_info_player_team1(this); } + spawnfunc(info_player_team2); + spawnfunc(team_CTF_blueplayer) { spawnfunc_info_player_team2(this); } + spawnfunc(team_CTF_bluespawn) { spawnfunc_info_player_team2(this); } + + spawnfunc(team_CTF_neutralflag) { spawnfunc_item_flag_neutral(this); } + spawnfunc(team_neutralobelisk) { spawnfunc_item_flag_neutral(this); } + + // compatibility for wop maps + spawnfunc(team_redplayer) { spawnfunc_info_player_team1(this); } + spawnfunc(team_blueplayer) { spawnfunc_info_player_team2(this); } + spawnfunc(team_ctl_redlolly) { spawnfunc_item_flag_team1(this); } + spawnfunc(team_CTL_redlolly) { spawnfunc_item_flag_team1(this); } + spawnfunc(team_ctl_bluelolly) { spawnfunc_item_flag_team2(this); } + spawnfunc(team_CTL_bluelolly) { spawnfunc_item_flag_team2(this); } + + + // ============== + // Initialization + // ============== + + // scoreboard setup + void ctf_ScoreRules(int teams) + { - CheckAllowedTeams(NULL); ++ //CheckAllowedTeams(NULL); // Bug? Need to get allowed teams? + GameRules_scoring(teams, SFL_SORT_PRIO_PRIMARY, 0, { + field_team(ST_CTF_CAPS, "caps", SFL_SORT_PRIO_PRIMARY); + field(SP_CTF_CAPS, "caps", SFL_SORT_PRIO_SECONDARY); + field(SP_CTF_CAPTIME, "captime", SFL_LOWER_IS_BETTER | SFL_TIME); + field(SP_CTF_PICKUPS, "pickups", 0); + field(SP_CTF_FCKILLS, "fckills", 0); + field(SP_CTF_RETURNS, "returns", 0); + field(SP_CTF_DROPS, "drops", SFL_LOWER_IS_BETTER); + }); + } + + // code from here on is just to support maps that don't have flag and team entities + void ctf_SpawnTeam (string teamname, int teamcolor) + { + entity this = new_pure(ctf_team); + this.netname = teamname; + this.cnt = teamcolor - 1; + this.spawnfunc_checked = true; + this.team = teamcolor; + } + + void ctf_DelayedInit(entity this) // Do this check with a delay so we can wait for teams to be set up. + { + ctf_teams = 0; + + entity tmp_entity; + for(tmp_entity = ctf_worldflaglist; tmp_entity; tmp_entity = tmp_entity.ctf_worldflagnext) + { + //if(tmp_entity.team == NUM_TEAM_3) { ctf_teams = max(3, ctf_teams); } + //if(tmp_entity.team == NUM_TEAM_4) { ctf_teams = max(4, ctf_teams); } + + switch(tmp_entity.team) + { + case NUM_TEAM_1: BITSET_ASSIGN(ctf_teams, BIT(0)); break; + case NUM_TEAM_2: BITSET_ASSIGN(ctf_teams, BIT(1)); break; + case NUM_TEAM_3: BITSET_ASSIGN(ctf_teams, BIT(2)); break; + case NUM_TEAM_4: BITSET_ASSIGN(ctf_teams, BIT(3)); break; + } + if(tmp_entity.team == 0) { ctf_oneflag = true; } + } + + havocbot_ctf_calculate_middlepoint(); + + if(NumTeams(ctf_teams) < 2) // somehow, there's not enough flags! + { + ctf_teams = 0; // so set the default red and blue teams + BITSET_ASSIGN(ctf_teams, BIT(0)); + BITSET_ASSIGN(ctf_teams, BIT(1)); + } + + //ctf_teams = bound(2, ctf_teams, 4); + + // if no teams are found, spawn defaults + if(find(NULL, classname, "ctf_team") == NULL) + { + LOG_TRACE("No \"ctf_team\" entities found on this map, creating them anyway."); + if(ctf_teams & BIT(0)) + ctf_SpawnTeam("Red", NUM_TEAM_1); + if(ctf_teams & BIT(1)) + ctf_SpawnTeam("Blue", NUM_TEAM_2); + if(ctf_teams & BIT(2)) + ctf_SpawnTeam("Yellow", NUM_TEAM_3); + if(ctf_teams & BIT(3)) + ctf_SpawnTeam("Pink", NUM_TEAM_4); + } + + ctf_ScoreRules(ctf_teams); + } + + void ctf_Initialize() + { + ctf_captimerecord = stof(db_get(ServerProgsDB, strcat(GetMapname(), "/captimerecord/time"))); + + ctf_captureshield_min_negscore = autocvar_g_ctf_shield_min_negscore; + ctf_captureshield_max_ratio = autocvar_g_ctf_shield_max_ratio; + ctf_captureshield_force = autocvar_g_ctf_shield_force; + + InitializeEntity(NULL, ctf_DelayedInit, INITPRIO_GAMETYPE); + } + #endif diff --cc qcsrc/common/gamemodes/gamemode/domination/domination.qc index 000000000,3faa4a89a..46067f907 mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/domination/domination.qc +++ b/qcsrc/common/gamemodes/gamemode/domination/domination.qc @@@ -1,0 -1,673 +1,669 @@@ + #include "domination.qh" + + // TODO: sv_domination + #ifdef SVQC + #include + + bool g_domination; + + int autocvar_g_domination_default_teams; + bool autocvar_g_domination_disable_frags; + int autocvar_g_domination_point_amt; + bool autocvar_g_domination_point_fullbright; + float autocvar_g_domination_round_timelimit; + float autocvar_g_domination_warmup; + float autocvar_g_domination_point_rate; + int autocvar_g_domination_teams_override; + + void dom_EventLog(string mode, float team_before, entity actor) // use an alias for easy changing and quick editing later + { + if(autocvar_sv_eventlog) + GameLogEcho(strcat(":dom:", mode, ":", ftos(team_before), ((actor != NULL) ? (strcat(":", ftos(actor.playerid))) : ""))); + } + + void set_dom_state(entity e) + { + STAT(DOM_TOTAL_PPS, e) = total_pps; + STAT(DOM_PPS_RED, e) = pps_red; + STAT(DOM_PPS_BLUE, e) = pps_blue; + if(domination_teams >= 3) + STAT(DOM_PPS_YELLOW, e) = pps_yellow; + if(domination_teams >= 4) + STAT(DOM_PPS_PINK, e) = pps_pink; + } + + void dompoint_captured(entity this) + { + float old_delay, old_team, real_team; + + // now that the delay has expired, switch to the latest team to lay claim to this point + entity head = this.owner; + + real_team = this.cnt; + this.cnt = -1; + + dom_EventLog("taken", this.team, this.dmg_inflictor); + this.dmg_inflictor = NULL; + + this.goalentity = head; + this.model = head.mdl; + this.modelindex = head.dmg; + this.skin = head.skin; + + float points, wait_time; + if (autocvar_g_domination_point_amt) + points = autocvar_g_domination_point_amt; + else + points = this.frags; + if (autocvar_g_domination_point_rate) + wait_time = autocvar_g_domination_point_rate; + else + wait_time = this.wait; + + if(domination_roundbased) + bprint(sprintf("^3%s^3%s\n", head.netname, this.message)); + else + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_DOMINATION_CAPTURE_TIME, head.netname, this.message, points, wait_time); + + if(this.enemy.playerid == this.enemy_playerid) + GameRules_scoring_add(this.enemy, DOM_TAKES, 1); + else + this.enemy = NULL; + + if (head.noise != "") + if(this.enemy) + _sound(this.enemy, CH_TRIGGER, head.noise, VOL_BASE, ATTEN_NORM); + else + _sound(this, CH_TRIGGER, head.noise, VOL_BASE, ATTEN_NORM); + if (head.noise1 != "") + play2all(head.noise1); + + this.delay = time + wait_time; + + // do trigger work + old_delay = this.delay; + old_team = this.team; + this.team = real_team; + this.delay = 0; + SUB_UseTargets (this, this, NULL); + this.delay = old_delay; + this.team = old_team; + + entity msg = WP_DomNeut; + switch(real_team) + { + case NUM_TEAM_1: msg = WP_DomRed; break; + case NUM_TEAM_2: msg = WP_DomBlue; break; + case NUM_TEAM_3: msg = WP_DomYellow; break; + case NUM_TEAM_4: msg = WP_DomPink; break; + } + + WaypointSprite_UpdateSprites(this.sprite, msg, WP_Null, WP_Null); + + total_pps = 0, pps_red = 0, pps_blue = 0, pps_yellow = 0, pps_pink = 0; + IL_EACH(g_dompoints, true, + { + if (autocvar_g_domination_point_amt) + points = autocvar_g_domination_point_amt; + else + points = it.frags; + if (autocvar_g_domination_point_rate) + wait_time = autocvar_g_domination_point_rate; + else + wait_time = it.wait; + switch(it.goalentity.team) + { + case NUM_TEAM_1: pps_red += points/wait_time; break; + case NUM_TEAM_2: pps_blue += points/wait_time; break; + case NUM_TEAM_3: pps_yellow += points/wait_time; break; + case NUM_TEAM_4: pps_pink += points/wait_time; break; + } + total_pps += points/wait_time; + }); + + WaypointSprite_UpdateTeamRadar(this.sprite, RADARICON_DOMPOINT, colormapPaletteColor(this.goalentity.team - 1, 0)); + WaypointSprite_Ping(this.sprite); + + this.captime = time; + + FOREACH_CLIENT(IS_REAL_CLIENT(it), { set_dom_state(it); }); + } + + void AnimateDomPoint(entity this) + { + if(this.pain_finished > time) + return; + this.pain_finished = time + this.t_width; + if(this.nextthink > this.pain_finished) + this.nextthink = this.pain_finished; + + this.frame = this.frame + 1; + if(this.frame > this.t_length) + this.frame = 0; + } + + void dompointthink(entity this) + { + float fragamt; + + this.nextthink = time + 0.1; + + //this.frame = this.frame + 1; + //if(this.frame > 119) + // this.frame = 0; + AnimateDomPoint(this); + + // give points + + if (game_stopped || this.delay > time || time < game_starttime) // game has ended, don't keep giving points + return; + + if(autocvar_g_domination_point_rate) + this.delay = time + autocvar_g_domination_point_rate; + else + this.delay = time + this.wait; + + // give credit to the team + // NOTE: this defaults to 0 + if (!domination_roundbased) + if (this.goalentity.netname != "") + { + if(autocvar_g_domination_point_amt) + fragamt = autocvar_g_domination_point_amt; + else + fragamt = this.frags; + TeamScore_AddToTeam(this.goalentity.team, ST_SCORE, fragamt); + TeamScore_AddToTeam(this.goalentity.team, ST_DOM_TICKS, fragamt); + + // give credit to the individual player, if he is still there + if (this.enemy.playerid == this.enemy_playerid) + { + GameRules_scoring_add(this.enemy, SCORE, fragamt); + GameRules_scoring_add(this.enemy, DOM_TICKS, fragamt); + } + else + this.enemy = NULL; + } + } + + void dompointtouch(entity this, entity toucher) + { + if (!IS_PLAYER(toucher)) + return; + if (toucher.health < 1) + return; + + if(round_handler_IsActive() && !round_handler_IsRoundStarted()) + return; + + if(time < this.captime + 0.3) + return; + + // only valid teams can claim it + entity head = find(NULL, classname, "dom_team"); + while (head && head.team != toucher.team) + head = find(head, classname, "dom_team"); + if (!head || head.netname == "" || head == this.goalentity) + return; + + // delay capture + + this.team = this.goalentity.team; // this stores the PREVIOUS team! + + this.cnt = toucher.team; + this.owner = head; // team to switch to after the delay + this.dmg_inflictor = toucher; + + // this.state = 1; + // this.delay = time + cvar("g_domination_point_capturetime"); + //this.nextthink = time + cvar("g_domination_point_capturetime"); + //this.think = dompoint_captured; + + // go to neutral team in the mean time + head = find(NULL, classname, "dom_team"); + while (head && head.netname != "") + head = find(head, classname, "dom_team"); + if(head == NULL) + return; + + WaypointSprite_UpdateSprites(this.sprite, WP_DomNeut, WP_Null, WP_Null); + WaypointSprite_UpdateTeamRadar(this.sprite, RADARICON_DOMPOINT, '0 1 1'); + WaypointSprite_Ping(this.sprite); + + this.goalentity = head; + this.model = head.mdl; + this.modelindex = head.dmg; + this.skin = head.skin; + + this.enemy = toucher; // individual player scoring + this.enemy_playerid = toucher.playerid; + dompoint_captured(this); + } + + void dom_controlpoint_setup(entity this) + { + entity head; + // find the spawnfunc_dom_team representing unclaimed points + head = find(NULL, classname, "dom_team"); + while(head && head.netname != "") + head = find(head, classname, "dom_team"); + if (!head) + objerror(this, "no spawnfunc_dom_team with netname \"\" found\n"); + + // copy important properties from spawnfunc_dom_team entity + this.goalentity = head; + _setmodel(this, head.mdl); // precision already set + this.skin = head.skin; + + this.cnt = -1; + + if(this.message == "") + this.message = " has captured a control point"; + + if(this.frags <= 0) + this.frags = 1; + if(this.wait <= 0) + this.wait = 5; + + float points, waittime; + if (autocvar_g_domination_point_amt) + points = autocvar_g_domination_point_amt; + else + points = this.frags; + if (autocvar_g_domination_point_rate) + waittime = autocvar_g_domination_point_rate; + else + waittime = this.wait; + + total_pps += points/waittime; + + if(!this.t_width) + this.t_width = 0.02; // frame animation rate + if(!this.t_length) + this.t_length = 239; // maximum frame + + setthink(this, dompointthink); + this.nextthink = time; + settouch(this, dompointtouch); + this.solid = SOLID_TRIGGER; + if(!this.flags & FL_ITEM) + IL_PUSH(g_items, this); + this.flags = FL_ITEM; + setsize(this, '-32 -32 -32', '32 32 32'); + setorigin(this, this.origin + '0 0 20'); + droptofloor(this); + + waypoint_spawnforitem(this); + WaypointSprite_SpawnFixed(WP_DomNeut, this.origin + '0 0 32', this, sprite, RADARICON_DOMPOINT); + } + -float total_controlpoints; ++int total_control_points; + void Domination_count_controlpoints() + { - total_controlpoints = redowned = blueowned = yellowowned = pinkowned = 0; ++ total_control_points = 0; ++ for (int i = 1; i <= NUM_TEAMS; ++i) ++ { ++ Team_SetNumberOfControlPoints(Team_GetTeamFromIndex(i), 0); ++ } + IL_EACH(g_dompoints, true, + { - ++total_controlpoints; - redowned += (it.goalentity.team == NUM_TEAM_1); - blueowned += (it.goalentity.team == NUM_TEAM_2); - yellowowned += (it.goalentity.team == NUM_TEAM_3); - pinkowned += (it.goalentity.team == NUM_TEAM_4); ++ ++total_control_points; ++ entity team_ = Entity_GetTeam(it.goalentity); ++ int num_control_points = Team_GetNumberOfControlPoints(team_); ++ ++num_control_points; ++ Team_SetNumberOfControlPoints(team_, num_control_points); + }); + } + -float Domination_GetWinnerTeam() ++int Domination_GetWinnerTeam() + { - float winner_team = 0; - if(redowned == total_controlpoints) - winner_team = NUM_TEAM_1; - if(blueowned == total_controlpoints) ++ int winner_team = 0; ++ if (Team_GetNumberOfControlPoints(Team_GetTeamFromIndex(1)) == ++ total_control_points) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_2; ++ winner_team = NUM_TEAM_1; + } - if(yellowowned == total_controlpoints) ++ for (int i = 2; i <= NUM_TEAMS; ++i) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_3; ++ if (Team_GetNumberOfControlPoints(Team_GetTeamFromIndex(i)) == ++ total_control_points) ++ { ++ if (winner_team != 0) ++ { ++ return 0; ++ } ++ winner_team = Team_IndexToTeam(i); ++ } + } - if(pinkowned == total_controlpoints) ++ if (winner_team) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_4; - } - if(winner_team) + return winner_team; ++ } + return -1; // no control points left? + } + -#define DOM_OWNED_CONTROLPOINTS() ((redowned > 0) + (blueowned > 0) + (yellowowned > 0) + (pinkowned > 0)) -#define DOM_OWNED_CONTROLPOINTS_OK() (DOM_OWNED_CONTROLPOINTS() < total_controlpoints) + float Domination_CheckWinner() + { + if(round_handler_GetEndTime() > 0 && round_handler_GetEndTime() - time <= 0) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_OVER); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_OVER); + + game_stopped = true; + round_handler_Init(5, autocvar_g_domination_warmup, autocvar_g_domination_round_timelimit); + return 1; + } + + Domination_count_controlpoints(); + + float winner_team = Domination_GetWinnerTeam(); + + if(winner_team == -1) + return 0; + + if(winner_team > 0) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(winner_team, CENTER_ROUND_TEAM_WIN)); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(winner_team, INFO_ROUND_TEAM_WIN)); + TeamScore_AddToTeam(winner_team, ST_DOM_CAPS, +1); + } + else if(winner_team == -1) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_TIED); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_TIED); + } + + game_stopped = true; + round_handler_Init(5, autocvar_g_domination_warmup, autocvar_g_domination_round_timelimit); + + return 1; + } + + float Domination_CheckPlayers() + { + return 1; + } + + void Domination_RoundStart() + { + FOREACH_CLIENT(IS_PLAYER(it), { it.player_blocked = false; }); + } + + //go to best items, or control points you don't own + void havocbot_goalrating_controlpoints(entity this, float ratingscale, vector org, float sradius) + { + IL_EACH(g_dompoints, vdist((((it.absmin + it.absmax) * 0.5) - org), <, sradius), + { + if(it.cnt > -1) // this is just being fought + navigation_routerating(this, it, ratingscale, 5000); + else if(it.goalentity.cnt == 0) // unclaimed + navigation_routerating(this, it, ratingscale * 0.5, 5000); + else if(it.goalentity.team != this.team) // other team's point + navigation_routerating(this, it, ratingscale * 0.2, 5000); + }); + } + + void havocbot_role_dom(entity this) + { + if(IS_DEAD(this)) + return; + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + havocbot_goalrating_controlpoints(this, 10000, this.origin, 15000); + havocbot_goalrating_items(this, 8000, this.origin, 8000); + //havocbot_goalrating_enemyplayers(this, 3000, this.origin, 2000); + havocbot_goalrating_waypoints(this, 1, this.origin, 3000); + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + -MUTATOR_HOOKFUNCTION(dom, CheckAllowedTeams) ++MUTATOR_HOOKFUNCTION(dom, TeamBalance_CheckAllowedTeams) + { + // fallback? + M_ARGV(0, float) = domination_teams; + string ret_string = "dom_team"; + + entity head = find(NULL, classname, ret_string); + while(head) + { + if(head.netname != "") + { - switch(head.team) ++ if (Team_IsValidTeam(head.team)) + { - case NUM_TEAM_1: c1 = 0; break; - case NUM_TEAM_2: c2 = 0; break; - case NUM_TEAM_3: c3 = 0; break; - case NUM_TEAM_4: c4 = 0; break; ++ M_ARGV(0, float) |= Team_TeamToBit(head.team); + } + } + + head = find(head, classname, ret_string); + } + + M_ARGV(1, string) = string_null; + + return true; + } + + MUTATOR_HOOKFUNCTION(dom, reset_map_players) + { + total_pps = 0, pps_red = 0, pps_blue = 0, pps_yellow = 0, pps_pink = 0; + FOREACH_CLIENT(IS_PLAYER(it), { + PutClientInServer(it); + if(domination_roundbased) + it.player_blocked = 1; + if(IS_REAL_CLIENT(it)) + set_dom_state(it); + }); + return true; + } + + MUTATOR_HOOKFUNCTION(dom, PlayerSpawn) + { + entity player = M_ARGV(0, entity); + + if(domination_roundbased) + if(!round_handler_IsRoundStarted()) + player.player_blocked = 1; + else + player.player_blocked = 0; + } + + MUTATOR_HOOKFUNCTION(dom, ClientConnect) + { + entity player = M_ARGV(0, entity); + + set_dom_state(player); + } + + MUTATOR_HOOKFUNCTION(dom, HavocBot_ChooseRole) + { + entity bot = M_ARGV(0, entity); + + bot.havocbot_role = havocbot_role_dom; + return true; + } + + /*QUAKED spawnfunc_dom_controlpoint (0 .5 .8) (-16 -16 -24) (16 16 32) + Control point for Domination gameplay. + */ + spawnfunc(dom_controlpoint) + { + if(!g_domination) + { + delete(this); + return; + } + setthink(this, dom_controlpoint_setup); + this.nextthink = time + 0.1; + this.reset = dom_controlpoint_setup; + + if(!this.scale) + this.scale = 0.6; + + this.effects = this.effects | EF_LOWPRECISION; + if (autocvar_g_domination_point_fullbright) + this.effects |= EF_FULLBRIGHT; + + IL_PUSH(g_dompoints, this); + } + + /*QUAKED spawnfunc_dom_team (0 .5 .8) (-32 -32 -24) (32 32 32) + Team declaration for Domination gameplay, this allows you to decide what team + names and control point models are used in your map. + + Note: If you use spawnfunc_dom_team entities you must define at least 3 and only two + can have netname set! The nameless team owns all control points at start. + + Keys: + "netname" + Name of the team (for example Red Team, Blue Team, Green Team, Yellow Team, Life, Death, etc) + "cnt" + Scoreboard color of the team (for example 4 is red and 13 is blue) + "model" + Model to use for control points owned by this team (for example + "progs/b_g_key.mdl" is a gold keycard, and "progs/b_s_key.mdl" is a silver + keycard) + "skin" + Skin of the model to use (for team skins on a single model) + "noise" + Sound to play when this team captures a point. + (this is a localized sound, like a small alarm or other effect) + "noise1" + Narrator speech to play when this team captures a point. + (this is a global sound, like "Red team has captured a control point") + */ + + spawnfunc(dom_team) + { + if(!g_domination || autocvar_g_domination_teams_override >= 2) + { + delete(this); + return; + } + precache_model(this.model); + if (this.noise != "") + precache_sound(this.noise); + if (this.noise1 != "") + precache_sound(this.noise1); + this.classname = "dom_team"; + _setmodel(this, this.model); // precision not needed + this.mdl = this.model; + this.dmg = this.modelindex; + this.model = ""; + this.modelindex = 0; + // this would have to be changed if used in quakeworld + if(this.cnt) + this.team = this.cnt + 1; // WHY are these different anyway? + } + + // scoreboard setup + void ScoreRules_dom(int teams) + { + if(domination_roundbased) + { + GameRules_scoring(teams, SFL_SORT_PRIO_PRIMARY, 0, { + field_team(ST_DOM_CAPS, "caps", SFL_SORT_PRIO_PRIMARY); + field(SP_DOM_TAKES, "takes", 0); + }); + } + else + { + float sp_domticks, sp_score; + sp_score = sp_domticks = 0; + if(autocvar_g_domination_disable_frags) + sp_domticks = SFL_SORT_PRIO_PRIMARY; + else + sp_score = SFL_SORT_PRIO_PRIMARY; + GameRules_scoring(teams, sp_score, sp_score, { + field_team(ST_DOM_TICKS, "ticks", sp_domticks); + field(SP_DOM_TICKS, "ticks", sp_domticks); + field(SP_DOM_TAKES, "takes", 0); + }); + } + } + + // code from here on is just to support maps that don't have control point and team entities + void dom_spawnteam (string teamname, float teamcolor, string pointmodel, float pointskin, Sound capsound, string capnarration, string capmessage) + { + TC(Sound, capsound); + entity e = new_pure(dom_team); + e.netname = strzone(teamname); + e.cnt = teamcolor; + e.model = pointmodel; + e.skin = pointskin; + e.noise = strzone(Sound_fixpath(capsound)); + e.noise1 = strzone(capnarration); + e.message = strzone(capmessage); + + // this code is identical to spawnfunc_dom_team + _setmodel(e, e.model); // precision not needed + e.mdl = e.model; + e.dmg = e.modelindex; + e.model = ""; + e.modelindex = 0; + // this would have to be changed if used in quakeworld + e.team = e.cnt + 1; + + //eprint(e); + } + + void dom_spawnpoint(vector org) + { + entity e = spawn(); + e.classname = "dom_controlpoint"; + setthink(e, spawnfunc_dom_controlpoint); + e.nextthink = time; + setorigin(e, org); + spawnfunc_dom_controlpoint(e); + } + + // spawn some default teams if the map is not set up for domination + void dom_spawnteams(int teams) + { + TC(int, teams); + dom_spawnteam(Team_ColoredFullName(NUM_TEAM_1), NUM_TEAM_1-1, "models/domination/dom_red.md3", 0, SND_DOM_CLAIM, "", "Red team has captured a control point"); + dom_spawnteam(Team_ColoredFullName(NUM_TEAM_2), NUM_TEAM_2-1, "models/domination/dom_blue.md3", 0, SND_DOM_CLAIM, "", "Blue team has captured a control point"); + if(teams >= 3) + dom_spawnteam(Team_ColoredFullName(NUM_TEAM_3), NUM_TEAM_3-1, "models/domination/dom_yellow.md3", 0, SND_DOM_CLAIM, "", "Yellow team has captured a control point"); + if(teams >= 4) + dom_spawnteam(Team_ColoredFullName(NUM_TEAM_4), NUM_TEAM_4-1, "models/domination/dom_pink.md3", 0, SND_DOM_CLAIM, "", "Pink team has captured a control point"); + dom_spawnteam("", 0, "models/domination/dom_unclaimed.md3", 0, SND_Null, "", ""); + } + + void dom_DelayedInit(entity this) // Do this check with a delay so we can wait for teams to be set up. + { + // if no teams are found, spawn defaults + if(find(NULL, classname, "dom_team") == NULL || autocvar_g_domination_teams_override >= 2) + { + LOG_TRACE("No \"dom_team\" entities found on this map, creating them anyway."); + domination_teams = autocvar_g_domination_teams_override; + if (domination_teams < 2) + domination_teams = autocvar_g_domination_default_teams; + domination_teams = bound(2, domination_teams, 4); + dom_spawnteams(domination_teams); + } + - CheckAllowedTeams(NULL); - //domination_teams = ((c4>=0) ? 4 : (c3>=0) ? 3 : 2); - - int teams = 0; - if(c1 >= 0) teams |= BIT(0); - if(c2 >= 0) teams |= BIT(1); - if(c3 >= 0) teams |= BIT(2); - if(c4 >= 0) teams |= BIT(3); ++ entity balance = TeamBalance_CheckAllowedTeams(NULL); ++ int teams = TeamBalance_GetAllowedTeams(balance); ++ TeamBalance_Destroy(balance); + domination_teams = teams; + + domination_roundbased = autocvar_g_domination_roundbased; + + ScoreRules_dom(domination_teams); + + if(domination_roundbased) + { + round_handler_Spawn(Domination_CheckPlayers, Domination_CheckWinner, Domination_RoundStart); + round_handler_Init(5, autocvar_g_domination_warmup, autocvar_g_domination_round_timelimit); + } + } + + void dom_Initialize() + { + g_domination = true; + InitializeEntity(NULL, dom_DelayedInit, INITPRIO_GAMETYPE); + } + #endif diff --cc qcsrc/common/gamemodes/gamemode/freezetag/freezetag.qc index 000000000,cceff4806..e86f6b72f mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/freezetag/freezetag.qc +++ b/qcsrc/common/gamemodes/gamemode/freezetag/freezetag.qc @@@ -1,0 -1,588 +1,607 @@@ + #include "freezetag.qh" + + // TODO: sv_freezetag + #ifdef SVQC ++ ++#include ++ + float autocvar_g_freezetag_frozen_maxtime; + float autocvar_g_freezetag_revive_clearspeed; + float autocvar_g_freezetag_round_timelimit; + //int autocvar_g_freezetag_teams; + int autocvar_g_freezetag_teams_override; + float autocvar_g_freezetag_warmup; + + void freezetag_count_alive_players() + { - total_players = redalive = bluealive = yellowalive = pinkalive = 0; - FOREACH_CLIENT(IS_PLAYER(it), { - switch(it.team) ++ total_players = 0; ++ for (int i = 1; i <= NUM_TEAMS; ++i) ++ { ++ Team_SetNumberOfAlivePlayers(Team_GetTeamFromIndex(i), 0); ++ } ++ FOREACH_CLIENT(IS_PLAYER(it) && Entity_HasValidTeam(it), ++ { ++ ++total_players; ++ if ((GetResourceAmount(it, RESOURCE_HEALTH) < 1) || ++ (STAT(FROZEN, it) == 1)) + { - case NUM_TEAM_1: ++total_players; if(it.health >= 1 && STAT(FROZEN, it) != 1) ++redalive; break; - case NUM_TEAM_2: ++total_players; if(it.health >= 1 && STAT(FROZEN, it) != 1) ++bluealive; break; - case NUM_TEAM_3: ++total_players; if(it.health >= 1 && STAT(FROZEN, it) != 1) ++yellowalive; break; - case NUM_TEAM_4: ++total_players; if(it.health >= 1 && STAT(FROZEN, it) != 1) ++pinkalive; break; ++ continue; + } ++ entity team_ = Entity_GetTeam(it); ++ int num_alive = Team_GetNumberOfAlivePlayers(team_); ++ ++num_alive; ++ Team_SetNumberOfAlivePlayers(team_, num_alive); + }); - FOREACH_CLIENT(IS_REAL_CLIENT(it), { - STAT(REDALIVE, it) = redalive; - STAT(BLUEALIVE, it) = bluealive; - STAT(YELLOWALIVE, it) = yellowalive; - STAT(PINKALIVE, it) = pinkalive; ++ FOREACH_CLIENT(IS_REAL_CLIENT(it), ++ { ++ STAT(REDALIVE, it) = Team_GetNumberOfAlivePlayers(Team_GetTeamFromIndex( ++ 1)); ++ STAT(BLUEALIVE, it) = Team_GetNumberOfAlivePlayers( ++ Team_GetTeamFromIndex(2)); ++ STAT(YELLOWALIVE, it) = Team_GetNumberOfAlivePlayers( ++ Team_GetTeamFromIndex(3)); ++ STAT(PINKALIVE, it) = Team_GetNumberOfAlivePlayers( ++ Team_GetTeamFromIndex(4)); + }); + + eliminatedPlayers.SendFlags |= 1; + } -#define FREEZETAG_ALIVE_TEAMS() ((redalive > 0) + (bluealive > 0) + (yellowalive > 0) + (pinkalive > 0)) -#define FREEZETAG_ALIVE_TEAMS_OK() (FREEZETAG_ALIVE_TEAMS() == NumTeams(freezetag_teams)) ++ ++#define FREEZETAG_ALIVE_TEAMS_OK() (Team_GetNumberOfAliveTeams() == NumTeams(freezetag_teams)) + + float freezetag_CheckTeams() + { + static float prev_missing_teams_mask; + if(FREEZETAG_ALIVE_TEAMS_OK()) + { + if(prev_missing_teams_mask > 0) + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS); + prev_missing_teams_mask = -1; + return 1; + } + if(total_players == 0) + { + if(prev_missing_teams_mask > 0) + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS); + prev_missing_teams_mask = -1; + return 0; + } + int missing_teams_mask = 0; - if(freezetag_teams & BIT(0)) - missing_teams_mask += (!redalive) * 1; - if(freezetag_teams & BIT(1)) - missing_teams_mask += (!bluealive) * 2; - if(freezetag_teams & BIT(2)) - missing_teams_mask += (!yellowalive) * 4; - if(freezetag_teams & BIT(3)) - missing_teams_mask += (!pinkalive) * 8; ++ for (int i = 1; i <= NUM_TEAMS; ++i) ++ { ++ if ((freezetag_teams & Team_IndexToBit(i)) && ++ (Team_GetNumberOfAlivePlayers(Team_GetTeamFromIndex(i)) == 0)) ++ { ++ missing_teams_mask |= Team_IndexToBit(i); ++ } ++ } + if(prev_missing_teams_mask != missing_teams_mask) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_MISSING_TEAMS, missing_teams_mask); + prev_missing_teams_mask = missing_teams_mask; + } + return 0; + } + -float freezetag_getWinnerTeam() ++int freezetag_getWinnerTeam() + { - float winner_team = 0; - if(redalive >= 1) - winner_team = NUM_TEAM_1; - if(bluealive >= 1) ++ int winner_team = 0; ++ if (Team_GetNumberOfAlivePlayers(Team_GetTeamFromIndex(1)) >= 1) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_2; ++ winner_team = NUM_TEAM_1; + } - if(yellowalive >= 1) ++ for (int i = 2; i <= NUM_TEAMS; ++i) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_3; ++ if (Team_GetNumberOfAlivePlayers(Team_GetTeamFromIndex(i)) >= 1) ++ { ++ if (winner_team != 0) ++ { ++ return 0; ++ } ++ winner_team = Team_IndexToTeam(i); ++ } + } - if(pinkalive >= 1) ++ if (winner_team) + { - if(winner_team) return 0; - winner_team = NUM_TEAM_4; - } - if(winner_team) + return winner_team; ++ } + return -1; // no player left + } + + void nades_Clear(entity); + void nades_GiveBonus(entity player, float score); + + float freezetag_CheckWinner() + { + if(round_handler_GetEndTime() > 0 && round_handler_GetEndTime() - time <= 0) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_OVER); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_OVER); + FOREACH_CLIENT(IS_PLAYER(it), { + it.freezetag_frozen_timeout = 0; + nades_Clear(it); + }); + game_stopped = true; + round_handler_Init(5, autocvar_g_freezetag_warmup, autocvar_g_freezetag_round_timelimit); + return 1; + } + - if(FREEZETAG_ALIVE_TEAMS() > 1) ++ if (Team_GetNumberOfAliveTeams() > 1) ++ { + return 0; ++ } + + int winner_team = freezetag_getWinnerTeam(); + if(winner_team > 0) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(winner_team, CENTER_ROUND_TEAM_WIN)); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(winner_team, INFO_ROUND_TEAM_WIN)); + TeamScore_AddToTeam(winner_team, ST_SCORE, +1); + } + else if(winner_team == -1) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_TIED); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_TIED); + } + + FOREACH_CLIENT(IS_PLAYER(it), { + it.freezetag_frozen_timeout = 0; + nades_Clear(it); + }); + + game_stopped = true; + round_handler_Init(5, autocvar_g_freezetag_warmup, autocvar_g_freezetag_round_timelimit); + return 1; + } + + entity freezetag_LastPlayerForTeam(entity this) + { + entity last_pl = NULL; + FOREACH_CLIENT(IS_PLAYER(it) && it != this, { + if(it.health >= 1) + if(!STAT(FROZEN, it)) + if(SAME_TEAM(it, this)) + if(!last_pl) + last_pl = it; + else + return NULL; + }); + return last_pl; + } + + void freezetag_LastPlayerForTeam_Notify(entity this) + { + if(round_handler_IsActive()) + if(round_handler_IsRoundStarted()) + { + entity pl = freezetag_LastPlayerForTeam(this); + if(pl) + Send_Notification(NOTIF_ONE, pl, MSG_CENTER, CENTER_ALONE); + } + } + + void freezetag_Add_Score(entity targ, entity attacker) + { + if(attacker == targ) + { + // you froze your own dumb targ + // counted as "suicide" already + GameRules_scoring_add(targ, SCORE, -1); + } + else if(IS_PLAYER(attacker)) + { + // got frozen by an enemy + // counted as "kill" and "death" already + GameRules_scoring_add(targ, SCORE, -1); + GameRules_scoring_add(attacker, SCORE, +1); + } + // else nothing - got frozen by the game type rules themselves + } + + void freezetag_Freeze(entity targ, entity attacker) + { + if(STAT(FROZEN, targ)) + return; + + if(autocvar_g_freezetag_frozen_maxtime > 0) + targ.freezetag_frozen_timeout = time + autocvar_g_freezetag_frozen_maxtime; + + Freeze(targ, 0, 1, true); + + freezetag_count_alive_players(); + + freezetag_Add_Score(targ, attacker); + } + + void freezetag_Unfreeze(entity this) + { + this.freezetag_frozen_time = 0; + this.freezetag_frozen_timeout = 0; + + Unfreeze(this); + } + + float freezetag_isEliminated(entity e) + { + if(IS_PLAYER(e) && (STAT(FROZEN, e) == 1 || IS_DEAD(e))) + return true; + return false; + } + + + // ================ + // Bot player logic + // ================ + + void(entity this) havocbot_role_ft_freeing; + void(entity this) havocbot_role_ft_offense; + + void havocbot_goalrating_freeplayers(entity this, float ratingscale, vector org, float sradius) + { + float t; + FOREACH_CLIENT(IS_PLAYER(it) && it != this && SAME_TEAM(it, this), { + if (STAT(FROZEN, it) == 1) + { + if(vdist(it.origin - org, >, sradius)) + continue; + navigation_routerating(this, it, ratingscale, 2000); + } + else if(vdist(it.origin - org, >, 400)) // avoid gathering all teammates in one place + { + // If teamate is not frozen still seek them out as fight better + // in a group. + t = 0.2 * 150 / (this.health + this.armorvalue); + navigation_routerating(this, it, t * ratingscale, 2000); + } + }); + } + + void havocbot_role_ft_offense(entity this) + { + if(IS_DEAD(this)) + return; + + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + random() * 10 + 20; + + // Count how many players on team are unfrozen. + int unfrozen = 0; + FOREACH_CLIENT(IS_PLAYER(it) && SAME_TEAM(it, this) && !(STAT(FROZEN, it) != 1), { unfrozen++; }); + + // If only one left on team or if role has timed out then start trying to free players. + if (((unfrozen == 0) && (!STAT(FROZEN, this))) || (time > this.havocbot_role_timeout)) + { + LOG_TRACE("changing role to freeing"); + this.havocbot_role = havocbot_role_ft_freeing; + this.havocbot_role_timeout = 0; + return; + } + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + havocbot_goalrating_items(this, 10000, this.origin, 10000); + havocbot_goalrating_enemyplayers(this, 20000, this.origin, 10000); + havocbot_goalrating_freeplayers(this, 9000, this.origin, 10000); + havocbot_goalrating_waypoints(this, 1, this.origin, 3000); + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_ft_freeing(entity this) + { + if(IS_DEAD(this)) + return; + + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + random() * 10 + 20; + + if (time > this.havocbot_role_timeout) + { + LOG_TRACE("changing role to offense"); + this.havocbot_role = havocbot_role_ft_offense; + this.havocbot_role_timeout = 0; + return; + } + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + havocbot_goalrating_items(this, 8000, this.origin, 10000); + havocbot_goalrating_enemyplayers(this, 10000, this.origin, 10000); + havocbot_goalrating_freeplayers(this, 20000, this.origin, 10000); + havocbot_goalrating_waypoints(this, 1, this.origin, 3000); + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + + // ============== + // Hook Functions + // ============== + + void ft_RemovePlayer(entity this) + { + this.health = 0; // neccessary to update correctly alive stats + if(!STAT(FROZEN, this)) + freezetag_LastPlayerForTeam_Notify(this); + freezetag_Unfreeze(this); + freezetag_count_alive_players(); + } + + MUTATOR_HOOKFUNCTION(ft, ClientDisconnect) + { + entity player = M_ARGV(0, entity); + + ft_RemovePlayer(player); + return true; + } + + MUTATOR_HOOKFUNCTION(ft, MakePlayerObserver) + { + entity player = M_ARGV(0, entity); + + ft_RemovePlayer(player); + } + + MUTATOR_HOOKFUNCTION(ft, PlayerDies) + { + entity frag_attacker = M_ARGV(1, entity); + entity frag_target = M_ARGV(2, entity); + float frag_deathtype = M_ARGV(3, float); + + if(round_handler_IsActive()) + if(round_handler_CountdownRunning()) + { + if(STAT(FROZEN, frag_target)) + freezetag_Unfreeze(frag_target); + freezetag_count_alive_players(); + return true; // let the player die so that he can respawn whenever he wants + } + + // Cases DEATH_TEAMCHANGE and DEATH_AUTOTEAMCHANGE are needed to fix a bug whe + // you succeed changing team through the menu: you both really die (gibbing) and get frozen + if(ITEM_DAMAGE_NEEDKILL(frag_deathtype) + || frag_deathtype == DEATH_TEAMCHANGE.m_id || frag_deathtype == DEATH_AUTOTEAMCHANGE.m_id) + { + // let the player die, he will be automatically frozen when he respawns + if(STAT(FROZEN, frag_target) != 1) + { + freezetag_Add_Score(frag_target, frag_attacker); + freezetag_count_alive_players(); + freezetag_LastPlayerForTeam_Notify(frag_target); + } + else + freezetag_Unfreeze(frag_target); // remove ice + frag_target.health = 0; // Unfreeze resets health + frag_target.freezetag_frozen_timeout = -2; // freeze on respawn + return true; + } + + if(STAT(FROZEN, frag_target)) + return true; + + freezetag_Freeze(frag_target, frag_attacker); + freezetag_LastPlayerForTeam_Notify(frag_target); + + if(frag_attacker == frag_target || frag_attacker == NULL) + { + if(IS_PLAYER(frag_target)) + Send_Notification(NOTIF_ONE, frag_target, MSG_CENTER, CENTER_FREEZETAG_SELF); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_FREEZETAG_SELF, frag_target.netname); + } + else + { + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_FREEZETAG_FREEZE, frag_target.netname, frag_attacker.netname); + } + + return true; + } + + MUTATOR_HOOKFUNCTION(ft, PlayerSpawn) + { + entity player = M_ARGV(0, entity); + + if(player.freezetag_frozen_timeout == -1) // if PlayerSpawn is called by reset_map_players + return true; // do nothing, round is starting right now + + if(player.freezetag_frozen_timeout == -2) // player was dead + { + freezetag_Freeze(player, NULL); + return true; + } + + freezetag_count_alive_players(); + + if(round_handler_IsActive()) + if(round_handler_IsRoundStarted()) + { + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_FREEZETAG_SPAWN_LATE); + freezetag_Freeze(player, NULL); + } + + return true; + } + + MUTATOR_HOOKFUNCTION(ft, reset_map_players) + { + FOREACH_CLIENT(IS_PLAYER(it), { + CS(it).killcount = 0; + it.freezetag_frozen_timeout = -1; + PutClientInServer(it); + it.freezetag_frozen_timeout = 0; + }); + freezetag_count_alive_players(); + return true; + } + + MUTATOR_HOOKFUNCTION(ft, GiveFragsForKill, CBC_ORDER_FIRST) + { + M_ARGV(2, float) = 0; // no frags counted in Freeze Tag + return true; + } + + MUTATOR_HOOKFUNCTION(ft, PlayerPreThink, CBC_ORDER_FIRST) + { + if(game_stopped) + return true; + + if(round_handler_IsActive()) + if(!round_handler_IsRoundStarted()) + return true; + + int n; + entity o = NULL; + entity player = M_ARGV(0, entity); + //if(STAT(FROZEN, player)) + //if(player.freezetag_frozen_timeout > 0 && time < player.freezetag_frozen_timeout) + //player.iceblock.alpha = ICE_MIN_ALPHA + (ICE_MAX_ALPHA - ICE_MIN_ALPHA) * (player.freezetag_frozen_timeout - time) / (player.freezetag_frozen_timeout - player.freezetag_frozen_time); + + if(player.freezetag_frozen_timeout > 0 && time >= player.freezetag_frozen_timeout) + n = -1; + else + { + vector revive_extra_size = '1 1 1' * autocvar_g_freezetag_revive_extra_size; + n = 0; + FOREACH_CLIENT(IS_PLAYER(it) && it != player, { + if(STAT(FROZEN, it) == 0) + if(!IS_DEAD(it)) + if(SAME_TEAM(it, player)) + if(boxesoverlap(player.absmin - revive_extra_size, player.absmax + revive_extra_size, it.absmin, it.absmax)) + { + if(!o) + o = it; + if(STAT(FROZEN, player) == 1) + it.reviving = true; + ++n; + } + }); + + } + + if(n && STAT(FROZEN, player) == 1) // OK, there is at least one teammate reviving us + { + STAT(REVIVE_PROGRESS, player) = bound(0, STAT(REVIVE_PROGRESS, player) + frametime * max(1/60, autocvar_g_freezetag_revive_speed), 1); + player.health = max(1, STAT(REVIVE_PROGRESS, player) * ((warmup_stage) ? warmup_start_health : start_health)); + + if(STAT(REVIVE_PROGRESS, player) >= 1) + { + freezetag_Unfreeze(player); + freezetag_count_alive_players(); + + if(n == -1) + { + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_FREEZETAG_AUTO_REVIVED, autocvar_g_freezetag_frozen_maxtime); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_FREEZETAG_AUTO_REVIVED, player.netname, autocvar_g_freezetag_frozen_maxtime); + return true; + } + + // EVERY team mate nearby gets a point (even if multiple!) + FOREACH_CLIENT(IS_PLAYER(it) && it.reviving, { + GameRules_scoring_add(it, FREEZETAG_REVIVALS, +1); + GameRules_scoring_add(it, SCORE, +1); + nades_GiveBonus(it,autocvar_g_nades_bonus_score_low); + }); + + Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_FREEZETAG_REVIVED, o.netname); + Send_Notification(NOTIF_ONE, o, MSG_CENTER, CENTER_FREEZETAG_REVIVE, player.netname); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_FREEZETAG_REVIVED, player.netname, o.netname); + } + + FOREACH_CLIENT(IS_PLAYER(it) && it.reviving, { + STAT(REVIVE_PROGRESS, it) = STAT(REVIVE_PROGRESS, player); + it.reviving = false; + }); + } + else if(!n && STAT(FROZEN, player) == 1) // only if no teammate is nearby will we reset + { + STAT(REVIVE_PROGRESS, player) = bound(0, STAT(REVIVE_PROGRESS, player) - frametime * autocvar_g_freezetag_revive_clearspeed, 1); + player.health = max(1, STAT(REVIVE_PROGRESS, player) * ((warmup_stage) ? warmup_start_health : start_health)); + } + else if(!n && !STAT(FROZEN, player)) + { + STAT(REVIVE_PROGRESS, player) = 0; // thawing nobody + } + + return true; + } + + MUTATOR_HOOKFUNCTION(ft, SetStartItems) + { + start_items &= ~IT_UNLIMITED_AMMO; + //start_health = warmup_start_health = cvar("g_lms_start_health"); + //start_armorvalue = warmup_start_armorvalue = cvar("g_lms_start_armor"); + start_ammo_shells = warmup_start_ammo_shells = cvar("g_lms_start_ammo_shells"); + start_ammo_nails = warmup_start_ammo_nails = cvar("g_lms_start_ammo_nails"); + start_ammo_rockets = warmup_start_ammo_rockets = cvar("g_lms_start_ammo_rockets"); + start_ammo_cells = warmup_start_ammo_cells = cvar("g_lms_start_ammo_cells"); + start_ammo_plasma = warmup_start_ammo_plasma = cvar("g_lms_start_ammo_plasma"); + start_ammo_fuel = warmup_start_ammo_fuel = cvar("g_lms_start_ammo_fuel"); + } + + MUTATOR_HOOKFUNCTION(ft, HavocBot_ChooseRole) + { + entity bot = M_ARGV(0, entity); + + if (!IS_DEAD(bot)) + { + if (random() < 0.5) + bot.havocbot_role = havocbot_role_ft_freeing; + else + bot.havocbot_role = havocbot_role_ft_offense; + } + + return true; + } + -MUTATOR_HOOKFUNCTION(ft, CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) ++MUTATOR_HOOKFUNCTION(ft, TeamBalance_CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) + { + M_ARGV(0, float) = freezetag_teams; ++ return true; + } + + MUTATOR_HOOKFUNCTION(ft, SetWeaponArena) + { + // most weapons arena + if(M_ARGV(0, string) == "0" || M_ARGV(0, string) == "") + M_ARGV(0, string) = "most"; + } + + MUTATOR_HOOKFUNCTION(ft, FragCenterMessage) + { + entity frag_attacker = M_ARGV(0, entity); + entity frag_target = M_ARGV(1, entity); + //float frag_deathtype = M_ARGV(2, float); + int kill_count_to_attacker = M_ARGV(3, int); + int kill_count_to_target = M_ARGV(4, int); + + if(STAT(FROZEN, frag_target)) + return; // target was already frozen, so this is just pushing them off the cliff + + Send_Notification(NOTIF_ONE, frag_attacker, MSG_CHOICE, CHOICE_FRAG_FREEZE, frag_target.netname, kill_count_to_attacker, (IS_BOT_CLIENT(frag_target) ? -1 : CS(frag_target).ping)); + Send_Notification(NOTIF_ONE, frag_target, MSG_CHOICE, CHOICE_FRAGGED_FREEZE, frag_attacker.netname, kill_count_to_target, frag_attacker.health, frag_attacker.armorvalue, (IS_BOT_CLIENT(frag_attacker) ? -1 : CS(frag_attacker).ping)); + + return true; + } + + void freezetag_Initialize() + { + freezetag_teams = autocvar_g_freezetag_teams_override; + if(freezetag_teams < 2) + freezetag_teams = cvar("g_freezetag_teams"); // read the cvar directly as it gets written earlier in the same frame + + freezetag_teams = BITS(bound(2, freezetag_teams, 4)); + GameRules_scoring(freezetag_teams, SFL_SORT_PRIO_PRIMARY, SFL_SORT_PRIO_PRIMARY, { + field(SP_FREEZETAG_REVIVALS, "revivals", 0); + }); + + round_handler_Spawn(freezetag_CheckTeams, freezetag_CheckWinner, func_null); + round_handler_Init(5, autocvar_g_freezetag_warmup, autocvar_g_freezetag_round_timelimit); + + EliminatedPlayers_Init(freezetag_isEliminated); + } + #endif diff --cc qcsrc/common/gamemodes/gamemode/invasion/invasion.qc index 000000000,d6f9860c9..9fb6e4969 mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/invasion/invasion.qc +++ b/qcsrc/common/gamemodes/gamemode/invasion/invasion.qc @@@ -1,0 -1,606 +1,607 @@@ + #include "invasion.qh" + + // TODO: sv_invasion + #ifdef SVQC + #include + #include + #include + + #include + + IntrusiveList g_invasion_roundends; + IntrusiveList g_invasion_waves; + IntrusiveList g_invasion_spawns; + STATIC_INIT(g_invasion) + { + g_invasion_roundends = IL_NEW(); + g_invasion_waves = IL_NEW(); + g_invasion_spawns = IL_NEW(); + } + + float autocvar_g_invasion_round_timelimit; + float autocvar_g_invasion_spawnpoint_spawn_delay; + float autocvar_g_invasion_warmup; + int autocvar_g_invasion_monster_count; + bool autocvar_g_invasion_zombies_only; + float autocvar_g_invasion_spawn_delay; + + bool victent_present; + .bool inv_endreached; + + bool inv_warning_shown; // spammy + + void target_invasion_roundend_use(entity this, entity actor, entity trigger) + { + if(!IS_PLAYER(actor)) { return; } + + actor.inv_endreached = true; + + int plnum = 0; + int realplnum = 0; + // let's not count bots + FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it), { + ++realplnum; + if(it.inv_endreached) + ++plnum; + }); + if(plnum < ceil(realplnum * min(1, this.count))) // 70% of players + return; + + this.winning = true; + } + + spawnfunc(target_invasion_roundend) + { + if(!g_invasion) { delete(this); return; } + + victent_present = true; // a victory entity is present, we don't need to rely on monster count TODO: merge this with the intrusive list (can check empty) + + if(!this.count) { this.count = 0.7; } // require at least 70% of the players to reach the end before triggering victory + + this.use = target_invasion_roundend_use; + + IL_PUSH(g_invasion_roundends, this); + } + + spawnfunc(invasion_wave) + { + if(!g_invasion) { delete(this); return; } + + IL_PUSH(g_invasion_waves, this); + } + + spawnfunc(invasion_spawnpoint) + { + if(!g_invasion) { delete(this); return; } + + this.classname = "invasion_spawnpoint"; + IL_PUSH(g_invasion_spawns, this); + } + + void ClearWinners(); + + // Invasion stage mode winning condition: If the attackers triggered a round end (by fulfilling all objectives) + // they win. + int WinningCondition_Invasion() + { + WinningConditionHelper(NULL); // set worldstatus + + int status = WINNING_NO; + + if(autocvar_g_invasion_type == INV_TYPE_STAGE) + { + SetWinners(inv_endreached, true); + + int found = 0; + IL_EACH(g_invasion_roundends, true, + { + ++found; + if(it.winning) + { + bprint("Invasion: round completed.\n"); + // winners already set (TODO: teamplay support) + + status = WINNING_YES; + break; + } + }); + + if(!found) + status = WINNING_YES; // just end it? TODO: should warn mapper! + } + else if(autocvar_g_invasion_type == INV_TYPE_HUNT) + { + ClearWinners(); + + int found = 0; // NOTE: this ends the round if no monsters are placed + IL_EACH(g_monsters, !(it.spawnflags & MONSTERFLAG_RESPAWNED), + { + ++found; + }); + + if(found <= 0) + { + FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it), + { + it.winning = true; + }); + status = WINNING_YES; + } + } + + return status; + } + + Monster invasion_PickMonster(int supermonster_count) + { + RandomSelection_Init(); + + FOREACH(Monsters, it != MON_Null, + { + if((it.spawnflags & MON_FLAG_HIDDEN) || (it.spawnflags & MONSTER_TYPE_PASSIVE) || (it.spawnflags & MONSTER_TYPE_FLY) || (it.spawnflags & MONSTER_TYPE_SWIM) || + (it.spawnflags & MONSTER_SIZE_QUAKE) || ((it.spawnflags & MON_FLAG_SUPERMONSTER) && supermonster_count >= 1)) + continue; + if(autocvar_g_invasion_zombies_only && !(it.spawnflags & MONSTER_TYPE_UNDEAD)) + continue; + RandomSelection_AddEnt(it, 1, 1); + }); + + return RandomSelection_chosen_ent; + } + + entity invasion_PickSpawn() + { + RandomSelection_Init(); + + IL_EACH(g_invasion_spawns, true, + { + RandomSelection_AddEnt(it, 1, ((time < it.spawnshieldtime) ? 0.2 : 1)); // give recently used spawnpoints a very low rating + it.spawnshieldtime = time + autocvar_g_invasion_spawnpoint_spawn_delay; + }); + + return RandomSelection_chosen_ent; + } + + entity invasion_GetWaveEntity(int wavenum) + { + IL_EACH(g_invasion_waves, it.cnt == wavenum, + { + return it; // found one + }); + + // if no specific one is found, find the last existing wave ent + entity best = NULL; + IL_EACH(g_invasion_waves, it.cnt <= wavenum, + { + if(!best || it.cnt > best.cnt) + best = it; + }); + + return best; + } + + void invasion_SpawnChosenMonster(Monster mon) + { + entity monster; + entity spawn_point = invasion_PickSpawn(); + entity wave_ent = invasion_GetWaveEntity(inv_roundcnt); + + string tospawn = ""; + if(wave_ent && wave_ent.spawnmob && wave_ent.spawnmob != "") + { + RandomSelection_Init(); + FOREACH_WORD(wave_ent.spawnmob, true, + { + RandomSelection_AddString(it, 1, 1); + }); + + tospawn = RandomSelection_chosen_string; + } + + if(spawn_point == NULL) + { + if(!inv_warning_shown) + { + inv_warning_shown = true; + LOG_TRACE("Warning: couldn't find any invasion_spawnpoint spawnpoints, attempting to spawn monsters in random locations"); + } + entity e = spawn(); + setsize(e, mon.m_mins, mon.m_maxs); + + if(MoveToRandomMapLocation(e, DPCONTENTS_SOLID | DPCONTENTS_CORPSE | DPCONTENTS_PLAYERCLIP, DPCONTENTS_SLIME | DPCONTENTS_LAVA | DPCONTENTS_SKY | DPCONTENTS_BODY | DPCONTENTS_DONOTENTER, Q3SURFACEFLAG_SKY, 10, 1024, 256)) + monster = spawnmonster(e, tospawn, mon.monsterid, NULL, NULL, e.origin, false, false, 2); + else + { + delete(e); + return; + } + } + else // if spawnmob field falls through (unset), fallback to mon (relying on spawnmonster for that behaviour) + monster = spawnmonster(spawn(), ((spawn_point.spawnmob && spawn_point.spawnmob != "") ? spawn_point.spawnmob : tospawn), mon.monsterid, spawn_point, spawn_point, spawn_point.origin, false, false, 2); + + if(!monster) + return; + + monster.spawnshieldtime = time; + + if(spawn_point) + { + if(spawn_point.target_range) + monster.target_range = spawn_point.target_range; + monster.target2 = spawn_point.target2; + } + + if(teamplay) + { + if(spawn_point && spawn_point.team && inv_monsters_perteam[spawn_point.team] > 0) + monster.team = spawn_point.team; + else + { + RandomSelection_Init(); + if(inv_monsters_perteam[NUM_TEAM_1] > 0) RandomSelection_AddFloat(NUM_TEAM_1, 1, 1); + if(inv_monsters_perteam[NUM_TEAM_2] > 0) RandomSelection_AddFloat(NUM_TEAM_2, 1, 1); + if(invasion_teams >= 3) if(inv_monsters_perteam[NUM_TEAM_3] > 0) { RandomSelection_AddFloat(NUM_TEAM_3, 1, 1); } + if(invasion_teams >= 4) if(inv_monsters_perteam[NUM_TEAM_4] > 0) { RandomSelection_AddFloat(NUM_TEAM_4, 1, 1); } + + monster.team = RandomSelection_chosen_float; + } + + monster_setupcolors(monster); + + if(monster.sprite) + { + WaypointSprite_UpdateTeamRadar(monster.sprite, RADARICON_DANGER, ((monster.team) ? Team_ColorRGB(monster.team) : '1 0 0')); + + monster.sprite.team = 0; + monster.sprite.SendFlags |= 1; + } + } + + if(monster.monster_attack) + IL_REMOVE(g_monster_targets, monster); + monster.monster_attack = false; // it's the player's job to kill all the monsters + + if(inv_roundcnt >= inv_maxrounds) + monster.spawnflags |= MONSTERFLAG_MINIBOSS; // last round spawns minibosses + } + + void invasion_SpawnMonsters(int supermonster_count) + { + Monster chosen_monster = invasion_PickMonster(supermonster_count); + + invasion_SpawnChosenMonster(chosen_monster); + } + + bool Invasion_CheckWinner() + { + if(round_handler_GetEndTime() > 0 && round_handler_GetEndTime() - time <= 0) + { + IL_EACH(g_monsters, true, + { + Monster_Remove(it); + }); + IL_CLEAR(g_monsters); + + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_OVER); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_OVER); + round_handler_Init(5, autocvar_g_invasion_warmup, autocvar_g_invasion_round_timelimit); + return 1; + } + + float total_alive_monsters = 0, supermonster_count = 0, red_alive = 0, blue_alive = 0, yellow_alive = 0, pink_alive = 0; + + IL_EACH(g_monsters, it.health > 0, + { + if((get_monsterinfo(it.monsterid)).spawnflags & MON_FLAG_SUPERMONSTER) + ++supermonster_count; + ++total_alive_monsters; + + if(teamplay) + switch(it.team) + { + case NUM_TEAM_1: ++red_alive; break; + case NUM_TEAM_2: ++blue_alive; break; + case NUM_TEAM_3: ++yellow_alive; break; + case NUM_TEAM_4: ++pink_alive; break; + } + }); + + if((total_alive_monsters + inv_numkilled) < inv_maxspawned && inv_maxcurrent < inv_maxspawned) + { + if(time >= inv_lastcheck) + { + invasion_SpawnMonsters(supermonster_count); + inv_lastcheck = time + autocvar_g_invasion_spawn_delay; + } + + return 0; + } + + if(inv_numspawned < 1) + return 0; // nothing has spawned yet + + if(teamplay) + { + if(((red_alive > 0) + (blue_alive > 0) + (yellow_alive > 0) + (pink_alive > 0)) > 1) + return 0; + } + else if(inv_numkilled < inv_maxspawned) + return 0; + + entity winner = NULL; + float winning_score = 0, winner_team = 0; + + + if(teamplay) + { + if(red_alive > 0) { winner_team = NUM_TEAM_1; } + if(blue_alive > 0) + if(winner_team) { winner_team = 0; } + else { winner_team = NUM_TEAM_2; } + if(yellow_alive > 0) + if(winner_team) { winner_team = 0; } + else { winner_team = NUM_TEAM_3; } + if(pink_alive > 0) + if(winner_team) { winner_team = 0; } + else { winner_team = NUM_TEAM_4; } + } + else + { + FOREACH_CLIENT(IS_PLAYER(it), { + float cs = GameRules_scoring_add(it, KILLS, 0); + if(cs > winning_score) + { + winning_score = cs; + winner = it; + } + }); + } + + IL_EACH(g_monsters, true, + { + Monster_Remove(it); + }); + IL_CLEAR(g_monsters); + + if(teamplay) + { + if(winner_team) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(winner_team, CENTER_ROUND_TEAM_WIN)); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(winner_team, INFO_ROUND_TEAM_WIN)); + } + } + else if(winner) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_ROUND_PLAYER_WIN, winner.netname); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_ROUND_PLAYER_WIN, winner.netname); + } + + round_handler_Init(5, autocvar_g_invasion_warmup, autocvar_g_invasion_round_timelimit); + + return 1; + } + + bool Invasion_CheckPlayers() + { + return true; + } + + void Invasion_RoundStart() + { + int numplayers = 0; + FOREACH_CLIENT(IS_PLAYER(it), { + it.player_blocked = false; + ++numplayers; + }); + + if(inv_roundcnt < inv_maxrounds) + inv_roundcnt += 1; // a limiter to stop crazy counts + + inv_monsterskill = inv_roundcnt + max(1, numplayers * 0.3); + + inv_maxcurrent = 0; + inv_numspawned = 0; + inv_numkilled = 0; + + inv_maxspawned = rint(max(autocvar_g_invasion_monster_count, autocvar_g_invasion_monster_count * (inv_roundcnt * 0.5))); + + if(teamplay) + { + DistributeEvenly_Init(inv_maxspawned, invasion_teams); + inv_monsters_perteam[NUM_TEAM_1] = DistributeEvenly_Get(1); + inv_monsters_perteam[NUM_TEAM_2] = DistributeEvenly_Get(1); + if(invasion_teams >= 3) inv_monsters_perteam[NUM_TEAM_3] = DistributeEvenly_Get(1); + if(invasion_teams >= 4) inv_monsters_perteam[NUM_TEAM_4] = DistributeEvenly_Get(1); + } + } + + MUTATOR_HOOKFUNCTION(inv, MonsterDies) + { + entity frag_target = M_ARGV(0, entity); + entity frag_attacker = M_ARGV(1, entity); + + if(!(frag_target.spawnflags & MONSTERFLAG_RESPAWNED)) + { + if(autocvar_g_invasion_type == INV_TYPE_ROUND) + { + inv_numkilled += 1; + inv_maxcurrent -= 1; + } + if(teamplay) { inv_monsters_perteam[frag_target.team] -= 1; } + + if(IS_PLAYER(frag_attacker)) + if(SAME_TEAM(frag_attacker, frag_target)) // in non-teamplay modes, same team = same player, so this works + GameRules_scoring_add(frag_attacker, KILLS, -1); + else + { + GameRules_scoring_add(frag_attacker, KILLS, +1); + if(teamplay) + TeamScore_AddToTeam(frag_attacker.team, ST_INV_KILLS, +1); + } + } + } + + MUTATOR_HOOKFUNCTION(inv, MonsterSpawn) + { + entity mon = M_ARGV(0, entity); + mon.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_BOTCLIP | DPCONTENTS_MONSTERCLIP; + + if(autocvar_g_invasion_type == INV_TYPE_HUNT) + return false; // allowed + + if(!(mon.spawnflags & MONSTERFLAG_SPAWNED)) + return true; + + if(!(mon.spawnflags & MONSTERFLAG_RESPAWNED)) + { + inv_numspawned += 1; + inv_maxcurrent += 1; + } + + mon.monster_skill = inv_monsterskill; + + if((get_monsterinfo(mon.monsterid)).spawnflags & MON_FLAG_SUPERMONSTER) + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_INVASION_SUPERMONSTER, mon.monster_name); + } + + MUTATOR_HOOKFUNCTION(inv, SV_StartFrame) + { + if(autocvar_g_invasion_type != INV_TYPE_ROUND) + return; // uses map spawned monsters + + monsters_total = inv_maxspawned; // TODO: make sure numspawned never exceeds maxspawned + monsters_killed = inv_numkilled; + } + + MUTATOR_HOOKFUNCTION(inv, PlayerRegen) + { + // no regeneration in invasion, regardless of the game type + return true; + } + + MUTATOR_HOOKFUNCTION(inv, PlayerSpawn) + { + entity player = M_ARGV(0, entity); + + if(player.bot_attack) + IL_REMOVE(g_bot_targets, player); + player.bot_attack = false; + } + + MUTATOR_HOOKFUNCTION(inv, Damage_Calculate) + { + entity frag_attacker = M_ARGV(1, entity); + entity frag_target = M_ARGV(2, entity); + float frag_damage = M_ARGV(4, float); + vector frag_force = M_ARGV(6, vector); + + if(IS_PLAYER(frag_attacker) && IS_PLAYER(frag_target) && frag_attacker != frag_target) + { + frag_damage = 0; + frag_force = '0 0 0'; + + M_ARGV(4, float) = frag_damage; + M_ARGV(6, vector) = frag_force; + } + } + + MUTATOR_HOOKFUNCTION(inv, BotShouldAttack) + { + entity targ = M_ARGV(1, entity); + + if(!IS_MONSTER(targ)) + return true; + } + + MUTATOR_HOOKFUNCTION(inv, SetStartItems) + { + if(autocvar_g_invasion_type == INV_TYPE_ROUND) + { + start_health = 200; + start_armorvalue = 200; + } + } + + MUTATOR_HOOKFUNCTION(inv, AccuracyTargetValid) + { + entity frag_target = M_ARGV(1, entity); + + if(IS_MONSTER(frag_target)) + return MUT_ACCADD_INVALID; + return MUT_ACCADD_INDIFFERENT; + } + + MUTATOR_HOOKFUNCTION(inv, AllowMobSpawning) + { + // monster spawning disabled during an invasion + M_ARGV(1, string) = "You cannot spawn monsters during an invasion!"; + return true; + } + + MUTATOR_HOOKFUNCTION(inv, CheckRules_World) + { + if(autocvar_g_invasion_type == INV_TYPE_ROUND) + return false; + + M_ARGV(0, float) = WinningCondition_Invasion(); + return true; + } + -MUTATOR_HOOKFUNCTION(inv, CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) ++MUTATOR_HOOKFUNCTION(inv, TeamBalance_CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) + { + M_ARGV(0, float) = invasion_teams; ++ return true; + } + + MUTATOR_HOOKFUNCTION(inv, AllowMobButcher) + { + M_ARGV(0, string) = "This command does not work during an invasion!"; + return true; + } + + void invasion_ScoreRules(int inv_teams) + { - if(inv_teams) { CheckAllowedTeams(NULL); } ++ //if(inv_teams) { CheckAllowedTeams(NULL); } // Another bug? + GameRules_score_enabled(false); + GameRules_scoring(inv_teams, 0, 0, { + if (inv_teams) { + field_team(ST_INV_KILLS, "frags", SFL_SORT_PRIO_PRIMARY); + } + field(SP_KILLS, "frags", ((inv_teams) ? SFL_SORT_PRIO_SECONDARY : SFL_SORT_PRIO_PRIMARY)); + }); + } + + void invasion_DelayedInit(entity this) // Do this check with a delay so we can wait for teams to be set up. + { + if(autocvar_g_invasion_type == INV_TYPE_HUNT || autocvar_g_invasion_type == INV_TYPE_STAGE) + cvar_set("fraglimit", "0"); + + if(autocvar_g_invasion_teams) + { + invasion_teams = BITS(bound(2, autocvar_g_invasion_teams, 4)); + } + else + invasion_teams = 0; + + independent_players = 1; // to disable extra useless scores + + invasion_ScoreRules(invasion_teams); + + independent_players = 0; + + if(autocvar_g_invasion_type == INV_TYPE_ROUND) + { + round_handler_Spawn(Invasion_CheckPlayers, Invasion_CheckWinner, Invasion_RoundStart); + round_handler_Init(5, autocvar_g_invasion_warmup, autocvar_g_invasion_round_timelimit); + + inv_roundcnt = 0; + inv_maxrounds = 15; // 15? + } + } + + void invasion_Initialize() + { + InitializeEntity(NULL, invasion_DelayedInit, INITPRIO_GAMETYPE); + } + #endif diff --cc qcsrc/common/gamemodes/gamemode/keyhunt/keyhunt.qc index 000000000,6523612e2..5e0d3fcbb mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/keyhunt/keyhunt.qc +++ b/qcsrc/common/gamemodes/gamemode/keyhunt/keyhunt.qc @@@ -1,0 -1,1324 +1,1325 @@@ + #include "keyhunt.qh" + + // TODO: sv_keyhunt + #ifdef SVQC + float autocvar_g_balance_keyhunt_damageforcescale; + float autocvar_g_balance_keyhunt_delay_collect; + float autocvar_g_balance_keyhunt_delay_damage_return; + float autocvar_g_balance_keyhunt_delay_return; + float autocvar_g_balance_keyhunt_delay_round; + float autocvar_g_balance_keyhunt_delay_tracking; + float autocvar_g_balance_keyhunt_return_when_unreachable; + float autocvar_g_balance_keyhunt_dropvelocity; + float autocvar_g_balance_keyhunt_maxdist; + float autocvar_g_balance_keyhunt_protecttime; + + int autocvar_g_balance_keyhunt_score_capture; + int autocvar_g_balance_keyhunt_score_carrierfrag; + int autocvar_g_balance_keyhunt_score_collect; + int autocvar_g_balance_keyhunt_score_destroyed; + int autocvar_g_balance_keyhunt_score_destroyed_ownfactor; + int autocvar_g_balance_keyhunt_score_push; + float autocvar_g_balance_keyhunt_throwvelocity; + + //int autocvar_g_keyhunt_teams; + int autocvar_g_keyhunt_teams_override; + + // #define KH_PLAYER_USE_ATTACHMENT + // #define KH_PLAYER_USE_CARRIEDMODEL + + #ifdef KH_PLAYER_USE_ATTACHMENT + const vector KH_PLAYER_ATTACHMENT_DIST_ROTATED = '0 -4 0'; + const vector KH_PLAYER_ATTACHMENT_DIST = '4 0 0'; + const vector KH_PLAYER_ATTACHMENT = '0 0 0'; + const vector KH_PLAYER_ATTACHMENT_ANGLES = '0 0 0'; + const string KH_PLAYER_ATTACHMENT_BONE = ""; + #else + const float KH_KEY_ZSHIFT = 22; + const float KH_KEY_XYDIST = 24; + const float KH_KEY_XYSPEED = 45; + #endif + const float KH_KEY_WP_ZSHIFT = 20; + + const vector KH_KEY_MIN = '-10 -10 -46'; + const vector KH_KEY_MAX = '10 10 3'; + const float KH_KEY_BRIGHTNESS = 2; + + bool kh_no_radar_circles; + + // kh_state + // bits 0- 4: team of key 1, or 0 for no such key, or 30 for dropped, or 31 for self + // bits 5- 9: team of key 2, or 0 for no such key, or 30 for dropped, or 31 for self + // bits 10-14: team of key 3, or 0 for no such key, or 30 for dropped, or 31 for self + // bits 15-19: team of key 4, or 0 for no such key, or 30 for dropped, or 31 for self + .float siren_time; // time delay the siren + //.float stuff_time; // time delay to stuffcmd a cvar + + int kh_keystatus[17]; + //kh_keystatus[0] = status of dropped keys, kh_keystatus[1 - 16] = player # + //replace 17 with cvar("maxplayers") or similar !!!!!!!!! + //for(i = 0; i < maxplayers; ++i) + // kh_keystatus[i] = "0"; + + int kh_Team_ByID(int t) + { + if(t == 0) return NUM_TEAM_1; + if(t == 1) return NUM_TEAM_2; + if(t == 2) return NUM_TEAM_3; + if(t == 3) return NUM_TEAM_4; + return 0; + } + + //entity kh_worldkeylist; + .entity kh_worldkeynext; + entity kh_controller; + //bool kh_tracking_enabled; + int kh_teams; + int kh_interferemsg_team; + float kh_interferemsg_time; + .entity kh_next, kh_prev; // linked list + .float kh_droptime; + .int kh_dropperteam; + .entity kh_previous_owner; + .int kh_previous_owner_playerid; + + int kh_key_dropped, kh_key_carried; + + int kh_Key_AllOwnedByWhichTeam(); + + const int ST_KH_CAPS = 1; + void kh_ScoreRules(int teams) + { + GameRules_scoring(teams, SFL_SORT_PRIO_PRIMARY, SFL_SORT_PRIO_PRIMARY, { + field_team(ST_KH_CAPS, "caps", SFL_SORT_PRIO_SECONDARY); + field(SP_KH_CAPS, "caps", SFL_SORT_PRIO_SECONDARY); + field(SP_KH_PUSHES, "pushes", 0); + field(SP_KH_DESTROYS, "destroyed", SFL_LOWER_IS_BETTER); + field(SP_KH_PICKUPS, "pickups", 0); + field(SP_KH_KCKILLS, "kckills", 0); + field(SP_KH_LOSSES, "losses", SFL_LOWER_IS_BETTER); + }); + } + + bool kh_KeyCarrier_waypointsprite_visible_for_player(entity this, entity player, entity view) // runs all the time + { + if(!IS_PLAYER(view) || DIFF_TEAM(this, view)) + if(!kh_tracking_enabled) + return false; + + return true; + } + + bool kh_Key_waypointsprite_visible_for_player(entity this, entity player, entity view) + { + if(!kh_tracking_enabled) + return false; + if(!this.owner) + return true; + if(!this.owner.owner) + return true; + return false; // draw only when key is not owned + } + + void kh_update_state() + { + entity key; + int f; + int s = 0; + FOR_EACH_KH_KEY(key) + { + if(key.owner) + f = key.team; + else + f = 30; + s |= (32 ** key.count) * f; + } + + FOREACH_CLIENT(true, { STAT(KH_KEYS, it) = s; }); + + FOR_EACH_KH_KEY(key) + { + if(key.owner) + STAT(KH_KEYS, key.owner) |= (32 ** key.count) * 31; + } + //print(ftos((nextent(NULL)).kh_state), "\n"); + } + + + + + var kh_Think_t kh_Controller_Thinkfunc; + void kh_Controller_SetThink(float t, kh_Think_t func) // runs occasionaly + { + kh_Controller_Thinkfunc = func; + kh_controller.cnt = ceil(t); + if(t == 0) + kh_controller.nextthink = time; // force + } + void kh_WaitForPlayers(); + void kh_Controller_Think(entity this) // called a lot + { + if(game_stopped) + return; + if(this.cnt > 0) + { + if(getthink(this) != kh_WaitForPlayers) + this.cnt -= 1; + } + else if(this.cnt == 0) + { + this.cnt -= 1; + kh_Controller_Thinkfunc(); + } + this.nextthink = time + 1; + } + + // frags f: take from cvar * f + // frags 0: no frags + void kh_Scores_Event(entity player, entity key, string what, float frags_player, float frags_owner) // update the score when a key is captured + { + string s; + if(game_stopped) + return; + + if(frags_player) + UpdateFrags(player, frags_player); + + if(key && key.owner && frags_owner) + UpdateFrags(key.owner, frags_owner); + + if(!autocvar_sv_eventlog) //output extra info to the console or text file + return; + + s = strcat(":keyhunt:", what, ":", ftos(player.playerid), ":", ftos(frags_player)); + + if(key && key.owner) + s = strcat(s, ":", ftos(key.owner.playerid)); + else + s = strcat(s, ":0"); + + s = strcat(s, ":", ftos(frags_owner), ":"); + + if(key) + s = strcat(s, key.netname); + + GameLogEcho(s); + } + + vector kh_AttachedOrigin(entity e) // runs when a team captures the flag, it can run 2 or 3 times. + { + if(e.tag_entity) + { + makevectors(e.tag_entity.angles); + return e.tag_entity.origin + e.origin.x * v_forward - e.origin.y * v_right + e.origin.z * v_up; + } + else + return e.origin; + } + + void kh_Key_Attach(entity key) // runs when a player picks up a key and several times when a key is assigned to a player at the start of a round + { + #ifdef KH_PLAYER_USE_ATTACHMENT + entity first = key.owner.kh_next; + if(key == first) + { + setattachment(key, key.owner, KH_PLAYER_ATTACHMENT_BONE); + if(key.kh_next) + { + setattachment(key.kh_next, key, ""); + setorigin(key, key.kh_next.origin - 0.5 * KH_PLAYER_ATTACHMENT_DIST); + setorigin(key.kh_next, KH_PLAYER_ATTACHMENT_DIST_ROTATED); + key.kh_next.angles = '0 0 0'; + } + else + setorigin(key, KH_PLAYER_ATTACHMENT); + key.angles = KH_PLAYER_ATTACHMENT_ANGLES; + } + else + { + setattachment(key, key.kh_prev, ""); + if(key.kh_next) + setattachment(key.kh_next, key, ""); + setorigin(key, KH_PLAYER_ATTACHMENT_DIST_ROTATED); + setorigin(first, first.origin - 0.5 * KH_PLAYER_ATTACHMENT_DIST); + key.angles = '0 0 0'; + } + #else + setattachment(key, key.owner, ""); + setorigin(key, '0 0 1' * KH_KEY_ZSHIFT); // fixing x, y in think + key.angles_y -= key.owner.angles.y; + #endif + key.flags = 0; + if(IL_CONTAINS(g_items, key)) + IL_REMOVE(g_items, key); + key.solid = SOLID_NOT; + set_movetype(key, MOVETYPE_NONE); + key.team = key.owner.team; + key.nextthink = time; + key.damageforcescale = 0; + key.takedamage = DAMAGE_NO; + key.modelindex = kh_key_carried; + navigation_dynamicgoal_unset(key); + } + + void kh_Key_Detach(entity key) // runs every time a key is dropped or lost. Runs several times times when all the keys are captured + { + #ifdef KH_PLAYER_USE_ATTACHMENT + entity first = key.owner.kh_next; + if(key == first) + { + if(key.kh_next) + { + setattachment(key.kh_next, key.owner, KH_PLAYER_ATTACHMENT_BONE); + setorigin(key.kh_next, key.origin + 0.5 * KH_PLAYER_ATTACHMENT_DIST); + key.kh_next.angles = KH_PLAYER_ATTACHMENT_ANGLES; + } + } + else + { + if(key.kh_next) + setattachment(key.kh_next, key.kh_prev, ""); + setorigin(first, first.origin + 0.5 * KH_PLAYER_ATTACHMENT_DIST); + } + // in any case: + setattachment(key, NULL, ""); + setorigin(key, key.owner.origin + '0 0 1' * (STAT(PL_MIN, key.owner).z - KH_KEY_MIN_z)); + key.angles = key.owner.angles; + #else + setorigin(key, key.owner.origin + key.origin.z * '0 0 1'); + setattachment(key, NULL, ""); + key.angles_y += key.owner.angles.y; + #endif + key.flags = FL_ITEM; + if(!IL_CONTAINS(g_items, key)) + IL_PUSH(g_items, key); + key.solid = SOLID_TRIGGER; + set_movetype(key, MOVETYPE_TOSS); + key.pain_finished = time + autocvar_g_balance_keyhunt_delay_return; + key.damageforcescale = autocvar_g_balance_keyhunt_damageforcescale; + key.takedamage = DAMAGE_YES; + // let key.team stay + key.modelindex = kh_key_dropped; + navigation_dynamicgoal_set(key); + key.kh_previous_owner = key.owner; + key.kh_previous_owner_playerid = key.owner.playerid; + } + + void kh_Key_AssignTo(entity key, entity player) // runs every time a key is picked up or assigned. Runs prior to kh_key_attach + { + if(key.owner == player) + return; + + int ownerteam0 = kh_Key_AllOwnedByWhichTeam(); + + if(key.owner) + { + kh_Key_Detach(key); + + // remove from linked list + if(key.kh_next) + key.kh_next.kh_prev = key.kh_prev; + key.kh_prev.kh_next = key.kh_next; + key.kh_next = NULL; + key.kh_prev = NULL; + + if(key.owner.kh_next == NULL) + { + // No longer a key carrier + if(!kh_no_radar_circles) + WaypointSprite_Ping(key.owner.waypointsprite_attachedforcarrier); + WaypointSprite_DetachCarrier(key.owner); + } + } + + key.owner = player; + + if(player) + { + // insert into linked list + key.kh_next = player.kh_next; + key.kh_prev = player; + player.kh_next = key; + if(key.kh_next) + key.kh_next.kh_prev = key; + + float i; + i = kh_keystatus[key.owner.playerid]; + if(key.netname == "^1red key") + i += 1; + if(key.netname == "^4blue key") + i += 2; + if(key.netname == "^3yellow key") + i += 4; + if(key.netname == "^6pink key") + i += 8; + kh_keystatus[key.owner.playerid] = i; + + kh_Key_Attach(key); + + if(key.kh_next == NULL) + { + // player is now a key carrier + entity wp = WaypointSprite_AttachCarrier(WP_Null, player, RADARICON_FLAGCARRIER); + wp.colormod = colormapPaletteColor(player.team - 1, 0); + player.waypointsprite_attachedforcarrier.waypointsprite_visible_for_player = kh_KeyCarrier_waypointsprite_visible_for_player; + WaypointSprite_UpdateRule(player.waypointsprite_attachedforcarrier, player.team, SPRITERULE_TEAMPLAY); + if(player.team == NUM_TEAM_1) + WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierRed, WP_KeyCarrierFriend, WP_KeyCarrierRed); + else if(player.team == NUM_TEAM_2) + WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierBlue, WP_KeyCarrierFriend, WP_KeyCarrierBlue); + else if(player.team == NUM_TEAM_3) + WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierYellow, WP_KeyCarrierFriend, WP_KeyCarrierYellow); + else if(player.team == NUM_TEAM_4) + WaypointSprite_UpdateSprites(player.waypointsprite_attachedforcarrier, WP_KeyCarrierPink, WP_KeyCarrierFriend, WP_KeyCarrierPink); + if(!kh_no_radar_circles) + WaypointSprite_Ping(player.waypointsprite_attachedforcarrier); + } + } + + // moved that here, also update if there's no player + kh_update_state(); + + key.pusher = NULL; + + int ownerteam = kh_Key_AllOwnedByWhichTeam(); + if(ownerteam != ownerteam0) + { + entity k; + if(ownerteam != -1) + { + kh_interferemsg_time = time + 0.2; + kh_interferemsg_team = player.team; + + // audit all key carrier sprites, update them to "Run here" + FOR_EACH_KH_KEY(k) + { + if (!k.owner) continue; + entity first = WP_Null; + FOREACH(Waypoints, it.netname == k.owner.waypointsprite_attachedforcarrier.model1, { first = it; break; }); + entity third = WP_Null; + FOREACH(Waypoints, it.netname == k.owner.waypointsprite_attachedforcarrier.model3, { third = it; break; }); + WaypointSprite_UpdateSprites(k.owner.waypointsprite_attachedforcarrier, first, WP_KeyCarrierFinish, third); + } + } + else + { + kh_interferemsg_time = 0; + + // audit all key carrier sprites, update them to "Key Carrier" + FOR_EACH_KH_KEY(k) + { + if (!k.owner) continue; + entity first = WP_Null; + FOREACH(Waypoints, it.netname == k.owner.waypointsprite_attachedforcarrier.model1, { first = it; break; }); + entity third = WP_Null; + FOREACH(Waypoints, it.netname == k.owner.waypointsprite_attachedforcarrier.model3, { third = it; break; }); + WaypointSprite_UpdateSprites(k.owner.waypointsprite_attachedforcarrier, first, WP_KeyCarrierFriend, third); + } + } + } + } + + void kh_Key_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force) + { + if(this.owner) + return; + if(ITEM_DAMAGE_NEEDKILL(deathtype)) + { + this.pain_finished = bound(time, time + autocvar_g_balance_keyhunt_delay_damage_return, this.pain_finished); + return; + } + if(force == '0 0 0') + return; + if(time > this.pushltime) + if(IS_PLAYER(attacker)) + this.team = attacker.team; + } + + void kh_Key_Collect(entity key, entity player) //a player picks up a dropped key + { + sound(player, CH_TRIGGER, SND_KH_COLLECT, VOL_BASE, ATTEN_NORM); + + if(key.kh_dropperteam != player.team) + { + kh_Scores_Event(player, key, "collect", autocvar_g_balance_keyhunt_score_collect, 0); + GameRules_scoring_add(player, KH_PICKUPS, 1); + } + key.kh_dropperteam = 0; + int realteam = kh_Team_ByID(key.count); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_PICKUP), player.netname); + + kh_Key_AssignTo(key, player); // this also updates .kh_state + } + + void kh_Key_Touch(entity this, entity toucher) // runs many, many times when a key has been dropped and can be picked up + { + if(game_stopped) + return; + + if(this.owner) // already carried + return; + + if(ITEM_TOUCH_NEEDKILL()) + { + this.pain_finished = bound(time, time + autocvar_g_balance_keyhunt_delay_damage_return, this.pain_finished); + return; + } + + if (!IS_PLAYER(toucher)) + return; + if(IS_DEAD(toucher)) + return; + if(toucher == this.enemy) + if(time < this.kh_droptime + autocvar_g_balance_keyhunt_delay_collect) + return; // you just dropped it! + kh_Key_Collect(this, toucher); + } + + void kh_Key_Remove(entity key) // runs after when all the keys have been collected or when a key has been dropped for more than X seconds + { + entity o = key.owner; + kh_Key_AssignTo(key, NULL); + if(o) // it was attached + WaypointSprite_Kill(key.waypointsprite_attachedforcarrier); + else // it was dropped + WaypointSprite_DetachCarrier(key); + + // remove key from key list + if (kh_worldkeylist == key) + kh_worldkeylist = kh_worldkeylist.kh_worldkeynext; + else + { + o = kh_worldkeylist; + while (o) + { + if (o.kh_worldkeynext == key) + { + o.kh_worldkeynext = o.kh_worldkeynext.kh_worldkeynext; + break; + } + o = o.kh_worldkeynext; + } + } + + delete(key); + + kh_update_state(); + } + + void kh_FinishRound() // runs when a team captures the keys + { + // prepare next round + kh_interferemsg_time = 0; + entity key; + + kh_no_radar_circles = true; + FOR_EACH_KH_KEY(key) + kh_Key_Remove(key); + kh_no_radar_circles = false; + + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_KEYHUNT_ROUNDSTART, autocvar_g_balance_keyhunt_delay_round); + kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round, kh_StartRound); + } + + void nades_GiveBonus(entity player, float score); + + void kh_WinnerTeam(int winner_team) // runs when a team wins + { + // all key carriers get some points + entity key; + float score = (NumTeams(kh_teams) - 1) * autocvar_g_balance_keyhunt_score_capture; + DistributeEvenly_Init(score, NumTeams(kh_teams)); + // twice the score for 3 team games, three times the score for 4 team games! + // note: for a win by destroying the key, this should NOT be applied + FOR_EACH_KH_KEY(key) + { + float f = DistributeEvenly_Get(1); + kh_Scores_Event(key.owner, key, "capture", f, 0); + GameRules_scoring_add_team(key.owner, KH_CAPS, 1); + nades_GiveBonus(key.owner, autocvar_g_nades_bonus_score_high); + } + + bool first = true; + string keyowner = ""; + FOR_EACH_KH_KEY(key) + if(key.owner.kh_next == key) + { + if(!first) + keyowner = strcat(keyowner, ", "); + keyowner = key.owner.netname; + first = false; + } + + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(winner_team, CENTER_ROUND_TEAM_WIN)); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(winner_team, INFO_KEYHUNT_CAPTURE), keyowner); + + first = true; + vector firstorigin = '0 0 0', lastorigin = '0 0 0', midpoint = '0 0 0'; + FOR_EACH_KH_KEY(key) + { + vector thisorigin = kh_AttachedOrigin(key); + //dprint("Key origin: ", vtos(thisorigin), "\n"); + midpoint += thisorigin; + + if(!first) + te_lightning2(NULL, lastorigin, thisorigin); + lastorigin = thisorigin; + if(first) + firstorigin = thisorigin; + first = false; + } + if(NumTeams(kh_teams) > 2) + { + te_lightning2(NULL, lastorigin, firstorigin); + } + midpoint = midpoint * (1 / NumTeams(kh_teams)); + te_customflash(midpoint, 1000, 1, Team_ColorRGB(winner_team) * 0.5 + '0.5 0.5 0.5'); // make the color >=0.5 in each component + + play2all(SND(KH_CAPTURE)); + kh_FinishRound(); + } + + void kh_LoserTeam(int loser_team, entity lostkey) // runs when a player pushes a flag carrier off the map + { + float f; + entity attacker = NULL; + if(lostkey.pusher) + if(lostkey.pusher.team != loser_team) + if(IS_PLAYER(lostkey.pusher)) + attacker = lostkey.pusher; + + if(attacker) + { + if(lostkey.kh_previous_owner) + kh_Scores_Event(lostkey.kh_previous_owner, NULL, "pushed", 0, -autocvar_g_balance_keyhunt_score_push); + // don't actually GIVE him the -nn points, just log + kh_Scores_Event(attacker, NULL, "push", autocvar_g_balance_keyhunt_score_push, 0); + GameRules_scoring_add(attacker, KH_PUSHES, 1); + //centerprint(attacker, "Your push is the best!"); // does this really need to exist? + } + else + { + int players = 0; + float of = autocvar_g_balance_keyhunt_score_destroyed_ownfactor; + + FOREACH_CLIENT(IS_PLAYER(it) && it.team != loser_team, { ++players; }); + + entity key; + int keys = 0; + FOR_EACH_KH_KEY(key) + if(key.owner && key.team != loser_team) + ++keys; + + if(lostkey.kh_previous_owner) + kh_Scores_Event(lostkey.kh_previous_owner, NULL, "destroyed", 0, -autocvar_g_balance_keyhunt_score_destroyed); + // don't actually GIVE him the -nn points, just log + + if(lostkey.kh_previous_owner.playerid == lostkey.kh_previous_owner_playerid) + GameRules_scoring_add(lostkey.kh_previous_owner, KH_DESTROYS, 1); + + DistributeEvenly_Init(autocvar_g_balance_keyhunt_score_destroyed, keys * of + players); + + FOR_EACH_KH_KEY(key) + if(key.owner && key.team != loser_team) + { + f = DistributeEvenly_Get(of); + kh_Scores_Event(key.owner, NULL, "destroyed_holdingkey", f, 0); + } + + int fragsleft = DistributeEvenly_Get(players); + + // Now distribute these among all other teams... + int j = NumTeams(kh_teams) - 1; + for(int i = 0; i < NumTeams(kh_teams); ++i) + { + int thisteam = kh_Team_ByID(i); + if(thisteam == loser_team) // bad boy, no cookie - this WILL happen + continue; + + players = 0; + FOREACH_CLIENT(IS_PLAYER(it) && it.team == thisteam, { ++players; }); + + DistributeEvenly_Init(fragsleft, j); + fragsleft = DistributeEvenly_Get(j - 1); + DistributeEvenly_Init(DistributeEvenly_Get(1), players); + + FOREACH_CLIENT(IS_PLAYER(it) && it.team == thisteam, { + f = DistributeEvenly_Get(1); + kh_Scores_Event(it, NULL, "destroyed", f, 0); + }); + + --j; + } + } + + int realteam = kh_Team_ByID(lostkey.count); + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, APP_TEAM_NUM(loser_team, CENTER_ROUND_TEAM_LOSS)); + if(attacker) + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_PUSHED), attacker.netname, lostkey.kh_previous_owner.netname); + else + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_DESTROYED), lostkey.kh_previous_owner.netname); + + play2all(SND(KH_DESTROY)); + te_tarexplosion(lostkey.origin); + + kh_FinishRound(); + } + + void kh_Key_Think(entity this) // runs all the time + { + if(game_stopped) + return; + + if(this.owner) + { + #ifndef KH_PLAYER_USE_ATTACHMENT + makevectors('0 1 0' * (this.cnt + (time % 360) * KH_KEY_XYSPEED)); + setorigin(this, v_forward * KH_KEY_XYDIST + '0 0 1' * this.origin.z); + #endif + } + + // if in nodrop or time over, end the round + if(!this.owner) + if(time > this.pain_finished) + kh_LoserTeam(this.team, this); + + if(this.owner) + if(kh_Key_AllOwnedByWhichTeam() != -1) + { + if(this.siren_time < time) + { + sound(this.owner, CH_TRIGGER, SND_KH_ALARM, VOL_BASE, ATTEN_NORM); // play a simple alarm + this.siren_time = time + 2.5; // repeat every 2.5 seconds + } + + entity key; + vector p = this.owner.origin; + FOR_EACH_KH_KEY(key) + if(vdist(key.owner.origin - p, >, autocvar_g_balance_keyhunt_maxdist)) + goto not_winning; + kh_WinnerTeam(this.team); + LABEL(not_winning) + } + + if(kh_interferemsg_time && time > kh_interferemsg_time) + { + kh_interferemsg_time = 0; + FOREACH_CLIENT(IS_PLAYER(it), { + if(it.team == kh_interferemsg_team) + if(it.kh_next) + Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_KEYHUNT_MEET); + else + Send_Notification(NOTIF_ONE, it, MSG_CENTER, CENTER_KEYHUNT_HELP); + else + Send_Notification(NOTIF_ONE, it, MSG_CENTER, APP_TEAM_NUM(kh_interferemsg_team, CENTER_KEYHUNT_INTERFERE)); + }); + } + + this.nextthink = time + 0.05; + } + + void key_reset(entity this) + { + kh_Key_AssignTo(this, NULL); + kh_Key_Remove(this); + } + + const string STR_ITEM_KH_KEY = "item_kh_key"; + void kh_Key_Spawn(entity initial_owner, float _angle, float i) // runs every time a new flag is created, ie after all the keys have been collected + { + entity key = spawn(); + key.count = i; + key.classname = STR_ITEM_KH_KEY; + settouch(key, kh_Key_Touch); + setthink(key, kh_Key_Think); + key.nextthink = time; + key.items = IT_KEY1 | IT_KEY2; + key.cnt = _angle; + key.angles = '0 360 0' * random(); + key.event_damage = kh_Key_Damage; + key.takedamage = DAMAGE_YES; + key.damagedbytriggers = autocvar_g_balance_keyhunt_return_when_unreachable; + key.damagedbycontents = autocvar_g_balance_keyhunt_return_when_unreachable; + key.modelindex = kh_key_dropped; + key.model = "key"; + key.kh_dropperteam = 0; + key.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP; + setsize(key, KH_KEY_MIN, KH_KEY_MAX); + key.colormod = Team_ColorRGB(initial_owner.team) * KH_KEY_BRIGHTNESS; + key.reset = key_reset; + navigation_dynamicgoal_init(key, false); + + switch(initial_owner.team) + { + case NUM_TEAM_1: + key.netname = "^1red key"; + break; + case NUM_TEAM_2: + key.netname = "^4blue key"; + break; + case NUM_TEAM_3: + key.netname = "^3yellow key"; + break; + case NUM_TEAM_4: + key.netname = "^6pink key"; + break; + default: + key.netname = "NETGIER key"; + break; + } + + // link into key list + key.kh_worldkeynext = kh_worldkeylist; + kh_worldkeylist = key; + + Send_Notification(NOTIF_ONE, initial_owner, MSG_CENTER, APP_TEAM_NUM(initial_owner.team, CENTER_KEYHUNT_START)); + + WaypointSprite_Spawn(WP_KeyDropped, 0, 0, key, '0 0 1' * KH_KEY_WP_ZSHIFT, NULL, key.team, key, waypointsprite_attachedforcarrier, false, RADARICON_FLAG); + key.waypointsprite_attachedforcarrier.waypointsprite_visible_for_player = kh_Key_waypointsprite_visible_for_player; + + kh_Key_AssignTo(key, initial_owner); + } + + // -1 when no team completely owns all keys yet + int kh_Key_AllOwnedByWhichTeam() // constantly called. check to see if all the keys are owned by the same team + { + entity key; + int teem = -1; + int keys = NumTeams(kh_teams); + FOR_EACH_KH_KEY(key) + { + if(!key.owner) + return -1; + if(teem == -1) + teem = key.team; + else if(teem != key.team) + return -1; + --keys; + } + if(keys != 0) + return -1; + return teem; + } + + void kh_Key_DropOne(entity key) + { + // prevent collecting this one for some time + entity player = key.owner; + + key.kh_droptime = time; + key.enemy = player; + + kh_Scores_Event(player, key, "dropkey", 0, 0); + GameRules_scoring_add(player, KH_LOSSES, 1); + int realteam = kh_Team_ByID(key.count); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_DROP), player.netname); + + kh_Key_AssignTo(key, NULL); + makevectors(player.v_angle); + key.velocity = W_CalculateProjectileVelocity(player, player.velocity, autocvar_g_balance_keyhunt_throwvelocity * v_forward, false); + key.pusher = NULL; + key.pushltime = time + autocvar_g_balance_keyhunt_protecttime; + key.kh_dropperteam = key.team; + + sound(player, CH_TRIGGER, SND_KH_DROP, VOL_BASE, ATTEN_NORM); + } + + void kh_Key_DropAll(entity player, float suicide) // runs whenever a player dies + { + if(player.kh_next) + { + entity mypusher = NULL; + if(player.pusher) + if(time < player.pushltime) + mypusher = player.pusher; + + entity key; + while((key = player.kh_next)) + { + kh_Scores_Event(player, key, "losekey", 0, 0); + GameRules_scoring_add(player, KH_LOSSES, 1); + int realteam = kh_Team_ByID(key.count); + Send_Notification(NOTIF_ALL, NULL, MSG_INFO, APP_TEAM_NUM(realteam, INFO_KEYHUNT_LOST), player.netname); + kh_Key_AssignTo(key, NULL); + makevectors('-1 0 0' * (45 + 45 * random()) + '0 360 0' * random()); + key.velocity = W_CalculateProjectileVelocity(player, player.velocity, autocvar_g_balance_keyhunt_dropvelocity * v_forward, false); + key.pusher = mypusher; + key.pushltime = time + autocvar_g_balance_keyhunt_protecttime; + if(suicide) + key.kh_dropperteam = player.team; + } + sound(player, CH_TRIGGER, SND_KH_DROP, VOL_BASE, ATTEN_NORM); + } + } + + int kh_GetMissingTeams() + { + int missing_teams = 0; + for(int i = 0; i < NumTeams(kh_teams); ++i) + { + int teem = kh_Team_ByID(i); + int players = 0; + FOREACH_CLIENT(IS_PLAYER(it), { + if(!IS_DEAD(it) && !PHYS_INPUT_BUTTON_CHAT(it) && it.team == teem) + ++players; + }); + if (!players) + missing_teams |= (2 ** i); + } + return missing_teams; + } + + void kh_WaitForPlayers() // delay start of the round until enough players are present + { + static int prev_missing_teams_mask; + if(time < game_starttime) + { + if (prev_missing_teams_mask > 0) + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS); + prev_missing_teams_mask = -1; + kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers); + return; + } + + int missing_teams_mask = kh_GetMissingTeams(); + if(!missing_teams_mask) + { + if(prev_missing_teams_mask > 0) + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS); + prev_missing_teams_mask = -1; + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_KEYHUNT_ROUNDSTART, autocvar_g_balance_keyhunt_delay_round); + kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_round, kh_StartRound); + } + else + { + if(player_count == 0) + { + if(prev_missing_teams_mask > 0) + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_MISSING_TEAMS); + prev_missing_teams_mask = -1; + } + else + { + if(prev_missing_teams_mask != missing_teams_mask) + { + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_MISSING_TEAMS, missing_teams_mask); + prev_missing_teams_mask = missing_teams_mask; + } + } + kh_Controller_SetThink(1, kh_WaitForPlayers); + } + } + + void kh_EnableTrackingDevice() // runs after each round + { + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT); + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT_OTHER); + + kh_tracking_enabled = true; + } + + void kh_StartRound() // runs at the start of each round + { + if(time < game_starttime) + { + kh_Controller_SetThink(game_starttime - time + 0.1, kh_WaitForPlayers); + return; + } + + if(kh_GetMissingTeams()) + { + kh_Controller_SetThink(1, kh_WaitForPlayers); + return; + } + + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT); + Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_KEYHUNT_OTHER); + + for(int i = 0; i < NumTeams(kh_teams); ++i) + { + int teem = kh_Team_ByID(i); + int players = 0; + entity my_player = NULL; + FOREACH_CLIENT(IS_PLAYER(it), { + if(!IS_DEAD(it) && !PHYS_INPUT_BUTTON_CHAT(it) && it.team == teem) + { + ++players; + if(random() * players <= 1) + my_player = it; + } + }); + kh_Key_Spawn(my_player, 360 * i / NumTeams(kh_teams), i); + } + + kh_tracking_enabled = false; + Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_KEYHUNT_SCAN, autocvar_g_balance_keyhunt_delay_tracking); + kh_Controller_SetThink(autocvar_g_balance_keyhunt_delay_tracking, kh_EnableTrackingDevice); + } + + float kh_HandleFrags(entity attacker, entity targ, float f) // adds to the player score + { + if(attacker == targ) + return f; + + if(targ.kh_next) + { + if(attacker.team == targ.team) + { + int nk = 0; + for(entity k = targ.kh_next; k != NULL; k = k.kh_next) + ++nk; + kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", -nk * autocvar_g_balance_keyhunt_score_collect, 0); + } + else + { + kh_Scores_Event(attacker, targ.kh_next, "carrierfrag", autocvar_g_balance_keyhunt_score_carrierfrag-1, 0); + GameRules_scoring_add(attacker, KH_KCKILLS, 1); + // the frag gets added later + } + } + + return f; + } + + void kh_Initialize() // sets up th KH environment + { + // setup variables + kh_teams = autocvar_g_keyhunt_teams_override; + if(kh_teams < 2) + kh_teams = cvar("g_keyhunt_teams"); // read the cvar directly as it gets written earlier in the same frame + kh_teams = BITS(bound(2, kh_teams, 4)); + + // make a KH entity for controlling the game + kh_controller = spawn(); + setthink(kh_controller, kh_Controller_Think); + kh_Controller_SetThink(0, kh_WaitForPlayers); + + setmodel(kh_controller, MDL_KH_KEY); + kh_key_dropped = kh_controller.modelindex; + /* + dprint(vtos(kh_controller.mins)); + dprint(vtos(kh_controller.maxs)); + dprint("\n"); + */ + #ifdef KH_PLAYER_USE_CARRIEDMODEL + setmodel(kh_controller, MDL_KH_KEY_CARRIED); + kh_key_carried = kh_controller.modelindex; + #else + kh_key_carried = kh_key_dropped; + #endif + + kh_controller.model = ""; + kh_controller.modelindex = 0; + + kh_ScoreRules(kh_teams); + } + + void kh_finalize() + { + // to be called before intermission + kh_FinishRound(); + delete(kh_controller); + kh_controller = NULL; + } + + // legacy bot role + + void(entity this) havocbot_role_kh_carrier; + void(entity this) havocbot_role_kh_defense; + void(entity this) havocbot_role_kh_offense; + void(entity this) havocbot_role_kh_freelancer; + + + void havocbot_goalrating_kh(entity this, float ratingscale_team, float ratingscale_dropped, float ratingscale_enemy) + { + entity head; + for (head = kh_worldkeylist; head; head = head.kh_worldkeynext) + { + if(head.owner == this) + continue; + if(!kh_tracking_enabled) + { + // if it's carried by our team we know about it + // otherwise we have to see it to know about it + if(!head.owner || head.team != this.team) + { + traceline(this.origin + this.view_ofs, head.origin, MOVE_NOMONSTERS, this); + if (trace_fraction < 1 && trace_ent != head) + continue; // skip what I can't see + } + } + if(!head.owner) + navigation_routerating(this, head, ratingscale_dropped * 10000, 100000); + else if(head.team == this.team) + navigation_routerating(this, head.owner, ratingscale_team * 10000, 100000); + else + navigation_routerating(this, head.owner, ratingscale_enemy * 10000, 100000); + } + + havocbot_goalrating_items(this, 1, this.origin, 10000); + } + + void havocbot_role_kh_carrier(entity this) + { + if(IS_DEAD(this)) + return; + + if (!(this.kh_next)) + { + LOG_TRACE("changing role to freelancer"); + this.havocbot_role = havocbot_role_kh_freelancer; + this.havocbot_role_timeout = 0; + return; + } + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + + if(kh_Key_AllOwnedByWhichTeam() == this.team) + havocbot_goalrating_kh(this, 10, 0.1, 0.1); // bring home + else + havocbot_goalrating_kh(this, 4, 4, 1); // play defensively + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_kh_defense(entity this) + { + if(IS_DEAD(this)) + return; + + if (this.kh_next) + { + LOG_TRACE("changing role to carrier"); + this.havocbot_role = havocbot_role_kh_carrier; + this.havocbot_role_timeout = 0; + return; + } + + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + random() * 10 + 20; + if (time > this.havocbot_role_timeout) + { + LOG_TRACE("changing role to freelancer"); + this.havocbot_role = havocbot_role_kh_freelancer; + this.havocbot_role_timeout = 0; + return; + } + + if (navigation_goalrating_timeout(this)) + { + float key_owner_team; + navigation_goalrating_start(this); + + key_owner_team = kh_Key_AllOwnedByWhichTeam(); + if(key_owner_team == this.team) + havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend key carriers + else if(key_owner_team == -1) + havocbot_goalrating_kh(this, 4, 1, 0.1); // play defensively + else + havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK ANYWAY + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_kh_offense(entity this) + { + if(IS_DEAD(this)) + return; + + if (this.kh_next) + { + LOG_TRACE("changing role to carrier"); + this.havocbot_role = havocbot_role_kh_carrier; + this.havocbot_role_timeout = 0; + return; + } + + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + random() * 10 + 20; + if (time > this.havocbot_role_timeout) + { + LOG_TRACE("changing role to freelancer"); + this.havocbot_role = havocbot_role_kh_freelancer; + this.havocbot_role_timeout = 0; + return; + } + + if (navigation_goalrating_timeout(this)) + { + float key_owner_team; + + navigation_goalrating_start(this); + + key_owner_team = kh_Key_AllOwnedByWhichTeam(); + if(key_owner_team == this.team) + havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend anyway + else if(key_owner_team == -1) + havocbot_goalrating_kh(this, 0.1, 1, 4); // play offensively + else + havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK! EMERGENCY! + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void havocbot_role_kh_freelancer(entity this) + { + if(IS_DEAD(this)) + return; + + if (this.kh_next) + { + LOG_TRACE("changing role to carrier"); + this.havocbot_role = havocbot_role_kh_carrier; + this.havocbot_role_timeout = 0; + return; + } + + if (!this.havocbot_role_timeout) + this.havocbot_role_timeout = time + random() * 10 + 10; + if (time > this.havocbot_role_timeout) + { + if (random() < 0.5) + { + LOG_TRACE("changing role to offense"); + this.havocbot_role = havocbot_role_kh_offense; + } + else + { + LOG_TRACE("changing role to defense"); + this.havocbot_role = havocbot_role_kh_defense; + } + this.havocbot_role_timeout = 0; + return; + } + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + + int key_owner_team = kh_Key_AllOwnedByWhichTeam(); + if(key_owner_team == this.team) + havocbot_goalrating_kh(this, 10, 0.1, 0.1); // defend anyway + else if(key_owner_team == -1) + havocbot_goalrating_kh(this, 1, 10, 4); // prefer dropped keys + else + havocbot_goalrating_kh(this, 0.1, 0.1, 10); // ATTACK ANYWAY + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + + // register this as a mutator + + MUTATOR_HOOKFUNCTION(kh, ClientDisconnect) + { + entity player = M_ARGV(0, entity); + + kh_Key_DropAll(player, true); + } + + MUTATOR_HOOKFUNCTION(kh, MakePlayerObserver) + { + entity player = M_ARGV(0, entity); + + kh_Key_DropAll(player, true); + } + + MUTATOR_HOOKFUNCTION(kh, PlayerDies) + { + entity frag_attacker = M_ARGV(1, entity); + entity frag_target = M_ARGV(2, entity); + + if(frag_target == frag_attacker) + kh_Key_DropAll(frag_target, true); + else if(IS_PLAYER(frag_attacker)) + kh_Key_DropAll(frag_target, false); + else + kh_Key_DropAll(frag_target, true); + } + + MUTATOR_HOOKFUNCTION(kh, GiveFragsForKill, CBC_ORDER_FIRST) + { + entity frag_attacker = M_ARGV(0, entity); + entity frag_target = M_ARGV(1, entity); + float frag_score = M_ARGV(2, float); + M_ARGV(2, float) = kh_HandleFrags(frag_attacker, frag_target, frag_score); + } + + MUTATOR_HOOKFUNCTION(kh, MatchEnd) + { + kh_finalize(); + } + -MUTATOR_HOOKFUNCTION(kh, CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) ++MUTATOR_HOOKFUNCTION(kh, TeamBalance_CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) + { + M_ARGV(0, float) = kh_teams; ++ return true; + } + + MUTATOR_HOOKFUNCTION(kh, SpectateCopy) + { + entity spectatee = M_ARGV(0, entity); + entity client = M_ARGV(1, entity); + + STAT(KH_KEYS, client) = STAT(KH_KEYS, spectatee); + } + + MUTATOR_HOOKFUNCTION(kh, PlayerUseKey) + { + entity player = M_ARGV(0, entity); + + if(MUTATOR_RETURNVALUE == 0) + { + entity k = player.kh_next; + if(k) + { + kh_Key_DropOne(k); + return true; + } + } + } + + MUTATOR_HOOKFUNCTION(kh, HavocBot_ChooseRole) + { + entity bot = M_ARGV(0, entity); + + if(IS_DEAD(bot)) + return true; + + float r = random() * 3; + if (r < 1) + bot.havocbot_role = havocbot_role_kh_offense; + else if (r < 2) + bot.havocbot_role = havocbot_role_kh_defense; + else + bot.havocbot_role = havocbot_role_kh_freelancer; + + return true; + } + + MUTATOR_HOOKFUNCTION(kh, DropSpecialItems) + { + entity frag_target = M_ARGV(0, entity); + + kh_Key_DropAll(frag_target, false); + } + + MUTATOR_HOOKFUNCTION(kh, reset_map_global) + { + kh_WaitForPlayers(); // takes care of killing the "missing teams" message + } + #endif diff --cc qcsrc/common/gamemodes/gamemode/race/race.qc index 000000000,c98e1b6a8..aaf83cb39 mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/race/race.qc +++ b/qcsrc/common/gamemodes/gamemode/race/race.qc @@@ -1,0 -1,492 +1,493 @@@ + #include "race.qh" + + // TODO: sv_race + #ifdef SVQC + #include + + #define autocvar_g_race_laps_limit cvar("g_race_laps_limit") + float autocvar_g_race_qualifying_timelimit; + float autocvar_g_race_qualifying_timelimit_override; + int autocvar_g_race_teams; + + // legacy bot roles + .float race_checkpoint; + void havocbot_role_race(entity this) + { + if(IS_DEAD(this)) + return; + + if (navigation_goalrating_timeout(this)) + { + navigation_goalrating_start(this); + + bool raw_touch_check = true; + int cp = this.race_checkpoint; + + LABEL(search_racecheckpoints) + IL_EACH(g_racecheckpoints, true, + { + if(it.cnt == cp || cp == -1) + { + // redirect bot to next goal if it touched the waypoint of an untouchable checkpoint + // e.g. checkpoint in front of Stormkeep's warpzone + // the same workaround is applied in CTS game mode + if (raw_touch_check && vdist(this.origin - it.nearestwaypoint.origin, <, 30)) + { + cp = race_NextCheckpoint(cp); + raw_touch_check = false; + goto search_racecheckpoints; + } + navigation_routerating(this, it, 1000000, 5000); + } + }); + + navigation_goalrating_end(this); + + navigation_goalrating_timeout_set(this); + } + } + + void race_ScoreRules() + { + GameRules_score_enabled(false); + GameRules_scoring(race_teams, 0, 0, { + if (race_teams) { + field_team(ST_RACE_LAPS, "laps", SFL_SORT_PRIO_PRIMARY); + field(SP_RACE_LAPS, "laps", SFL_SORT_PRIO_PRIMARY); + field(SP_RACE_TIME, "time", SFL_SORT_PRIO_SECONDARY | SFL_LOWER_IS_BETTER | SFL_TIME); + field(SP_RACE_FASTEST, "fastest", SFL_LOWER_IS_BETTER | SFL_TIME); + } else if (g_race_qualifying) { + field(SP_RACE_FASTEST, "fastest", SFL_SORT_PRIO_PRIMARY | SFL_LOWER_IS_BETTER | SFL_TIME); + } else { + field(SP_RACE_LAPS, "laps", SFL_SORT_PRIO_PRIMARY); + field(SP_RACE_TIME, "time", SFL_SORT_PRIO_SECONDARY | SFL_LOWER_IS_BETTER | SFL_TIME); + field(SP_RACE_FASTEST, "fastest", SFL_LOWER_IS_BETTER | SFL_TIME); + } + }); + } + + void race_EventLog(string mode, entity actor) // use an alias for easy changing and quick editing later + { + if(autocvar_sv_eventlog) + GameLogEcho(strcat(":race:", mode, ":", ((actor != NULL) ? (strcat(":", ftos(actor.playerid))) : ""))); + } + + float WinningCondition_Race(float fraglimit) + { + float wc; + float n, c; + + n = 0; + c = 0; + FOREACH_CLIENT(IS_PLAYER(it), { + ++n; + if(CS(it).race_completed) + ++c; + }); + if(n && (n == c)) + return WINNING_YES; + wc = WinningCondition_Scores(fraglimit, 0); + + // ALWAYS initiate overtime, unless EVERYONE has finished the race! + if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME) + // do NOT support equality when the laps are all raced! + return WINNING_STARTSUDDENDEATHOVERTIME; + else + return WINNING_NEVER; + } + + float WinningCondition_QualifyingThenRace(float limit) + { + float wc; + wc = WinningCondition_Scores(limit, 0); + + // NEVER initiate overtime + if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME) + { + return WINNING_YES; + } + + return wc; + } + + MUTATOR_HOOKFUNCTION(rc, ClientKill) + { + if(g_race_qualifying) + M_ARGV(1, float) = 0; // killtime + } + + MUTATOR_HOOKFUNCTION(rc, AbortSpeedrun) + { + entity player = M_ARGV(0, entity); + + if(autocvar_g_allow_checkpoints) + race_PreparePlayer(player); // nice try + } + + MUTATOR_HOOKFUNCTION(rc, PlayerPhysics) + { + entity player = M_ARGV(0, entity); + float dt = M_ARGV(1, float); + + player.race_movetime_frac += dt; + float f = floor(player.race_movetime_frac); + player.race_movetime_frac -= f; + player.race_movetime_count += f; + player.race_movetime = player.race_movetime_frac + player.race_movetime_count; + + #ifdef SVQC + if(IS_PLAYER(player)) + { + if (player.race_penalty) + if (time > player.race_penalty) + player.race_penalty = 0; + if(player.race_penalty) + { + player.velocity = '0 0 0'; + set_movetype(player, MOVETYPE_NONE); + player.disableclientprediction = 2; + } + } + #endif + + // force kbd movement for fairness + float wishspeed; + vector wishvel; + + // if record times matter + // ensure nothing EVIL is being done (i.e. div0_evade) + // this hinders joystick users though + // but it still gives SOME analog control + wishvel.x = fabs(CS(player).movement.x); + wishvel.y = fabs(CS(player).movement.y); + if(wishvel.x != 0 && wishvel.y != 0 && wishvel.x != wishvel.y) + { + wishvel.z = 0; + wishspeed = vlen(wishvel); + if(wishvel.x >= 2 * wishvel.y) + { + // pure X motion + if(CS(player).movement.x > 0) + CS(player).movement_x = wishspeed; + else + CS(player).movement_x = -wishspeed; + CS(player).movement_y = 0; + } + else if(wishvel.y >= 2 * wishvel.x) + { + // pure Y motion + CS(player).movement_x = 0; + if(CS(player).movement.y > 0) + CS(player).movement_y = wishspeed; + else + CS(player).movement_y = -wishspeed; + } + else + { + // diagonal + if(CS(player).movement.x > 0) + CS(player).movement_x = M_SQRT1_2 * wishspeed; + else + CS(player).movement_x = -M_SQRT1_2 * wishspeed; + if(CS(player).movement.y > 0) + CS(player).movement_y = M_SQRT1_2 * wishspeed; + else + CS(player).movement_y = -M_SQRT1_2 * wishspeed; + } + } + } + + MUTATOR_HOOKFUNCTION(rc, reset_map_global) + { + float s; + + Score_NicePrint(NULL); + + race_ClearRecords(); + PlayerScore_Sort(race_place, 0, 1, 0); + + FOREACH_CLIENT(true, { + if(it.race_place) + { + s = GameRules_scoring_add(it, RACE_FASTEST, 0); + if(!s) + it.race_place = 0; + } + race_EventLog(ftos(it.race_place), it); + }); + + if(g_race_qualifying == 2) + { + g_race_qualifying = 0; + independent_players = 0; + cvar_set("fraglimit", ftos(race_fraglimit)); + cvar_set("leadlimit", ftos(race_leadlimit)); + cvar_set("timelimit", ftos(race_timelimit)); + race_ScoreRules(); + } + } + + MUTATOR_HOOKFUNCTION(rc, ClientConnect) + { + entity player = M_ARGV(0, entity); + + race_PreparePlayer(player); + player.race_checkpoint = -1; + + string rr = RACE_RECORD; + + if(IS_REAL_CLIENT(player)) + { + msg_entity = player; + race_send_recordtime(MSG_ONE); + race_send_speedaward(MSG_ONE); + + speedaward_alltimebest = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/speed"))); + speedaward_alltimebest_holder = uid2name(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/crypto_idfp"))); + race_send_speedaward_alltimebest(MSG_ONE); + + float i; + int m = min(RANKINGS_CNT, autocvar_g_cts_send_rankings_cnt); + race_send_rankings_cnt(MSG_ONE); + for (i = 1; i <= m; ++i) + { + race_SendRankings(i, 0, 0, MSG_ONE); + } + } + } + + MUTATOR_HOOKFUNCTION(rc, MakePlayerObserver) + { + entity player = M_ARGV(0, entity); + + if(g_race_qualifying) + if(GameRules_scoring_add(player, RACE_FASTEST, 0)) + player.frags = FRAGS_LMS_LOSER; + else + player.frags = FRAGS_SPECTATOR; + + race_PreparePlayer(player); + player.race_checkpoint = -1; + } + + MUTATOR_HOOKFUNCTION(rc, PlayerSpawn) + { + entity player = M_ARGV(0, entity); + entity spawn_spot = M_ARGV(1, entity); + + if(spawn_spot.target == "") + // Emergency: this wasn't a real spawnpoint. Can this ever happen? + race_PreparePlayer(player); + + // if we need to respawn, do it right + player.race_respawn_checkpoint = player.race_checkpoint; + player.race_respawn_spotref = spawn_spot; + + player.race_place = 0; + } + + MUTATOR_HOOKFUNCTION(rc, PutClientInServer) + { + entity player = M_ARGV(0, entity); + + if(IS_PLAYER(player)) + if(!game_stopped) + { + if(CS(player).killcount == FRAGS_SPECTATOR /* initial spawn */ || g_race_qualifying) // spawn + race_PreparePlayer(player); + else // respawn + race_RetractPlayer(player); + + race_AbandonRaceCheck(player); + } + } + + MUTATOR_HOOKFUNCTION(rc, PlayerDies) + { + entity frag_target = M_ARGV(2, entity); + + frag_target.respawn_flags |= RESPAWN_FORCE; + race_AbandonRaceCheck(frag_target); + } + + MUTATOR_HOOKFUNCTION(rc, HavocBot_ChooseRole) + { + entity bot = M_ARGV(0, entity); + + bot.havocbot_role = havocbot_role_race; + return true; + } + + MUTATOR_HOOKFUNCTION(rc, GetPressedKeys) + { + entity player = M_ARGV(0, entity); + + if(CS(player).cvar_cl_allow_uidtracking == 1 && CS(player).cvar_cl_allow_uid2name == 1) + { + if (!player.stored_netname) + player.stored_netname = strzone(uid2name(player.crypto_idfp)); + if(player.stored_netname != player.netname) + { + db_put(ServerProgsDB, strcat("/uid2name/", player.crypto_idfp), player.netname); + strcpy(player.stored_netname, player.netname); + } + } + + if (!IS_OBSERVER(player)) + { + if(vdist(player.velocity - player.velocity_z * '0 0 1', >, speedaward_speed)) + { + speedaward_speed = vlen(player.velocity - player.velocity_z * '0 0 1'); + speedaward_holder = player.netname; + speedaward_uid = player.crypto_idfp; + speedaward_lastupdate = time; + } + if (speedaward_speed > speedaward_lastsent && time - speedaward_lastupdate > 1) + { + string rr = RACE_RECORD; + race_send_speedaward(MSG_ALL); + speedaward_lastsent = speedaward_speed; + if (speedaward_speed > speedaward_alltimebest && speedaward_uid != "") + { + speedaward_alltimebest = speedaward_speed; + speedaward_alltimebest_holder = speedaward_holder; + speedaward_alltimebest_uid = speedaward_uid; + db_put(ServerProgsDB, strcat(GetMapname(), rr, "speed/speed"), ftos(speedaward_alltimebest)); + db_put(ServerProgsDB, strcat(GetMapname(), rr, "speed/crypto_idfp"), speedaward_alltimebest_uid); + race_send_speedaward_alltimebest(MSG_ALL); + } + } + } + } + + MUTATOR_HOOKFUNCTION(rc, ForbidPlayerScore_Clear) + { + if(g_race_qualifying) + return true; // in qualifying, you don't lose score by observing + } + -MUTATOR_HOOKFUNCTION(rc, CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) ++MUTATOR_HOOKFUNCTION(rc, TeamBalance_CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) + { + M_ARGV(0, float) = race_teams; ++ return true; + } + + MUTATOR_HOOKFUNCTION(rc, Scores_CountFragsRemaining) + { + // announce remaining frags if not in qualifying mode + if(!g_race_qualifying) + return true; + } + + MUTATOR_HOOKFUNCTION(rc, GetRecords) + { + int record_page = M_ARGV(0, int); + string ret_string = M_ARGV(1, string); + + for(int i = record_page * 200; i < MapInfo_count && i < record_page * 200 + 200; ++i) + { + if(MapInfo_Get_ByID(i)) + { + float r = race_readTime(MapInfo_Map_bspname, 1); + + if(!r) + continue; + + string h = race_readName(MapInfo_Map_bspname, 1); + ret_string = strcat(ret_string, strpad(32, MapInfo_Map_bspname), " ", strpad(-8, TIME_ENCODED_TOSTRING(r)), " ", h, "\n"); + } + } + + M_ARGV(1, string) = ret_string; + } + + MUTATOR_HOOKFUNCTION(rc, HideTeamNagger) + { + return true; // doesn't work so well + } + + MUTATOR_HOOKFUNCTION(rc, FixClientCvars) + { + entity player = M_ARGV(0, entity); + + stuffcmd(player, "cl_cmd settemp cl_movecliptokeyboard 2\n"); + } + + MUTATOR_HOOKFUNCTION(rc, CheckRules_World) + { + float checkrules_timelimit = M_ARGV(1, float); + float checkrules_fraglimit = M_ARGV(2, float); + + if(checkrules_timelimit >= 0) + { + if(!g_race_qualifying) + { + M_ARGV(0, float) = WinningCondition_Race(checkrules_fraglimit); + return true; + } + else if(g_race_qualifying == 2) + { + M_ARGV(0, float) = WinningCondition_QualifyingThenRace(checkrules_fraglimit); + return true; + } + } + } + + MUTATOR_HOOKFUNCTION(rc, ReadLevelCvars) + { + if(g_race_qualifying == 2) + warmup_stage = 0; + } + + void race_Initialize() + { + race_ScoreRules(); + if(g_race_qualifying == 2) + warmup_stage = 0; + } + + void rc_SetLimits() + { + int fraglimit_override, leadlimit_override; + float timelimit_override, qualifying_override; + + if(autocvar_g_race_teams) + { + GameRules_teams(true); + race_teams = BITS(bound(2, autocvar_g_race_teams, 4)); + } + else + race_teams = 0; + + qualifying_override = autocvar_g_race_qualifying_timelimit_override; + fraglimit_override = autocvar_g_race_laps_limit; + leadlimit_override = 0; // currently not supported by race + timelimit_override = autocvar_timelimit_override; + + float want_qualifying = ((qualifying_override >= 0) ? qualifying_override : autocvar_g_race_qualifying_timelimit) > 0; + + if(autocvar_g_campaign) + { + g_race_qualifying = 1; + independent_players = 1; + } + else if(want_qualifying) + { + g_race_qualifying = 2; + independent_players = 1; + race_fraglimit = (fraglimit_override >= 0) ? fraglimit_override : autocvar_fraglimit; + race_leadlimit = (leadlimit_override >= 0) ? leadlimit_override : autocvar_leadlimit; + race_timelimit = (timelimit_override >= 0) ? timelimit_override : autocvar_timelimit; + qualifying_override = (qualifying_override >= 0) ? qualifying_override : autocvar_g_race_qualifying_timelimit; + fraglimit_override = 0; + leadlimit_override = 0; + timelimit_override = qualifying_override; + } + else + g_race_qualifying = 0; + GameRules_limit_score(fraglimit_override); + GameRules_limit_lead(leadlimit_override); + GameRules_limit_time(timelimit_override); + GameRules_limit_time_qualifying(qualifying_override); + } + #endif diff --cc qcsrc/common/gamemodes/gamemode/tdm/tdm.qc index 000000000,39e5fec1e..cf328902b mode 000000,100644..100644 --- a/qcsrc/common/gamemodes/gamemode/tdm/tdm.qc +++ b/qcsrc/common/gamemodes/gamemode/tdm/tdm.qc @@@ -1,0 -1,67 +1,66 @@@ + #include "tdm.qh" + + // TODO: sv_tdm + // TODO? rename to teamdeathmatch + #ifdef SVQC + int autocvar_g_tdm_teams; + int autocvar_g_tdm_teams_override; + + /*QUAKED spawnfunc_tdm_team (0 .5 .8) (-16 -16 -24) (16 16 32) + Team declaration for TDM gameplay, this allows you to decide what team names and control point models are used in your map. + Note: If you use spawnfunc_tdm_team entities you must define at least 2! However, unlike domination, you don't need to make a blank one too. + Keys: + "netname" Name of the team (for example Red, Blue, Green, Yellow, Life, Death, Offense, Defense, etc)... + "cnt" Scoreboard color of the team (for example 4 is red and 13 is blue)... */ + spawnfunc(tdm_team) + { + if(!g_tdm || !this.cnt) { delete(this); return; } + + this.classname = "tdm_team"; + this.team = this.cnt + 1; + } + + // code from here on is just to support maps that don't have team entities + void tdm_SpawnTeam (string teamname, int teamcolor) + { + entity this = new_pure(tdm_team); + this.netname = teamname; + this.cnt = teamcolor - 1; + this.team = teamcolor; + this.spawnfunc_checked = true; + //spawnfunc_tdm_team(this); + } + + void tdm_DelayedInit(entity this) + { + // if no teams are found, spawn defaults + if(find(NULL, classname, "tdm_team") == NULL) + { + LOG_TRACE("No \"tdm_team\" entities found on this map, creating them anyway."); + + int numteams = autocvar_g_tdm_teams_override; + if(numteams < 2) { numteams = autocvar_g_tdm_teams; } + + int teams = BITS(bound(2, numteams, 4)); + if(teams & BIT(0)) + tdm_SpawnTeam("Red", NUM_TEAM_1); + if(teams & BIT(1)) + tdm_SpawnTeam("Blue", NUM_TEAM_2); + if(teams & BIT(2)) + tdm_SpawnTeam("Yellow", NUM_TEAM_3); + if(teams & BIT(3)) + tdm_SpawnTeam("Pink", NUM_TEAM_4); + } + } + -MUTATOR_HOOKFUNCTION(tdm, CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) ++MUTATOR_HOOKFUNCTION(tdm, TeamBalance_CheckAllowedTeams, CBC_ORDER_EXCLUSIVE) + { + M_ARGV(1, string) = "tdm_team"; - return true; + } + + MUTATOR_HOOKFUNCTION(tdm, Scores_CountFragsRemaining) + { + // announce remaining frags + return true; + } + #endif diff --cc qcsrc/common/gamemodes/sv_rules.qh index 35a643d53,979477cba..ca1b6f8e7 --- a/qcsrc/common/gamemodes/sv_rules.qh +++ b/qcsrc/common/gamemodes/sv_rules.qh @@@ -1,5 -1,9 +1,8 @@@ #pragma once + // TODO: find a better location for these? + float total_players; -float redalive, bluealive, yellowalive, pinkalive; + // todo: accept the number of teams as a parameter void GameRules_teams(bool value); diff --cc qcsrc/server/teamplay.qc index 3faa2d8a8,a30e4696d..22ea23546 --- a/qcsrc/server/teamplay.qc +++ b/qcsrc/server/teamplay.qc @@@ -12,113 -12,144 +12,113 @@@ #include "mutators/_mod.qh" #include "../common/deathtypes/all.qh" - #include "../common/gamemodes/_mod.qh" + #include #include "../common/teams.qh" -void TeamchangeFrags(entity e) +/// \brief Describes a state of team balance entity. +enum { - PlayerScore_Clear(e); -} + TEAM_BALANCE_UNINITIALIZED, ///< The team balance has not been initialized. + /// \brief TeamBalance_CheckAllowedTeams has been called. + TEAM_BALANCE_TEAMS_CHECKED, + /// \brief TeamBalance_GetTeamCounts has been called. + TEAM_BALANCE_TEAM_COUNTS_FILLED +}; -void LogTeamchange(float player_id, float team_number, float type) -{ - if(!autocvar_sv_eventlog) - return; +/// \brief Indicates that the player is not allowed to join a team. +const int TEAM_NOT_ALLOWED = -1; - if(player_id < 1) - return; +.int m_team_balance_state; ///< Holds the state of the team balance entity. +.entity m_team_balance_team[NUM_TEAMS]; ///< ??? - GameLogEcho(strcat(":team:", ftos(player_id), ":", ftos(team_number), ":", ftos(type))); -} +.float m_team_score; ///< The score of the team. +.int m_num_players; ///< Number of players (both humans and bots) in a team. +.int m_num_bots; ///< Number of bots in a team. +.int m_num_players_alive; ///< Number of alive players in a team. +.int m_num_control_points; ///< Number of control points owned by a team. + +entity g_team_entities[NUM_TEAMS]; ///< Holds global team entities. -void default_delayedinit(entity this) +STATIC_INIT(g_team_entities) { - if(!scores_initialized) - ScoreRules_generic(); + for (int i = 0; i < NUM_TEAMS; ++i) + { + g_team_entities[i] = spawn(); + } } -void InitGameplayMode() +entity Team_GetTeamFromIndex(int index) { - VoteReset(); - - // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds - get_mi_min_max(1); - // assign reflectively to avoid "assignment to world" warning - int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) { - string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0'; - if (v) { - putentityfieldstring(i, world, sprintf("%v", v)); - if (++done == 2) break; - } - } - // currently, NetRadiant's limit is 131072 qu for each side - // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu - // set the distance according to map size but don't go over the limit to avoid issues with float precision - // in case somebody makes extremely large maps - max_shot_distance = min(230000, vlen(world.maxs - world.mins)); - - MapInfo_LoadMapSettings(mapname); - GameRules_teams(false); - - if (!cvar_value_issafe(world.fog)) - { - LOG_INFO("The current map contains a potentially harmful fog setting, ignored"); - world.fog = string_null; - } - if(MapInfo_Map_fog != "") - if(MapInfo_Map_fog == "none") - world.fog = string_null; - else - world.fog = strzone(MapInfo_Map_fog); - clientstuff = strzone(MapInfo_Map_clientstuff); - - MapInfo_ClearTemps(); - - gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype); - - cache_mutatormsg = strzone(""); - cache_lastmutatormsg = strzone(""); - - InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK); + if (!Team_IsValidIndex(index)) + { + LOG_FATALF("Team_GetTeamFromIndex: Index is invalid: %f", index); + } + return g_team_entities[index - 1]; } -string GetClientVersionMessage(entity this) +entity Team_GetTeam(int team_num) { - if (CS(this).version_mismatch) { - if(CS(this).version < autocvar_gameversion) { - return strcat("This is Xonotic ", autocvar_g_xonoticversion, - "\n^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8"); - } else { - return strcat("This is Xonotic ", autocvar_g_xonoticversion, - "\n^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8"); - } - } else { - return strcat("Welcome to Xonotic ", autocvar_g_xonoticversion); + if (!Team_IsValidTeam(team_num)) + { + LOG_FATALF("Team_GetTeam: Value is invalid: %f", team_num); } + return g_team_entities[Team_TeamToIndex(team_num) - 1]; } -string getwelcomemessage(entity this) +float Team_GetTeamScore(entity team_ent) { - MUTATOR_CALLHOOK(BuildMutatorsPrettyString, ""); - string modifications = M_ARGV(0, string); + return team_ent.m_team_score; +} - if(g_weaponarena) - { - if(g_weaponarena_random) - modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena"); // TODO: somehow get this into the mutator - else - modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena"); - } - else if(cvar("g_balance_blaster_weaponstartoverride") == 0) - modifications = strcat(modifications, ", No start weapons"); - if(cvar("sv_gravity") < stof(cvar_defstring("sv_gravity"))) - modifications = strcat(modifications, ", Low gravity"); - if(g_weapon_stay && !g_cts) - modifications = strcat(modifications, ", Weapons stay"); - if(g_jetpack) - modifications = strcat(modifications, ", Jet pack"); - if(autocvar_g_powerups == 0) - modifications = strcat(modifications, ", No powerups"); - if(autocvar_g_powerups > 0) - modifications = strcat(modifications, ", Powerups"); - modifications = substring(modifications, 2, strlen(modifications) - 2); +void Team_SetTeamScore(entity team_ent, float score) +{ + team_ent.m_team_score = score; +} - string versionmessage = GetClientVersionMessage(this); - string s = strcat(versionmessage, "^8\n^8\nmatch type is ^1", gamemode_name, "^8\n"); +int Team_GetNumberOfAlivePlayers(entity team_ent) +{ + return team_ent.m_num_players_alive; +} - if(modifications != "") - s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n"); +void Team_SetNumberOfAlivePlayers(entity team_ent, int number) +{ + team_ent.m_num_players_alive = number; +} - if(cache_lastmutatormsg != autocvar_g_mutatormsg) +int Team_GetNumberOfAliveTeams() +{ + int result = 0; + for (int i = 0; i < NUM_TEAMS; ++i) { - strcpy(cache_lastmutatormsg, autocvar_g_mutatormsg); - strcpy(cache_mutatormsg, cache_lastmutatormsg); - } - - if (cache_mutatormsg != "") { - s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg); + if (g_team_entities[i].m_num_players_alive > 0) + { + ++result; + } } + return result; +} - string mutator_msg = ""; - MUTATOR_CALLHOOK(BuildGameplayTipsString, mutator_msg); - mutator_msg = M_ARGV(0, string); +int Team_GetNumberOfControlPoints(entity team_ent) +{ + return team_ent.m_num_control_points; +} - s = strcat(s, mutator_msg); // trust that the mutator will do proper formatting +void Team_SetNumberOfControlPoints(entity team_ent, int number) +{ + team_ent.m_num_control_points = number; +} - string motd = autocvar_sv_motd; - if (motd != "") { - s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd)); +int Team_GetNumberOfTeamsWithControlPoints() +{ + int result = 0; + for (int i = 0; i < NUM_TEAMS; ++i) + { + if (g_team_entities[i].m_num_control_points > 0) + { + ++result; + } } - return s; + return result; } void setcolor(entity this, int clr)