private static bool MapLibraryName(string assemblyLocation, string originalLibName, out string mappedLibName)
        {
            mappedLibName = null;
            if (mapped.TryGetValue(originalLibName, out mappedLibName))
            {
                return(true);
            }
            string xmlPath = assemblyLocation + ".config";

            if (!File.Exists(xmlPath))
            {
                return(TryFind(assemblyLocation, originalLibName, out mappedLibName));
            }
            FLLog.Debug("DllMap", xmlPath);
            XElement root = XElement.Load(xmlPath);
            var      map  =
                (from el in root.Elements("dllmap")
                 where ((string)el.Attribute("dll") == originalLibName) && ((string)el.Attribute("os") == "linux")
                 select el).SingleOrDefault();

            if (map != null)
            {
                mappedLibName = map.Attribute("target").Value;
                mapped.Add(originalLibName, mappedLibName);
            }

            return(mappedLibName != null);
        }
        public void LoadSound(string name)
        {
            if (loadedSounds.ContainsKey(name))
            {
                return;
            }
            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;
            }
            AddLoaded(loaded);
        }
Beispiel #3
0
 public override void Update(double delta)
 {
     session.Update();
     ProcessCutscenes();
     if (scene != null)
     {
         scene.UpdateViewport(Game.RenderContext.CurrentViewport);
         if (paused)
         {
             scene.Update(0);
         }
         else
         {
             scene.Update(firstFrame ? 0 : delta);
         }
     }
     firstFrame = false;
     if (!firstFrame)
     {
         if (session.Popups.Count > 0 && session.Popups.TryDequeue(out var popup))
         {
             FLLog.Debug("Room", "Displaying popup");
             ui.Event("Popup", popup.Title, popup.Contents, popup.ID);
         }
     }
     ui.Update(Game);
     if (ui.KeyboardGrabbed)
     {
         Game.EnableTextInput();
     }
     else
     {
         Game.DisableTextInput();
     }
 }
Beispiel #4
0
        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 + "#define VERTEX_SHADER\n" + ProcessIncludes(Resources.LoadString("LibreLancer.Shaders." + vs)),
                        prelude + "#define FRAGMENT_SHADER\n" + ProcessIncludes(Resources.LoadString("LibreLancer.Shaders." + fs)))
                    );
                shaders.Add(k, sh);
            }
            return(sh);
        }
 public override void Update(double delta)
 {
     if (loading)
     {
         if (loader.Update(delta))
         {
             loading = false;
             loader  = null;
             FinishLoad();
         }
         return;
     }
     session.GameplayUpdate(this);
     if (session.Update())
     {
         return;
     }
     if (ShowHud && (Thn == null || !Thn.Running))
     {
         ui.Update(Game);
     }
     if (ui.KeyboardGrabbed)
     {
         Game.EnableTextInput();
     }
     else
     {
         Game.DisableTextInput();
     }
     world.Update(paused ? 0 : delta);
     if (Thn != null && Thn.Running)
     {
         sysrender.Camera = Thn.CameraHandle;
     }
     else
     {
         sysrender.Camera = camera;
     }
     if (frameCount < 2)
     {
         frameCount++;
         if (frameCount == 2)
         {
             session.BeginUpdateProcess();
         }
     }
     else
     {
         if (session.Popups.Count > 0 && session.Popups.TryDequeue(out var popup))
         {
             FLLog.Debug("Space", "Displaying popup");
             if (!session.Multiplayer)
             {
                 paused = true;
             }
             session.Pause();
             ui.Event("Popup", popup.Title, popup.Contents, popup.ID);
         }
     }
 }
Beispiel #6
0
        public override Texture FindTexture(string name)
        {
            if (name == NullTextureName)
            {
                return(NullTexture);
            }
            if (name == WhiteTextureName)
            {
                return(WhiteTexture);
            }
            Texture outtex;

            if (!textures.TryGetValue(name, out outtex))
            {
                return(null);
            }
            if (outtex == null)
            {
                var file = texturefiles[name];
                FLLog.Debug("Resources", string.Format("Reloading {0} from {1}", name, file));
                LoadResourceFile(file);
                outtex = textures[name];
            }
            return(outtex);
        }
 void DoTrigger(ScriptedTrigger tr)
 {
     FLLog.Debug("Mission", "Running trigger " + tr.Nickname);
     foreach (var act in tr.Actions)
     {
         act.Invoke(this, Script);
     }
 }
        public Texture FindTexture(string name)
        {
            if (name == NullTextureName)
            {
                return(NullTexture);
            }
            if (name == WhiteTextureName)
            {
                return(WhiteTexture);
            }
            Texture outtex;

            if ((outtex = textures[name]) == null)
            {
                var file = texturefiles[name];
                FLLog.Debug("Resources", string.Format("Reloading {0} from {1}", name, file));
                if (file.EndsWith(".mat", StringComparison.OrdinalIgnoreCase))
                {
                    loadedMatFiles.Remove(file);
                    LoadMat(file);
                }
                else if (file.EndsWith(".cmp", StringComparison.OrdinalIgnoreCase))
                {
                    var c = new CmpFile(file, this);
                    if (c.MaterialLibrary != null)
                    {
                        AddMaterials(c.MaterialLibrary, file);
                    }
                    AddTextures(c.TextureLibrary, file);
                }
                else if (file.EndsWith(".3db", StringComparison.OrdinalIgnoreCase))
                {
                    var m = new ModelFile(file, this);
                    if (m.MaterialLibrary != null)
                    {
                        AddMaterials(m.MaterialLibrary, file);
                    }
                    AddTextures(m.TextureLibrary, file);
                }
                else if (file.EndsWith(".txm", StringComparison.OrdinalIgnoreCase))
                {
                    loadedTxmFiles.Remove(file);
                    LoadTxm(file);
                }
                else
                {
                    textures[name] = ImageLib.Generic.FromFile(file);
                }
                outtex = textures[name];
            }
            return(outtex);
        }
 public void Allocate(T[] vertices, ushort[] indices, out VertexBuffer vbo, out int startIndex, out int baseVertex, out IndexResourceHandle index)
 {
     foreach (var buf in buffers)
     {
         if (buf.Allocate(vertices, indices, out startIndex, out baseVertex, out index))
         {
             vbo = buf.Buffer;
             return;
         }
     }
     FLLog.Debug("Vertices", "Allocating 16MiB for " + typeof(T).Name);
     buffers.Add(new VertexResourceBuffer <T>());
     buffers[buffers.Count - 1].Allocate(vertices, indices, out startIndex, out baseVertex, out index);
     vbo = buffers[buffers.Count - 1].Buffer;
 }
Beispiel #10
0
        //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.GetString(GL.GL_EXTENSIONS, i));
            }
            FLLog.Debug("GL", "Extensions: \n" + string.Join("\n", ExtensionList));
        }
Beispiel #11
0
        //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.GetString(GL.GL_EXTENSIONS, i));
            }
            var versionStr = GL.GetString(GL.GL_VERSION).Trim();

            versionInteger = int.Parse(versionStr[0].ToString()) * 100 + int.Parse(versionStr[2].ToString()) * 10;
            FLLog.Debug("GL", "Extensions: \n" + string.Join("\n", ExtensionList));
        }
Beispiel #12
0
        public string Get(string val)
        {
            //Evaluate bottom to top
            for (int i = regexmaps.Count - 1; i >= 0; i--)
            {
                if (regexmaps [i].Regex.IsMatch(val))
                {
                    FLLog.Debug("MaterialMap", "Matched " + val + " to " + regexmaps [i].Value);
                    return(regexmaps [i].Value);
                }
            }

            if (maps.ContainsKey(val))
            {
                FLLog.Debug("MaterialMap", "Matched " + val + " to " + maps [val]);
                return(maps [val]);
            }

            return(null);
        }
        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;
                if (h.Sound.Data != null)
                {
                    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;
        }
Beispiel #14
0
 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!");
     }
 }
Beispiel #15
0
        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 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;
            }
        }
Beispiel #17
0
        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
                        )
                    );
            }
        }
Beispiel #18
0
        public void HandlePacket(IPacket pkt)
        {
            if (!(pkt is ObjectUpdatePacket))
            {
                FLLog.Debug("Client", "Got packet of type " + pkt.GetType());
            }
            switch (pkt)
            {
            case CallThornPacket ct:
                RunSync(() => {
                    var thn = new ThnScript(Game.GameData.ResolveDataPath(ct.Thorn));
                    gp.Thn  = new Cutscene(new ThnScript[] { thn }, gp);
                });
                break;

            case UpdateRTCPacket rtc:
                AddRTC(rtc.RTCs);
                break;

            case MsnDialogPacket msndlg:
                RunSync(() => {
                    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();
                AddRTC(b.RTCs);
                break;

            case SpawnSolarPacket solar:
                RunSync(() =>
                {
                    foreach (var si in solar.Solars)
                    {
                        if (!objects.ContainsKey(si.ID))
                        {
                            var arch          = Game.GameData.GetSolarArchetype(si.Archetype);
                            var go            = new GameObject(arch, Game.ResourceManager, true);
                            go.StaticPosition = si.Position;
                            go.Transform      = Matrix4x4.CreateFromQuaternion(si.Orientation) *
                                                Matrix4x4.CreateTranslation(si.Position);
                            go.Nickname = $"$Solar{si.ID}";
                            go.World    = gp.world;
                            go.Register(go.World.Physics);
                            go.CollisionGroups = arch.CollisionGroups;
                            FLLog.Debug("Client", $"Spawning object {si.ID}");
                            gp.world.Objects.Add(go);
                            objects.Add(si.ID, go);
                        }
                    }
                });
                break;

            case DestroyPartPacket p:
                RunSync(() =>
                {
                    objects[p.ID].DisableCmpPart(p.PartName);
                });
                break;

            case SpawnDebrisPacket p:
                RunSync(() =>
                {
                    var arch = Game.GameData.GetSolarArchetype(p.Archetype);
                    var mdl  =
                        ((IRigidModelFile)arch.ModelFile.LoadFile(Game.ResourceManager)).CreateRigidModel(true);
                    var newpart  = mdl.Parts[p.Part].Clone();
                    var newmodel = new RigidModel()
                    {
                        Root          = newpart,
                        AllParts      = new[] { newpart },
                        MaterialAnims = mdl.MaterialAnims,
                        Path          = mdl.Path,
                    };
                    var go       = new GameObject($"debris{p.ID}", newmodel, Game.ResourceManager, p.Part, p.Mass, true);
                    go.Transform = Matrix4x4.CreateFromQuaternion(p.Orientation) *
                                   Matrix4x4.CreateTranslation(p.Position);
                    go.World = gp.world;
                    go.Register(go.World.Physics);
                    gp.world.Objects.Add(go);
                    objects.Add(p.ID, go);
                });
                break;

            case SpawnObjectPacket p:
                RunSync(() =>
                {
                    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);
                    if (connection is GameNetClient)
                    {
                        newobj.Components.Add(new CNetPositionComponent(newobj));
                    }
                    objects.Add(p.ID, newobj);
                    gp.world.Objects.Add(newobj);
                });
                break;

            case ObjectUpdatePacket p:
                RunSync(() =>
                {
                    foreach (var update in p.Updates)
                    {
                        UpdateObject(p.Tick, update);
                    }
                });
                break;

            case DespawnObjectPacket p:
                RunSync(() =>
                {
                    var despawn = objects[p.ID];
                    gp.world.Objects.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 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;
                }
            }
        }
Beispiel #20
0
        void DoTrigger(int i)
        {
            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);
                            break;
                        }
                    }
                    break;

                case TriggerActions.Act_PlaySoundEffect:
                    player.PlaySound(act.Entry[0].ToString());
                    break;

                case TriggerActions.Act_ForceLand:
                    player.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(), player);
                    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:
                    player.WorldAction(() =>
                    {
                        var fuse    = player.World.Server.GameData.GetFuse(act.Entry[1].ToString());
                        var gameObj = player.World.GameWorld.GetObject(act.Entry[0].ToString());
                        var fzr     = new SFuseRunnerComponent(gameObj)
                        {
                            Fuse = fuse
                        };
                        gameObj.Components.Add(fzr);
                        fzr.Run();
                    });
                    break;

                case TriggerActions.Act_PlayMusic:
                    player.PlayMusic(act.Entry[3].ToString());
                    break;

                case TriggerActions.Act_CallThorn:
                    player.CallThorn(act.Entry[0].ToString());
                    break;

                case TriggerActions.Act_AddRTC:
                    player.AddRTC(act.Entry[0].ToString());
                    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;
                }
            }
        }