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 PositionUpdatePacket p: World.PositionUpdate(this, p.Position, p.Orientation); break; case LineSpokenPacket lp: msnRuntime?.LineFinished(lp.Hash); break; } }
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"); }
public void Update(TimeSpan delta) { int counter = 0; accumTime += delta.TotalSeconds; while (accumTime > (1.0 / 120.0)) { _Update(TimeSpan.FromSeconds(TIMESTEP)); accumTime -= TIMESTEP; counter++; if (counter > MAX_STEPS) { // okay, okay... we can't keep up FLLog.Warning("Thn", "Can't keep up!"); accumTime = 0.0f; break; } } }
void Launch() { var b = server.GameData.GetBase(Base); var sys = server.GameData.GetSystem(b.System); server.RequestWorld(sys, (world) => { this.World = world; var obj = sys.Objects.FirstOrDefault((o) => { return(o.Dock != null && o.Dock.Kind == DockKinds.Base && o.Dock.Target.Equals(Base, StringComparison.OrdinalIgnoreCase)); }); System = b.System; Orientation = Quaternion.Identity; Position = Vector3.Zero; if (obj == null) { FLLog.Error("Base", "Can't find object in " + sys + " docking to " + b); } else { Position = obj.Position; Orientation = (obj.Rotation == null ? Matrix3.Identity : new Matrix3(obj.Rotation.Value)).ExtractRotation(); Position = Vector3.Transform(new Vector3(0, 0, 500), Orientation) + obj.Position; //TODO: This is bad } var msg = server.NetServer.CreateMessage(); msg.Write(new SpawnPlayerPacket() { System = System, Position = Position, Orientation = Orientation, Ship = Character.EncodeLoadout() }); server.NetServer.SendMessage(msg, connection, NetDeliveryMethod.ReliableOrdered); world.SpawnPlayer(this, Position, Orientation); }); }
LoadedSound OnLoadSound(string name) { FLLog.Debug("Sounds", "Loading sound " + name); var loaded = new LoadedSound(); loaded.Entry = data.GetAudioEntry(name); loaded.Name = name; if (loaded.Entry.File.ToLowerInvariant().Replace('\\', '/') == "audio/null.wav") { //HACK: Don't bother with sounds using null.wav, makes awful popping noise loaded.Data = null; } else { var path = data.GetAudioPath(name); var snd = audio.AllocateData(); snd.LoadFile(path); loaded.Data = snd; } return(loaded); }
void ProcessStartPSys(ThnEvent ev) { if (!Objects.ContainsKey((string)ev.Targets[0])) { FLLog.Error("Thn", "Entity " + ev.Targets[0].ToString() + " does not exist"); return; } var obj = Objects[(string)ev.Targets[0]]; if (obj.Object == null) { FLLog.Error("Thn", "Entity " + ev.Targets[0].ToString() + " null renderer"); return; } var r = (ParticleEffectRenderer)obj.Object.RenderComponent; r.Active = true; Coroutines.Add(new StopPSys() { Duration = ev.Duration, Fx = r }); }
//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"); } }
void ProcessEvent(ThnEvent ev) { if (ev.Type == EventTypes.SetCamera) { ProcessSetCamera(ev); } else if (ev.Type == EventTypes.StartPSys) { ProcessStartPSys(ev); } else { IThnEventRunner er; if (eventRunners.TryGetValue(ev.Type, out er)) { er.Process(ev, this); } else { FLLog.Error("Thn", "Unimplemented event: " + ev.Type.ToString()); } } }
public void StartAnimation(string animationName, bool loop = true, float start_time = 0, float time_scale = 1, float duration = 0) { if (Parent?.RenderComponent is CharacterRenderer characterRenderer) { if (anm.Scripts.TryGetValue(animationName, out Script sc)) { characterRenderer.Skeleton.StartScript(sc, start_time, time_scale, duration, loop); } return; } if (anm.Scripts.ContainsKey(animationName)) { var sc = anm.Scripts[animationName]; animations.Add(new ActiveAnimation() { Name = animationName, Script = sc, StartTime = totalTime, Loop = loop }); } else { FLLog.Error("Animation", animationName + " not present"); } }
public void JumpTo(string system, string target) { rpcClient.StartJumpTunnel(); if (World != null) { World.RemovePlayer(this); } var sys = Game.GameData.GetSystem(system); Game.RequestWorld(sys, (world) => { this.World = world; var obj = sys.Objects.FirstOrDefault((o) => { return(o.Nickname.Equals(target, StringComparison.OrdinalIgnoreCase)); }); System = system; Base = null; Position = Vector3.Zero; if (obj == null) { FLLog.Error("Server", $"Can't find target {target} to spawn player in {system}"); } else { Position = obj.Position; Orientation = (obj.Rotation ?? Matrix4x4.Identity).ExtractRotation(); Position = Vector3.Transform(new Vector3(0, 0, 500), Orientation) + obj.Position; //TODO: This is bad } BaseData = null; Base = null; rpcClient.SpawnPlayer(System, world.TotalTime, Position, Orientation); world.SpawnPlayer(this, Position, Orientation); msnRuntime?.EnteredSpace(); }); }
void AddLoaded(LoadedSound snd) { if (lruHead == null) { lruHead = lruTail = new LoadedSoundPtr() { Sound = snd }; loadedSounds[snd.Name] = snd; return; } LoadedSoundPtr ptr; if (loadedSounds.Count == SOUNDS_MAX) { FLLog.Debug("Sounds", "Evicting sound"); //Evict oldest and reuse ptr object var h = lruHead; h.Sound.Data.Dispose(); loadedSounds.Remove(h.Sound.Name); lruHead = h.Next; ptr = h; ptr.Sound = snd; ptr.Next = null; ptr.Previous = lruTail; } else { ptr = new LoadedSoundPtr() { Sound = snd, Previous = lruTail }; } lruTail.Next = ptr; lruTail = ptr; loadedSounds[snd.Name] = snd; }
public void DoAuthSuccess() { try { client.SendPacket(new LoginSuccessPacket(), NetDeliveryMethod.ReliableOrdered); Account = new PlayerAccount(); client.SendPacket(new OpenCharacterListPacket() { Info = new CharacterSelectInfo() { ServerName = game.ServerName, ServerDescription = game.ServerDescription, ServerNews = game.ServerNews, Characters = new List <SelectableCharacter>() } }, NetDeliveryMethod.ReliableOrdered); } catch (Exception ex) { FLLog.Error("Player", ex.Message); FLLog.Error("Player", ex.StackTrace); } }
public void ProcessPacket(IPacket packet) { if (ResponseHandler.HandlePacket(packet)) { return; } try { var hsp = GeneratedProtocol.HandleServerPacket(packet, this, this); hsp.Wait(); if (hsp.Result) { return; } } catch (Exception e) { FLLog.Exception("Player", e); throw; } try { switch (packet) { case PositionUpdatePacket p: //TODO: Error handling World?.PositionUpdate(this, p.Position, p.Orientation, p.Speed); break; } } catch (Exception e) { FLLog.Exception("Player", e); throw; } }
public static ShaderVariables Get(string vs, string fs, ShaderCaps caps = ShaderCaps.None) { var k = new Strings2(vs, fs, caps); ShaderVariables sh; if (!shaders.TryGetValue(k, out sh)) { string prelude; if (GLExtensions.Features430) { prelude = "#version 430\n#define FEATURES430\n" + caps.GetDefines() + "\n#line 0\n"; } else { prelude = "#version 150\n" + caps.GetDefines() + "\n#line 0\n"; } FLLog.Debug("Shader", "Compiling [ " + vs + " , " + fs + " ]"); sh = new ShaderVariables( new Shader(prelude + Resources.LoadString("LibreLancer.Shaders." + vs), prelude + ProcessIncludes(Resources.LoadString("LibreLancer.Shaders." + fs))) ); shaders.Add(k, sh); } return(sh); }
public RenderState() { GL.ClearColor(0f, 0f, 0f, 1f); GL.Enable(GL.GL_BLEND); GL.Enable(GL.GL_DEPTH_TEST); GL.BlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); GL.DepthFunc(GL.GL_LEQUAL); GL.Enable(GL.GL_CULL_FACE); GL.CullFace(GL.GL_BACK); Instance = this; PreferredFilterLevel = TextureFiltering.Trilinear; if (GLExtensions.Anisotropy) { int af; GL.GetIntegerv(GL.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, out af); MaxAnisotropy = af; FLLog.Debug("GL", "Max Anisotropy: " + af); } else { MaxAnisotropy = 0; FLLog.Debug("GL", "Anisotropic Filter Not Supported!"); } }
void FinishLoad() { Game.Saves.Selected = -1; ui.OpenScene("hud"); var shp = Game.GameData.GetShip(session.PlayerShip); //Set up player object + camera player = new GameObject(shp.ModelFile.LoadFile(Game.ResourceManager), Game.ResourceManager); control = new ShipPhysicsComponent(player); control.Ship = shp; shipInput = new ShipInputComponent(player); player.Components.Add(shipInput); player.Components.Add(control); weapons = new WeaponControlComponent(player); player.Components.Add(weapons); player.Components.Add(new CDamageFuseComponent(player, shp.Fuses)); player.SetLocalTransform(session.PlayerOrientation * Matrix4x4.CreateTranslation(session.PlayerPosition)); player.PhysicsComponent.Mass = shp.Mass; playerHealth = new CHealthComponent(player); playerHealth.MaxHealth = shp.Hitpoints; playerHealth.CurrentHealth = shp.Hitpoints; player.Components.Add(playerHealth); if (shp.Mass < 0) { FLLog.Error("Ship", "Mass < 0"); } player.Tag = GameObject.ClientPlayerTag; foreach (var equipment in session.Items.Where(x => !string.IsNullOrEmpty(x.Hardpoint))) { EquipmentObjectManager.InstantiateEquipment(player, Game.ResourceManager, EquipmentType.LocalPlayer, equipment.Hardpoint, equipment.Equipment); } powerCore = player.GetComponent <PowerCoreComponent>(); if (powerCore == null) { throw new Exception("Player launched without a powercore equipped!"); } camera = new ChaseCamera(Game.RenderContext.CurrentViewport, Game.GameData.Ini.Cameras); camera.ChasePosition = session.PlayerPosition; camera.ChaseOrientation = player.LocalTransform.ClearTranslation(); var offset = shp.ChaseOffset; camera.DesiredPositionOffset = offset; if (shp.CameraHorizontalTurnAngle > 0) { camera.HorizontalTurnAngle = shp.CameraHorizontalTurnAngle; } if (shp.CameraVerticalTurnUpAngle > 0) { camera.VerticalTurnUpAngle = shp.CameraVerticalTurnUpAngle; } if (shp.CameraVerticalTurnDownAngle > 0) { camera.VerticalTurnDownAngle = shp.CameraVerticalTurnDownAngle; } camera.Reset(); sysrender = new SystemRenderer(camera, Game.GameData, Game.ResourceManager, Game); sysrender.ZOverride = true; //Draw all with regular Z world = new GameWorld(sysrender); world.LoadSystem(sys, Game.ResourceManager, false, session.SpawnTime); session.WorldReady(); player.World = world; world.AddObject(player); world.RenderUpdate += World_RenderUpdate; world.PhysicsUpdate += World_PhysicsUpdate; player.Register(world.Physics); Game.Sound.PlayMusic(sys.MusicSpace); //world.Physics.EnableWireframes(debugphysics); cur_arrow = Game.ResourceManager.GetCursor("arrow"); cur_cross = Game.ResourceManager.GetCursor("cross"); cur_reticle = Game.ResourceManager.GetCursor("fire_neutral"); current_cur = cur_cross; Game.Keyboard.TextInput += Game_TextInput; Game.Keyboard.KeyDown += Keyboard_KeyDown; Game.Mouse.MouseDown += Mouse_MouseDown; Game.Mouse.MouseUp += Mouse_MouseUp; input = new InputManager(Game); input.ToggleActivated += Input_ToggleActivated; input.ToggleUp += Input_ToggleUp; pilotcomponent = new AutopilotComponent(player); player.Components.Add(pilotcomponent); player.World = world; world.MessageBroadcasted += World_MessageBroadcasted; Game.Sound.ResetListenerVelocity(); FadeIn(0.5, 0.5); }
void NetThread() { var netconf = new NetPeerConfiguration(AppIdentifier); netconf.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); netconf.EnableMessageType(NetIncomingMessageType.ConnectionApproval); netconf.EnableMessageType(NetIncomingMessageType.UnconnectedData); netconf.DualStack = true; netconf.Port = Port; netconf.MaximumConnections = 200; NetServer = new NetServer(netconf); NetServer.Start(); FLLog.Info("Server", "Listening on port " + Port); NetIncomingMessage im; while (running) { while ((im = NetServer.ReadMessage()) != null) { switch (im.MessageType) { case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.ErrorMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.VerboseDebugMessage: FLLog.Info("Lidgren", im.ReadString()); NetServer.Recycle(im); break; case NetIncomingMessageType.ConnectionApproval: //Ban IP? im.SenderConnection.Approve(); NetServer.Recycle(im); break; case NetIncomingMessageType.DiscoveryRequest: NetOutgoingMessage dresp = NetServer.CreateMessage(); //Include Server Data dresp.Write(game.ServerName); dresp.Write(game.ServerDescription); dresp.Write(game.GameData.DataVersion); dresp.Write(NetServer.ConnectionsCount); dresp.Write(NetServer.Configuration.MaximumConnections); //Send off NetServer.SendDiscoveryResponse(dresp, im.SenderEndPoint); NetServer.Recycle(im); break; case NetIncomingMessageType.UnconnectedData: //Respond to pings try { if (im.ReadUInt32() == NetConstants.PING_MAGIC) { var om = NetServer.CreateMessage(); om.Write(NetConstants.PING_MAGIC); NetServer.SendUnconnectedMessage(om, im.SenderEndPoint); } } finally { NetServer.Recycle(im); } break; case NetIncomingMessageType.StatusChanged: NetConnectionStatus status = (NetConnectionStatus)im.ReadByte(); string reason = im.ReadString(); FLLog.Info("Lidgren", NetUtility.ToHexString(im.SenderConnection.RemoteUniqueIdentifier) + " " + status + ": " + reason); if (status == NetConnectionStatus.Connected) { FLLog.Info("Lidgren", "Remote hail: " + im.SenderConnection.RemoteHailMessage.ReadString()); BeginAuthentication(NetServer, im.SenderConnection); } else if (status == NetConnectionStatus.Disconnected) { FLLog.Info("Lidgren", im.SenderEndPoint.ToString() + " disconnected"); if (im.SenderConnection.Tag is Player player) { player.Disconnected(); lock (game.ConnectedPlayers) { game.ConnectedPlayers.Remove(player); } } } NetServer.Recycle(im); break; case NetIncomingMessageType.Data: IPacket pkt; try { pkt = im.ReadPacket(); } catch (Exception) { pkt = null; im.SenderConnection.Disconnect("Malformed Packet"); if (im.SenderConnection.Tag is Player) { ((Player)im.SenderConnection.Tag).Disconnected(); } } if (pkt != null) { if (im.SenderConnection.Tag == TagConnecting) { if (pkt is AuthenticationReplyPacket) { var auth = (AuthenticationReplyPacket)pkt; var p = new Player(new RemotePacketClient(im.SenderConnection, NetServer), game, auth.Guid); im.SenderConnection.Tag = p; Task.Run(() => p.DoAuthSuccess()); lock (game.ConnectedPlayers) { game.ConnectedPlayers.Add(p); } } else { im.SenderConnection.Disconnect("Invalid Packet"); } NetServer.Recycle(im); } else { var player = (Player)im.SenderConnection.Tag; Task.Run(() => player.ProcessPacket(pkt)); NetServer.Recycle(im); } } break; } } Thread.Sleep(0); //Reduce CPU load } NetServer.Shutdown("Shutdown"); }
public virtual void Run(ThnScriptInstance instance) { FLLog.Error("Thn", $"({Time}): Unimplemented event: {Type}"); }
void ProcessAttachEntity(ThnEvent ev) { object tmp; if (!Objects.ContainsKey((string)ev.Targets[0])) { FLLog.Error("Thn", "Object doesn't exist " + (string)ev.Targets[0]); return; } var objA = Objects[(string)ev.Targets[0]]; var objB = Objects[(string)ev.Targets[1]]; var targetType = ThnEnum.Check <TargetTypes>(ev.Properties["target_type"]); var flags = AttachFlags.Position | AttachFlags.Orientation; Vector3 offset; if (ev.Properties.TryGetValue("flags", out tmp)) { flags = ThnEnum.Check <AttachFlags>(tmp); } ev.Properties.TryGetVector3("offset", out offset); //Attach GameObjects to eachother if (objA.Object != null && objB.Object != null) { if (targetType == TargetTypes.Hardpoint) { var targetHp = ev.Properties["target_part"].ToString(); if (!objB.Object.HardpointExists(targetHp)) { FLLog.Error("Thn", "object " + objB.Name + " does not have hardpoint " + targetHp); return; } var hp = objB.Object.GetHardpoint(targetHp); objA.Object.Attachment = hp; objA.Object.Parent = objB.Object; objA.Object.Transform = Matrix4.CreateTranslation(offset); } else if (targetType == TargetTypes.Root) { objA.Object.Transform = Matrix4.CreateTranslation(offset); objA.Object.Parent = objB.Object; } } //Attach GameObjects and Cameras to eachother if (objA.Object != null && objB.Camera != null) { } if (objA.Camera != null && objB.Object != null) { if ((flags & AttachFlags.LookAt) == AttachFlags.LookAt) { objA.Camera.LookAt = objB.Object; } GameObject part = null; if (targetType == TargetTypes.Hardpoint) { part = new GameObject(); part.Parent = objB.Object; part.Attachment = objB.Object.GetHardpoint(ev.Properties["target_part"].ToString()); } if (targetType == TargetTypes.Part) { var hp = new Hardpoint(null, part.CmpConstructs.Find(ev.Properties["target_part"].ToString())); //Create a dummy hardpoint to attach to part = new GameObject(); part.Parent = objB.Object; part.Attachment = hp; } coroutines.Add(new AttachCameraToObject() { Duration = ev.Duration, Camera = objA.Camera, Object = objB.Object, Part = part, Position = ((flags & AttachFlags.Position) == AttachFlags.Position), Orientation = ((flags & AttachFlags.Orientation) == AttachFlags.Orientation), LookAt = ((flags & AttachFlags.LookAt) == AttachFlags.LookAt) }); } }
void ProcessStartLightPropAnim(ThnEvent ev) { FLLog.Error("Thn", "Unimplemented event StartLightPropAnim"); }
internal unsafe void AddCharacter(GlyphCollection col, uint cp) { if (cp == (uint)'\t') { var spaceGlyph = col.GetGlyph((uint)' '); col.glyphs.Add(cp, new GlyphInfo(spaceGlyph.AdvanceX * 4, spaceGlyph.AdvanceY, spaceGlyph.CharIndex, spaceGlyph.Kerning)); } Face.SetCharSize(0, col.Size, 0, 96); var c_face = Face; bool dobold = emulate_bold; bool doitalics = emulate_italics; bool dokern = true; uint index = c_face.GetCharIndex(cp); if (index == 0) { //Glyph does not exist in font if (cp == (uint)'?') { throw new Exception("Font does not have required ASCII character '?'"); } var fallback = Platform.GetFallbackFace(ren.FT, cp); if ((index = fallback.GetCharIndex(cp)) != 0) { try { c_face = fallback; c_face.SetCharSize(0, col.Size, 0, 96); dobold = doitalics = dokern = false; } catch (Exception) { var qmGlyph = col.GetGlyph((uint)'?'); col.glyphs.Add(cp, qmGlyph); return; } } else { var qmGlyph = col.GetGlyph((uint)'?'); col.glyphs.Add(cp, qmGlyph); return; } } c_face.LoadGlyph(index, LoadFlags.Default | LoadFlags.ForceAutohint, LoadTarget.Normal); if (dobold) { //Automatically determine a strength var strength = (c_face.UnitsPerEM * c_face.Size.Metrics.ScaleY.Value) / 0x10000; strength /= 24; c_face.Glyph.Outline.Embolden(Fixed26Dot6.FromRawValue(strength)); } if (doitalics) { c_face.Glyph.Outline.Transform(new FTMatrix(0x10000, 0x0366A, 0x00000, 0x10000)); } c_face.Glyph.RenderGlyph(RenderMode.Normal); if (c_face.Glyph.Bitmap.Width == 0 || c_face.Glyph.Bitmap.Rows == 0) { col.glyphs.Add(cp, new GlyphInfo( (int)Math.Ceiling((float)c_face.Glyph.Advance.X), (int)Math.Ceiling((float)c_face.Glyph.Advance.Y), index, dokern && Face.HasKerning ) ); } else { if (c_face.Glyph.Bitmap.PixelMode != PixelMode.Gray) { throw new NotImplementedException(); } if (currentX + c_face.Glyph.Bitmap.Width > TEXTURE_SIZE) { currentX = 0; currentY += lineMax; lineMax = 0; } if (currentY + c_face.Glyph.Bitmap.Rows > TEXTURE_SIZE) { currentX = 0; currentY = 0; lineMax = 0; textures.Add(new Texture2D( TEXTURE_SIZE, TEXTURE_SIZE, false, SurfaceFormat.R8 )); FLLog.Debug("Text", string.Format("{0}@{1}, New Texture", facename, col.Size)); } lineMax = (int)Math.Max(lineMax, c_face.Glyph.Bitmap.Rows); var rect = new Rectangle( currentX, currentY, c_face.Glyph.Bitmap.Width, c_face.Glyph.Bitmap.Rows ); var tex = textures [textures.Count - 1]; GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 1); //Set tex.SetData(0, rect, c_face.Glyph.Bitmap.Buffer); GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 4); currentX += c_face.Glyph.Bitmap.Width; col.glyphs.Add( cp, new GlyphInfo( tex, rect, (int)Math.Ceiling((float)c_face.Glyph.Advance.X), (int)Math.Ceiling((float)c_face.Glyph.Advance.Y), (int)Math.Ceiling((float)c_face.Glyph.Metrics.HorizontalAdvance), c_face.Glyph.BitmapLeft, c_face.Glyph.BitmapTop, index, dokern && Face.HasKerning ) ); } }
public SpaceGameplay(FreelancerGame g, GameSession session) : base(g) { FLLog.Info("Game", "Starting Gameplay Demo"); sys = g.GameData.GetSystem(session.PlayerSystem); var shp = g.GameData.GetShip(session.PlayerShip); //Set up player object + camera this.session = session; player = new GameObject(shp.Drawable, g.ResourceManager, false); control = new ShipControlComponent(player); control.Ship = shp; player.Components.Add(control); powerCore = new PowerCoreComponent(player) { ThrustCapacity = 1000, ThrustChargeRate = 100 }; player.Components.Add(powerCore); player.PhysicsComponent.Position = session.PlayerPosition; player.PhysicsComponent.Orientation = session.PlayerOrientation; player.PhysicsComponent.Material.Restitution = 1; player.PhysicsComponent.Mass = shp.Mass; player.Nickname = "player"; foreach (var equipment in session.MountedEquipment) { var equip = g.GameData.GetEquipment(equipment.Value); var obj = new GameObject(equip, player.GetHardpoint(equipment.Key), player); player.Children.Add(obj); } camera = new ChaseCamera(Game.Viewport); camera.ChasePosition = session.PlayerPosition; camera.ChaseOrientation = new Matrix4(player.PhysicsComponent.Orientation); camera.Reset(); sysrender = new SystemRenderer(camera, g.GameData, g.ResourceManager, g); world = new GameWorld(sysrender); world.LoadSystem(sys, g.ResourceManager); world.Objects.Add(player); world.Physics.SetDampingFactors(0.01f, 1f); world.RenderUpdate += World_RenderUpdate; world.PhysicsUpdate += World_PhysicsUpdate; var eng = new GameData.Items.Engine() { FireEffect = "gf_li_smallengine02_fire", LinearDrag = 600, MaxForce = 48000 }; player.Components.Add((ecpt = new EngineComponent(player, eng, g))); ecpt.Speed = 0; player.Register(sysrender, world.Physics); g.Sound.PlayMusic(sys.MusicSpace); trender = new Renderer2D(Game.RenderState); font = g.Fonts.GetSystemFont("Agency FB"); g.Keyboard.TextInput += G_Keyboard_TextInput; debugphysics = new PhysicsDebugRenderer(); cur_arrow = g.ResourceManager.GetCursor("cross"); cur_reticle = g.ResourceManager.GetCursor("fire_neutral"); current_cur = cur_arrow; hud = new Hud(g); hud.SetManeuver("FreeFlight"); Game.Keyboard.TextInput += Game_TextInput; g.Keyboard.KeyDown += Keyboard_KeyDown; input = new InputManager(Game); input.ToggleActivated += Input_ToggleActivated; input.ToggleUp += Input_ToggleUp; hud.OnManeuverSelected += Hud_OnManeuverSelected; hud.OnEntered += Hud_OnTextEntry; pilotcomponent = new AutopilotComponent(player); pilotcomponent.DockComplete += Pilotcomponent_DockComplete; player.Components.Add(pilotcomponent); player.World = world; world.MessageBroadcasted += World_MessageBroadcasted; }
public void HandlePacket(IPacket pkt) { if (!(pkt is ObjectUpdatePacket)) { FLLog.Debug("Client", "Got packet of type " + pkt.GetType()); } switch (pkt) { case CallThornPacket ct: AddGameplayAction(gp => { var thn = new ThnScript(Game.GameData.ResolveDataPath(ct.Thorn)); gp.Thn = new Cutscene(new ThnScript[] { thn }, gp); }); break; case AddRTCPacket rtc: AddRTC(rtc.RTC); break; case MsnDialogPacket msndlg: AddGameplayAction(gp => { RunDialog(msndlg.Lines); }); break; case PlaySoundPacket psnd: PlaySound(psnd.Sound); break; case PlayMusicPacket mus: PlayMusic(mus.Music); break; case SpawnPlayerPacket p: PlayerBase = null; PlayerSystem = p.System; PlayerPosition = p.Position; PlayerOrientation = Matrix4x4.CreateFromQuaternion(p.Orientation); SetSelfLoadout(p.Ship); SceneChangeRequired(); break; case BaseEnterPacket b: PlayerBase = b.Base; SetSelfLoadout(b.Ship); SceneChangeRequired(); break; case SpawnObjectPacket p: var shp = Game.GameData.GetShip((int)p.Loadout.ShipCRC); //Set up player object + camera var newobj = new GameObject(shp, Game.ResourceManager); newobj.Name = "NetPlayer " + p.ID; newobj.Transform = Matrix4x4.CreateFromQuaternion(p.Orientation) * Matrix4x4.CreateTranslation(p.Position); objects.Add(p.ID, newobj); if (worldReady) { gp.world.Objects.Add(newobj); } else { toAdd.Add(newobj); } break; case ObjectUpdatePacket p: foreach (var update in p.Updates) { UpdateObject(update); } break; case DespawnObjectPacket p: var despawn = objects[p.ID]; if (worldReady) { gp.world.Objects.Remove(despawn); } else { toAdd.Remove(despawn); } objects.Remove(p.ID); break; default: if (ExtraPackets != null) { ExtraPackets(pkt); } else { FLLog.Error("Network", "Unknown packet type " + pkt.GetType().ToString()); } break; } }
void NetThread() { FLLog.Info("Server", "Loading Game Data..."); GameData.LoadData(); FLLog.Info("Server", "Finished Loading Game Data"); Database = new ServerDatabase(DbConnectionString); var netconf = new NetPeerConfiguration(AppIdentifier); netconf.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); netconf.EnableMessageType(NetIncomingMessageType.ConnectionApproval); netconf.EnableMessageType(NetIncomingMessageType.UnconnectedData); netconf.Port = Port; netconf.MaximumConnections = 200; NetServer = new NetServer(netconf); NetServer.Start(); FLLog.Info("Server", "Listening on port " + Port); NetIncomingMessage im; while (running) { while ((im = NetServer.ReadMessage()) != null) { switch (im.MessageType) { case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.ErrorMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.VerboseDebugMessage: FLLog.Info("Lidgren", im.ReadString()); NetServer.Recycle(im); break; case NetIncomingMessageType.ConnectionApproval: //Ban IP? im.SenderConnection.Approve(); NetServer.Recycle(im); break; case NetIncomingMessageType.DiscoveryRequest: NetOutgoingMessage dresp = NetServer.CreateMessage(); //Include Server Data dresp.Write(ServerName); dresp.Write(ServerDescription); dresp.Write(GameData.DataVersion); dresp.Write(NetServer.ConnectionsCount); dresp.Write(NetServer.Configuration.MaximumConnections); //Send off NetServer.SendDiscoveryResponse(dresp, im.SenderEndPoint); NetServer.Recycle(im); break; case NetIncomingMessageType.UnconnectedData: //Respond to pings try { if (im.ReadUInt32() == NetConstants.PING_MAGIC) { var om = NetServer.CreateMessage(); om.Write(NetConstants.PING_MAGIC); NetServer.SendUnconnectedMessage(om, im.SenderEndPoint); } } catch (Exception) { } break; case NetIncomingMessageType.StatusChanged: NetConnectionStatus status = (NetConnectionStatus)im.ReadByte(); string reason = im.ReadString(); FLLog.Info("Lidgren", NetUtility.ToHexString(im.SenderConnection.RemoteUniqueIdentifier) + " " + status + ": " + reason); if (status == NetConnectionStatus.Connected) { FLLog.Info("Lidgren", "Remote hail: " + im.SenderConnection.RemoteHailMessage.ReadString()); BeginAuthentication(NetServer, im.SenderConnection); } else if (status == NetConnectionStatus.Disconnected) { FLLog.Info("Lidgren", im.SenderEndPoint.ToString() + " disconnected"); if (im.SenderConnection.Tag is NetPlayer) { ((NetPlayer)im.SenderConnection.Tag).Disconnected(); } } NetServer.Recycle(im); break; case NetIncomingMessageType.Data: var pkt = im.ReadPacket(); if (im.SenderConnection.Tag == TagConnecting) { if (pkt is AuthenticationReplyPacket) { var auth = (AuthenticationReplyPacket)pkt; //im.SenderConnection.Disconnect("boilerplate reason from server"); /* * var authkind = (AuthenticationKind)im.ReadByte(); * var guid = new Guid(im.ReadBytes(16)); * if (guid == Guid.Empty) im.SenderConnection.Disconnect("Invalid UUID"); * FLLog.Info("Lidgren", "GUID for " + im.SenderEndPoint + " = " + guid.ToString()); * var p = new NetPlayer(im.SenderConnection, this, guid); * im.SenderConnection.Tag = p; * AsyncManager.RunTask(() => p.DoAuthSuccess());*/ var p = new NetPlayer(im.SenderConnection, this, auth.Guid); im.SenderConnection.Tag = p; AsyncManager.RunTask(() => p.DoAuthSuccess()); } else { im.SenderConnection.Disconnect("Invalid Packet"); } NetServer.Recycle(im); } else { var player = (NetPlayer)im.SenderConnection.Tag; AsyncManager.RunTask(() => player.ProcessPacket(pkt)); NetServer.Recycle(im); } break; } } Thread.Sleep(0); //Reduce CPU load } NetServer.Shutdown("Shutdown"); Database.Dispose(); }
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; } } }
void DoTrigger(int i, SpaceGameplay gameplay) { active[i] = true; var tr = msn.Triggers[i]; if (!CheckConditions(tr)) { return; } FLLog.Debug("Mission", "Running trigger " + tr.Nickname); if (timers.ContainsKey(tr.Nickname)) { timers.Remove(tr.Nickname); } triggered[i] = true; foreach (var act in tr.Actions) { switch (act.Type) { case TriggerActions.Act_ActTrig: var trname = act.Entry[0].ToString(); for (int j = 0; j < msn.Triggers.Count; j++) { if (trname.Equals(msn.Triggers[j].Nickname, StringComparison.OrdinalIgnoreCase)) { DoTrigger(j, gameplay); break; } } break; case TriggerActions.Act_PlaySoundEffect: session.Game.Sound.PlaySound(act.Entry[0].ToString()); break; case TriggerActions.Act_ForceLand: session.ForceLand(act.Entry[0].ToString()); break; case TriggerActions.Act_AdjAcct: session.Credits += act.Entry[0].ToInt32(); break; case TriggerActions.Act_SpawnSolar: SpawnSolar(act.Entry[0].ToString(), gameplay.world); break; case TriggerActions.Act_StartDialog: RunDialog(msn.Dialogs.First((x) => x.Nickname.Equals(act.Entry[0].ToString(), StringComparison.OrdinalIgnoreCase))); break; case TriggerActions.Act_MovePlayer: gameplay.player.Transform = Matrix4.CreateTranslation(act.Entry[0].ToSingle(), act.Entry[1].ToSingle(), act.Entry[2].ToSingle()); //last param seems to always be one? break; case TriggerActions.Act_LightFuse: var fuse = session.Game.GameData.GetFuse(act.Entry[1].ToString()); var gameObj = gameplay.world.GetObject(act.Entry[0].ToString()); var fzr = new FuseRunnerComponent(gameObj) { Fuse = fuse }; gameObj.Components.Add(fzr); fzr.Run(); break; case TriggerActions.Act_PlayMusic: session.Game.Sound.PlayMusic(act.Entry[3].ToString()); break; case TriggerActions.Act_CallThorn: var thn = new ThnScript(gameplay.FlGame.GameData.ResolveDataPath(act.Entry[0].ToString())); gameplay.Thn = new Cutscene(new ThnScript[] { thn }, gameplay); break; case TriggerActions.Act_SetShipAndLoadout: if (!act.Entry[0].ToString().Equals("none", StringComparison.OrdinalIgnoreCase)) { var loadout = session.Game.GameData.Ini.Loadouts.FindLoadout(act.Entry[1].ToString()); if (loadout != null) { session.PlayerShip = act.Entry[0].ToString(); session.Mounts = new List <EquipMount>(); foreach (var equip in loadout.Equip) { if (equip.Value == null) { continue; } var hp = equip.Key.StartsWith("__noHardpoint") ? null : equip.Key; session.Mounts.Add(new EquipMount(hp, equip.Value)); } } } break; } } }
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"); }
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); Audio.MasterVolume = _cfg.MasterVolume; Audio.Music.Volume = _cfg.MusicVolume; //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); Services.Add(Sound); FLLog.Info("Game", "Finished loading game data"); InitialLoadComplete = true; }); GameDataLoaderThread.Name = "GamedataLoader"; GameDataLoaderThread.Start(); // Renderer2D = new Renderer2D(RenderState); Fonts = new FontManager(); Billboards = new Billboards(); Nebulae = new NebulaVertices(); ViewportManager = new ViewportManager(RenderState); ViewportManager.Push(0, 0, Width, Height); Screenshots = new ScreenshotManager(this); Typewriter = new Typewriter(this); Services.Add(Billboards); Services.Add(Nebulae); Services.Add(ResourceManager); Services.Add(Renderer2D); Services.Add(Config); Services.Add(Fonts); Services.Add(GameData); Services.Add(Sound); Services.Add(Typewriter); if (useintromovies && IntroMovies.Count > 0) { ChangeState(new IntroMovie(this, 0)); } else { ChangeState(new LoadingDataState(this)); } }
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(); }
public GameData.Nebula GetNebula(GameData.StarSystem sys, Legacy.Universe.Nebula nbl) { var n = new GameData.Nebula(); n.Zone = sys.Zones.Where((z) => z.Nickname.ToLower() == nbl.ZoneName.ToLower()).First(); var panels = new Legacy.Universe.TexturePanels(nbl.TexturePanels.Files[0]); foreach (var txmfile in panels.Files) { resource.LoadTxm(Compatibility.VFS.GetPath(fldata.Freelancer.DataPath + txmfile)); } n.ExteriorFill = nbl.ExteriorFillShape; n.ExteriorColor = nbl.ExteriorColor ?? Color4.White; n.FogColor = nbl.FogColor ?? Color4.Black; n.FogEnabled = (nbl.FogEnabled ?? 0) != 0; n.FogRange = new Vector2(nbl.FogNear ?? 0, nbl.FogDistance ?? 0); n.SunBurnthroughScale = n.SunBurnthroughIntensity = 1f; if (nbl.NebulaLights != null && nbl.NebulaLights.Count > 0) { n.AmbientColor = nbl.NebulaLights[0].Ambient; n.SunBurnthroughScale = nbl.NebulaLights[0].SunBurnthroughScaler ?? 1f; n.SunBurnthroughIntensity = nbl.NebulaLights[0].SunBurnthroughIntensity ?? 1f; } if (nbl.CloudsPuffShape != null) { n.HasInteriorClouds = true; GameData.CloudShape[] shapes = new GameData.CloudShape[nbl.CloudsPuffShape.Count]; for (int i = 0; i < shapes.Length; i++) { var name = nbl.CloudsPuffShape[i]; if (!panels.Shapes.ContainsKey(name)) { FLLog.Error("Nebula", "Shape " + name + " does not exist in " + nbl.TexturePanels.Files[0]); shapes[i].Texture = ResourceManager.NullTextureName; shapes[i].Dimensions = new RectangleF(0, 0, 1, 1); } else { shapes[i].Texture = panels.Shapes[name].TextureName; shapes[i].Dimensions = panels.Shapes[name].Dimensions; } } n.InteriorCloudShapes = new WeightedRandomCollection <GameData.CloudShape>( shapes, nbl.CloudsPuffWeights.ToArray() ); n.InteriorCloudColorA = nbl.CloudsPuffColorA.Value; n.InteriorCloudColorB = nbl.CloudsPuffColorB.Value; n.InteriorCloudRadius = nbl.CloudsPuffRadius.Value; n.InteriorCloudCount = nbl.CloudsPuffCount.Value; n.InteriorCloudMaxDistance = nbl.CloudsMaxDistance.Value; n.InteriorCloudMaxAlpha = nbl.CloudsPuffMaxAlpha ?? 1f; n.InteriorCloudFadeDistance = nbl.CloudsNearFadeDistance.Value; n.InteriorCloudDrift = nbl.CloudsPuffDrift.Value; } if (nbl.ExteriorShape != null) { n.HasExteriorBits = true; GameData.CloudShape[] shapes = new GameData.CloudShape[nbl.ExteriorShape.Count]; for (int i = 0; i < shapes.Length; i++) { var name = nbl.ExteriorShape[i]; if (!panels.Shapes.ContainsKey(name)) { FLLog.Error("Nebula", "Shape " + name + " does not exist in " + nbl.TexturePanels.Files[0]); shapes[i].Texture = ResourceManager.NullTextureName; shapes[i].Dimensions = new RectangleF(0, 0, 1, 1); } else { shapes[i].Texture = panels.Shapes[name].TextureName; shapes[i].Dimensions = panels.Shapes[name].Dimensions; } } n.ExteriorCloudShapes = new WeightedRandomCollection <GameData.CloudShape>( shapes, nbl.ExteriorShapeWeights.ToArray() ); n.ExteriorMinBits = nbl.ExteriorMinBits.Value; n.ExteriorMaxBits = nbl.ExteriorMaxBits.Value; n.ExteriorBitRadius = nbl.ExteriorBitRadius.Value; n.ExteriorBitRandomVariation = nbl.ExteriorBitRadiusRandomVariation ?? 0; n.ExteriorMoveBitPercent = nbl.ExteriorMoveBitPercent ?? 0; } if (nbl.ExclusionZones != null) { n.ExclusionZones = new List <GameData.ExclusionZone>(); foreach (var excz in nbl.ExclusionZones) { if (excz.Exclusion == null) { continue; } var e = new GameData.ExclusionZone(); e.Zone = sys.Zones.Where((z) => z.Nickname.ToLower() == excz.Exclusion.Nickname.ToLower()).First(); e.FogFar = excz.FogFar ?? n.FogRange.Y; if (excz.ZoneShellPath != null) { var pth = Compatibility.VFS.GetPath(fldata.Freelancer.DataPath + excz.ZoneShellPath); e.Shell = resource.GetDrawable(pth); e.ShellTint = excz.Tint ?? Color3f.White; e.ShellScalar = excz.ShellScalar ?? 1f; e.ShellMaxAlpha = excz.MaxAlpha ?? 1f; } n.ExclusionZones.Add(e); } } if (nbl.BackgroundLightningDuration != null) { n.BackgroundLightning = true; n.BackgroundLightningDuration = nbl.BackgroundLightningDuration.Value; n.BackgroundLightningColor = nbl.BackgroundLightningColor.Value; n.BackgroundLightningGap = nbl.BackgroundLightningGap.Value; } if (nbl.DynamicLightningDuration != null) { n.DynamicLightning = true; n.DynamicLightningGap = nbl.DynamicLightningGap.Value; n.DynamicLightningColor = nbl.DynamicLightningColor.Value; n.DynamicLightningDuration = nbl.DynamicLightningDuration.Value; } if (nbl.CloudsLightningDuration != null) { n.CloudLightning = true; n.CloudLightningDuration = nbl.CloudsLightningDuration.Value; n.CloudLightningColor = nbl.CloudsLightningColor.Value; n.CloudLightningGap = nbl.CloudsLightningGap.Value; n.CloudLightningIntensity = nbl.CloudsLightningIntensity.Value; } return(n); }