protected override void Load() { Thread.CurrentThread.Name = "FreelancerGame UIThread"; //Move to stop _TSGetMainThread error on OSX MinimumWindowSize = new Point(640, 480); SetVSync(Config.VSync); new IdentityCamera(this); uithread = Thread.CurrentThread.ManagedThreadId; useintromovies = _cfg.IntroMovies; FLLog.Info("Platform", Platform.RunningOS.ToString() + (IntPtr.Size == 4 ? " 32-bit" : " 64-bit")); FLLog.Info("Available Threads", Environment.ProcessorCount.ToString()); //Cache ResourceManager = new GameResourceManager(this); //Init Audio FLLog.Info("Audio", "Initialising Audio"); Audio = new AudioManager(this); if (_cfg.MuteMusic) { Audio.Music.Volume = 0f; } //Load data FLLog.Info("Game", "Loading game data"); GameData = new GameDataManager(_cfg.FreelancerPath, ResourceManager); IntroMovies = GameData.GetIntroMovies(); MpvOverride = _cfg.MpvOverride; Thread GameDataLoaderThread = new Thread(() => { GameData.LoadData(); Sound = new SoundManager(GameData, Audio); FLLog.Info("Game", "Finished loading game data"); InitialLoadComplete = true; }); GameDataLoaderThread.Name = "GamedataLoader"; GameDataLoaderThread.Start(); // Renderer2D = new Renderer2D(RenderState); Fonts = new FontManager(this); Billboards = new Billboards(); Nebulae = new NebulaVertices(); ViewportManager = new ViewportManager(RenderState); ViewportManager.Push(0, 0, Width, Height); Screenshots = new ScreenshotManager(this); Services.Add(Billboards); Services.Add(Nebulae); Services.Add(ResourceManager); Services.Add(Renderer2D); Services.Add(Config); Services.Add(Fonts); if (useintromovies && IntroMovies.Count > 0) { ChangeState(new IntroMovie(this, 0)); } else { ChangeState(new LoadingDataState(this)); } }
public void DoAuthSuccess() { try { FLLog.Info("Server", "Account logged in"); Client.SendPacket(new LoginSuccessPacket(), PacketDeliveryMethod.ReliableOrdered); CharacterList = game.Database.PlayerLogin(playerGuid); Client.SendPacket(new OpenCharacterListPacket() { Info = new CharacterSelectInfo() { ServerName = game.ServerName, ServerDescription = game.ServerDescription, ServerNews = game.ServerNews, Characters = CharacterList, } }, PacketDeliveryMethod.ReliableOrdered); } catch (Exception ex) { FLLog.Error("Player", ex.Message); FLLog.Error("Player", ex.StackTrace); } }
public void RequestDock(Player player, string nickname) { actions.Enqueue(() => { var obj = Players[player]; FLLog.Info("Server", $"{player.Name} requested dock at {nickname}"); var dock = GameWorld.Objects.FirstOrDefault(x => x.Nickname.Equals(nickname, StringComparison.OrdinalIgnoreCase)); if (dock == null) { FLLog.Warning("Server", $"Dock object {nickname} does not exist."); } else { var component = dock.GetComponent <SDockableComponent>(); if (component == null) { FLLog.Warning("Server", $"object {nickname} is not dockable."); } else { component.StartDock(obj, 0); } } }); }
public LuaMenu(FreelancerGame g) : base(g) { api = new MenuAPI(this); ui = Game.Ui; ui.GameApi = api; ui.Visible = true; ui.OpenScene("mainmenu"); g.GameData.PopulateCursors(); g.CursorKind = CursorKind.None; intro = g.GameData.GetIntroScene(); scene = new Cutscene(new ThnScriptContext(null), Game.GameData, Game.RenderContext.CurrentViewport, Game); scene.BeginScene(intro.Scripts); FLLog.Info("Thn", "Playing " + intro.ThnName); cur = g.ResourceManager.GetCursor("arrow"); GC.Collect(); //crap g.Sound.PlayMusic(intro.Music); g.Keyboard.KeyDown += UiKeyDown; g.Keyboard.TextInput += UiTextInput; #if DEBUG g.Keyboard.KeyDown += Keyboard_KeyDown; #endif Game.Saves.Selected = -1; if (g.LoadTimer != null) { g.LoadTimer.Stop(); FLLog.Info("Game", $"Initial load took {g.LoadTimer.Elapsed.TotalSeconds} seconds"); g.LoadTimer = null; } FadeIn(0.1, 0.3); }
public void ProcessPacket(IPacket packet) { FLLog.Info("Server", "Got packet of type " + packet.GetType()); switch (packet) { case CharacterListActionPacket c: ListAction(c); break; case LaunchPacket l: Launch(); break; case EnterLocationPacket lc: msnRuntime?.EnterLocation(lc.Room, lc.Base); break; case PositionUpdatePacket p: World.PositionUpdate(this, p.Position, p.Orientation); break; case RTCCompletePacket cp: RemoveRTC(cp.RTC); break; case LineSpokenPacket lp: msnRuntime?.LineFinished(lp.Hash); break; } }
internal void _Update() { if (netClient == null) { return; } while (netClient.PollPacket(out var pkt)) { switch (pkt) { case OpenCharacterListPacket oclist: FLLog.Info("Net", "Opening Character List"); this.cselInfo = oclist.Info; foreach (var sc in oclist.Info.Characters) { ResolveNicknames(sc); } state.ui.Event("CharacterList"); break; case AddCharacterPacket ac: ResolveNicknames(ac.Character); cselInfo.Characters.Add(ac.Character); break; case NewCharacterDBPacket ncdb: state.ui.Event("OpenNewCharacter"); break; default: netSession.HandlePacket(pkt); break; } } }
Task <bool> IServerPlayer.SelectCharacter(int index) { if (index >= 0 && index < CharacterList.Count) { var sc = CharacterList[index]; FLLog.Info("Server", $"opening id {sc.Id}"); Character = NetCharacter.FromDb(sc.Id, Game); Name = Character.Name; rpcClient.UpdateBaselinePrices(Game.BaselineGoodPrices); rpcClient.UpdateInventory(Character.Credits, GetShipWorth(), Character.EncodeLoadout()); Base = Character.Base; System = Character.System; Position = Character.Position; if (Base != null) { PlayerEnterBase(); } else { SpaceInitialSpawn(null); } return(Task.FromResult(false)); } else { return(Task.FromResult(true)); } }
public SpaceGameplay(FreelancerGame g, GameSession session) : base(g) { FLLog.Info("Game", "Entering system " + session.PlayerSystem); g.ResourceManager.ClearTextures(); //Do before loading things this.session = session; font = Game.Fonts.GetSystemFont("Agency FB"); sys = g.GameData.GetSystem(session.PlayerSystem); loader = new LoadingScreen(g, g.GameData.LoadSystemResources(sys)); }
public static bool CheckStringSDL() { _getString = (GetString)Marshal.GetDelegateForFunctionPointer(SDL.SDL_GL_GetProcAddress("glGetString"), typeof(GetString)); var str = GetString(GL.GL_VERSION); FLLog.Info("GL", "Version String: " + GetString(GL.GL_VERSION)); var major = int.Parse(str[0].ToString()); return(major >= 3); }
public SpaceGameplay(FreelancerGame g, CGameSession session) : base(g) { FLLog.Info("Game", "Entering system " + session.PlayerSystem); g.ResourceManager.ClearTextures(); //Do before loading things this.session = session; sys = g.GameData.GetSystem(session.PlayerSystem); ui = Game.Ui; ui.GameApi = uiApi = new LuaAPI(this); loader = new LoadingScreen(g, g.GameData.LoadSystemResources(sys)); loader.Init(); }
Task <bool> IServerPlayer.CreateNewCharacter(string name, int index) { FLLog.Info("Player", $"New char {name}"); if (!Game.Database.NameInUse(name)) { Character ch = null; Game.Database.AddCharacter(playerGuid, (db) => { ch = db; var sg = Game.NewCharacter(name, index); db.Name = sg.Player.Name; db.Base = sg.Player.Base; db.System = sg.Player.System; db.Rank = 1; db.Costume = sg.Player.Costume; db.ComCostume = sg.Player.ComCostume; db.Money = sg.Player.Money; db.Ship = sg.Player.ShipArchetype; db.Items = new List <CargoItem>(); foreach (var eq in sg.Player.Equip) { db.Items.Add(new CargoItem() { ItemName = eq.EquipName, Hardpoint = string.IsNullOrEmpty(eq.Hardpoint) ? "internal" : eq.Hardpoint, ItemCount = 1 }); } foreach (var cg in sg.Player.Cargo) { db.Items.Add(new CargoItem() { ItemName = cg.CargoName, ItemCount = cg.Count }); } }); var sel = NetCharacter.FromDb(ch.Id, Game).ToSelectable(); CharacterList.Add(sel); Client.SendPacket(new AddCharacterPacket() { Character = sel }, PacketDeliveryMethod.ReliableOrdered); return(Task.FromResult(true)); } else { return(Task.FromResult(false)); } }
public static bool CheckStringSDL(bool checkGles = false) { _glGetString = (delegate * unmanaged <int, IntPtr>)SDL.SDL_GL_GetProcAddress("glGetString"); var str = GetString(GL.GL_VERSION); FLLog.Info("GL", "Version String: " + GetString(GL.GL_VERSION)); if (checkGles) { return(str.StartsWith("OpenGL ES 3")); } var major = int.Parse(str[0].ToString()); return(major >= 3); }
void Process(TimeSpan time) { while (!localPackets.IsEmpty && localPackets.TryDequeue(out var local)) { LocalPlayer.ProcessPacket(local); } Action a; if (worldRequests.Count > 0 && worldRequests.TryDequeue(out a)) { a(); } //Update if (!(LocalPlayer?.World?.Paused ?? false)) { LocalPlayer?.UpdateMissionRuntime(time.TotalSeconds); } ConcurrentBag <StarSystem> toSpinDown = new ConcurrentBag <StarSystem>(); Parallel.ForEach(worlds, (world) => { if (!world.Value.Update(time.TotalSeconds)) { toSpinDown.Add(world.Key); } }); //Remove if (toSpinDown.Count > 0) { lock (availableWorlds) { foreach (var w in toSpinDown) { if (worlds[w].PlayerCount <= 0) { worlds[w].Finish(); availableWorlds.Remove(w); worlds.Remove(w); FLLog.Info("Server", $"Shut down world {w.Nickname} ({w.Name})"); } } } } processingLoop.TimeStep = worlds.Count > 0 ? RATE_60 : RATE_30; if (!running) { processingLoop.Stop(); } }
public static void Load() { //Eliminate ARM PortableExecutableKinds peKind; ImageFileMachine machine; typeof(object).Module.GetPEKind(out peKind, out machine); if (machine != ImageFileMachine.AMD64 && machine != ImageFileMachine.I386) { FLLog.Info("SSE", "SSE Math Disabled: Reason - Unsupported Architecture"); return; } var mytype = typeof(SSEMath); foreach (var field in mytype.GetFields(BindingFlags.Public | BindingFlags.Static)) { AsmMethodAttribute a = null; foreach (var attr in field.GetCustomAttributes()) { if (attr is AsmMethodAttribute) { a = (AsmMethodAttribute)attr; } } if (a != null) { Delegate func = null; if (IntPtr.Size == 4) { func = GetFunction(field.FieldType, a.X86Name); } else { if (IsUnix) { func = GetFunction(field.FieldType, a.UnixName); } else { func = GetFunction(field.FieldType, a.WindowsName); } } field.SetValue(null, func); } } FLLog.Info("SSE", "SSE Math Enabled"); IsAccelerated = true; }
void GameThread() { if (needLoadData) { FLLog.Info("Server", "Loading Game Data..."); GameData.LoadData(); FLLog.Info("Server", "Finished Loading Game Data"); } if (!string.IsNullOrWhiteSpace(DbConnectionString)) { Database = new ServerDatabase(DbConnectionString); } Listener?.Start(); Stopwatch sw = Stopwatch.StartNew(); double lastTime = 0; while (running) { while (!localPackets.IsEmpty && localPackets.TryDequeue(out var local)) { LocalPlayer.ProcessPacket(local); } Action a; if (worldRequests.Count > 0 && worldRequests.TryDequeue(out a)) { a(); } //Start Loop var time = sw.Elapsed.TotalMilliseconds; var elapsed = (time - lastTime); if (elapsed < 2) { continue; } elapsed /= 1000f; lastTime = time; //Update LocalPlayer?.UpdateMissionRuntime(TimeSpan.FromSeconds(elapsed)); foreach (var world in worlds.Values) { world.Update(TimeSpan.FromSeconds(elapsed)); } //Sleep Thread.Sleep(0); } Listener?.Stop(); }
void GameThread() { if (needLoadData) { FLLog.Info("Server", "Loading Game Data..."); GameData.LoadData(null); FLLog.Info("Server", "Finished Loading Game Data"); } InitBaselinePrices(); Database = new ServerDatabase(this); Listener?.Start(); double lastTime = 0; processingLoop = new ServerLoop(Process); processingLoop.Start(); Listener?.Stop(); }
public DemoSystemView(FreelancerGame g) : base(g) { FLLog.Info("Game", "Starting System Viewer Demo"); sys = g.GameData.GetSystem("li01"); camera = new DebugCamera(g.Viewport); camera.Zoom = 5000; sysrender = new SystemRenderer(camera, g.GameData, g.ResourceManager, g); world = new GameWorld(sysrender); world.LoadSystem(sys, g.ResourceManager); g.Sound.PlayMusic(sys.MusicSpace); camera.UpdateProjection(); trender = new Renderer2D(Game.RenderState); font = g.Fonts.GetSystemFont("Agency FB"); g.Keyboard.KeyDown += G_Keyboard_KeyDown; g.Keyboard.TextInput += G_Keyboard_TextInput; }
internal void _Update() { if (netClient == null) { return; } while (netClient.PollPacket(out var pkt)) { switch (pkt) { case OpenCharacterListPacket oclist: FLLog.Info("Net", "Opening Character List"); this.cselInfo = oclist.Info; foreach (var sc in oclist.Info.Characters) { ResolveNicknames(sc); } state.ui.Event("CharacterList"); break; case AddCharacterPacket ac: ResolveNicknames(ac.Character); cselInfo.Characters.Add(ac.Character); break; case NewCharacterDBPacket ncdb: state.ui.Event("OpenNewCharacter"); break; case CharacterListActionResponsePacket cresp: switch (cresp.Action) { case CharacterListAction.DeleteCharacter: if (cresp.Status == CharacterListStatus.OK) { cselInfo.Characters.RemoveAt(delIndex); delIndex = -1; } break; } break; } } }
private void SceneOnScriptFinished(ThnScript obj) { if (waitingForFinish != null && obj == waitingForFinish) { if (currentCutscene != null) { if (cState == CutsceneState.Decision) { return; } FadeOut(0.25, () => { RoomDoSceneScript(null, ScriptState.None); ui.Visible = true; FLLog.Info("Thn", "Finished cutscene"); if (cState == CutsceneState.Regular) { session.FinishCutscene(currentCutscene); currentCutscene = null; if (toPlay.Count > 0) { ProcessNextCutscene(); } } else if (cState == CutsceneState.Offer) { PlayScript(currentCutscene, CutsceneState.Decision); ui.Event("MissionOffer", currentCutscene.Encounters[0].MissionTextId); } FadeIn(0.2, 0.25); }); } else if (currentState == ScriptState.Launch) { SendLaunch(); } else { currentState = ScriptState.None; SetRoomCameraAndShip(); animatingLetterbox = true; } } }
public SpaceGameplay(FreelancerGame g, GameSession session) : base(g) { FLLog.Info("Game", "Entering system " + session.PlayerSystem); g.ResourceManager.ClearTextures(); //Do before loading things this.session = session; font = Game.Fonts.GetSystemFont("Agency FB"); #if false pyw = new DebugGraph(); pyw.AddLine(Color4.Red, 240, -1, 1); pyw.AddLine(Color4.Green, 240, -1, 1); pyw.AddLine(Color4.Blue, 240, -1, 1); pyw.X = 850; pyw.Y = 10; pyw.Width = 170; pyw.Height = 124; #endif sys = g.GameData.GetSystem(session.PlayerSystem); loader = new LoadingScreen(g, g.GameData.LoadSystemResources(sys)); }
public override void Draw(double delta) { xCnt++; Game.RenderContext.Renderer2D.DrawImageStretched(splash, new Rectangle(0, 0, Game.Width, Game.Height), Color4.White, true); DoFade(delta); if (!shadersCompiled && (xCnt >= 3)) { Shaders.AllShaders.Compile(); shadersCompiled = true; } if (xCnt >= 3 && Game.InisLoaded && !uiLoaded) { Game.Fonts.LoadFontsFromGameData(Game.GameData); Game.Ui = new UiContext(Game); Game.Ui.LoadCode(); FLLog.Info("UI", "Interface loaded"); uiLoaded = true; } }
public LuaMenu(FreelancerGame g) : base(g) { api = new LuaAPI(this); ui = new XmlUIManager(g, "menu", api, g.GameData.GetInterfaceXml("mainmenu")); ui.OnConstruct(); ui.Enter(); g.GameData.PopulateCursors(); g.CursorKind = CursorKind.None; intro = g.GameData.GetIntroScene(); scene = new Cutscene(intro.Scripts, Game); scene.Update(TimeSpan.FromSeconds(1f / 60f)); //Do all the setup events - smoother entrance FLLog.Info("Thn", "Playing " + intro.ThnName); cur = g.ResourceManager.GetCursor("arrow"); GC.Collect(); //crap g.Sound.PlayMusic(intro.Music); #if DEBUG g.Keyboard.KeyDown += Keyboard_KeyDown; #endif FadeIn(0.1, 0.3); }
public LuaMenu(FreelancerGame g) : base(g) { api = new MenuAPI(this); ui = new UiContext(g); ui.GameApi = new MenuAPI(this); widget = ui.CreateAll("mainmenu.xml"); g.GameData.PopulateCursors(); g.CursorKind = CursorKind.None; intro = g.GameData.GetIntroScene(); scene = new Cutscene(new ThnScriptContext(intro.Scripts), Game.GameData, Game.Viewport, Game); scene.Update(TimeSpan.FromSeconds(1f / 60f)); //Do all the setup events - smoother entrance FLLog.Info("Thn", "Playing " + intro.ThnName); cur = g.ResourceManager.GetCursor("arrow"); GC.Collect(); //crap g.Sound.PlayMusic(intro.Music); #if DEBUG g.Keyboard.KeyDown += Keyboard_KeyDown; #endif FadeIn(0.1, 0.3); }
public SpaceGameplay(FreelancerGame g, GameSession session) : base(g) { FLLog.Info("Game", "Entering system " + session.PlayerSystem); g.ResourceManager.ClearTextures(); //Do before loading things this.session = session; #if false pyw = new DebugGraph(); pyw.AddLine(Color4.Red, 240, -1, 1); pyw.AddLine(Color4.Green, 240, -1, 1); pyw.AddLine(Color4.Blue, 240, -1, 1); pyw.X = 850; pyw.Y = 10; pyw.Width = 170; pyw.Height = 124; #endif sys = g.GameData.GetSystem(session.PlayerSystem); loader = new LoadingScreen(g, g.GameData.LoadSystemResources(sys)); ui = new UiContext(g); ui.GameApi = uiApi = new LuaAPI(this); widget = ui.CreateAll("hud.xml"); }
public void RequestWorld(GameData.StarSystem system, Action <ServerWorld> spunUp) { lock (availableWorlds) { if (availableWorlds.Contains(system)) { spunUp(worlds[system]); return; } } worldRequests.Enqueue(() => { var world = new ServerWorld(system, this); FLLog.Info("Server", "Spun up " + system.Nickname + " (" + system.Name + ")"); worlds.Add(system, world); lock (availableWorlds) { availableWorlds.Add(system); } spunUp(world); }); }
//Global method for checking extensions. Called upon GraphicsDevice creation public static void PopulateExtensions() { if (ExtensionList != null) { return; } int n; GL.GetIntegerv(GL.GL_NUM_EXTENSIONS, out n); ExtensionList = new List <string> (n); for (int i = 0; i < n; i++) { ExtensionList.Add(GL.GetStringi(GL.GL_EXTENSIONS, i)); } if (GL.GLES) { versionInteger = 310; } else { var versionStr = GL.GetString(GL.GL_VERSION).Trim(); versionInteger = int.Parse(versionStr[0].ToString()) * 100 + int.Parse(versionStr[2].ToString()) * 10; } FLLog.Info("GL", "Extensions: \n" + string.Join(", ", ExtensionList)); s3tc = ExtensionList.Contains("GL_EXT_texture_compression_s3tc"); debugInfo = ExtensionList.Contains("GL_KHR_debug"); if (debugInfo) { FLLog.Info("GL", "KHR_debug supported"); } if (s3tc) { FLLog.Info("GL", "S3TC extension supported"); } else { FLLog.Info("GL", "S3TC extension not supported"); } }
public static void Load(Func <string, Type, Delegate> getprocaddress) { tid = Thread.CurrentThread.ManagedThreadId; errors = new Dictionary <int, string>(); errors.Add(0x0500, "Invalid Enum"); errors.Add(0x0501, "Invalid Value"); errors.Add(0x0502, "Invalid Operation"); errors.Add(0x0503, "Stack Overflow"); errors.Add(0x0504, "Stack Underflow"); errors.Add(0x0505, "Out Of Memory"); errors.Add(0x0506, "Invalid Framebuffer Operation"); int loaded = 0; foreach (var f in typeof(GL).GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { string proc = null; foreach (var attr in f.CustomAttributes) { if (attr.AttributeType == typeof(MapsToAttribute)) { proc = (string)attr.ConstructorArguments[0].Value; } } if (proc == null) { continue; } //var del = Marshal.GetDelegateForFunctionPointer(getprocaddress(proc), f.FieldType); var del = getprocaddress(proc, f.FieldType); if (proc != "glGetError" && del != null) { del = MakeWrapper(f.FieldType, del); } f.SetValue(null, del); loaded++; } FLLog.Info("OpenGL", "Loaded " + loaded + " function pointers"); }
void NetworkThread() { sw = Stopwatch.StartNew(); var listener = new EventBasedNetListener(); client = new NetManager(listener) { UnconnectedMessagesEnabled = true, IPv6Enabled = true, NatPunchEnabled = true, ChannelsCount = 3 }; listener.NetworkReceiveUnconnectedEvent += (remote, msg, type) => { if (type == UnconnectedMessageType.Broadcast) { return; } if (msg.GetInt() == 0) { lock (srvinfo) { foreach (var info in srvinfo) { if (info.EndPoint.Equals(remote)) { var t = sw.ElapsedMilliseconds; info.Ping = (int)(t - info.LastPingTime); if (info.Ping < 0) { info.Ping = 0; } } } } } else if (ServerFound != null) { var info = new LocalServerInfo(); info.EndPoint = remote; info.Unique = msg.GetInt(); info.Name = msg.GetString(); info.Description = msg.GetString(); info.DataVersion = msg.GetString(); info.CurrentPlayers = msg.GetInt(); info.MaxPlayers = msg.GetInt(); info.LastPingTime = sw.ElapsedMilliseconds; NetDataWriter writer = new NetDataWriter(); writer.Put(LNetConst.PING_MAGIC); client.SendUnconnectedMessage(writer, remote); lock (srvinfo) { bool add = true; for (int i = 0; i < srvinfo.Count; i++) { if (srvinfo[i].Unique == info.Unique) { add = false; //Prefer IPv6 if (srvinfo[i].EndPoint.AddressFamily != AddressFamily.InterNetwork && info.EndPoint.AddressFamily == AddressFamily.InterNetwork) { srvinfo[i].EndPoint = info.EndPoint; } break; } } if (add) { srvinfo.Add(info); mainThread.QueueUIThread(() => ServerFound?.Invoke(info)); } } } msg.Recycle(); }; listener.NetworkReceiveEvent += (peer, reader, method) => { try { var packetCount = reader.GetByte(); //reliable packets can be merged if (packetCount > 1) { FLLog.Debug("Net", $"Received {packetCount} merged packets"); } for (int i = 0; i < packetCount; i++) { var pkt = Packets.Read(reader); if (connecting) { if (pkt is AuthenticationPacket) { var auth = (AuthenticationPacket)pkt; FLLog.Info("Net", "Authentication Packet Received"); if (auth.Type == AuthenticationKind.Token) { FLLog.Info("Net", "Token"); var str = reader.GetString(); mainThread.QueueUIThread(() => AuthenticationRequired(str)); } else if (auth.Type == AuthenticationKind.GUID) { FLLog.Info("Net", "GUID"); SendPacket(new AuthenticationReplyPacket() { Guid = this.UUID }, PacketDeliveryMethod.ReliableOrdered); } } else if (pkt is LoginSuccessPacket) { FLLog.Info("Client", "Login success"); connecting = false; } else { client.DisconnectAll(); } } else { packets.Enqueue(pkt); } } } catch (Exception e) { FLLog.Error("Client", "Error reading packet"); client.DisconnectAll(); } }; listener.PeerDisconnectedEvent += (peer, info) => { mainThread.QueueUIThread(() => { Disconnected?.Invoke(info.Reason.ToString()); }); }; client.Start(); while (running) { if (Interlocked.Read(ref localPeerRequests) > 0) { Interlocked.Decrement(ref localPeerRequests); var dw = new NetDataWriter(); dw.Put(LNetConst.BROADCAST_KEY); client.SendBroadcast(dw, LNetConst.DEFAULT_PORT); } //ping servers lock (srvinfo) { foreach (var inf in srvinfo) { var nowMs = sw.ElapsedMilliseconds; if (nowMs - inf.LastPingTime > 2000) //ping every 2 seconds? { inf.LastPingTime = nowMs; var om = new NetDataWriter(); om.Put(LNetConst.PING_MAGIC); client.SendUnconnectedMessage(om, inf.EndPoint); } } } //events client.PollEvents(); Thread.Sleep(1); } client.DisconnectAll(); client.Stop(); }
void NetworkThread() { sw = Stopwatch.StartNew(); var conf = new NetPeerConfiguration(NetConstants.DEFAULT_APP_IDENT); conf.EnableMessageType(NetIncomingMessageType.UnconnectedData); conf.DualStack = true; client = new NetClient(conf); client.Start(); NetIncomingMessage im; while (running) { //ping servers lock (srvinfo) { foreach (var inf in srvinfo) { var nowMs = (long)(NetTime.Now * 1000); if (nowMs - inf.LastPingTime > 600) { inf.LastPingTime = nowMs; var om = client.CreateMessage(); om.Write(NetConstants.PING_MAGIC); client.SendUnconnectedMessage(om, inf.EndPoint); } } } while ((im = client.ReadMessage()) != null) { try { switch (im.MessageType) { case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.ErrorMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.VerboseDebugMessage: FLLog.Info("Lidgren", im.ReadString()); break; case NetIncomingMessageType.UnconnectedData: lock (srvinfo) { foreach (var info in srvinfo) { if (info.EndPoint.Equals(im.SenderEndPoint)) { var t = (long)(im.ReceiveTime * 1000); info.Ping = (int)(t - info.LastPingTime); if (info.Ping < 0) { info.Ping = 0; } } } } break; case NetIncomingMessageType.DiscoveryResponse: if (ServerFound != null) { var info = new LocalServerInfo(); info.EndPoint = im.SenderEndPoint; info.Name = im.ReadString(); info.Description = im.ReadString(); info.DataVersion = im.ReadString(); info.CurrentPlayers = im.ReadInt32(); info.MaxPlayers = im.ReadInt32(); info.LastPingTime = sw.ElapsedMilliseconds; var om = client.CreateMessage(); om.Write(NetConstants.PING_MAGIC); client.SendUnconnectedMessage(om, info.EndPoint); lock (srvinfo) srvinfo.Add(info); mainThread.QueueUIThread(() => ServerFound?.Invoke(info)); } break; case NetIncomingMessageType.StatusChanged: var status = (NetConnectionStatus)im.ReadByte(); if (status == NetConnectionStatus.Disconnected) { FLLog.Info("Net", "Disconnected"); var reason = im.ReadString(); mainThread.QueueUIThread(() => Disconnected?.Invoke(reason)); running = false; } break; case NetIncomingMessageType.Data: var pkt = im.ReadPacket(); if (connecting) { if (pkt is AuthenticationPacket) { var auth = (AuthenticationPacket)pkt; FLLog.Info("Net", "Authentication Packet Received"); if (auth.Type == AuthenticationKind.Token) { FLLog.Info("Net", "Token"); var str = im.ReadString(); mainThread.QueueUIThread(() => AuthenticationRequired(str)); } else if (auth.Type == AuthenticationKind.GUID) { FLLog.Info("Net", "GUID"); var response = client.CreateMessage(); response.Write(new AuthenticationReplyPacket() { Guid = this.UUID }); client.SendMessage(response, NetDeliveryMethod.ReliableOrdered); } } else if (pkt is LoginSuccessPacket) { connecting = false; } else { client.Disconnect("Invalid Packet"); } } else { packets.Enqueue(pkt); } break; } } catch (Exception) { FLLog.Error("Net", "Error reading message of type " + im.MessageType.ToString()); throw; } client.Recycle(im); } Thread.Sleep(1); } FLLog.Info("Lidgren", "Client shutdown"); client.Shutdown("Shutdown"); }
void ListAction(CharacterListActionPacket pkt) { switch (pkt.Action) { case CharacterListAction.RequestCharacterDB: { Client.SendPacket(new NewCharacterDBPacket() { Factions = game.GameData.Ini.NewCharDB.Factions, Packages = game.GameData.Ini.NewCharDB.Packages, Pilots = game.GameData.Ini.NewCharDB.Pilots }, PacketDeliveryMethod.ReliableOrdered); break; } case CharacterListAction.SelectCharacter: { if (pkt.IntArg > 0 && pkt.IntArg < CharacterList.Count) { var sc = CharacterList[pkt.IntArg]; FLLog.Info("Server", $"opening id {sc.Id}"); Character = NetCharacter.FromDb(sc.Id, game); FLLog.Info("Server", $"sending packet"); Base = Character.Base; Client.SendPacket(new BaseEnterPacket() { Base = Character.Base, Ship = Character.EncodeLoadout() }, PacketDeliveryMethod.ReliableOrdered); } else { Client.SendPacket(new CharacterListActionResponsePacket() { Action = CharacterListAction.SelectCharacter, Status = CharacterListStatus.ErrBadIndex }, PacketDeliveryMethod.ReliableOrdered); } break; } case CharacterListAction.DeleteCharacter: { var sc = CharacterList[pkt.IntArg]; game.Database.DeleteCharacter(sc.Id); CharacterList.Remove(sc); Client.SendPacket(new CharacterListActionResponsePacket() { Action = CharacterListAction.DeleteCharacter, Status = CharacterListStatus.OK }, PacketDeliveryMethod.ReliableOrdered); break; } case CharacterListAction.CreateNewCharacter: { if (!game.Database.NameInUse(pkt.StringArg)) { Character ch = null; game.Database.AddCharacter(playerGuid, (db) => { ch = db; var sg = game.NewCharacter(pkt.StringArg, pkt.IntArg); db.Name = sg.Player.Name; db.Base = sg.Player.Base; db.System = sg.Player.System; db.Rank = 1; db.Costume = sg.Player.Costume; db.ComCostume = sg.Player.ComCostume; db.Money = sg.Player.Money; db.Ship = sg.Player.ShipArchetype; db.Equipment = new HashSet <EquipmentEntity>(); db.Cargo = new HashSet <CargoItem>(); foreach (var eq in sg.Player.Equip) { db.Equipment.Add(new EquipmentEntity() { EquipmentNickname = eq.EquipName, EquipmentHardpoint = eq.Hardpoint }); } foreach (var cg in sg.Player.Cargo) { db.Cargo.Add(new CargoItem() { ItemName = cg.CargoName, ItemCount = cg.Count }); } }); var sel = NetCharacter.FromDb(ch.Id, game).ToSelectable(); CharacterList.Add(sel); Client.SendPacket(new AddCharacterPacket() { Character = sel }, PacketDeliveryMethod.ReliableOrdered); } else { Client.SendPacket(new CharacterListActionResponsePacket() { Action = CharacterListAction.CreateNewCharacter, Status = CharacterListStatus.ErrUnknown }, PacketDeliveryMethod.ReliableOrdered); } break; } } }