Move ServerTraits into Mods.

This commit is contained in:
Paul Chote
2010-11-10 09:57:11 +13:00
parent 8e007131c9
commit dfa14f16d3
7 changed files with 82 additions and 74 deletions

View File

@@ -192,10 +192,7 @@
<Compile Include="Traits\ActorStance.cs" />
<Compile Include="Traits\Armor.cs" />
<Compile Include="Graphics\CursorProvider.cs" />
<Compile Include="ServerTraits\TraitInterfaces.cs" />
<Compile Include="ServerTraits\LobbyCommands.cs" />
<Compile Include="ServerTraits\PlayerCommands.cs" />
<Compile Include="ServerTraits\MasterServerPinger.cs" />
<Compile Include="Server\TraitInterfaces.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OpenRA.FileFormats\OpenRA.FileFormats.csproj">

View File

@@ -20,7 +20,6 @@ using System.Threading;
using OpenRA.FileFormats;
using OpenRA.GameRules;
using OpenRA.Network;
using OpenRA.Server.Traits;
namespace OpenRA.Server
{

View File

@@ -10,7 +10,7 @@
using System;
using OpenRA.Network;
namespace OpenRA.Server.Traits
namespace OpenRA.Server
{
// Returns true if order is handled
public interface IInterpretCommand { bool InterpretCommand(Connection conn, Session.Client client, string cmd); }

View File

@@ -1,318 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Network;
using OpenRA.FileFormats;
namespace OpenRA.Server.Traits
{
public class LobbyCommands : ServerTrait, IInterpretCommand, INotifyServerStart, IClientJoined
{
public static int MaxSpectators = 4; // How many spectators to allow // @todo Expose this as an option
public bool InterpretCommand(Connection conn, Session.Client client, string cmd)
{
if (Server.GameStarted)
{
Server.SendChatTo(conn, "Cannot change state when game started. ({0})".F(cmd));
return false;
}
else if (client.State == Session.ClientState.Ready && !(cmd == "ready" || cmd == "startgame"))
{
Server.SendChatTo(conn, "Cannot change state when marked as ready.");
return false;
}
var dict = new Dictionary<string, Func<string, bool>>
{
{ "ready",
s =>
{
// if we're downloading, we can't ready up.
if (client.State == Session.ClientState.NotReady)
client.State = Session.ClientState.Ready;
else if (client.State == Session.ClientState.Ready)
client.State = Session.ClientState.NotReady;
Log.Write("server", "Player @{0} is {1}",
conn.socket.RemoteEndPoint, client.State);
Server.SyncLobbyInfo();
if (Server.conns.Count > 0 && Server.conns.All(c => Server.GetClient(c).State == Session.ClientState.Ready))
InterpretCommand(conn, client, "startgame");
return true;
}},
{ "startgame",
s =>
{
Server.StartGame();
return true;
}},
{ "lag",
s =>
{
int lag;
if (!int.TryParse(s, out lag)) { Log.Write("server", "Invalid order lag: {0}", s); return false; }
Log.Write("server", "Order lag is now {0} frames.", lag);
Server.lobbyInfo.GlobalSettings.OrderLatency = lag;
Server.SyncLobbyInfo();
return true;
}},
{ "spectator",
s =>
{
var slotData = Server.lobbyInfo.Slots.Where(ax => ax.Spectator && !Server.lobbyInfo.Clients.Any(l => l.Slot == ax.Index)).FirstOrDefault();
if (slotData == null)
return true;
client.Slot = slotData.Index;
SyncClientToPlayerReference(client, slotData.MapPlayer != null ? Server.Map.Players[slotData.MapPlayer] : null);
Server.SyncLobbyInfo();
return true;
}},
{ "slot",
s =>
{
int slot;
if (!int.TryParse(s, out slot)) { Log.Write("server", "Invalid slot: {0}", s ); return false; }
var slotData = Server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == slot );
if (slotData == null || slotData.Closed || slotData.Bot != null
|| Server.lobbyInfo.Clients.Any( c => c.Slot == slot ))
return false;
client.Slot = slot;
SyncClientToPlayerReference(client, slotData.MapPlayer != null ? Server.Map.Players[slotData.MapPlayer] : null);
Server.SyncLobbyInfo();
return true;
}},
{ "slot_close",
s =>
{
int slot;
if (!int.TryParse(s, out slot)) { Log.Write("server", "Invalid slot: {0}", s ); return false; }
var slotData = Server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == slot );
if (slotData == null)
return false;
if (conn.PlayerIndex != 0)
{
Server.SendChatTo( conn, "Only the host can alter slots" );
return true;
}
slotData.Closed = true;
slotData.Bot = null;
/* kick any player that's in the slot */
var occupant = Server.lobbyInfo.Clients.FirstOrDefault( c => c.Slot == slotData.Index );
if (occupant != null)
{
var occupantConn = Server.conns.FirstOrDefault( c => c.PlayerIndex == occupant.Index );
if (occupantConn != null)
Server.DropClient( occupantConn, new Exception() );
}
Server.SyncLobbyInfo();
return true;
}},
{ "slot_open",
s =>
{
int slot;
if (!int.TryParse(s, out slot)) { Log.Write("server", "Invalid slot: {0}", s ); return false; }
var slotData = Server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == slot );
if (slotData == null)
return false;
if (conn.PlayerIndex != 0)
{
Server.SendChatTo( conn, "Only the host can alter slots" );
return true;
}
slotData.Closed = false;
slotData.Bot = null;
Server.SyncLobbyInfo();
return true;
}},
{ "slot_bot",
s =>
{
var parts = s.Split(' ');
if (parts.Length != 2)
{
Server.SendChatTo( conn, "Malformed slot_bot command" );
return true;
}
int slot;
if (!int.TryParse(parts[0], out slot)) { Log.Write("server", "Invalid slot: {0}", s ); return false; }
var slotData = Server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == slot );
if (slotData == null)
return false;
if (conn.PlayerIndex != 0)
{
Server.SendChatTo( conn, "Only the host can alter slots" );
return true;
}
slotData.Bot = parts[1];
Server.SyncLobbyInfo();
return true;
}},
{ "map",
s =>
{
if (conn.PlayerIndex != 0)
{
Server.SendChatTo( conn, "Only the host can change the map" );
return true;
}
Server.lobbyInfo.GlobalSettings.Map = s;
LoadMap();
foreach(var c in Server.lobbyInfo.Clients)
{
c.SpawnPoint = 0;
var slotData = Server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == c.Slot );
if (slotData != null && slotData.MapPlayer != null)
SyncClientToPlayerReference(c, Server.Map.Players[slotData.MapPlayer]);
c.State = Session.ClientState.NotReady;
}
Server.SyncLobbyInfo();
return true;
}},
{ "lockteams",
s =>
{
if (conn.PlayerIndex != 0)
{
Server.SendChatTo( conn, "Only the host can set that option" );
return true;
}
bool.TryParse(s, out Server.lobbyInfo.GlobalSettings.LockTeams);
Server.SyncLobbyInfo();
return true;
}},
};
var cmdName = cmd.Split(' ').First();
var cmdValue = string.Join(" ", cmd.Split(' ').Skip(1).ToArray());
Func<string,bool> a;
if (!dict.TryGetValue(cmdName, out a))
return false;
return a(cmdValue);
}
public void ServerStarted() { LoadMap(); }
static Session.Slot MakeSlotFromPlayerReference(PlayerReference pr)
{
if (!pr.Playable) return null;
return new Session.Slot
{
MapPlayer = pr.Name,
Bot = null, /* todo: allow the map to specify a bot class? */
Closed = false,
};
}
public static void LoadMap()
{
Server.Map = new Map(Server.ModData.AvailableMaps[Server.lobbyInfo.GlobalSettings.Map]);
Server.lobbyInfo.Slots = Server.Map.Players
.Select(p => MakeSlotFromPlayerReference(p.Value))
.Where(s => s != null)
.Select((s, i) => { s.Index = i; return s; })
.ToList();
// Generate slots for spectators
for (int i = 0; i < MaxSpectators; i++)
Server.lobbyInfo.Slots.Add(new Session.Slot
{
Spectator = true,
Index = Server.lobbyInfo.Slots.Count(),
MapPlayer = null,
Bot = null
});
}
public void ClientJoined(Connection newConn)
{
var defaults = new GameRules.PlayerSettings();
var client = new Session.Client()
{
Index = newConn.PlayerIndex,
Color1 = defaults.Color1,
Color2 = defaults.Color2,
Name = defaults.Name,
Country = "random",
State = Session.ClientState.NotReady,
SpawnPoint = 0,
Team = 0,
Slot = ChooseFreeSlot(),
};
var slotData = Server.lobbyInfo.Slots.FirstOrDefault( x => x.Index == client.Slot );
if (slotData != null)
SyncClientToPlayerReference(client, Server.Map.Players[slotData.MapPlayer]);
Server.lobbyInfo.Clients.Add(client);
Log.Write("server", "Client {0}: Accepted connection from {1}",
newConn.PlayerIndex, newConn.socket.RemoteEndPoint);
Server.SendChat(newConn, "has joined the game.");
Server.SyncLobbyInfo();
}
static int ChooseFreeSlot()
{
return Server.lobbyInfo.Slots.First(s => !s.Closed && s.Bot == null
&& !Server.lobbyInfo.Clients.Any( c => c.Slot == s.Index )).Index;
}
public static void SyncClientToPlayerReference(Session.Client c, PlayerReference pr)
{
if (pr == null)
return;
if (pr.LockColor)
{
c.Color1 = pr.Color;
c.Color2 = pr.Color2;
}
if (pr.LockRace)
c.Country = pr.Race;
}
}
}

View File

@@ -1,91 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Net;
namespace OpenRA.Server.Traits
{
public class MasterServerPinger : ServerTrait, ITick, INotifySyncLobbyInfo, IStartGame
{
const int MasterPingInterval = 60 * 3; // 3 minutes. server has a 5 minute TTL for games, so give ourselves a bit
// of leeway.
public int TickTimeout { get { return MasterPingInterval * 10000; } }
public void Tick()
{
if (Environment.TickCount - lastPing > MasterPingInterval * 1000)
PingMasterServer();
else
lock (masterServerMessages)
while (masterServerMessages.Count > 0)
Server.SendChat(null, masterServerMessages.Dequeue());
}
public void LobbyInfoSynced() { PingMasterServer(); }
public void GameStarted() { PingMasterServer(); }
static int lastPing = 0;
// Todo: use the settings passed to the server instead
static bool isInternetServer = Game.Settings.Server.AdvertiseOnline;
static string masterServerUrl = Game.Settings.Server.MasterServer;
static int externalPort = Game.Settings.Server.ExternalPort;
static bool isInitialPing = true;
static volatile bool isBusy;
static Queue<string> masterServerMessages = new Queue<string>();
public static void PingMasterServer()
{
if (isBusy || !isInternetServer) return;
lastPing = Environment.TickCount;
isBusy = true;
Action a = () =>
{
try
{
var url = "ping.php?port={0}&name={1}&state={2}&players={3}&mods={4}&map={5}";
if (isInitialPing) url += "&new=1";
using (var wc = new WebClient())
{
wc.DownloadData(
masterServerUrl + url.F(
externalPort, Uri.EscapeUriString(Server.Name),
Server.GameStarted ? 2 : 1, // todo: post-game states, etc.
Server.lobbyInfo.Clients.Count,
string.Join(",", Server.lobbyInfo.GlobalSettings.Mods),
Server.lobbyInfo.GlobalSettings.Map));
if (isInitialPing)
{
isInitialPing = false;
lock (masterServerMessages)
masterServerMessages.Enqueue("Master server communication established.");
}
}
}
catch(Exception ex)
{
Log.Write("server", ex.ToString());
lock( masterServerMessages )
masterServerMessages.Enqueue( "Master server communication failed." );
}
isBusy = false;
};
a.BeginInvoke(null, null);
}
}
}

View File

@@ -1,102 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.Network;
namespace OpenRA.Server.Traits
{
public class PlayerCommands : ServerTrait, IInterpretCommand
{
public bool InterpretCommand(Connection conn, Session.Client client, string cmd)
{
if (Server.GameStarted)
{
Server.SendChatTo(conn, "Cannot change state when game started. ({0})".F(cmd));
return false;
}
else if (client.State == Session.ClientState.Ready && !(cmd == "ready" || cmd == "startgame"))
{
Server.SendChatTo(conn, "Cannot change state when marked as ready.");
return false;
}
var dict = new Dictionary<string, Func<string, bool>>
{
{ "name",
s =>
{
Log.Write("server", "Player@{0} is now known as {1}", conn.socket.RemoteEndPoint, s);
client.Name = s;
Server.SyncLobbyInfo();
return true;
}},
{ "race",
s =>
{
client.Country = s;
Server.SyncLobbyInfo();
return true;
}},
{ "team",
s =>
{
int team;
if (!int.TryParse(s, out team)) { Log.Write("server", "Invalid team: {0}", s ); return false; }
client.Team = team;
Server.SyncLobbyInfo();
return true;
}},
{ "spawn",
s =>
{
int spawnPoint;
if (!int.TryParse(s, out spawnPoint) || spawnPoint < 0 || spawnPoint > 8) //TODO: SET properly!
{
Log.Write("server", "Invalid spawn point: {0}", s);
return false;
}
if (Server.lobbyInfo.Clients.Where( c => c != client ).Any( c => (c.SpawnPoint == spawnPoint) && (c.SpawnPoint != 0) ))
{
Server.SendChatTo( conn, "You can't be at the same spawn point as another player" );
return true;
}
client.SpawnPoint = spawnPoint;
Server.SyncLobbyInfo();
return true;
}},
{ "color",
s =>
{
var c = s.Split(',').Select(cc => int.Parse(cc)).ToArray();
client.Color1 = Color.FromArgb(c[0],c[1],c[2]);
client.Color2 = Color.FromArgb(c[3],c[4],c[5]);
Server.SyncLobbyInfo();
return true;
}}
};
var cmdName = cmd.Split(' ').First();
var cmdValue = string.Join(" ", cmd.Split(' ').Skip(1).ToArray());
Func<string,bool> a;
if (!dict.TryGetValue(cmdName, out a))
return false;
return a(cmdValue);
}
}
}