Created
June 13, 2015 22:42
-
-
Save AmazingTurtle/a5ffde7951418b66e34d to your computer and use it in GitHub Desktop.
Server snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using TWRC.Network; | |
using TWRC.Network.Handler; | |
using Dapper; | |
namespace TWRC.Game.Network.Handler | |
{ | |
public class JoinServer : HandlerBase<Client.VirtualClient> | |
{ | |
private void SendLobbyResponse(Client.VirtualClient sender) | |
{ | |
// send join server response | |
sender.Send(new Packet.JoinServer( | |
sender.Data.SessionId, | |
sender.Data.Account.Id, | |
sender.Data.Account.Nickname, | |
sender.Data.Details.Experience, | |
sender.Data.Details.Dinar, | |
sender.Data.Details.Kills, | |
sender.Data.Details.Deaths, | |
sender.Data.Inventory.SlotCode, | |
new string[] { | |
sender.Data.Inventory.Equipment[0].ToString(), | |
sender.Data.Inventory.Equipment[1].ToString(), | |
sender.Data.Inventory.Equipment[2].ToString(), | |
sender.Data.Inventory.Equipment[3].ToString(), | |
sender.Data.Inventory.Equipment[4].ToString() | |
}, | |
new string[] { | |
sender.Data.Inventory.Character[0].ToString(), | |
sender.Data.Inventory.Character[1].ToString(), | |
sender.Data.Inventory.Character[2].ToString(), | |
sender.Data.Inventory.Character[3].ToString(), | |
sender.Data.Inventory.Character[4].ToString() | |
}, | |
sender.Data.Inventory.GetInventory(), | |
sender.Data.Inventory.EquipmentLimit, | |
sender.Data.Inventory.GetInventory(true), | |
sender.Data.Details.Premium | |
)); | |
// send motd | |
foreach(string motdLine in QA.Motd) | |
sender.Send(Network.Packet.Chat.System(motdLine)); | |
// todo: event, gift, ... | |
} | |
public override async Task<Result> Handle(Client.VirtualClient sender, TWRC.Network.Packet.InPacket packet, bool customHandle = false) | |
{ | |
await base.Handle(sender, packet, customHandle); | |
uint userId; | |
string username; | |
string nickname; | |
uint token; | |
if(base.RequireLength(17) && | |
base.RequireExact(0, "1") && | |
base.RequireExact(8, "-1") && | |
base.RequireExact(9, "-1") && | |
base.RequireExact(10, "-1") && | |
base.RequireExact(11, "INVALID") && | |
base.RequireExact(12, "-1") && | |
base.RequireExact(13, "-1") && | |
base.RequireExact(14, "0") && | |
base.RequireExact(16, "dnjfhr^") && | |
base.RequireValue(1, out userId) && | |
base.TakeValue(3, out username) && | |
base.TakeValue(4, out nickname) && | |
base.RequireValue(15, out token)) | |
{ | |
if(!sender.HasState(Core.Enum.ConnectionState.HasSerial)) | |
return new Result("ConnectionState.HasSerial flag required"); | |
if(sender.HasState(Core.Enum.ConnectionState.HasJoined)) | |
return new Result("ConnectionState.HasJoined flag already set"); | |
// fetch required data from databases | |
Core.DBC.Result.PlayerQuery queryResult; | |
Core.DBC.Result.Items items; | |
Core.DBC.Result.PlayerEquipment playerEquipment; | |
Core.DBC.Data.Outbox[] outboxItems; | |
using(Core.DBC.IDatabaseConnection databaseGame = await Program.Instance.DBCGame.GetConnection()) | |
using(Core.DBC.IDatabaseConnection database = await Program.Instance.DBC.GetConnection()) | |
{ | |
queryResult = await Program.Instance.DBCGame.PlayerQuery(new { id = userId, username = username, nickname = nickname }, database, databaseGame); | |
items = await Program.Instance.DBCGame.GetItems(userId, databaseGame); | |
playerEquipment = await Program.Instance.DBCGame.GetEquipment(userId, databaseGame); | |
outboxItems = await Program.Instance.DBCGame.GetOutboxItems(userId, databaseGame); | |
} | |
// several integrity checks | |
if (!queryResult.Success) | |
return new Result("Account not identified by id, username and nickname (#{0}, {1}, {2})".Process(userId, username, nickname)); | |
else if (!queryResult.Account.Token.HasValue) | |
return new Result("Token mismatch (no token set)"); | |
else if (queryResult.Account.Token != token) | |
return new Result("Token mismatch ({0} requested, {1} given)".Process(token, queryResult.Account.Token)); | |
// initialize data, inventory and session id | |
sender.Data.JoinServer( | |
queryResult.Account, | |
queryResult.Details, | |
items.Equipment, | |
items.Character, | |
outboxItems, | |
playerEquipment, | |
QA.Resolve<Modules.Session>().Assign(sender) | |
); | |
// set state and send response | |
sender.SetState(Core.Enum.ConnectionState.HasJoined); | |
SendLobbyResponse(sender); | |
return Result.Success; | |
} | |
return Result.Default; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using Dapper; | |
using System.Linq; | |
using TWRC.Core.DBC; | |
using System.Net; | |
namespace TWRC.Game | |
{ | |
public class Program : TWRC.AppCore.Program | |
{ | |
#region Main | |
/// <summary> | |
/// Program entry point, called on startup | |
/// </summary> | |
/// <param name="args">Arguments passed to process as start info</param> | |
public static void Main(string[] args) | |
{ | |
TWRC.AppCore.Program.MainStub<Program>(args, () => { return new Program(); }); | |
} | |
/// <summary> | |
/// Application constructor | |
/// </summary> | |
private Program() | |
: base() | |
{ | |
Program.Instance = this; | |
Program.LogChat = log4net.LogManager.GetLogger("ChatFileAppender"); | |
// gama database interface <-- profesional | |
{ | |
Core.Configuration.DBC.Config dbconfig = base.ReadConfiguration<Core.Configuration.DBC.Config>(Core.Project.FileNames["File.GameDatabaseConfig"]); | |
int dbcIndex = base.RequestDbc<Core.DBC.Specific.IGame>(dbconfig); | |
this.DBCGame = (Core.DBC.Specific.IGame)base._privateDbcs[dbcIndex]; | |
} | |
// console, general | |
Console.Title = (string)Core.Project.Vars["Game.Title"]; | |
string configFilename = Core.Project.FileNames["File.GameConfig"]; | |
Log.DebugFormat("Reading configuration file '{0}' for Program".Process(configFilename)); | |
this.Config = Core.ConfigurationReader.Deserialize<Core.Configuration.Game.Config>(configFilename); | |
this.ModuleContainer.DependencyResolve += DependencyResolve; | |
// server instance | |
var localEp = new IPEndPoint( | |
IPAddress.Parse(this.Config.Server.Host), | |
this.Config.Server.Port); | |
this.Server = new AppCore.WRProtoServer<Client.VirtualClient>( | |
localEp, | |
this.Config.Server.Buffer.ClientLimit, | |
this.Config.Server.Buffer.BufferSize, | |
new Network.CryptoImpl()); | |
this.Server.LowerServer.OnClientDisconnected += OnClientDisconnected; | |
this.UdpServer = new Network.UDP(); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.C_SERIAL_GSERV, new Network.Handler.Serial()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.JOIN_SERV, new Network.Handler.JoinServer()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.SET_CHANNEL, new Network.Handler.SetChannel()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.ROOM_LIST, new Network.Handler.RoomList()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.CHAT, new Network.Handler.Chat()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.NCASH_PROCESS, new Network.Handler.CashProcess()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.ITEM_PROCESS, new Network.Handler.ItemProcess()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.ITEM_DESTROY, new Network.Handler.ItemDestroy()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.BITEM_CHANGE, new Network.Handler.ItemChange()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.CSHOP_DEPOT, new Network.Handler.CashShopDepot()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.CREATE_ROOM, new Network.Handler.CreateRoom()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.EXIT_ROOM, new Network.Handler.ExitRoom()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.JOIN_ROOM, new Network.Handler.JoinRoom()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.GAME_PROCESS, new Network.Handler.GameProcess()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.GAME_SCORE, new Network.Handler.GameScore()); | |
this.Server.Manager.AddHandler((int)TWRC.Network.PacketCodes.BOMB_PROCESS, new Network.Handler.BombProcess()); | |
ApplyNetworkLogging(this.Config.Server.Log); | |
if (!this.Config.Server.Log) | |
Log.DebugFormat("Network logging disabled"); | |
} | |
#endregion | |
#region Members | |
public static Program Instance { get; private set; } | |
public readonly Core.Configuration.Game.Config Config; | |
public static log4net.ILog LogChat { get; set; } | |
public readonly AppCore.WRProtoServer<Client.VirtualClient> Server; | |
public readonly Network.UDP UdpServer; | |
public Core.DBC.Specific.IGame DBCGame { get; private set; } | |
#endregion | |
#region Functions | |
/// <summary> | |
/// Load the item activator and add event handlers | |
/// </summary> | |
private void initActivationManager() | |
{ | |
Log.Debug("init: activation manager"); | |
var manager = QA.Resolve<Activator.Manager>(); | |
manager.OnGivePremium += activationManager_OnGivePremium; | |
manager.OnGiveItem += activationManager_OnGiveItem; | |
} | |
/// <summary> | |
/// Initialize the lobby and add event handlers | |
/// </summary> | |
private void initLobby() | |
{ | |
Log.Debug("init: lobby"); | |
var lobby = QA.Resolve<Modules.Lobby>(); | |
foreach(var channel in lobby.Channels) | |
{ | |
channel.OnRoomCreated += channel_OnRoomCreated; | |
channel.OnRoomDeleted += channel_OnRoomDeleted; | |
} | |
} | |
/// <summary> | |
/// Starts the server and all components | |
/// </summary> | |
protected override void Run() | |
{ | |
this.initActivationManager(); | |
this.initLobby(); | |
// load data/* files | |
QA.Resolve<Modules.Game>(); | |
Program.Log.DebugFormat("Loading shop information"); | |
QA.Resolve<Modules.Shop>(); | |
Program.Log.DebugFormat("Loading game/lobby/gamemode"); | |
QA.Resolve<Modules.Game>(); | |
QA.Resolve<Modules.Lobby>(); | |
QA.Resolve<Modules.GameMode>().Run(); | |
Program.Log.DebugFormat("Starting MMC"); | |
QA.Resolve<Modules.MMC.MMC>().Start(); | |
Program.Log.DebugFormat("Starting game and UDP server"); | |
// read configuration | |
this.Server.Start(); | |
this.UdpServer.Start(); | |
Log.InfoFormat("Server is running"); | |
/*for(int i = 0; i < 4; i++) | |
{ | |
int flowMode = 0; | |
Lobby.Room eventRoom = gameLobby[(int)Core.Enum.Channel.CQC].AddRoom(Core.Enum.Game.Type.Event, new Lobby.RoomInformation() { Name = "(event) Flow: {0}".Process(flowMode), MapId = game.Maps.GetID("Marien"), SuperHostType = flowMode }); | |
Lobby.Room normalRoom = gameLobby[(int)Core.Enum.Channel.CQC].AddRoom(Core.Enum.Game.Type.Normal, new Lobby.RoomInformation() { Name = "(normal) Flow: {0}".Process(flowMode), MapId = game.Maps.GetID("Marien"), SuperHostType = flowMode }); | |
Lobby.Room knifeRoom = gameLobby[(int)Core.Enum.Channel.CQC].AddRoom(Core.Enum.Game.Type.Knife, new Lobby.RoomInformation() { Name = "(knife) Flow: {0}".Process(flowMode), MapId = game.Maps.GetID("Marien"), SuperHostType = flowMode }); | |
}*/ | |
} | |
/// <summary> | |
/// Send the RoomInfoChange packet to everyone who deserves it :) | |
/// </summary> | |
private void lobbyUpdateRoomInfo(Lobby.Room room, Core.Enum.RoomInfoChangeAction action) | |
{ | |
var targets = QA.FindAllClients(x => x.Data.Lobby.Room == null && !x.HasState(Core.Enum.ConnectionState.JoiningRoom)); | |
var updatePacket = new Network.Packet.RoomInfoChange(room, action); | |
foreach (var player in targets) | |
{ | |
if (player.Data.Lobby.WaitingRoom || (player.Data.Lobby.LobbyStartIndex >= room.Id && player.Data.Lobby.LobbyStartIndex < room.Id + 15)) | |
player.Send(updatePacket); | |
} | |
} | |
#endregion | |
#region Event Handler | |
/// <summary> | |
/// Event handler for the game servers OnClientDisconnected event | |
/// </summary> | |
/// <param name="sender"></param> | |
/// <param name="e"></param> | |
private async void OnClientDisconnected(object sender, AsyncTCPLib.OnClientDisconnectedEventArgs<Client.VirtualClient> e) | |
{ | |
if (e.Client.HasState(Core.Enum.ConnectionState.HasJoined)) | |
{ | |
QA.Resolve<Modules.Session>().Remove(e.Client); | |
e.Client.Data.Lobby.ExitRoom(true); | |
await e.Client.Exit(); | |
} | |
} | |
/// <summary> | |
/// Weired guess of resolving dependencies for dependency injection design pattern... | |
/// </summary> | |
private void DependencyResolve(object sender, AppCore.Module.DependencyResolveEventArgs e) | |
{ | |
Program.Log.FatalFormat("Can't resolve dependency: {0}", e.Dependency.FullName); | |
} | |
/// <summary> | |
/// Event handler for Activation.Manager modules OnGivePremium event | |
/// </summary> | |
private void activationManager_OnGivePremium(object sender, Activator.GivePremiumEventArgs e) | |
{ | |
var client = (Client.VirtualClient)e.Player; | |
if (client.Data.Details.Premium < e.Premium) | |
client.Data.Details.Premium = e.Premium; | |
client.Data.Details.PremiumDuration += e.Duration; | |
} | |
/// <summary> | |
/// Event handler for Activation.Manager modules OnGiveItem event | |
/// </summary> | |
private void activationManager_OnGiveItem(object sender, Activator.GiveItemEventArgs e) | |
{ | |
var client = (Client.VirtualClient)e.Player; | |
bool isCharacter = e.ItemCode[0] == 'B'; | |
// extend existing item, or create new one | |
var existingItem = client.Data.Inventory.GetExistingItem(e.ItemCode); | |
if (existingItem != null) | |
{ | |
existingItem.Duration += e.Duration; | |
DBCGame.UpdateItem(existingItem, isCharacter); | |
} | |
else | |
{ | |
var item = new Core.DBC.Data.Item() { Code = e.ItemCode, Duration = e.Duration, BuyTime = DateTime.Now, UserId = client.Data.Account.Id }; | |
DBCGame.CreateItem(item, isCharacter); | |
client.Data.Inventory.AddItem(item); | |
} | |
} | |
/// <summary> | |
/// Event handler for lobby modules OnRoomDeleted event | |
/// </summary> | |
private void channel_OnRoomDeleted(object sender, Lobby.RoomEventArgs e) | |
{ | |
var targets = QA.FindAllClients(x => x.Data.Lobby.Room == null && !x.HasState(Core.Enum.ConnectionState.JoiningRoom)); | |
var updatePacket = new Network.Packet.RoomInfoChange(e.Room, Core.Enum.RoomInfoChangeAction.Deleted); | |
foreach (var player in targets) | |
{ | |
if (player.Data.Lobby.WaitingRoom || (player.Data.Lobby.LobbyStartIndex >= e.Room.Id && player.Data.Lobby.LobbyStartIndex < e.Room.Id + 15)) | |
player.Send(updatePacket); | |
} | |
} | |
/// <summary> | |
/// Event handler for lobby modules OnRoomCreated event | |
/// </summary> | |
private void channel_OnRoomCreated(object sender, Lobby.RoomEventArgs e) | |
{ | |
e.Room.Events.OnPlayerJoined += room_OnPlayerJoined; | |
e.Room.Events.OnPlayerLeft += room_OnPlayerLeft; | |
e.Room.Events.OnUpdated += room_OnUpdated; | |
e.Room.Events.OnSettingsChanged += room_OnSettingsChanged; | |
//e.Room.Events.RaiseOnUpdated(); | |
this.lobbyUpdateRoomInfo(e.Room, Core.Enum.RoomInfoChangeAction.Created); | |
} | |
/// <summary> | |
/// Event handler for room event managers OnUpdated event | |
/// </summary> | |
private void room_OnUpdated(object sender, EventArgs e) | |
{ | |
var eventManager = sender as Lobby.EventManager; | |
var room = eventManager.Owner; | |
this.lobbyUpdateRoomInfo(room, Core.Enum.RoomInfoChangeAction.Updated); | |
} | |
/// <summary> | |
/// Event handler for room event managers OnSettingsChanged event | |
/// </summary> | |
private void room_OnSettingsChanged(object sender, EventArgs e) | |
{ | |
var eventManager = sender as Lobby.EventManager; | |
var room = eventManager.Owner; | |
room.GameMode.Impl.OnSettingsChanged(); | |
} | |
/// <summary> | |
/// Event handler for room event managers OnPlayerLeft event | |
/// </summary> | |
private void room_OnPlayerLeft(object sender, Lobby.PlayerEventArgs e) | |
{ | |
var eventManager = sender as Lobby.EventManager; | |
var room = eventManager.Owner; | |
room.GameMode.Impl.OnPlayerLeft(e.Client, e.Index); | |
if (room.Players.Count() == 0) | |
{ | |
var lobby = QA.Resolve<Modules.Lobby>(); | |
var channel = lobby.Channels[(int)room.Channel]; | |
channel.RemoveRoom(room); | |
Program.Log.DebugFormat("Removed room {0}, no players left", room.Id); | |
} | |
else | |
room.Events.RaiseOnUpdated(); | |
} | |
/// <summary> | |
/// Event handler for room event managers OnPlayerJoined event | |
/// </summary> | |
private void room_OnPlayerJoined(object sender, Lobby.PlayerEventArgs e) | |
{ | |
var eventManager = sender as Lobby.EventManager; | |
var room = eventManager.Owner; | |
Program.Log.DebugFormat("Player {0} joined room {1}", e.Client.Data.Account.Nickname, room.Id); | |
room.Events.RaiseOnUpdated(); | |
} | |
#endregion | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace TWRC.WRGame | |
{ | |
public class Packer | |
{ | |
protected static Dictionary<Core.Enum.Game.Mode, string> GameModeTranslator { get; private set; } | |
protected static Dictionary<string, Core.Enum.Premium> PremiumTranslator { get; private set; } | |
public System.Xml.XmlDocument Document { get; private set; } | |
protected Dictionary<int, string> MapList { get; private set; } | |
static Packer() | |
{ | |
Packer.GameModeTranslator = new Dictionary<Core.Enum.Game.Mode, string>(); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.Explosive, "Explosive"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.FreeForAll, "FFA"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.FourVsFour, "DeathMatch"); // requires CQC | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.Deathmatch, "DeathMatch|DeathMatchLarge"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.Conquest, "Conquest"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.ExplosiveBG, "LargeMission"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.HeroMode, "SmallHero"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.TotalWar, "TotalWar"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.Survive, "Survival"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.Defence, "Defence"); | |
Packer.GameModeTranslator.Add(Core.Enum.Game.Mode.Escape, "Infection"); | |
Packer.PremiumTranslator = new Dictionary<string, Core.Enum.Premium>(); | |
Packer.PremiumTranslator.Add("Free", Core.Enum.Premium.None); | |
Packer.PremiumTranslator.Add("Bronze", Core.Enum.Premium.Bronze); | |
Packer.PremiumTranslator.Add("Silver", Core.Enum.Premium.Silver); | |
Packer.PremiumTranslator.Add("Gold", Core.Enum.Premium.Gold); | |
Packer.PremiumTranslator.Add("Platinum", Core.Enum.Premium.Platin); //not sure | |
} | |
public Packer() | |
{ | |
this.Document = new System.Xml.XmlDocument(); | |
this.Document.LoadXml("<MapDetails></MapDetails>"); | |
this.MapList = new Dictionary<int, string>(); | |
} | |
/// <summary> | |
/// Use this to automatically skip disabled maps | |
/// </summary> | |
/// <param name="MapFolder">Folder containg MapList.xml and Map Folders</param> | |
public bool ProcessMapsFolder(string MapFolder) | |
{ | |
string MapListFile = System.IO.Path.Combine(MapFolder, "MapList.xml"); | |
if (!System.IO.File.Exists(MapListFile)) | |
return false; | |
System.Xml.XmlDocument MapListDocument = new System.Xml.XmlDocument(); | |
MapListDocument.Load(MapListFile); | |
foreach (string iFolder in System.IO.Directory.GetDirectories(MapFolder)) | |
{ | |
int mapReturnCode = this.DoMap(iFolder); | |
if (mapReturnCode == 1 || mapReturnCode == -1) | |
continue; | |
else if (mapReturnCode == -2) | |
return false; | |
} | |
return true; | |
} | |
public int DoMap(string MapFolder) | |
{ | |
string MapInfoFile = System.IO.Path.Combine(MapFolder, "MapInfo.xml"); | |
string ControlPointTemplateFile = System.IO.Path.Combine(MapFolder, "ControlPointTemplate.dat"); | |
string StaticObjectFile = System.IO.Path.Combine(MapFolder, "StaticObject.dat"); | |
string ObjectSpawnTemplateFile = System.IO.Path.Combine(MapFolder, "ObjectSpawnTemplate.dat"); | |
if (!System.IO.File.Exists(MapInfoFile) || | |
!System.IO.File.Exists(ControlPointTemplateFile) || | |
!System.IO.File.Exists(StaticObjectFile)) | |
return -1; | |
System.Xml.XmlDocument iMapInfo = new System.Xml.XmlDocument(); | |
iMapInfo.Load(MapInfoFile); | |
System.Xml.XmlNode nMap = this.Document.CreateElement("Map"); | |
// Head | |
{ | |
System.Xml.XmlAttribute aMapID = this.Document.CreateAttribute("ID"); | |
aMapID.Value = iMapInfo["MapInfo"]["Identity"].Attributes["ID"].Value; | |
nMap.Attributes.Append(aMapID); | |
System.Xml.XmlAttribute aMapName = this.Document.CreateAttribute("Name"); | |
aMapName.Value = iMapInfo["MapInfo"]["Display"].Attributes["DisplayName"].Value; | |
nMap.Attributes.Append(aMapName); | |
int iMapID = int.Parse(aMapID.Value); | |
if (this.MapList.ContainsKey(iMapID)) | |
{ | |
Console.WriteLine("Map exists [" + iMapID.ToString() + ";" + aMapName.Value + "]: " + this.MapList[iMapID]); | |
return -2; | |
} | |
else | |
this.MapList.Add(int.Parse(aMapID.Value), aMapName.Value); | |
System.Xml.XmlNode nMapHead = this.Document.CreateElement("Head"); | |
System.Xml.XmlNode nMapHeadChannel = this.Document.CreateElement("Channel"); | |
System.Xml.XmlAttribute aMapHeadChannelCQC = this.Document.CreateAttribute("CQC"); | |
bool allowsCQC = (iMapInfo["MapInfo"]["Channel"].Attributes["Mission"].Value.ToLower()[0] == 't' ? true : false); | |
aMapHeadChannelCQC.Value = allowsCQC.ToString().ToLower(); | |
nMapHeadChannel.Attributes.Append(aMapHeadChannelCQC); | |
System.Xml.XmlAttribute aMapHeadChannelBG = this.Document.CreateAttribute("BG"); | |
aMapHeadChannelBG.Value = (iMapInfo["MapInfo"]["Channel"].Attributes["Large"].Value.ToLower()[0] == 't' ? "true" : "false"); | |
nMapHeadChannel.Attributes.Append(aMapHeadChannelBG); | |
// v -> complicated shit. | |
System.Xml.XmlAttribute aMapHeadChannelAI = this.Document.CreateAttribute("AI"); | |
aMapHeadChannelAI.Value = (iMapInfo["MapInfo"]["Channel"].Attributes["AI"] != null && iMapInfo["MapInfo"]["Channel"].Attributes["AI"].Value.ToLower()[0] == 't' ? "true" : "false"); | |
nMapHeadChannel.Attributes.Append(aMapHeadChannelAI); | |
nMapHead.AppendChild(nMapHeadChannel); | |
System.Xml.XmlNode nMapHeadGameMode = this.Document.CreateElement("GameMode"); | |
foreach (Core.Enum.Game.Mode iGameMode in Enum.GetValues(typeof(Core.Enum.Game.Mode))) | |
{ | |
System.Xml.XmlNode nMapHeadGameMode_ModeNode = this.Document.CreateElement("Mode"); | |
System.Xml.XmlAttribute nMapHeadGameMode_ModeNode_Type = this.Document.CreateAttribute("Name"); | |
nMapHeadGameMode_ModeNode_Type.Value = iGameMode.ToString(); | |
nMapHeadGameMode_ModeNode.Attributes.Append(nMapHeadGameMode_ModeNode_Type); | |
System.Xml.XmlAttribute nMapHeadGameMode_ModeNode_Allowed = this.Document.CreateAttribute("Allowed"); | |
nMapHeadGameMode_ModeNode_Allowed.Value = "false"; | |
if (iGameMode == Core.Enum.Game.Mode.FourVsFour) | |
{ | |
if (allowsCQC && | |
iMapInfo["MapInfo"]["Icon"] != null && | |
iMapInfo["MapInfo"]["Icon"].Attributes["b4vs4"].Value.ToLower() == "true" && | |
iMapInfo["MapInfo"]["GameMode"][GameModeTranslator[Core.Enum.Game.Mode.FourVsFour]] != null && | |
iMapInfo["MapInfo"]["GameMode"][GameModeTranslator[Core.Enum.Game.Mode.FourVsFour]].Attributes["Support"].Value.ToLower() == "true") | |
nMapHeadGameMode_ModeNode_Allowed.Value = "true"; | |
} | |
else if (iGameMode == Core.Enum.Game.Mode.FreeForAll) | |
{ | |
if (iMapInfo["MapInfo"]["GameMode"][GameModeTranslator[Core.Enum.Game.Mode.FreeForAll]] != null && | |
int.Parse(iMapInfo["MapInfo"]["GameMode"][GameModeTranslator[Core.Enum.Game.Mode.FreeForAll]].Attributes["Scale"].Value) > 0) | |
nMapHeadGameMode_ModeNode_Allowed.Value = "true"; | |
} | |
else | |
{ | |
bool oneAllowed = false; | |
foreach (string aGameMode in GameModeTranslator[iGameMode].Split('|')) | |
{ | |
if (iMapInfo["MapInfo"]["GameMode"][aGameMode] != null && | |
iMapInfo["MapInfo"]["GameMode"][aGameMode].Attributes["Support"].Value.ToLower() == "true") | |
{ | |
oneAllowed = true; | |
break; | |
} | |
} | |
if(oneAllowed) | |
nMapHeadGameMode_ModeNode_Allowed.Value = "true"; | |
} | |
nMapHeadGameMode_ModeNode.Attributes.Append(nMapHeadGameMode_ModeNode_Allowed); | |
nMapHeadGameMode.AppendChild(nMapHeadGameMode_ModeNode); | |
} | |
nMapHead.AppendChild(nMapHeadGameMode); | |
Core.Enum.Premium premiumRestriction = PremiumTranslator[iMapInfo["MapInfo"]["Restriction"].Attributes["PayType"].Value]; | |
System.Xml.XmlNode nMapHeadPremium = this.Document.CreateElement("Premium"); | |
System.Xml.XmlAttribute nMapHeadPremiumType = this.Document.CreateAttribute("Type"); | |
nMapHeadPremiumType.Value = premiumRestriction.ToString(); | |
nMapHeadPremium.Attributes.Append(nMapHeadPremiumType); | |
nMapHead.AppendChild(nMapHeadPremium); | |
System.Xml.XmlNode nMapHeadSpecial = this.Document.CreateElement("Special"); | |
System.Xml.XmlAttribute nMapHeadSpecialNew = this.Document.CreateAttribute("New"); | |
nMapHeadSpecialNew.Value = ((iMapInfo["MapInfo"]["Icon"] != null && iMapInfo["MapInfo"]["Icon"].Attributes["New"].Value.ToLower()[0] == 't') ? "true" : "false"); | |
nMapHeadSpecial.Attributes.Append(nMapHeadSpecialNew); | |
System.Xml.XmlAttribute nMapHeadSpecialEvent = this.Document.CreateAttribute("Event"); | |
nMapHeadSpecialEvent.Value = ((iMapInfo["MapInfo"]["Icon"] != null && iMapInfo["MapInfo"]["Icon"].Attributes["Event"].Value.ToLower()[0] == 't') ? "true" : "false"); | |
nMapHeadSpecial.Attributes.Append(nMapHeadSpecialEvent); | |
System.Xml.XmlAttribute nMapHeadSpecialExperience = this.Document.CreateAttribute("Experience"); | |
double experienceMultiplicator = 1.0; | |
if (iMapInfo["MapInfo"]["Icon"] != null && iMapInfo["MapInfo"]["Icon"].Attributes["Exp5Up"].Value.ToLower()[0] == 't') experienceMultiplicator += .05; | |
if (iMapInfo["MapInfo"]["Icon"] != null && iMapInfo["MapInfo"]["Icon"].Attributes["Exp10Up"].Value.ToLower()[0] == 't') experienceMultiplicator += .10; | |
nMapHeadSpecialExperience.Value = experienceMultiplicator.ToString(); | |
nMapHeadSpecial.Attributes.Append(nMapHeadSpecialExperience); | |
nMapHead.AppendChild(nMapHeadSpecial); | |
nMap.AppendChild(nMapHead); | |
} | |
// Object | |
{ | |
System.Xml.XmlNode nMapObject = this.Document.CreateElement("Object"); | |
string strControlPointTemplate = System.IO.File.ReadAllText(ControlPointTemplateFile); | |
string strStaticObject = System.IO.File.ReadAllText(StaticObjectFile); | |
foreach (System.Text.RegularExpressions.Match iMatch in System.Text.RegularExpressions.Regex.Matches(strControlPointTemplate, | |
@"ControlPoint.Name\s+?(?<controlName>[a-zA-Z0-9_\-]+?).*?ControlPoint.Team\s+?(?<controlTeam>(0|1|-1)).*?ControlPoint.Position\s+?(?<controlPositionX>-?[0-9]+?)\.[0-9]+?/(?<controlPositionY>-?[0-9]+?)\.[0-9]+?/(?<controlPositionZ>-?[0-9]+?)\.[0-9]+?", | |
System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.CultureInvariant)) | |
{ | |
System.Xml.XmlNode nMapObjectFlag = this.Document.CreateElement("Flag"); | |
System.Xml.XmlAttribute nMapObjectFlagX = this.Document.CreateAttribute("X"), | |
nMapObjectFlagY = this.Document.CreateAttribute("Y"), | |
nMapObjectFlagZ = this.Document.CreateAttribute("Z"); | |
nMapObjectFlagX.Value = iMatch.Groups["controlPositionX"].Value; | |
nMapObjectFlagY.Value = iMatch.Groups["controlPositionY"].Value; | |
nMapObjectFlagZ.Value = iMatch.Groups["controlPositionZ"].Value; | |
nMapObjectFlag.Attributes.Append(nMapObjectFlagX); | |
nMapObjectFlag.Attributes.Append(nMapObjectFlagY); | |
nMapObjectFlag.Attributes.Append(nMapObjectFlagZ); | |
System.Xml.XmlAttribute nMapObjectFlagTeam = this.Document.CreateAttribute("Team"); | |
Core.Enum.Team aTeam = Core.Enum.Team.None; | |
iMatch.Groups["controlTeam"].Value.CastEnum(out aTeam); | |
nMapObjectFlagTeam.Value = aTeam.ToString(); | |
nMapObjectFlag.Attributes.Append(nMapObjectFlagTeam); | |
nMapObject.AppendChild(nMapObjectFlag); | |
} | |
foreach (System.Text.RegularExpressions.Match iMatch in System.Text.RegularExpressions.Regex.Matches(strStaticObject, | |
@"StandardMesh.Name\s+?bomb.*?StandardMesh.Position\s+?(?<controlPositionX>-?[0-9]+?)\.[0-9]+?/(?<controlPositionY>-?[0-9]+?)\.[0-9]+?/(?<controlPositionZ>-?[0-9]+?)\.[0-9]+?", | |
System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.CultureInvariant)) | |
{ | |
System.Xml.XmlNode nMapObjectBomb = this.Document.CreateElement("Bomb"); | |
System.Xml.XmlAttribute nMapObjectBombX = this.Document.CreateAttribute("X"), | |
nMapObjectBombY = this.Document.CreateAttribute("Y"), | |
nMapObjectBombZ = this.Document.CreateAttribute("Z"); | |
nMapObjectBombX.Value = iMatch.Groups["controlPositionX"].Value; | |
nMapObjectBombY.Value = iMatch.Groups["controlPositionY"].Value; | |
nMapObjectBombZ.Value = iMatch.Groups["controlPositionZ"].Value; | |
nMapObjectBomb.Attributes.Append(nMapObjectBombX); | |
nMapObjectBomb.Attributes.Append(nMapObjectBombY); | |
nMapObjectBomb.Attributes.Append(nMapObjectBombZ); | |
nMapObject.AppendChild(nMapObjectBomb); | |
} | |
if (System.IO.File.Exists(ObjectSpawnTemplateFile)) | |
{ | |
string strObjectSpawnTemplate = System.IO.File.ReadAllText(ObjectSpawnTemplateFile); | |
foreach (System.Text.RegularExpressions.Match iMatch in System.Text.RegularExpressions.Regex.Matches(strObjectSpawnTemplate, | |
@"ObjectSpawn.Target\s+(?<objectName>[a-zA-Z0-9_-]+).*?ObjectSpawn.Position\s+?(?<controlPositionX>-?[0-9]+?)\.[0-9]+?/(?<controlPositionY>-?[0-9]+?)\.[0-9]+?/(?<controlPositionZ>-?[0-9]+?)\.[0-9]+?.*?ObjectSpawn.Code\s+?(?<objectCode>[a-zA-Z0-9]{4}).*?ObjectSpawn.SpawnInterval\s+?(?<objectSpawn>[0-9]+)", | |
System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.CultureInvariant)) | |
{ | |
System.Xml.XmlNode nMapObjectEntity = this.Document.CreateElement("Entity"); | |
System.Xml.XmlAttribute nMapObjectEntityX = this.Document.CreateAttribute("X"), | |
nMapObjectEntityY = this.Document.CreateAttribute("Y"), | |
nMapObjectEntityZ = this.Document.CreateAttribute("Z"); | |
nMapObjectEntityX.Value = iMatch.Groups["controlPositionX"].Value; | |
nMapObjectEntityY.Value = iMatch.Groups["controlPositionY"].Value; | |
nMapObjectEntityZ.Value = iMatch.Groups["controlPositionZ"].Value; | |
nMapObjectEntity.Attributes.Append(nMapObjectEntityX); | |
nMapObjectEntity.Attributes.Append(nMapObjectEntityY); | |
nMapObjectEntity.Attributes.Append(nMapObjectEntityZ); | |
System.Xml.XmlAttribute nMapObjectEntityCode = this.Document.CreateAttribute("Code"), | |
nMapObjectEntityTarget = this.Document.CreateAttribute("Target"), | |
nMapObjectEntitySpawnInterval = this.Document.CreateAttribute("SpawnInterval"); | |
nMapObjectEntityCode.Value = iMatch.Groups["objectCode"].Value; | |
nMapObjectEntityTarget.Value = iMatch.Groups["objectName"].Value; | |
nMapObjectEntitySpawnInterval.Value = iMatch.Groups["objectSpawn"].Value; | |
nMapObjectEntity.Attributes.Append(nMapObjectEntityCode); | |
nMapObjectEntity.Attributes.Append(nMapObjectEntityTarget); | |
nMapObjectEntity.Attributes.Append(nMapObjectEntitySpawnInterval); | |
nMapObject.AppendChild(nMapObjectEntity); | |
} | |
} | |
nMap.AppendChild(nMapObject); | |
} | |
this.Document["MapDetails"].AppendChild(nMap); | |
return 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment