コード例 #1
0
        public override void Bad(string tagged_text, DebugMode mode)
        {
            string text = TheServer.Commands.CommandSystem.TagSystem.ParseTagsFromText(tagged_text, TextStyle.Color_Outbad, null, mode, (o) => { throw new Exception("Tag exception: " + o); }, true);

            SysConsole.Output(OutputType.WARNING, TextStyle.Color_Outbad + text);
        }
コード例 #2
0
 public UnturnedFreneticCommands(UnturnedFreneticMod mod, UnturnedFreneticOutputter output)
 {
     try
     {
         TheMod        = mod;
         System        = new Commands();
         output.Syst   = System;
         System.Output = output;
         System.Init();
         // Common Commands
         System.RegisterCommand(new AddCommandCommand());
         // Entity Commands
         System.RegisterCommand(new AICommand());
         System.RegisterCommand(new AnimateCommand());
         System.RegisterCommand(new DamageCommand());
         System.RegisterCommand(new HealCommand());
         System.RegisterCommand(new KillCommand());
         System.RegisterCommand(new LaunchCommand());
         System.RegisterCommand(new MaxHealthCommand());
         System.RegisterCommand(new PowerCommand());
         System.RegisterCommand(new RemoveCommand());
         System.RegisterCommand(new SpawnCommand());
         System.RegisterCommand(new TeleportCommand());
         System.RegisterCommand(new WalkCommand());
         // Player Commands
         System.RegisterCommand(new ExperienceCommand());
         System.RegisterCommand(new BleedingCommand());
         System.RegisterCommand(new BrokenCommand());
         System.RegisterCommand(new FoodCommand());
         System.RegisterCommand(new GiveCommand());
         System.RegisterCommand(new OxygenCommand());
         System.RegisterCommand(new StaminaCommand());
         System.RegisterCommand(new TakeCommand());
         System.RegisterCommand(new TellCommand());
         System.RegisterCommand(new UseItemCommand());
         System.RegisterCommand(new VirusCommand());
         System.RegisterCommand(new WarmthCommand());
         System.RegisterCommand(new WaterCommand());
         // World Commands
         System.RegisterCommand(new AnnounceCommand());
         System.RegisterCommand(new EffectCommand());
         System.RegisterCommand(new TimeCommand());
         // Tag Objects
         System.TagSystem.Register(new AnimalAssetTagBase());
         System.TagSystem.Register(new AnimalTagBase());
         System.TagSystem.Register(new BarricadeTagBase());
         System.TagSystem.Register(new ColorTagBase());
         System.TagSystem.Register(new EffectAssetTagBase());
         System.TagSystem.Register(new EntityTagBase());
         System.TagSystem.Register(new ItemAssetTagBase());
         System.TagSystem.Register(new ItemTagBase());
         System.TagSystem.Register(new LocationTagBase());
         System.TagSystem.Register(new OfflinePlayerTagBase());
         System.TagSystem.Register(new PlayerTagBase());
         System.TagSystem.Register(new ResourceAssetTagBase());
         System.TagSystem.Register(new ResourceTagBase());
         System.TagSystem.Register(new ServerTagBase());
         System.TagSystem.Register(new StructureTagBase());
         System.TagSystem.Register(new VehicleAssetTagBase());
         System.TagSystem.Register(new VehicleTagBase());
         System.TagSystem.Register(new WorldObjectAssetTagBase());
         System.TagSystem.Register(new WorldObjectTagBase());
         System.TagSystem.Register(new ZombieTagBase());
         // Events
         UnturnedFreneticEvents.RegisterAll(System);
         // Wrap up
         System.PostInit();
     }
     catch (Exception ex)
     {
         SysConsole.Output(OutputType.ERROR, "Error registering commands: " + ex.ToString());
     }
 }
コード例 #3
0
        public Model FromScene(Model3D scene, string name, AnimationEngine engine)
        {
            if (scene.Meshes.Count == 0)
            {
                throw new Exception("Scene has no meshes! (" + name + ")");
            }
            Model model = new Model(name);

            model.Engine   = this;
            model.Original = scene;
            model.Root     = convert(scene.MatrixA);
            foreach (Model3DMesh mesh in scene.Meshes)
            {
                if (mesh.Name.ToLowerFast().Contains("collision") || mesh.Name.ToLowerFast().Contains("norender"))
                {
                    continue;
                }
                ModelMesh modmesh = new ModelMesh(mesh.Name);
                modmesh.vbo.Prepare();
                bool hastc = mesh.TexCoords.Count == mesh.Vertices.Count;
                bool hasn  = mesh.Normals.Count == mesh.Vertices.Count;
                if (!hasn)
                {
                    SysConsole.Output(OutputType.WARNING, "Mesh has no normals! (" + name + ")");
                }
                if (!hastc)
                {
                    SysConsole.Output(OutputType.WARNING, "Mesh has no texcoords! (" + name + ")");
                }
                for (int i = 0; i < mesh.Vertices.Count; i++)
                {
                    BEPUutilities.Vector3 vertex = mesh.Vertices[i];
                    modmesh.vbo.Vertices.Add(new Vector3((float)vertex.X, (float)vertex.Y, (float)vertex.Z));
                    if (!hastc)
                    {
                        modmesh.vbo.TexCoords.Add(new Vector3(0, 0, 0));
                    }
                    else
                    {
                        BEPUutilities.Vector2 texCoord = mesh.TexCoords[i];
                        modmesh.vbo.TexCoords.Add(new Vector3((float)texCoord.X, 1 - (float)texCoord.Y, 0));
                    }
                    if (!hasn)
                    {
                        modmesh.vbo.Normals.Add(new Vector3(0, 0, 1));
                    }
                    else
                    {
                        modmesh.vbo.Normals.Add(new Vector3((float)mesh.Normals[i].X, (float)mesh.Normals[i].Y, (float)mesh.Normals[i].Z));
                    }
                    modmesh.vbo.Colors.Add(new Vector4(1, 1, 1, 1)); // TODO: From the mesh?
                }
                for (int i = 0; i < mesh.Indices.Count; i++)
                {
                    modmesh.vbo.Indices.Add((uint)mesh.Indices[i]);
                }
                int bc = mesh.Bones.Count;
                if (bc > 200)
                {
                    SysConsole.Output(OutputType.WARNING, "Mesh has " + bc + " bones! (" + name + ")");
                    bc = 200;
                }
                modmesh.vbo.BoneIDs      = new Vector4[modmesh.vbo.Vertices.Count].ToList();
                modmesh.vbo.BoneWeights  = new Vector4[modmesh.vbo.Vertices.Count].ToList();
                modmesh.vbo.BoneIDs2     = new Vector4[modmesh.vbo.Vertices.Count].ToList();
                modmesh.vbo.BoneWeights2 = new Vector4[modmesh.vbo.Vertices.Count].ToList();
                int[] pos = new int[modmesh.vbo.Vertices.Count];
                for (int i = 0; i < bc; i++)
                {
                    for (int x = 0; x < mesh.Bones[i].Weights.Count; x++)
                    {
                        int   IDa     = mesh.Bones[i].IDs[x];
                        float Weighta = (float)mesh.Bones[i].Weights[x];
                        int   spot    = pos[IDa]++;
                        if (spot > 7)
                        {
                            //SysConsole.Output(OutputType.WARNING, "Too many bones influencing " + vw.VertexID + "!");
                            ForceSet(modmesh.vbo.BoneWeights, IDa, 3, modmesh.vbo.BoneWeights[IDa][3] + Weighta);
                        }
                        else if (spot > 3)
                        {
                            ForceSet(modmesh.vbo.BoneIDs2, IDa, spot - 4, i);
                            ForceSet(modmesh.vbo.BoneWeights2, IDa, spot - 4, Weighta);
                        }
                        else
                        {
                            ForceSet(modmesh.vbo.BoneIDs, IDa, spot, i);
                            ForceSet(modmesh.vbo.BoneWeights, IDa, spot, Weighta);
                        }
                    }
                }
                model.Meshes.Add(modmesh);
            }
            model.RootNode = new ModelNode()
            {
                Parent = null, Name = scene.RootNode.Name.ToLowerFast()
            };
            List <ModelNode> allNodes = new List <ModelNode>();

            PopulateChildren(model.RootNode, scene.RootNode, model, engine, allNodes);
            for (int i = 0; i < model.Meshes.Count; i++)
            {
                for (int x = 0; x < scene.Meshes[i].Bones.Count; x++)
                {
                    ModelNode nodet = null;
                    string    nl    = scene.Meshes[i].Bones[x].Name.ToLowerFast();
                    for (int n = 0; n < allNodes.Count; n++)
                    {
                        if (allNodes[n].Name == nl)
                        {
                            nodet = allNodes[n];
                            break;
                        }
                    }
                    ModelBone mb = new ModelBone()
                    {
                        Offset = convert(scene.Meshes[i].Bones[x].MatrixA)
                    };
                    nodet.Bones.Add(mb);
                    model.Meshes[i].Bones.Add(mb);
                }
            }
            return(model);
        }
コード例 #4
0
        /// <summary>
        /// Starts up and run the server.
        /// </summary>
        /// <param name="game">The game name.</param>
        /// <param name="loaded">The action to fire when the server is loaded.</param>
        public void StartUp(string game, Action loaded = null)
        {
            CurThread = Thread.CurrentThread;
            Files     = new FileHandler();
            GameName  = FileHandler.CleanFileName(game);
            Files.SetSaveDirEarly("server_" + GameName);
            SysConsole.Written += OnConsoleWritten;
            SysConsole.Output(OutputType.INIT, "Launching as new server, this is " + (this == Central ? "" : "NOT ") + "the Central server.");
            SysConsole.Output(OutputType.INIT, "Loading console input handler...");
            ConsoleHandler.Init();
            ConsoleHandler.OnCommandInput += CommandInputHandle;
            SysConsole.Output(OutputType.INIT, "Loading command engine...");
            Commands = new ServerCommands();
            Commands.Init(new ServerOutputter(this), this);
            SysConsole.Output(OutputType.INIT, "Loading CVar engine...");
            CVars = new ServerCVar();
            CVars.Init(this, Commands.Output);
            SysConsole.Output(OutputType.INIT, "Loading default settings...");
            Config   = new FDSSection(Files.ReadText("server_config.fds"));
            Settings = new ServerSettings(this, Config);
            if (Files.Exists("serverdefaultsettings.cfg"))
            {
                string contents = Files.ReadText("serverdefaultsettings.cfg");
                Commands.ExecuteCommands(contents);
            }
            if (Files.Exists("server_eid.txt"))
            {
                cID = long.Parse(Files.ReadText("server_eid.txt") ?? "1");
            }
            SysConsole.Output(OutputType.INIT, "Loading player command engine...");
            PCEngine = new PlayerCommandEngine();
            SysConsole.Output(OutputType.INIT, "Loading permissions engine...");
            PermGroups = new PermissionsGroupEngine()
            {
                TheServer = this
            };
            SysConsole.Output(OutputType.INIT, "Loading item registry...");
            ItemInfos = new ItemInfoRegistry();
            Items     = new ItemRegistry(this);
            Recipes   = new RecipeRegistry()
            {
                TheServer = this
            };
            SysConsole.Output(OutputType.INIT, "Loading model handler...");
            Models = new ModelEngine(this);
            SysConsole.Output(OutputType.INIT, "Loading animation handler...");
            Animations = new AnimationEngine();
            SysConsole.Output(OutputType.INIT, "Preparing networking...");
            Networking = new NetworkBase(this);
            Networking.Init();
            SysConsole.Output(OutputType.INIT, "Loading plugins...");
            Plugins = new PluginManager(this);
            Plugins.Init();
            SysConsole.Output(OutputType.INIT, "Loading scripts...");
            AutorunScripts();
            SysConsole.Output(OutputType.INIT, "Building initial world(s)...");
            foreach (string str in Settings.Worlds)
            {
                LoadWorld(str.ToLowerFast());
            }
            SysConsole.Output(OutputType.INIT, "Preparing block image system...");
            BlockImages = new BlockImageManager();
            BlockImages.Init(this);
            loaded?.Invoke();
            SysConsole.Output(OutputType.INIT, "Ticking...");
            // Tick
            double    TARGETFPS    = 30d;
            Stopwatch Counter      = new Stopwatch();
            Stopwatch DeltaCounter = new Stopwatch();

            DeltaCounter.Start();
            double TotalDelta   = 0;
            double CurrentDelta = 0d;
            double TargetDelta  = 0d;
            int    targettime   = 0;

            try
            {
                while (true)
                {
                    // Update the tick time usage counter
                    Counter.Reset();
                    Counter.Start();
                    // Update the tick delta counter
                    DeltaCounter.Stop();
                    // Delta time = Elapsed ticks * (ticks/second)
                    CurrentDelta = ((double)DeltaCounter.ElapsedTicks) / ((double)Stopwatch.Frequency);
                    // Begin the delta counter to find out how much time is /really/ slept+ticked for
                    DeltaCounter.Reset();
                    DeltaCounter.Start();
                    // How much time should pass between each tick ideally
                    TARGETFPS = Settings.FPS;
                    if (TARGETFPS < 1 || TARGETFPS > 600)
                    {
                        Settings.FPS = 30;
                        TARGETFPS    = 30;
                    }
                    TargetDelta = (1d / TARGETFPS);
                    // How much delta has been built up
                    TotalDelta += CurrentDelta;
                    while (TotalDelta > TargetDelta * 3)
                    {
                        // Lagging - cheat to catch up!
                        TargetDelta *= 2;
                    }
                    // As long as there's more delta built up than delta wanted, tick
                    while (TotalDelta > TargetDelta)
                    {
                        if (NeedShutdown.IsCancellationRequested)
                        {
                            CurThread = Thread.CurrentThread;
                            ShutDown(ShutdownCallback);
                            return;
                        }
                        else if (NeedsQuickShutdown.IsCancellationRequested)
                        {
                            CurThread = Thread.CurrentThread;
                            ShutDownQuickly();
                            return;
                        }
                        lock (TickLock)
                        {
                            Tick(TargetDelta);
                        }
                        TotalDelta -= TargetDelta;
                    }
                    // The tick is done, stop measuring it
                    Counter.Stop();
                    // Only sleep for target milliseconds/tick minus how long the tick took... this is imprecise but that's okay
                    targettime = (int)((1000d / TARGETFPS) - Counter.ElapsedMilliseconds);
                    // Only sleep at all if we're not lagging
                    if (targettime > 0)
                    {
                        // Try to sleep for the target time - very imprecise, thus we deal with precision inside the tick code
                        Thread.Sleep(targettime);
                    }
                }
            }
            catch (ThreadAbortException)
            {
                return;
            }
        }
コード例 #5
0
 private void glControlView_Paint(object sender, PaintEventArgs e)
 {
     try
     {
         sortEntities();
         CurrentContext = ContextView;
         glControlView.MakeCurrent();
         GL.ClearBuffer(ClearBuffer.Color, 0, new float[] { 0.1f, 0.1f, 0.1f, 1f });
         GL.ClearBuffer(ClearBuffer.Depth, 0, new float[] { 1.0f });
         GL.Enable(EnableCap.DepthTest);
         if (renderLightingToolStripMenuItem.Checked)
         {
             s_shadow.Bind();
             for (int i = 0; i < Lights.Count; i++)
             {
                 for (int x = 0; x < Lights[i].InternalLights.Count; x++)
                 {
                     Lights[i].InternalLights[x].Attach();
                     Render3D(CurrentContext, false, false, true, false);
                     Lights[i].InternalLights[x].Complete();
                 }
             }
             SetViewport();
             s_fbo.Bind();
             Location CameraTarget = CameraPos + Utilities.ForwardVector_Deg(CameraYaw, CameraPitch);
             proj     = Matrix4.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(CameraFOV), (float)CurrentContext.Control.Width / (float)CurrentContext.Control.Height, CameraZNear, CameraZFar);
             view     = Matrix4.LookAt(CameraPos.ToOVector(), CameraTarget.ToOVector(), CameraUp.ToOVector());
             combined = view * proj;
             GL.UniformMatrix4(1, false, ref combined);
             GL.ActiveTexture(TextureUnit.Texture0);
             RS4P.Bind();
             Render3D(CurrentContext, true, false, true, true);
             RS4P.Unbind();
             GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo_main);
             GL.ClearBuffer(ClearBuffer.Color, 0, new float[] { 0.0f, 0.0f, 0.0f, 1.0f });
             GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
             GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo2_main);
             GL.ClearBuffer(ClearBuffer.Color, 0, new float[] { 0.0f, 0.0f, 0.0f, 1.0f });
             GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
             s_shadowadder.Bind();
             GL.ActiveTexture(TextureUnit.Texture1);
             GL.BindTexture(TextureTarget.Texture2D, RS4P.PositionTexture);
             GL.ActiveTexture(TextureUnit.Texture2);
             GL.BindTexture(TextureTarget.Texture2D, RS4P.NormalsTexture);
             GL.ActiveTexture(TextureUnit.Texture3);
             GL.BindTexture(TextureTarget.Texture2D, RS4P.DepthTexture);
             GL.ActiveTexture(TextureUnit.Texture5);
             GL.BindTexture(TextureTarget.Texture2D, RS4P.RenderhintTexture);
             GL.ActiveTexture(TextureUnit.Texture6);
             GL.BindTexture(TextureTarget.Texture2D, RS4P.DiffuseTexture);
             Matrix4 mat = Matrix4.CreateOrthographicOffCenter(-1, 1, -1, 1, -1, 1);
             GL.UniformMatrix4(1, false, ref mat);
             mat = Matrix4.Identity;
             GL.UniformMatrix4(2, false, ref mat);
             GL.Uniform3(10, CameraPos.ToOVector());
             bool first = true;
             GL.BindFramebuffer(FramebufferTarget.Framebuffer, first ? fbo_main : fbo2_main);
             GL.DrawBuffer(DrawBufferMode.ColorAttachment0);
             GL.Disable(EnableCap.CullFace);
             for (int i = 0; i < Lights.Count; i++)
             {
                 for (int x = 0; x < Lights[i].InternalLights.Count; x++)
                 {
                     GL.BindFramebuffer(FramebufferTarget.Framebuffer, first ? fbo_main : fbo2_main);
                     GL.ActiveTexture(TextureUnit.Texture0);
                     GL.BindTexture(TextureTarget.Texture2D, first ? fbo2_texture : fbo_texture);
                     GL.ActiveTexture(TextureUnit.Texture4);
                     GL.BindTexture(TextureTarget.Texture2D, Lights[i].InternalLights[x].fbo_depthtex);
                     Matrix4 smat = Lights[i].InternalLights[x].GetMatrix();
                     GL.UniformMatrix4(3, false, ref smat);
                     GL.Uniform3(4, ref Lights[i].InternalLights[x].eye);
                     GL.Uniform3(8, ref Lights[i].InternalLights[x].color);
                     GL.Uniform1(9, Lights[i].InternalLights[x].maxrange);
                     CurrentContext.Rendering.RenderRectangle(-1, -1, 1, 1);
                     first = !first;
                     GL.ActiveTexture(TextureUnit.Texture0);
                     GL.BindTexture(TextureTarget.Texture2D, 0);
                 }
             }
             GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
             GL.DrawBuffer(DrawBufferMode.Back);
             s_main.Bind();
             GL.Uniform3(5, ambient.ToOVector());
             GL.ActiveTexture(TextureUnit.Texture4);
             GL.BindTexture(TextureTarget.Texture2D, first ? fbo2_texture : fbo_texture);
             GL.ActiveTexture(TextureUnit.Texture0);
             GL.BindTexture(TextureTarget.Texture2D, RS4P.DiffuseTexture);
             mat = Matrix4.CreateOrthographicOffCenter(-1, 1, -1, 1, -1, 1);
             GL.UniformMatrix4(1, false, ref mat);
             mat = Matrix4.Identity;
             GL.UniformMatrix4(2, false, ref mat);
             CurrentContext.Rendering.RenderRectangle(-1, -1, 1, 1);
             GL.ActiveTexture(TextureUnit.Texture6);
             GL.BindTexture(TextureTarget.Texture2D, 0);
             GL.ActiveTexture(TextureUnit.Texture5);
             GL.BindTexture(TextureTarget.Texture2D, 0);
             GL.ActiveTexture(TextureUnit.Texture4);
             GL.BindTexture(TextureTarget.Texture2D, 0);
             GL.ActiveTexture(TextureUnit.Texture3);
             GL.BindTexture(TextureTarget.Texture2D, 0);
             GL.ActiveTexture(TextureUnit.Texture2);
             GL.BindTexture(TextureTarget.Texture2D, 0);
             GL.ActiveTexture(TextureUnit.Texture1);
             GL.BindTexture(TextureTarget.Texture2D, 0);
             GL.ActiveTexture(TextureUnit.Texture0);
             GL.BindTexture(TextureTarget.Texture2D, 0);
             s_transponly.Bind();
             GL.UniformMatrix4(1, false, ref combined);
             GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, RS4P.fbo);
             GL.BlitFramebuffer(0, 0, glControlView.Width, glControlView.Height, 0, 0, glControlView.Width, glControlView.Height, ClearBufferMask.DepthBufferBit, BlitFramebufferFilter.Nearest);
             GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, 0);
             Render3D(CurrentContext, false, false, true, false);
             CurrentContext.Shaders.ColorMultShader.Bind();
             GL.UniformMatrix4(1, false, ref combined);
             GL.Enable(EnableCap.CullFace);
             if (wireframe)
             {
                 renderWires(CurrentContext);
             }
             renderSelections(CurrentContext, true);
         }
         else
         {
             CurrentContext.Shaders.ColorMultShader.Bind();
             Location CameraTarget = CameraPos + Utilities.ForwardVector_Deg(CameraYaw, CameraPitch);
             proj     = Matrix4.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(CameraFOV), (float)CurrentContext.Control.Width / (float)CurrentContext.Control.Height, CameraZNear, CameraZFar);
             view     = Matrix4.LookAt(CameraPos.ToOVector(), CameraTarget.ToOVector(), CameraUp.ToOVector());
             combined = view * proj;
             GL.UniformMatrix4(1, false, ref combined);
             Render3D(CurrentContext, true, false, true, false);
             if (wireframe)
             {
                 renderWires(CurrentContext);
             }
             renderSelections(CurrentContext, true);
         }
         GL.Disable(EnableCap.DepthTest);
         CurrentContext.Shaders.ColorMultShader.Bind();
         ortho = Matrix4.CreateOrthographicOffCenter(0, CurrentContext.Control.Width, CurrentContext.Control.Height, 0, -1, 1);
         CurrentContext.FontSets.SlightlyBigger.DrawColoredText("^S^" + (glControlView.Focused ? "@" : "!") + "^e^7" + CameraYaw + "/" + CameraPitch + " at " + CameraPos.ToString(), new Location(0, 0, 0));
         glControlView.SwapBuffers();
     }
     catch (Exception ex)
     {
         SysConsole.Output(OutputType.ERROR, "PaintView: " + ex.ToString());
     }
 }
コード例 #6
0
        public void TickSocket(Socket sock, ref byte[] rd, ref int rdsf)
        {
            int avail = sock.Available;

            if (avail <= 0)
            {
                return;
            }
            if (avail + rdsf > MAX)
            {
                avail = MAX - rdsf;
                if (avail == 0)
                {
                    throw new Exception("Received overly massive packet?!");
                }
            }
            sock.Receive(rd, rdsf, avail, SocketFlags.None);
            rdsf += avail;
            if (rdsf < 5)
            {
                return;
            }
            while (true)
            {
                byte[] len_bytes = new byte[4];
                Array.Copy(rd, len_bytes, 4);
                int len = Utilities.BytesToInt(len_bytes);
                if (len + 5 > MAX)
                {
                    throw new Exception("Unreasonably huge packet!");
                }
                if (rdsf < 5 + len)
                {
                    return;
                }
                ServerToClientPacket packetID = (ServerToClientPacket)rd[4];
                byte[] data = new byte[len];
                Array.Copy(rd, 5, data, 0, len);
                byte[] rem_data = new byte[rdsf - (len + 5)];
                if (rem_data.Length > 0)
                {
                    Array.Copy(rd, len + 5, rem_data, 0, rem_data.Length);
                    Array.Copy(rem_data, rd, rem_data.Length);
                }
                rdsf -= len + 5;
                AbstractPacketIn packet;
                bool             asyncable = false;
                NetUsageType     usage;
                switch (packetID) // TODO: Packet registry?
                {
                case ServerToClientPacket.PING:
                    packet = new PingPacketIn();
                    usage  = NetUsageType.PINGS;
                    break;

                case ServerToClientPacket.YOUR_POSITION:
                    packet = new YourPositionPacketIn();
                    usage  = NetUsageType.PLAYERS;
                    break;

                case ServerToClientPacket.SPAWN_ENTITY:
                    packet = new SpawnEntityPacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.PHYSICS_ENTITY_UPDATE:
                    packet = new PhysicsEntityUpdatePacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.MESSAGE:
                    packet = new MessagePacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.CHARACTER_UPDATE:
                    packet = new CharacterUpdatePacketIn();
                    usage  = NetUsageType.PLAYERS;
                    break;

                case ServerToClientPacket.DESPAWN_ENTITY:
                    packet = new DespawnEntityPacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.NET_STRING:
                    packet = new NetStringPacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.SPAWN_ITEM:
                    packet = new SpawnItemPacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.YOUR_STATUS:
                    packet = new YourStatusPacketIn();
                    usage  = NetUsageType.PLAYERS;
                    break;

                case ServerToClientPacket.ADD_JOINT:
                    packet = new AddJointPacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.YOUR_EID:
                    packet = new YourEIDPacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.DESTROY_JOINT:
                    packet = new DestroyJointPacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.PRIMITIVE_ENTITY_UPDATE:
                    packet = new PrimitiveEntityUpdatePacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.ANIMATION:
                    packet = new AnimationPacketIn();
                    usage  = NetUsageType.PLAYERS;
                    break;

                case ServerToClientPacket.FLASHLIGHT:
                    packet = new FlashLightPacketIn();
                    usage  = NetUsageType.PLAYERS;
                    break;

                case ServerToClientPacket.REMOVE_ITEM:
                    packet = new RemoveItemPacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.SET_ITEM:
                    packet = new SetItemPacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.CVAR_SET:
                    packet = new CVarSetPacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.SET_HELD_ITEM:
                    packet = new SetHeldItemPacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.CHUNK_INFO:
                    packet = new ChunkInfoPacketIn();
                    usage  = NetUsageType.CHUNKS;
                    break;

                case ServerToClientPacket.BLOCK_EDIT:
                    packet = new BlockEditPacketIn();
                    usage  = NetUsageType.CHUNKS;
                    break;

                case ServerToClientPacket.SUN_ANGLE:
                    packet = new SunAnglePacketIn();
                    usage  = NetUsageType.EFFECTS;
                    break;

                case ServerToClientPacket.TELEPORT:
                    packet = new TeleportPacketIn();
                    usage  = NetUsageType.PLAYERS;
                    break;

                case ServerToClientPacket.OPERATION_STATUS:
                    packet = new OperationStatusPacketIn();
                    usage  = NetUsageType.GENERAL;
                    break;

                case ServerToClientPacket.PARTICLE_EFFECT:
                    packet = new ParticleEffectPacketIn();
                    usage  = NetUsageType.EFFECTS;
                    break;

                case ServerToClientPacket.PATH:
                    packet = new PathPacketIn();
                    usage  = NetUsageType.EFFECTS;
                    break;

                case ServerToClientPacket.CHUNK_FORGET:
                    packet = new ChunkForgetPacketIn();
                    usage  = NetUsageType.CHUNKS;
                    break;

                case ServerToClientPacket.FLAG_ENTITY:
                    packet = new FlagEntityPacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.DEFAULT_SOUND:
                    packet = new DefaultSoundPacketIn();
                    usage  = NetUsageType.EFFECTS;
                    break;

                case ServerToClientPacket.GAIN_CONTROL_OF_VEHICLE:
                    packet = new GainControlOfVehiclePacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.ADD_CLOUD:
                    packet = new AddCloudPacketIn();
                    usage  = NetUsageType.CLOUDS;
                    break;

                case ServerToClientPacket.REMOVE_CLOUD:
                    packet = new RemoveCloudPacketIn();
                    usage  = NetUsageType.CLOUDS;
                    break;

                case ServerToClientPacket.ADD_TO_CLOUD:
                    packet = new AddToCloudPacketIn();
                    usage  = NetUsageType.CLOUDS;
                    break;

                case ServerToClientPacket.SET_STATUS:
                    packet = new SetStatusPacketIn();
                    usage  = NetUsageType.PLAYERS;
                    break;

                case ServerToClientPacket.HIGHLIGHT:
                    packet = new HighlightPacketIn();
                    usage  = NetUsageType.EFFECTS;
                    break;

                case ServerToClientPacket.PLAY_SOUND:
                    packet = new PlaySoundPacketIn();
                    usage  = NetUsageType.EFFECTS;
                    break;

                case ServerToClientPacket.LOD_MODEL:
                    packet = new LODModelPacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                case ServerToClientPacket.LOSE_CONTROL_OF_VEHICLE:
                    packet = new LoseControlOfVehiclePacketIn();
                    usage  = NetUsageType.ENTITIES;
                    break;

                default:
                    throw new Exception("Invalid packet ID: " + packetID);
                }
                UsagesThisSecond[(int)usage] += 5 + data.Length;
                UsagesTotal[(int)usage]      += 5 + data.Length;
                packet.TheClient              = TheClient;
                packet.ChunkN = sock == ChunkSocket;
                ServerToClientPacket pid = packetID;
                if (asyncable)
                {
                    // TODO: StartASyncTask?
                    if (!packet.ParseBytesAndExecute(data))
                    {
                        SysConsole.Output(OutputType.ERROR, "Bad async packet (ID=" + pid + ") data!");
                    }
                }
                else
                {
                    TheClient.Schedule.ScheduleSyncTask(() =>
                    {
                        try
                        {
                            if (!packet.ParseBytesAndExecute(data))
                            {
                                SysConsole.Output(OutputType.ERROR, "Bad sync packet (ID=" + pid + ") data!");
                            }
                        }
                        catch (Exception ex)
                        {
                            SysConsole.Output(OutputType.ERROR, "Bad sync packet (ID=" + pid + ") data: " + ex.ToString());
                        }
                    });
                }
            }
        }
コード例 #7
0
ファイル: Connection.cs プロジェクト: BlackCoyote/Voxalia
        public void Tick(double delta)
        {
            try
            {
                Time += delta;
                if (!GotBase && Time >= MaxTime)
                {
                    throw new Exception("Connection timed out!");
                }
                int avail = PrimarySocket.Available;
                if (avail <= 0)
                {
                    return;
                }
                if (avail + recdsofar > MAX)
                {
                    avail = MAX - recdsofar;
                    if (avail == 0)
                    {
                        throw new Exception("Received overly massive packet?!");
                    }
                }
                PrimarySocket.Receive(recd, recdsofar, avail, SocketFlags.None);
                recdsofar += avail;
                if (recdsofar < 5)
                {
                    return;
                }
                if (trying)
                {
                    return;
                }
                if (GotBase)
                {
                    while (true)
                    {
                        byte[] len_bytes = new byte[4];
                        Array.Copy(recd, len_bytes, 4);
                        int len = Utilities.BytesToInt(len_bytes);
                        if (len + 5 > MAX)
                        {
                            throw new Exception("Unreasonably huge packet!");
                        }
                        if (recdsofar < 5 + len)
                        {
                            return;
                        }
                        ClientToServerPacket packetID = (ClientToServerPacket)recd[4];
                        byte[] data = new byte[len];
                        Array.Copy(recd, 5, data, 0, len);
                        byte[] rem_data = new byte[recdsofar - (len + 5)];
                        if (rem_data.Length > 0)
                        {
                            Array.Copy(recd, len + 5, rem_data, 0, rem_data.Length);
                            Array.Copy(rem_data, recd, rem_data.Length);
                        }
                        recdsofar -= len + 5;
                        AbstractPacketIn packet;
                        switch (packetID) // TODO: Packet registry?
                        {
                        case ClientToServerPacket.PING:
                            packet = new PingPacketIn();
                            break;

                        case ClientToServerPacket.KEYS:
                            packet = new KeysPacketIn();
                            break;

                        case ClientToServerPacket.COMMAND:
                            packet = new CommandPacketIn();
                            break;

                        case ClientToServerPacket.HOLD_ITEM:
                            packet = new HoldItemPacketIn();
                            break;

                        case ClientToServerPacket.DISCONNECT:
                            packet = new DisconnectPacketIn();
                            break;

                        case ClientToServerPacket.SET_STATUS:
                            packet = new SetStatusPacketIn();
                            break;

                        case ClientToServerPacket.PLEASE_REDEFINE:
                            packet = new PleaseRedefinePacketIn();
                            break;

                        default:
                            throw new Exception("Invalid packet ID: " + packetID);
                        }
                        packet.Chunk  = PE.ChunkNetwork == this;
                        packet.Player = PE;
                        DataReader dr = new DataReader(new DataStream(data));
                        PE.TheRegion.TheWorld.Schedule.ScheduleSyncTask(() =>
                        {
                            if (!packet.ParseBytesAndExecute(dr))
                            {
                                throw new Exception("Imperfect packet data for " + packetID);
                            }
                        });
                    }
                }
                else
                {
                    if (recd[0] == 'G' && recd[1] == 'E' && recd[2] == 'T' && recd[3] == ' ' && recd[4] == '/')
                    {
                        // HTTP GET
                        if (recd[recdsofar - 1] == '\n' && (recd[recdsofar - 2] == '\n' || recd[recdsofar - 3] == '\n'))
                        {
                            WebPage wp = new WebPage(TheServer, this);
                            wp.Init(FileHandler.encoding.GetString(recd, 0, recdsofar));
                            PrimarySocket.Send(wp.GetFullData());
                            PrimarySocket.Close(5);
                            Alive = false;
                        }
                    }
                    else if (recd[0] == 'P' && recd[1] == 'O' && recd[2] == 'S' && recd[3] == 'T' && recd[4] == ' ')
                    {
                        // HTTP POST
                        throw new NotImplementedException("HTTP POST not yet implemented");
                    }
                    else if (recd[0] == 'H' && recd[1] == 'E' && recd[2] == 'A' && recd[3] == 'D' && recd[4] == ' ')
                    {
                        // HTTP HEAD
                        if (recd[recdsofar - 1] == '\n' && (recd[recdsofar - 2] == '\n' || recd[recdsofar - 3] == '\n'))
                        {
                            WebPage wp = new WebPage(TheServer, this);
                            wp.Init(FileHandler.encoding.GetString(recd, 0, recdsofar));
                            PrimarySocket.Send(FileHandler.encoding.GetBytes(wp.GetHeaders()));
                            PrimarySocket.Close(5);
                            Alive = false;
                        }
                    }
                    else if (recd[0] == 'V' && recd[1] == 'O' && recd[2] == 'X' && recd[3] == 'p' && recd[4] == '_')
                    {
                        // VOXALIA ping
                        if (recd[recdsofar - 1] == '\n')
                        {
                            PrimarySocket.Send(FileHandler.encoding.GetBytes("SUCCESS\rVoxalia Server Online\n"));
                            PrimarySocket.Close(5);
                            Alive = false;
                        }
                    }
                    else if (recd[0] == 'V' && recd[1] == 'O' && recd[2] == 'X' && recd[3] == '_' && recd[4] == '_')
                    {
                        // VOXALIA connect
                        if (recd[recdsofar - 1] == '\n')
                        {
                            string   data   = FileHandler.encoding.GetString(recd, 6, recdsofar - 7);
                            string[] datums = data.SplitFast('\r');
                            if (datums.Length != 5)
                            {
                                throw new Exception("Invalid VOX__ connection details!");
                            }
                            string   name  = datums[0];
                            string   key   = datums[1];
                            string   host  = datums[2];
                            string   port  = datums[3];
                            string   rdist = datums[4];
                            string[] rds   = rdist.SplitFast(',');
                            if (rds.Length != 7)
                            {
                                throw new Exception("Invalid VOX__ connection details: RenderDist!");
                            }
                            if (!Utilities.ValidateUsername(name))
                            {
                                throw new Exception("Invalid connection - unreasonable username!");
                            }
                            trying = true;
                            TheServer.Schedule.StartAsyncTask(() =>
                            {
                                try
                                {
                                    CheckWebSession(name, key);
                                    TheServer.LoadedWorlds[0].Schedule.ScheduleSyncTask(() =>
                                    {
                                        // TODO: Additional details?
                                        // TODO: Choose a world smarter.
                                        PlayerEntity player = new PlayerEntity(TheServer.LoadedWorlds[0].MainRegion, this, name)
                                        {
                                            SessionKey          = key,
                                            Host                = host,
                                            Port                = port,
                                            IP                  = PrimarySocket.RemoteEndPoint.ToString(),
                                            ViewRadiusInChunks  = Math.Min(TheServer.CVars.g_maxrenderdist.ValueI, Math.Max(1, Utilities.StringToInt(rds[0]))),
                                            ViewRadExtra2       = Math.Min(TheServer.CVars.g_maxrenderdist.ValueI, Math.Max(0, Utilities.StringToInt(rds[1]))),
                                            ViewRadExtra2Height = Math.Min(TheServer.CVars.g_maxrenderdist.ValueI, Math.Max(0, Utilities.StringToInt(rds[2]))),
                                            ViewRadExtra5       = Math.Min(TheServer.CVars.g_maxrenderdist.ValueI, Math.Max(0, Utilities.StringToInt(rds[3]))),
                                            ViewRadExtra5Height = Math.Min(TheServer.CVars.g_maxrenderdist.ValueI, Math.Max(0, Utilities.StringToInt(rds[4]))),
                                            ViewRadExtra6       = Math.Min(TheServer.CVars.g_maxlodrenderdist.ValueI, Math.Max(0, Utilities.StringToInt(rds[5]))),
                                            ViewRadExtra15      = Math.Min(TheServer.CVars.g_maxlodrenderdist.ValueI, Math.Max(0, Utilities.StringToInt(rds[6])))
                                        };
                                        PE          = player;
                                        player.Host = host;
                                        TheServer.Schedule.ScheduleSyncTask(() =>
                                        {
                                            TheServer.PlayersWaiting.Add(player);
                                            PrimarySocket.Send(FileHandler.encoding.GetBytes("ACCEPT\n"));
                                        });
                                        GotBase   = true;
                                        recdsofar = 0;
                                        trying    = false;
                                    });
                                }
                                catch (Exception ex)
                                {
                                    TheServer.Schedule.ScheduleSyncTask(() =>
                                    {
                                        if (!Alive)
                                        {
                                            return;
                                        }
                                        PrimarySocket.Close();
                                        Utilities.CheckException(ex);
                                        SysConsole.Output(OutputType.WARNING, "Forcibly disconnected client: " + ex.GetType().Name + ": " + ex.Message);
                                        if (TheServer.CVars.s_debug.ValueB)
                                        {
                                            SysConsole.Output(ex);
                                        }
                                        Alive = false;
                                    });
                                }
                            });
                        }
                    }
                    else if (recd[0] == 'V' && recd[1] == 'O' && recd[2] == 'X' && recd[3] == 'c' && recd[4] == '_')
                    {
                        // VOXALIA chunk connect
                        if (recd[recdsofar - 1] == '\n')
                        {
                            string   data   = FileHandler.encoding.GetString(recd, 6, recdsofar - 7);
                            string[] datums = data.SplitFast('\r');
                            if (datums.Length != 4)
                            {
                                throw new Exception("Invalid VOXc_ connection details!");
                            }
                            string name = datums[0];
                            string key  = datums[1];
                            string host = datums[2];
                            string port = datums[3];
                            if (!Utilities.ValidateUsername(name))
                            {
                                throw new Exception("Invalid connection - unreasonable username!");
                            }
                            TheServer.Schedule.ScheduleSyncTask(() =>
                            {
                                PlayerEntity player = null;
                                for (int i = 0; i < TheServer.PlayersWaiting.Count; i++)
                                {
                                    if (TheServer.PlayersWaiting[i].Name == name && TheServer.PlayersWaiting[i].Host == host &&
                                        TheServer.PlayersWaiting[i].Port == port && TheServer.PlayersWaiting[i].SessionKey == key)
                                    {
                                        player = TheServer.PlayersWaiting[i];
                                        TheServer.PlayersWaiting.RemoveAt(i);
                                        break;
                                    }
                                }

                                PE = player ?? throw new Exception("Can't find player for VOXc_:" + name + ", " + host + ", " + port + ", " + key.Length);
                                player.ChunkNetwork = this;
                                PrimarySocket.Send(FileHandler.encoding.GetBytes("ACCEPT\n"));
                                // TODO: What if the world disappears during connect sequence?
                                player.LastPingByte           = 0;
                                player.LastCPingByte          = 0;
                                PrimarySocket.SendBufferSize *= 10;
                                SendPacket(new PingPacketOut(0));
                                player.Network.SendPacket(new PingPacketOut(0));
                                player.SendStatus();
                                GotBase   = true;
                                recdsofar = 0;
                                player.TheRegion.TheWorld.Schedule.ScheduleSyncTask(() =>
                                {
                                    player.InitPlayer();
                                    player.TheRegion.SpawnEntity(player);
                                });
                            });
                        }
                    }
                    else
                    {
                        throw new Exception("Unknown initial byte set!");
                    }
                }
            }
            catch (Exception ex)
            {
                PrimarySocket.Close();
                try
                {
                    if (PE != null)
                    {
                        PE.Kick("Internal exception.");
                    }
                }
                finally
                {
                    Utilities.CheckException(ex);
                    SysConsole.Output(OutputType.WARNING, "Forcibly disconnected client: " + ex.GetType().Name + ": " + ex.Message);
                    if (TheServer.CVars.s_debug.ValueB)
                    {
                        SysConsole.Output(ex);
                    }
                    Alive = false;
                }
            }
        }
コード例 #8
0
ファイル: PlayerEntity.cs プロジェクト: BlackCoyote/Voxalia
        // TODO: Merge with base.Render() as much as possible!
        public override void Render()
        {
            View3D.CheckError("Render - Player - Pre");
            Location renderrelpos = GetWeldSpot();

            if (TheClient.IsMainMenu || !TheClient.CVars.r_drawself.ValueB)
            {
                return;
            }
            TheClient.SetEnts();
            if (TheClient.CVars.n_debugmovement.ValueB)
            {
                if (ServerLocation.IsInfinite() || ServerLocation.IsNaN() || renderrelpos.IsInfinite() || renderrelpos.IsNaN())
                {
                    SysConsole.Output(OutputType.WARNING, "NaN server data");
                }
                else
                {
                    TheClient.Rendering.RenderLine(ServerLocation, renderrelpos);
                    View3D.CheckError("Render - Player - Line");
                    TheClient.Rendering.RenderLineBox(ServerLocation + new Location(-0.2), ServerLocation + new Location(0.2));
                    if (View3D.CheckError("Render - Player - LineBox"))
                    {
                        SysConsole.Output(OutputType.DEBUG, "Caught: " + (ServerLocation + new Location(-0.2)) + "::: " + (ServerLocation + new Location(0.2)));
                    }
                }
            }
            if (TheClient.VR != null)
            {
                return;
            }
            View3D.CheckError("Render - Player - 0");
            OpenTK.Matrix4d mat = OpenTK.Matrix4d.Scale(1.5f)
                                  * OpenTK.Matrix4d.CreateRotationZ((Direction.Yaw * Utilities.PI180))
                                  * PlayerAngleMat
                                  * OpenTK.Matrix4d.CreateTranslation(ClientUtilities.ConvertD(renderrelpos));
            TheClient.MainWorldView.SetMatrix(2, mat);
            TheClient.Rendering.SetMinimumLight(0.0f);
            model.CustomAnimationAdjustments = new Dictionary <string, OpenTK.Matrix4>(SavedAdjustmentsOTK)
            {
                // TODO: safe (no-collision) rotation check?
                { "spine04", GetAdjustmentOTK("spine04") * OpenTK.Matrix4.CreateRotationX(-(float)(Direction.Pitch / 2f * Utilities.PI180)) }
            };
            View3D.CheckError("Render - Player - 1");
            if (!TheClient.MainWorldView.RenderingShadows && TheClient.CVars.g_firstperson.ValueB)
            {
                model.CustomAnimationAdjustments["neck01"] = GetAdjustmentOTK("neck01") * OpenTK.Matrix4.CreateRotationX(-(float)(160f * Utilities.PI180));
            }
            else
            {
                model.CustomAnimationAdjustments["neck01"] = GetAdjustmentOTK("neck01");
            }
            model.Draw(aHTime, hAnim, aTTime, tAnim, aLTime, lAnim);
            Model mod   = TheClient.GetItemForSlot(TheClient.QuickBarPos).Mod;
            bool  hasjp = HasJetpack();

            View3D.CheckError("Render - Player - 2");
            if (!hasjp && tAnim != null && mod != null)
            {
                mat = OpenTK.Matrix4d.CreateTranslation(ClientUtilities.ConvertD(renderrelpos));
                TheClient.MainWorldView.SetMatrix(2, mat);
                Dictionary <string, Matrix> adjs = new Dictionary <string, Matrix>(SavedAdjustments);
                // TODO: Logic of this rotation math?
                Matrix rotforw = Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitX, ((float)(Direction.Pitch / 2f * Utilities.PI180) % 360f)));
                adjs["spine04"] = GetAdjustment("spine04") * rotforw;
                SingleAnimationNode hand = tAnim.GetNode("metacarpal2.r");
                Matrix m4 = Matrix.CreateScale(1.5f, 1.5f, 1.5f)
                            * (Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitZ, (float)((-Direction.Yaw + 90) * Utilities.PI180) % 360f))
                               * hand.GetBoneTotalMatrix(aTTime, adjs))
                            * Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitZ, (float)((-90) * Utilities.PI180) % 360f));
                OpenTK.Matrix4 bonemat = new OpenTK.Matrix4((float)m4.M11, (float)m4.M12, (float)m4.M13, (float)m4.M14,
                                                            (float)m4.M21, (float)m4.M22, (float)m4.M23, (float)m4.M24,
                                                            (float)m4.M31, (float)m4.M32, (float)m4.M33, (float)m4.M34,
                                                            (float)m4.M41, (float)m4.M42, (float)m4.M43, (float)m4.M44);
                GL.UniformMatrix4(100, false, ref bonemat);
                mod.LoadSkin(TheClient.Textures);
                mod.Draw();
                bonemat = OpenTK.Matrix4.Identity;
                GL.UniformMatrix4(100, false, ref bonemat);
            }
            View3D.CheckError("Render - Player - 3");
            if (hasjp)
            {
                // TODO: Abstractify!
                Model jetp = GetHeldItem().Mod;
                mat = OpenTK.Matrix4d.CreateTranslation(ClientUtilities.ConvertD(renderrelpos));
                TheClient.MainWorldView.SetMatrix(2, mat);
                Dictionary <string, Matrix> adjs = new Dictionary <string, Matrix>();
                Matrix rotforw = Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitX, ((float)(Direction.Pitch / 2f * Utilities.PI180) % 360f)));
                adjs["spine04"] = GetAdjustment("spine04") * rotforw;
                SingleAnimationNode spine = tAnim.GetNode("spine04");
                Matrix m4 = Matrix.CreateScale(1.5f, 1.5f, 1.5f)
                            * (Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitZ, (float)((-Direction.Yaw + 90) * Utilities.PI180) % 360f))
                               * spine.GetBoneTotalMatrix(aTTime, adjs))
                            * Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(Vector3.UnitX, (float)((90) * Utilities.PI180) % 360f));
                OpenTK.Matrix4 bonemat = new OpenTK.Matrix4((float)m4.M11, (float)m4.M12, (float)m4.M13, (float)m4.M14, (float)m4.M21, (float)m4.M22, (float)m4.M23, (float)m4.M24,
                                                            (float)m4.M31, (float)m4.M32, (float)m4.M33, (float)m4.M34, (float)m4.M41, (float)m4.M42, (float)m4.M43, (float)m4.M44);
                GL.UniformMatrix4(100, false, ref bonemat);
                jetp.LoadSkin(TheClient.Textures);
                jetp.Draw();
                bonemat = OpenTK.Matrix4.Identity;
                GL.UniformMatrix4(100, false, ref bonemat);
            }
            View3D.CheckError("Render - Player - 4");
            if (IsTyping)
            {
                TheClient.Textures.GetTexture("ui/game/typing").Bind(); // TODO: store!
                TheClient.Rendering.RenderBillboard(renderrelpos + new Location(0, 0, 4), new Location(2), TheClient.MainWorldView.CameraPos);
            }
            View3D.CheckError("Render - Player - Post");
        }
コード例 #9
0
 /// <summary>
 /// Handles the full main tick.
 /// </summary>
 /// <param name="delt">The current delta timings (See Delta).</param>
 void Tick(double delt)
 {
     lock (TickLock)
     {
         Delta = delt * CVars.g_timescale.ValueD;
         GlobalTickTimeLocal  += Delta;
         Engine.GlobalTickTime = GlobalTickTimeLocal;
         try
         {
             opsat += Delta;
             if (opsat >= 1)
             {
                 opsat -= 1;
                 OncePerSecondActions();
             }
             Schedule.RunAllSyncTasks(Delta);
             Textures.Update(GlobalTickTimeLocal);
             Shaders.Update(GlobalTickTimeLocal);
             Models.Update(GlobalTickTimeLocal);
             KeyHandler.Tick();
             if (RawGamePad != null)
             {
                 for (int i = 0; i < 4; i++)
                 {
                     if (GamePad.GetCapabilities(i).IsConnected)
                     {
                         RawGamePad.SetVibration(i, GamePadVibration, GamePadVibration);
                     }
                 }
             }
             Gamepad.Tick(Delta);
             MouseHandler.Tick();
             UIConsole.Tick();
             Commands.Tick();
             TickWorld(Delta);
             TickChatSystem();
             TickInvMenu();
             CWindow.ClientEngineTick();
             CWindow.MouseX = MouseHandler.MouseX();
             CWindow.MouseY = MouseHandler.MouseY();
             CScreen.FullTick(Delta);
             Sounds.Update(MainWorldView.CameraPos, MainWorldView.CameraTarget - MainWorldView.CameraPos, MainWorldView.CameraUp(), Player.GetVelocity(), Window.Focused);
             Schedule.RunAllSyncTasks(0);
             Player.PostTick();
             TheRegion.SolveJoints();
             //ProcessChunks();
         }
         catch (Exception ex)
         {
             SysConsole.Output(OutputType.ERROR, "Ticking: " + ex.ToString());
         }
         PlayerEyePosition = Player.ItemSource();
         Location forw = Player.ItemDir();
         bool     h    = TheRegion.SpecialCaseRayTrace(PlayerEyePosition, forw, 100, MaterialSolidity.ANY, IgnorePlayer, out RayCastResult rcr);
         Location loc  = new Location(rcr.HitData.Location);
         Location nrm  = new Location(rcr.HitData.Normal);
         h = h && !loc.IsInfinite() && !loc.IsNaN() && nrm.LengthSquared() > 0;
         if (h)
         {
             nrm = nrm.Normalize();
         }
         CameraFinalTarget  = h ? loc - nrm * 0.01: PlayerEyePosition + forw * 100;
         CameraImpactNormal = h ? new Location(rcr.HitData.Normal).Normalize() : Location.Zero;
         CameraDistance     = h ? rcr.HitData.T: 100;
         if (CameraDistance <= 0.01)
         {
             CameraDistance = 0.01;
         }
         double cping = Math.Max(LastPingValue, GlobalTickTimeLocal - LastPingTime);
         AveragePings.Push(new KeyValuePair <double, double>(GlobalTickTimeLocal, cping));
         while ((GlobalTickTimeLocal - AveragePings.Peek().Key) > 1)
         {
             AveragePings.Pop();
         }
         APing = 0;
         for (int i = 0; i < AveragePings.Length; i++)
         {
             APing += AveragePings[i].Value;
         }
         APing /= (double)AveragePings.Length;
         if (FogEnhanceTime > 0.0)
         {
             FogEnhanceTime -= Delta;
         }
         else
         {
             FogEnhanceTime = 0.0;
         }
     }
 }
コード例 #10
0
        public override void Execute(PlayerCommandEntry entry)
        {
            if (entry.InputArguments.Count <= 0)
            {
                ShowUsage(entry);
                return;
            }
            string arg0 = entry.InputArguments[0];

            if (arg0 == "spawnCar" && entry.InputArguments.Count > 1)
            {
                CarEntity ve = new CarEntity(entry.InputArguments[1], entry.Player.TheRegion);
                ve.SetPosition(entry.Player.GetEyePosition() + entry.Player.ForwardVector() * 5);
                entry.Player.TheRegion.SpawnEntity(ve);
            }
            else if (arg0 == "spawnHeli" && entry.InputArguments.Count > 1)
            {
                HelicopterEntity ve = new HelicopterEntity(entry.InputArguments[1], entry.Player.TheRegion);
                ve.SetPosition(entry.Player.GetEyePosition() + entry.Player.ForwardVector() * 5);
                entry.Player.TheRegion.SpawnEntity(ve);
            }
            else if (arg0 == "spawnPlane" && entry.InputArguments.Count > 1)
            {
                PlaneEntity ve = new PlaneEntity(entry.InputArguments[1], entry.Player.TheRegion);
                ve.SetPosition(entry.Player.GetEyePosition() + entry.Player.ForwardVector() * 5);
                entry.Player.TheRegion.SpawnEntity(ve);
            }
            else if (arg0 == "heloTilt" && entry.InputArguments.Count > 1)
            {
                if (entry.Player.CurrentSeat != null && entry.Player.CurrentSeat.SeatHolder is HelicopterEntity)
                {
                    ((HelicopterEntity)entry.Player.CurrentSeat.SeatHolder).TiltMod = Utilities.StringToFloat(entry.InputArguments[1]);
                }
            }
            else if (arg0 == "shortRange")
            {
                entry.Player.ViewRadiusInChunks  = 3;
                entry.Player.ViewRadExtra2       = 0;
                entry.Player.ViewRadExtra2Height = 0;
                entry.Player.ViewRadExtra5       = 0;
                entry.Player.ViewRadExtra5Height = 0;
            }
            else if (arg0 == "countEnts")
            {
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Ents: " + entry.Player.TheRegion.Entities.Count);
            }
            else if (arg0 == "fly")
            {
                if (entry.Player.IsFlying)
                {
                    entry.Player.Unfly();
                    entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Unflying!");
                }
                else
                {
                    entry.Player.Fly();
                    entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Flying!");
                }
            }
            else if (arg0 == "playerDebug")
            {
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "YOU: " + entry.Player.Name + ", tractionForce: " + entry.Player.CBody.TractionForce
                                         + ", mass: " + entry.Player.CBody.Body.Mass + ", radius: " + entry.Player.CBody.BodyRadius + ", hasSupport: " + entry.Player.CBody.SupportFinder.HasSupport
                                         + ", hasTraction: " + entry.Player.CBody.SupportFinder.HasTraction + ", isAFK: " + entry.Player.IsAFK + ", timeAFK: " + entry.Player.TimeAFK);
            }
            else if (arg0 == "playBall")
            {
                // TODO: Item for this?
                ModelEntity me = new ModelEntity("sphere", entry.Player.TheRegion);
                me.SetMass(5);
                me.SetPosition(entry.Player.GetCenter() + entry.Player.ForwardVector());
                me.mode = ModelCollisionMode.SPHERE;
                me.SetVelocity(entry.Player.ForwardVector());
                me.SetBounciness(0.95f);
                entry.Player.TheRegion.SpawnEntity(me);
            }
            else if (arg0 == "playDisc")
            {
                // TODO: Item for this?
                ModelEntity me = new ModelEntity("flyingdisc", entry.Player.TheRegion);
                me.SetMass(5);
                me.SetPosition(entry.Player.GetCenter() + entry.Player.ForwardVector() * 1.5f); // TODO: 1.5 -> 'reach' value?
                me.mode = ModelCollisionMode.AABB;
                me.SetVelocity(entry.Player.ForwardVector() * 25f);                             // TODO: 25 -> 'strength' value?
                me.SetAngularVelocity(new Location(0, 0, 10));
                entry.Player.TheRegion.SpawnEntity(me);
                entry.Player.TheRegion.AddJoint(new JointFlyingDisc(me));
            }
            else if (arg0 == "secureMovement")
            {
                entry.Player.SecureMovement = !entry.Player.SecureMovement;
                entry.Player.SendLanguageData(TextChannel.COMMAND_RESPONSE, "voxalia", "commands.player.devel.secure_movement", entry.Player.Network.GetLanguageData("voxalia", "common." + (entry.Player.SecureMovement ? "true" : "false")));
                if (entry.Player.SecureMovement)
                {
                    entry.Player.Flags &= ~YourStatusFlags.INSECURE_MOVEMENT;
                }
                else
                {
                    entry.Player.Flags |= YourStatusFlags.INSECURE_MOVEMENT;
                }
                entry.Player.SendStatus();
            }
            else if (arg0 == "chunkDebug")
            {
                Location posBlock = entry.Player.GetPosition().GetBlockLocation();
                double   h        = entry.Player.TheRegion.Generator.GetHeight(entry.Player.TheRegion.TheWorld.Seed, entry.Player.TheRegion.TheWorld.Seed2, entry.Player.TheRegion.TheWorld.Seed3,
                                                                               entry.Player.TheRegion.TheWorld.Seed4, entry.Player.TheRegion.TheWorld.Seed5, (double)posBlock.X, (double)posBlock.Y, (double)posBlock.Z, out Biome biome);
                BlockInternal bi = entry.Player.TheRegion.GetBlockInternal_NoLoad((entry.Player.GetPosition() + new Location(0, 0, -0.05f)).GetBlockLocation());
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Mat: " + bi.Material + ", data: " + ((int)bi.BlockData) + ", locDat: " + ((int)bi.BlockLocalData)
                                         + ", Damage: " + bi.Damage + ", Paint: " + bi.BlockPaint
                                         + ", xp: " + BlockShapeRegistry.BSD[bi.BlockData].OccupiesXP() + ", xm: " + BlockShapeRegistry.BSD[bi.BlockData].OccupiesXM()
                                         + ", yp: " + BlockShapeRegistry.BSD[bi.BlockData].OccupiesYP() + ", ym: " + BlockShapeRegistry.BSD[bi.BlockData].OccupiesYM()
                                         + ", zp: " + BlockShapeRegistry.BSD[bi.BlockData].OccupiesTOP() + ", zm: " + BlockShapeRegistry.BSD[bi.BlockData].OccupiesBOTTOM());
                double temp = entry.Player.TheRegion.Generator.GetBiomeGen().GetTemperature(entry.Player.TheRegion.TheWorld.Seed2, entry.Player.TheRegion.TheWorld.Seed3, (double)posBlock.X, (double)posBlock.Y);
                double down = entry.Player.TheRegion.Generator.GetBiomeGen().GetDownfallRate(entry.Player.TheRegion.TheWorld.Seed3, entry.Player.TheRegion.TheWorld.Seed4, (double)posBlock.X, (double)posBlock.Y);
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Height: " + h + ", temperature: " + temp + ", downfallrate: " + down + ", biome yield: " + biome.GetName());
                BlockUpperArea.TopBlock top = entry.Player.TheRegion.GetHighestBlock(posBlock);
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Material: " + top.BasicMat + ", height: " + top.Height);
            }
            else if (arg0 == "structureSelect" && entry.InputArguments.Count > 1)
            {
                string arg1 = entry.InputArguments[1];
                entry.Player.Items.GiveItem(new ItemStack("structureselector", arg1, entry.Player.TheServer, 1, "items/admin/structure_selector",
                                                          "Structure Selector", "Selects and creates a '" + arg1 + "' structure!", System.Drawing.Color.White, "items/admin/structure_selector", false, 0));
            }
            else if (arg0 == "structureCreate" && entry.InputArguments.Count > 1)
            {
                string arg1 = entry.InputArguments[1];
                entry.Player.Items.GiveItem(new ItemStack("structurecreate", arg1, entry.Player.TheServer, 1, "items/admin/structure_create",
                                                          "Structure Creator", "Creates a '" + arg1 + "' structure!", System.Drawing.Color.White, "items/admin/structure_create", false, 0));
            }
            else if (arg0 == "musicBlock" && entry.InputArguments.Count > 3)
            {
                int    arg1 = Utilities.StringToInt(entry.InputArguments[1]);
                double arg2 = Utilities.StringToFloat(entry.InputArguments[2]);
                double arg3 = Utilities.StringToFloat(entry.InputArguments[3]);
                entry.Player.Items.GiveItem(new ItemStack("customblock", entry.Player.TheServer, 1, "items/custom_blocks/music_block",
                                                          "Music Block", "Plays music!", System.Drawing.Color.White, "items/custom_blocks/music_block", false, 0,
                                                          new KeyValuePair <string, TemplateObject>("music_type", new IntegerTag(arg1)),
                                                          new KeyValuePair <string, TemplateObject>("music_volume", new NumberTag(arg2)),
                                                          new KeyValuePair <string, TemplateObject>("music_pitch", new NumberTag(arg3)))
                {
                    Datum = new BlockInternal((ushort)Material.DEBUG, 0, 0, 0).GetItemDatum()
                });
            }
            else if (arg0 == "structurePaste" && entry.InputArguments.Count > 1)
            {
                string arg1 = entry.InputArguments[1];
                entry.Player.Items.GiveItem(new ItemStack("structurepaste", arg1, entry.Player.TheServer, 1, "items/admin/structure_paste",
                                                          "Structor Paster", "Pastes a ;" + arg1 + "; structure!", System.Drawing.Color.White, "items/admin/structure_paste", false, 0));
            }
            else if (arg0 == "testPerm" && entry.InputArguments.Count > 1)
            {
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Testing " + entry.InputArguments[1] + ": " + entry.Player.HasPermission(entry.InputArguments[1]));
            }
            else if (arg0 == "spawnTree" && entry.InputArguments.Count > 1)
            {
                entry.Player.TheRegion.SpawnTree(entry.InputArguments[1].ToLowerFast(), entry.Player.GetPosition(), null);
            }
            else if (arg0 == "spawnTarget")
            {
                TargetEntity te = new TargetEntity(entry.Player.TheRegion);
                te.SetPosition(entry.Player.GetPosition() + entry.Player.ForwardVector() * 5);
                te.TheRegion.SpawnEntity(te);
            }
            else if (arg0 == "spawnSlime" && entry.InputArguments.Count > 2)
            {
                SlimeEntity se = new SlimeEntity(entry.Player.TheRegion, Utilities.StringToFloat(entry.InputArguments[2]))
                {
                    mod_color = ColorTag.For(entry.InputArguments[1]).Internal
                };
                se.SetPosition(entry.Player.GetPosition() + entry.Player.ForwardVector() * 5);
                se.TheRegion.SpawnEntity(se);
            }
            else if (arg0 == "timePathfind" && entry.InputArguments.Count > 1)
            {
                double dist = Utilities.StringToDouble(entry.InputArguments[1]);
                entry.Player.TheServer.Schedule.StartAsyncTask(() =>
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    List <Location> locs = entry.Player.TheRegion.FindPath(entry.Player.GetPosition(), entry.Player.GetPosition() + new Location(dist, 0, 0), dist * 2, 1.5f);
                    sw.Stop();
                    entry.Player.TheRegion.TheWorld.Schedule.ScheduleSyncTask(() =>
                    {
                        if (locs != null)
                        {
                            entry.Player.Network.SendPacket(new PathPacketOut(locs));
                        }
                        entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Took " + sw.ElapsedMilliseconds + "ms, passed: " + (locs != null));
                    });
                });
            }
            else if (arg0 == "findPath")
            {
                Location eye  = entry.Player.GetEyePosition();
                Location forw = entry.Player.ForwardVector();
                Location goal;
                if (entry.Player.TheRegion.SpecialCaseRayTrace(eye, forw, 150, MaterialSolidity.FULLSOLID, entry.Player.IgnorePlayers, out RayCastResult rcr))
                {
                    goal = new Location(rcr.HitData.Location);
                }
                else
                {
                    goal = eye + forw * 50;
                }
                entry.Player.TheServer.Schedule.StartAsyncTask(() =>
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    List <Location> locs;
                    try
                    {
                        locs = entry.Player.TheRegion.FindPath(entry.Player.GetPosition(), goal, 75, 1.5f);
                    }
                    catch (Exception ex)
                    {
                        Utilities.CheckException(ex);
                        SysConsole.Output("pathfinding", ex);
                        locs = null;
                    }
                    sw.Stop();
                    entry.Player.TheRegion.TheWorld.Schedule.ScheduleSyncTask(() =>
                    {
                        if (locs != null)
                        {
                            entry.Player.Network.SendPacket(new PathPacketOut(locs));
                        }
                        entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Took " + sw.ElapsedMilliseconds + "ms, passed: " + (locs != null));
                    });
                });
            }
            else if (arg0 == "gameMode" && entry.InputArguments.Count > 1)
            {
                if (Enum.TryParse(entry.InputArguments[1].ToUpperInvariant(), out GameMode mode))
                {
                    entry.Player.Mode = mode;
                }
            }
            else if (arg0 == "teleport" && entry.InputArguments.Count > 1)
            {
                entry.Player.Teleport(Location.FromString(entry.InputArguments[1]));
            }
            else if (arg0 == "loadPos")
            {
                entry.Player.UpdateLoadPos = !entry.Player.UpdateLoadPos;
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Now: " + (entry.Player.UpdateLoadPos ? "true" : "false"));
            }
            else if (arg0 == "tickRate")
            {
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Intended tick rate: " + entry.Player.TheServer.CVars.g_fps.ValueI + ", actual tick rate (last second): " + entry.Player.TheServer.TPS);
            }
            else if (arg0 == "paintBrush" && entry.InputArguments.Count > 1)
            {
                ItemStack its = entry.Player.TheServer.Items.GetItem("tools/paintbrush");
                byte      col = Colors.ForName(entry.InputArguments[1]);
                its.Datum     = col;
                its.DrawColor = Colors.ForByte(col);
                entry.Player.Items.GiveItem(its);
            }
            else if (arg0 == "paintBomb" && entry.InputArguments.Count > 1)
            {
                ItemStack its = entry.Player.TheServer.Items.GetItem("weapons/grenades/paintbomb", 10);
                byte      col = Colors.ForName(entry.InputArguments[1]);
                its.Datum     = col;
                its.DrawColor = Colors.ForByte(col);
                entry.Player.Items.GiveItem(its);
            }
            else if (arg0 == "sledgeHammer" && entry.InputArguments.Count > 1)
            {
                ItemStack its = entry.Player.TheServer.Items.GetItem("tools/sledgehammer");
                int       bsd = BlockShapeRegistry.GetBSDFor(entry.InputArguments[1]);
                its.Datum = bsd;
                entry.Player.Items.GiveItem(its);
            }
            else if (arg0 == "blockDamage" && entry.InputArguments.Count > 1)
            {
                if (Enum.TryParse(entry.InputArguments[1], out BlockDamage damage))
                {
                    Location      posBlock = (entry.Player.GetPosition() + new Location(0, 0, -0.05f)).GetBlockLocation();
                    BlockInternal bi       = entry.Player.TheRegion.GetBlockInternal(posBlock);
                    bi.Damage = damage;
                    entry.Player.TheRegion.SetBlockMaterial(posBlock, bi);
                }
                else
                {
                    entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "/devel <subcommand> [ values ... ]");
                }
            }
            else if (arg0 == "blockShare" && entry.InputArguments.Count > 1)
            {
                Location      posBlock = (entry.Player.GetPosition() + new Location(0, 0, -0.05f)).GetBlockLocation();
                BlockInternal bi       = entry.Player.TheRegion.GetBlockInternal(posBlock);
                bool          temp     = entry.InputArguments[1].ToLowerFast() == "true";
                bi.BlockShareTex = temp;
                entry.Player.TheRegion.SetBlockMaterial(posBlock, bi);
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Block " + posBlock + " which is a " + bi.Material + " set ShareTex mode to " + temp + " yields " + bi.BlockShareTex);
            }
            else if (arg0 == "webPass" && entry.InputArguments.Count > 1)
            {
                entry.Player.PlayerConfig.Set("web.passcode", Utilities.HashQuick(entry.Player.Name.ToLowerFast(), entry.InputArguments[1]));
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "Set.");
            }
            else if (arg0 == "spawnMessage" && entry.InputArguments.Count > 1)
            {
                string             mes = entry.InputArguments[1].Replace("\\n", "\n");
                HoverMessageEntity hme = new HoverMessageEntity(entry.Player.TheRegion, mes)
                {
                    Position = entry.Player.GetEyePosition()
                };
                entry.Player.TheRegion.SpawnEntity(hme);
            }
            else if (arg0 == "chunkTimes")
            {
                foreach (Tuple <string, double> time in entry.Player.TheRegion.Generator.GetTimings())
                {
                    entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "--> " + time.Item1 + ": " + time.Item2);
                }
#if TIMINGS
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "--> [Image]: " + entry.Player.TheRegion.TheServer.BlockImages.Timings_General);
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "--> [Image/A]: " + entry.Player.TheRegion.TheServer.BlockImages.Timings_A);
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "--> [Image/B]: " + entry.Player.TheRegion.TheServer.BlockImages.Timings_B);
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "--> [Image/C]: " + entry.Player.TheRegion.TheServer.BlockImages.Timings_C);
                entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "--> [Image/D]: " + entry.Player.TheRegion.TheServer.BlockImages.Timings_D);
                if (entry.InputArguments.Count > 1 && entry.InputArguments[1] == "clear")
                {
                    entry.Player.TheRegion.Generator.ClearTimings();
                    entry.Player.TheRegion.TheServer.BlockImages.Timings_General = 0;
                    entry.Player.TheRegion.TheServer.BlockImages.Timings_A       = 0;
                    entry.Player.TheRegion.TheServer.BlockImages.Timings_B       = 0;
                    entry.Player.TheRegion.TheServer.BlockImages.Timings_C       = 0;
                    entry.Player.TheRegion.TheServer.BlockImages.Timings_D       = 0;
                }
#endif
            }
            else if (arg0 == "fireWork" && entry.InputArguments.Count > 1)
            {
                ParticleEffectPacketOut pepo;
                Location pos = entry.Player.GetEyePosition() + entry.Player.ForwardVector() * 10;
                switch (entry.InputArguments[1])
                {
                case "rainbow_huge":
                    pepo = new ParticleEffectPacketOut(ParticleEffectNetType.FIREWORK, 15, pos, new Location(-1, -1, -1), new Location(-1, -1, -1), 150);
                    break;

                case "red_big":
                    pepo = new ParticleEffectPacketOut(ParticleEffectNetType.FIREWORK, 10, pos, new Location(1, 0, 0), new Location(1, 0, 0), 100);
                    break;

                case "green_medium":
                    pepo = new ParticleEffectPacketOut(ParticleEffectNetType.FIREWORK, 7.5, pos, new Location(0.25, 1, 0.25), new Location(0.25, 1, 1), 100);
                    break;

                case "blue_small":
                    pepo = new ParticleEffectPacketOut(ParticleEffectNetType.FIREWORK, 5, pos, new Location(0, 0, 1), new Location(0, 0, -1), 50);
                    break;

                default:
                    ShowUsage(entry);
                    return;
                }
                entry.Player.Network.SendPacket(pepo);
            }
            else
            {
                ShowUsage(entry);
                return;
            }
        }
コード例 #11
0
        /// <summary>
        /// Prepares the font system.
        /// </summary>
        /// <param name="files">The backing file system.</param>
        public void Init(FileEngine files)
        {
            Files = files;
            if (Fonts != null)
            {
                for (int i = 0; i < Fonts.Count; i++)
                {
                    Fonts[i].Remove();
                    i--;
                }
            }
            // Generate the texture
            CurrentBMP = new Bitmap(DEFAULT_TEXTURE_SIZE_WIDTH, DEFAULT_TEXTURE_SIZE_HEIGHT);
            using (Graphics gfx = Graphics.FromImage(CurrentBMP))
            {
                gfx.Clear(Color.Transparent);
                gfx.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, 20, 20));
            }
            // Load other stuff
            LoadTextFile();
            Fonts = new List <GLFont>();
            // Choose a default font.
            FontFamily[] families        = FontFamily.Families;
            FontFamily   family          = FontFamily.GenericMonospace;
            int          family_priority = 0;

            for (int i = 0; i < families.Length; i++)
            {
                if (family_priority < 20 && families[i].Name.ToLowerFast() == "segoe ui emoji")
                {
                    family          = families[i];
                    family_priority = 20;
                }
                else if (family_priority < 10 && families[i].Name.ToLowerFast() == "segoe ui")
                {
                    family          = families[i];
                    family_priority = 10;
                }
                else if (family_priority < 5 && families[i].Name.ToLowerFast() == "arial")
                {
                    family          = families[i];
                    family_priority = 5;
                }
                else if (family_priority < 2 && families[i].Name.ToLowerFast() == "calibri")
                {
                    family          = families[i];
                    family_priority = 2;
                }
                else if (family_priority < 1 && families[i].Name.ToLowerFast() == "dejavu serif")
                {
                    family          = families[i];
                    family_priority = 1;
                }
            }
            BackupFontFamily = family;
            SysConsole.Output(OutputType.INIT, "Select backup font: " + BackupFontFamily.Name);
            string fname = "sourcecodepro";

            try
            {
                pfc = new PrivateFontCollection();
                // TODO: Move out of data directory, as we don't use the file handler at all anyway?
                pfc.AddFontFile(Environment.CurrentDirectory + "/data/fonts/" + fname + ".ttf");
                family          = pfc.Families[0];
                family_priority = 100;
            }
            catch (Exception ex)
            {
                SysConsole.Output(OutputType.WARNING, "Loading " + fname + ": " + ex.ToString());
            }
            Font def = new Font(family, 12);

            Standard = new GLFont(def, this);
            Fonts.Add(Standard);
            SysConsole.Output(OutputType.INIT, "Select main font: " + family.Name);
            UpdateTexture();
        }
コード例 #12
0
 /// <summary>
 /// Loads an animation by name.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="Files">The file system.</param>
 /// <returns>The animation.</returns>
 SingleAnimation LoadAnimation(string name, FileEngine Files)
 {
     if (Files.TryReadFileText("animations/" + name + ".anim", out string fileText))
     {
         SingleAnimation created = new SingleAnimation()
         {
             Name = name
         };
         string[] data = fileText.SplitFast('\n');
         int      entr = 0;
         for (int i = 0; i < data.Length; i++)
         {
             if (data[i].StartsWith("//"))
             {
                 continue;
             }
             string type = data[i];
             if (data.Length <= i + 1 || data[i + 1] != "{")
             {
                 break;
             }
             List <KeyValuePair <string, string> > entries = new List <KeyValuePair <string, string> >();
             for (i += 2; i < data.Length; i++)
             {
                 if (data[i].Trim().StartsWith("//"))
                 {
                     continue;
                 }
                 if (data[i] == "}")
                 {
                     break;
                 }
                 string[] dat = data[i].SplitFast(':');
                 if (dat.Length <= 1)
                 {
                     SysConsole.Output(OutputType.WARNING, "Invalid key dat: " + dat[0]);
                 }
                 else
                 {
                     string key   = dat[0].Trim();
                     string value = dat[1].Substring(0, dat[1].Length - 1).Trim();
                     entries.Add(new KeyValuePair <string, string>(key, value));
                 }
             }
             bool isgeneral           = type == "general" && entr == 0;
             SingleAnimationNode node = null;
             if (!isgeneral)
             {
                 node = new SingleAnimationNode()
                 {
                     Name = type.ToLowerFast()
                 };
             }
             foreach (KeyValuePair <string, string> entry in entries)
             {
                 if (isgeneral)
                 {
                     if (entry.Key == "length")
                     {
                         created.Length = StringConversionHelper.StringToDouble(entry.Value);
                     }
                     else
                     {
                         SysConsole.Output(OutputType.WARNING, "Unknown GENERAL key: " + entry.Key);
                     }
                 }
                 else
                 {
                     if (entry.Key == "positions")
                     {
                         string[] poses = entry.Value.SplitFast(' ');
                         for (int x = 0; x < poses.Length; x++)
                         {
                             if (poses[x].Length > 0)
                             {
                                 string[] posdata = poses[x].SplitFast('=');
                                 node.PosTimes.Add(StringConversionHelper.StringToDouble(posdata[0]));
                                 node.Positions.Add(new Location(StringConversionHelper.StringToFloat(posdata[1]),
                                                                 StringConversionHelper.StringToFloat(posdata[2]), StringConversionHelper.StringToFloat(posdata[3])));
                             }
                         }
                     }
                     else if (entry.Key == "rotations")
                     {
                         string[] rots = entry.Value.SplitFast(' ');
                         for (int x = 0; x < rots.Length; x++)
                         {
                             if (rots[x].Length > 0)
                             {
                                 string[] posdata = rots[x].SplitFast('=');
                                 node.RotTimes.Add(StringConversionHelper.StringToDouble(posdata[0]));
                                 node.Rotations.Add(new BEPUutilities.Quaternion(StringConversionHelper.StringToFloat(posdata[1]), StringConversionHelper.StringToFloat(posdata[2]),
                                                                                 StringConversionHelper.StringToFloat(posdata[3]), StringConversionHelper.StringToFloat(posdata[4])));
                             }
                         }
                     }
                     else if (entry.Key == "parent")
                     {
                         node.ParentName = entry.Value.ToLowerFast();
                     }
                     else if (entry.Key == "offset")
                     {
                         string[] posdata = entry.Value.SplitFast('=');
                         node.Offset = new Location(StringConversionHelper.StringToFloat(posdata[0]),
                                                    StringConversionHelper.StringToFloat(posdata[1]), StringConversionHelper.StringToFloat(posdata[2]));
                     }
                     else
                     {
                         SysConsole.Output(OutputType.WARNING, "Unknown NODE key: " + entry.Key);
                     }
                 }
             }
             if (!isgeneral)
             {
                 created.Nodes.Add(node);
                 created.node_map.Add(node.Name, node);
             }
             entr++;
         }
         foreach (SingleAnimationNode node in created.Nodes)
         {
             for (int i = 0; i < created.Nodes.Count; i++)
             {
                 if (created.Nodes[i].Name == node.ParentName)
                 {
                     node.Parent = created.Nodes[i];
                     break;
                 }
             }
         }
         created.Engine = this;
         return(created);
     }
     else
     {
         throw new Exception("Invalid animation file - file not found: animations/" + name + ".anim");
     }
 }
コード例 #13
0
        public void Generate(Client tclient, ClientCVar cvars, TextureEngine eng, bool delayable)
        {
            TheClient = tclient;
            if (TextureID > -1)
            {
                GL.DeleteTexture(TextureID);
                GL.DeleteTexture(NormalTextureID);
                GL.DeleteTexture(HelpTextureID);
            }
            List <MaterialTextureInfo> texs = new List <MaterialTextureInfo>(MaterialHelpers.Textures.Length);

            TexList = texs;
            int extras = 0;

            for (int i = 0; i < MaterialHelpers.Textures.Length; i++)
            {
                string[] basic = MaterialHelpers.Textures[i].SplitFast('@')[0].SplitFast('$')[0].SplitFast('%')[0].SplitFast(',');
                texs.Add(new MaterialTextureInfo()
                {
                    Mat = i, ResultantID = extras
                });
                extras += basic.Length;
            }
            TEngine   = eng;
            TextureID = GL.GenTexture();
            TWidth    = cvars.r_blocktexturewidth.ValueI;
            HelpTWMin = TEX_REQUIRED_BITS / (TWidth * TWidth);
            GL.BindTexture(TextureTarget.Texture2DArray, TextureID);
            int levels = TheClient.CVars.r_block_mipmaps.ValueB ? (TWidth == 256 ? 6 : 4) : 1; // TODO: 6/4 -> Setting

            GL.TexStorage3D(TextureTarget3d.Texture2DArray, levels, SizedInternalFormat.Rgba8, TWidth, TWidth, extras);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)(cvars.r_blocktexturelinear.ValueB ? TextureMinFilter.LinearMipmapLinear : TextureMinFilter.Nearest));
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)(cvars.r_blocktexturelinear.ValueB ? TextureMagFilter.Linear : TextureMagFilter.Nearest));
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            HelpTextureID = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2DArray, HelpTextureID);
            GL.TexStorage3D(TextureTarget3d.Texture2DArray, levels, SizedInternalFormat.Rgba8, TWidth, TWidth, extras + HelpTWMin);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            NormalTextureID = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
            GL.TexStorage3D(TextureTarget3d.Texture2DArray, levels, SizedInternalFormat.Rgba8, TWidth, TWidth, extras);
            GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            // TODO: Use normal.a!
            IntTexs = new string[MaterialHelpers.Textures.Length];
            for (int ia = 0; ia < MaterialHelpers.Textures.Length; ia++)
            {
                int    i = ia;
                Action a = () =>
                {
                    MaterialTextureInfo tex = texs[i];
                    int      resID          = tex.ResultantID;
                    string[] refrornot      = MaterialHelpers.Textures[i].SplitFast('@');
                    if (refrornot.Length > 1)
                    {
                        string[] rorn = refrornot[1].SplitFast('%');
                        if (rorn.Length > 1)
                        {
                            tex.RefrRate = Utilities.StringToFloat(rorn[1]);
                        }
                        tex.RefractTextures = rorn[0].SplitFast(',');
                    }
                    string[] glowornot = refrornot[0].SplitFast('!');
                    if (glowornot.Length > 1)
                    {
                        tex.GlowingTextures = glowornot[1].SplitFast(',');
                    }
                    string[] reflornot = glowornot[0].SplitFast('*');
                    if (reflornot.Length > 1)
                    {
                        tex.ReflectTextures = reflornot[1].SplitFast(',');
                    }
                    string[] specularornot = reflornot[0].SplitFast('&');
                    if (specularornot.Length > 1)
                    {
                        tex.SpecularTextures = specularornot[1].SplitFast(',');
                    }
                    string[] normalornot = specularornot[0].SplitFast('$');
                    GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
                    if (normalornot.Length > 1)
                    {
                        string[] rorn = normalornot[1].SplitFast('%');
                        if (rorn.Length > 1)
                        {
                            tex.NormRate = Utilities.StringToFloat(rorn[1]);
                        }
                        tex.NormalTextures = rorn[0].SplitFast(',');
                        if (tex.NormalTextures.Length > 1)
                        {
                            SetAnimated((int)resID, tex.NormRate, tex.NormalTextures, NormalTextureID, -1);
                        }
                    }
                    else
                    {
                        SetTexture((int)resID, "normal_def", -1);
                    }
                    string[] rateornot = normalornot[0].SplitFast('%');
                    if (rateornot.Length > 1)
                    {
                        tex.Rate = Utilities.StringToFloat(rateornot[1]);
                    }
                    tex.Textures = rateornot[0].SplitFast(',');
                    GL.BindTexture(TextureTarget.Texture2DArray, TextureID);
                    if (tex.Textures.Length > 1)
                    {
                        SetAnimated((int)resID, tex.Rate, tex.Textures, TextureID, resID);
                        if (tex.NormalTextures == null)
                        {
                            GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
                            tex.NormalTextures = new string[tex.Textures.Length];
                            tex.NormRate       = tex.Rate;
                            for (int fz = 0; fz < tex.NormalTextures.Length; fz++)
                            {
                                tex.NormalTextures[fz] = "normal_def";
                            }
                            SetAnimated((int)resID, tex.Rate, tex.NormalTextures, NormalTextureID, -1);
                        }
                    }
                    else
                    {
                        SetTexture((int)resID, tex.Textures[0], resID);
                        if (tex.NormalTextures == null)
                        {
                            tex.NormalTextures = new string[] { "normal_def" };
                        }
                    }
                    if (tex.ReflectTextures == null)
                    {
                        tex.ReflectTextures = new string[tex.Textures.Length];
                        for (int fz = 0; fz < tex.ReflectTextures.Length; fz++)
                        {
                            tex.ReflectTextures[fz] = "black";
                        }
                        tex.RefractTextures  = tex.ReflectTextures;
                        tex.GlowingTextures  = tex.ReflectTextures;
                        tex.SpecularTextures = tex.ReflectTextures;
                    }
                    if (tex.NormRate != tex.Rate || tex.RefrRate != tex.Rate)
                    {
                        SysConsole.Output(OutputType.WARNING, "Rates wrong for " + MaterialHelpers.Textures[i]);
                        tex.NormRate = tex.Rate;
                        tex.RefrRate = tex.Rate;
                    }
                    if (tex.Textures.Length != tex.NormalTextures.Length || tex.ReflectTextures.Length != tex.Textures.Length)
                    {
                        SysConsole.Output(OutputType.WARNING, "Texture counts wrong for " + MaterialHelpers.Textures[i]);
                    }
                    IntTexs[(int)tex.Mat] = tex.Textures[0];
                    if (!delayable)
                    {
                        TheClient.PassLoadScreen();
                    }
                };
                if (delayable)
                {
                    TheClient.Schedule.ScheduleSyncTask(a, i * LoadRate);
                }
                else
                {
                    a();
                }
            }
            double time = (MaterialHelpers.Textures.Length + 1) * LoadRate;

            for (int ia = 0; ia < texs.Count; ia++)
            {
                int    i = ia;
                Action a = () =>
                {
                    GL.BindTexture(TextureTarget.Texture2DArray, HelpTextureID);
                    Bitmap combo = GetCombo(texs[i], 0);
                    if ((texs[i].SpecularTextures != null) && (texs[i].ReflectTextures != null) && (texs[i].RefractTextures != null) && (texs[i].GlowingTextures != null) && texs[i].SpecularTextures.Length > 1)
                    {
                        Bitmap[] bmps = new Bitmap[texs[i].SpecularTextures.Length];
                        bmps[0] = combo;
                        for (int x = 1; x < bmps.Length; x++)
                        {
                            bmps[x] = GetCombo(texs[i], x);
                        }
                        SetAnimated((int)texs[i].ResultantID + HelpTWMin, texs[i].RefrRate, bmps, HelpTextureID);
                        for (int x = 1; x < bmps.Length; x++)
                        {
                            bmps[x].Dispose();
                        }
                    }
                    else
                    {
                        TEngine.LockBitmapToTexture(combo, (int)texs[i].ResultantID + HelpTWMin);
                    }
                    combo.Dispose();
                    if (!delayable)
                    {
                        TheClient.PassLoadScreen();
                    }
                };
                if (delayable)
                {
                    TheClient.Schedule.ScheduleSyncTask(a, time + i * LoadRate);
                }
                else
                {
                    a();
                }
            }
            if (TheClient.CVars.r_block_mipmaps.ValueB)
            {
                Action mipmap = () =>
                {
                    GL.BindTexture(TextureTarget.Texture2DArray, TextureID);
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
                    GL.BindTexture(TextureTarget.Texture2DArray, NormalTextureID);
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
                    GL.BindTexture(TextureTarget.Texture2DArray, HelpTextureID);
                    GL.GenerateMipmap(GenerateMipmapTarget.Texture2DArray);
                    GraphicsUtil.CheckError("Mipmapping");
                };
                if (delayable)
                {
                    TheClient.Schedule.ScheduleSyncTask(mipmap, time * 2);
                }
                else
                {
                    mipmap();
                }
            }
            GL.BindTexture(TextureTarget.Texture2DArray, 0);
        }
コード例 #14
0
        /// <summary>
        /// Called when the window is loading, only to be used by the startup process.
        /// </summary>
        void Window_Load(object sender, EventArgs e)
        {
            SysConsole.Output(OutputType.INIT, "Window generated!");
            DPIScale = Window.Width / CVars.r_width.ValueF;
            SysConsole.Output(OutputType.INIT, "DPIScale is " + DPIScale + "!");
            SysConsole.Output(OutputType.INIT, "Loading base textures...");
            PreInitRendering();
            Textures = new TextureEngine();
            Textures.InitTextureSystem(this);
            ItemFrame = Textures.GetTexture("ui/hud/item_frame");
            SysConsole.Output(OutputType.INIT, "Loading shaders...");
            Shaders  = new ShaderEngine();
            GLVendor = GL.GetString(StringName.Vendor);
            CVars.s_glvendor.Value = GLVendor;
            GLVersion = GL.GetString(StringName.Version);
            CVars.s_glversion.Value = GLVersion;
            GLRenderer = GL.GetString(StringName.Renderer);
            CVars.s_glrenderer.Value = GLRenderer;
            SysConsole.Output(OutputType.INIT, "Vendor: " + GLVendor + ", GLVersion: " + GLVersion + ", Renderer: " + GLRenderer);
            if (GLVendor.ToLowerFast().Contains("intel"))
            {
                SysConsole.Output(OutputType.INIT, "Disabling good graphics (Appears to be Intel: '" + GLVendor + "')");
                Shaders.MCM_GOOD_GRAPHICS = false;
            }
            Shaders.InitShaderSystem(this);
            View3D.CheckError("Load - Shaders");
            SysConsole.Output(OutputType.INIT, "Loading rendering helper...");
            Rendering = new Renderer(Textures, Shaders);
            Rendering.Init();
            SysConsole.Output(OutputType.INIT, "Preparing load screen...");
            Texture load_screen = Textures.GetTexture("ui/menus/loadscreen");

            load_screen.Bind();
            Shaders.ColorMultShader.Bind();
            Establish2D();
            Rendering.RenderRectangle(0, 0, Window.Width, Window.Height);
            Window.SwapBuffers();
            SysConsole.Output(OutputType.INIT, "Loading block textures...");
            TBlock = new TextureBlock();
            TBlock.Generate(this, CVars, Textures);
            View3D.CheckError("Load - Textures");
            SysConsole.Output(OutputType.INIT, "Loading fonts...");
            Fonts = new GLFontEngine(Shaders);
            Fonts.Init(this);
            FontSets = new FontSetEngine(Fonts);
            FontSets.Init(this);
            View3D.CheckError("Load - Fonts");
            SysConsole.Output(OutputType.INIT, "Loading animation engine...");
            Animations = new AnimationEngine();
            SysConsole.Output(OutputType.INIT, "Loading model engine...");
            Models = new ModelEngine();
            Models.Init(Animations, this);
            SysConsole.Output(OutputType.INIT, "Loading general graphics settings...");
            CVars.r_vsync.OnChanged += onVsyncChanged;
            onVsyncChanged(CVars.r_vsync, null);
            CVars.r_cloudshadows.OnChanged += onCloudShadowChanged;
            View3D.CheckError("Load - General Graphics");
            SysConsole.Output(OutputType.INIT, "Loading UI engine...");
            UIConsole.InitConsole(); // TODO: make this non-static
            InitChatSystem();
            View3D.CheckError("Load - UI");
            SysConsole.Output(OutputType.INIT, "Preparing rendering engine...");
            InitRendering();
            View3D.CheckError("Load - Rendering");
            SysConsole.Output(OutputType.INIT, "Loading particle effect engine...");
            Particles = new ParticleHelper(this)
            {
                Engine = new ParticleEngine(this)
            };
            SysConsole.Output(OutputType.INIT, "Preparing mouse, keyboard, and gamepad handlers...");
            KeyHandler.Init();
            GamePadHandler.Init();
            View3D.CheckError("Load - Keyboard/mouse");
            SysConsole.Output(OutputType.INIT, "Building the sound system...");
            Sounds = new SoundEngine();
            Sounds.Init(this, CVars);
            View3D.CheckError("Load - Sound");
            SysConsole.Output(OutputType.INIT, "Building game world...");
            BuildWorld();
            View3D.CheckError("Load - World");
            SysConsole.Output(OutputType.INIT, "Preparing networking...");
            Network = new NetworkBase(this);
            RegisterDefaultEntityTypes();
            View3D.CheckError("Load - Net");
            SysConsole.Output(OutputType.INIT, "Playing background music...");
            BackgroundMusic();
            CVars.a_musicvolume.OnChanged += onMusicVolumeChanged;
            CVars.a_musicpitch.OnChanged  += onMusicPitchChanged;
            CVars.a_music.OnChanged       += onMusicChanged;
            CVars.a_echovolume.OnChanged  += OnEchoVolumeChanged;
            OnEchoVolumeChanged(null, null);
            SysConsole.Output(OutputType.INIT, "Setting up screens...");
            TheMainMenuScreen         = new MainMenuScreen(this);
            TheGameScreen             = new GameScreen(this);
            TheSingleplayerMenuScreen = new SingleplayerMenuScreen(this);
            SysConsole.Output(OutputType.INIT, "Preparing inventory...");
            InitInventory();
            SysConsole.Output(OutputType.INIT, "Showing main menu...");
            ShowMainMenu();
            SysConsole.Output(OutputType.INIT, "Trying to grab RawGamePad...");
            try
            {
                RawGamePad = new XInput();
            }
            catch (Exception ex)
            {
                SysConsole.Output(OutputType.INIT, "Failed to grab RawGamePad: " + ex.Message);
            }
            View3D.CheckError("Load - Final");
            SysConsole.Output(OutputType.INIT, "Ready and looping!");
        }
コード例 #15
0
        /// <summary>
        /// NOTE: *NOT* guaranteed to play a sound effect immediately, regardless of input! Some sound effects will be delayed! If too many audible sounds are already playing, this will refuse to play.
        /// </summary>
        public void Play(SoundEffect sfx, bool loop, Location pos, float pitch = 1, float volume = 1, float seek_seconds = 0, Action <ActiveSound> callback = null)
        {
            if (sfx == null)
            {
                //SysConsole.Output(OutputType.DEBUG, "Audio / null");
                return;
            }
            if (PlayingNow.Count > 200 && AudioInternal == null)
            {
                if (!CanClean())
                {
                    //SysConsole.Output(OutputType.DEBUG, "Audio / count");
                    return;
                }
            }
            if (sfx.Internal == -2)
            {
                Play(GetSound(sfx.Name), loop, pos, pitch, volume, seek_seconds, callback);
                return;
            }
            if (pitch <= 0 || pitch > 2)
            {
                throw new ArgumentException("Must be between 0 and 2", "pitch");
            }
            if (volume == 0)
            {
                SysConsole.Output(OutputType.DEBUG, "Audio / volume");
                return;
            }
            if (volume <= 0 || volume > 1)
            {
                throw new ArgumentException("Must be between 0 and 1", "volume");
            }
            Action playSound = () =>
            {
                if (sfx.Clip == null && sfx.Internal < 0)
                {
                    //SysConsole.Output(OutputType.DEBUG, "Audio / clip");
                    return;
                }
                ActiveSound actsfx = new ActiveSound(sfx)
                {
                    Engine   = this,
                    Position = pos,
                    Pitch    = pitch * CVars.a_globalpitch.ValueF,
                    Gain     = volume,
                    Loop     = loop
                };
                actsfx.Create();
                if (actsfx.AudioInternal == null && actsfx.Src < 0)
                {
                    //SysConsole.Output(OutputType.DEBUG, "Audio / src");
                    return;
                }
                CheckError("Create:" + sfx.Name);
                if (TimeDeaf > 0.0)
                {
                    actsfx.IsDeafened = true;
                    if (AudioInternal == null)
                    {
                        AL.Source(actsfx.Src, ALSourcef.Gain, 0.0001f);
                    }
                    else
                    {
                        actsfx.AudioInternal.Gain = 0.0001f;
                    }
                }
                if (seek_seconds != 0)
                {
                    actsfx.Seek(seek_seconds);
                }
                CheckError("Preconfig:" + sfx.Name);
                actsfx.Play();
                CheckError("Play:" + sfx.Name);
                //SysConsole.Output(OutputType.DEBUG, "Audio / sucess");
                PlayingNow.Add(actsfx);
                callback?.Invoke(actsfx);
            };

            lock (sfx)
            {
                if (sfx.Clip == null && sfx.Internal == -1)
                {
                    //SysConsole.Output(OutputType.DEBUG, "Audio / delay");
                    sfx.Loaded += (o, e) =>
                    {
                        playSound();
                    };
                    return;
                }
            }
            playSound();
        }
コード例 #16
0
 public override void GoodOutput(string text)
 {
     SysConsole.Output(OutputType.INFO, TextStyle.Color_Outgood + text);
 }
コード例 #17
0
 /// <summary>
 /// Renders a single frame of the game, and also ticks.
 /// </summary>
 /// <param name="sender">Irrelevant.</param>
 /// <param name="e">Holds the frame time (delta).</param>
 private void Window_RenderFrame(object sender, FrameEventArgs e)
 {
     try
     {
         StackNoteHelper.Push("GameClientWindow - Render and tick frame", this);
         // First step: check delta
         Delta = e.Time;
         CurrentEngine.Delta = Delta;
         if (e.Time <= 0.0)
         {
             return;
         }
         GlobalTickTime += Delta;
         ErrorCode ec = GL.GetError();
         while (ec != ErrorCode.NoError)
         {
             SysConsole.Output(OutputType.WARNING, "Uncaught GL Error: " + ec);
             ec = GL.GetError();
         }
         // Second step: clear the screen
         GL.ClearBuffer(ClearBuffer.Color, 0, ScreenClearColor);
         GL.ClearBuffer(ClearBuffer.Depth, 0, DepthClear);
         GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
         GL.DrawBuffer(DrawBufferMode.Back);
         GraphicsUtil.CheckError("GameClient - Pre");
         // Tick helpers
         Models.Update(GlobalTickTime);
         GraphicsUtil.CheckError("GameClient - PostModelUpdate");
         // Third step: general game rendering
         if (ProcessMainEngine)
         {
             CurrentEngine.RenderSingleFrame();
             GraphicsUtil.CheckError("GameClient - PostMainEngine");
         }
         // Add the UI Layer too
         MainUI.Draw();
         GraphicsUtil.CheckError("GameClient - PostUI");
         // Fourth step: clean up!
         GL.BindTexture(TextureTarget.Texture2D, 0);
         GL.BindVertexArray(0);
         GL.UseProgram(0);
         // Semi-final step: Tick logic!
         GraphicsUtil.CheckError("GameClient - PreTick");
         // Pre-tick.
         ClientEngineTick();
         // Primary entity tick
         if (ProcessMainEngine)
         {
             CurrentEngine.Tick();
         }
         // Primary UI tick
         MainUI.Tick();
         GraphicsUtil.CheckError("GameClient - PostTick");
         // Final step: Swap the render buffer onto the screen!
         Window.SwapBuffers();
         GraphicsUtil.CheckError("GameClient - Post");
     }
     finally
     {
         StackNoteHelper.Pop();
     }
 }
コード例 #18
0
 public override void BadOutput(string text)
 {
     SysConsole.Output(OutputType.WARNING, TextStyle.Color_Outbad + text);
 }
コード例 #19
0
 void ConnectInternal()
 {
     try
     {
         string    key     = GetWebSession();
         IPAddress address = GetAddress(LastIP);
         ConnectionSocket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         ConnectionSocket.LingerState.LingerTime = 5;
         ConnectionSocket.LingerState.Enabled    = true;
         ConnectionSocket.ReceiveTimeout         = 10000;
         ConnectionSocket.SendTimeout            = 10000;
         ConnectionSocket.ReceiveBufferSize      = 5 * 1024 * 1024;
         ConnectionSocket.SendBufferSize         = 5 * 1024 * 1024;
         int tport = Utilities.StringToInt(LastPort);
         ConnectionSocket.Connect(new IPEndPoint(address, tport));
         ConnectionSocket.Send(FileHandler.encoding.GetBytes("VOX__\r" + Username
                                                             + "\r" + key + "\r" + LastIP + "\r" + LastPort + "\n"));
         byte[] resp = ReceiveUntil(ConnectionSocket, 150, (byte)'\n');
         if (FileHandler.encoding.GetString(resp) != "ACCEPT")
         {
             ConnectionSocket.Close();
             throw new Exception("Server did not accept connection");
         }
         ConnectionSocket.Blocking = false;
         ChunkSocket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
         ChunkSocket.LingerState.LingerTime = 5;
         ChunkSocket.LingerState.Enabled    = true;
         ChunkSocket.ReceiveTimeout         = 10000;
         ChunkSocket.SendTimeout            = 10000;
         ChunkSocket.ReceiveBufferSize      = 5 * 1024 * 1024;
         ChunkSocket.SendBufferSize         = 5 * 1024 * 1024;
         ChunkSocket.Connect(new IPEndPoint(address, tport));
         ChunkSocket.Send(FileHandler.encoding.GetBytes("VOXc_\r" + Username
                                                        + "\r" + key + "\r" + LastIP + "\r" + LastPort + "\n"));
         resp = ReceiveUntil(ChunkSocket, 150, (byte)'\n');
         if (FileHandler.encoding.GetString(resp) != "ACCEPT")
         {
             ConnectionSocket.Close();
             ChunkSocket.Close();
             throw new Exception("Server did not accept connection");
         }
         ChunkSocket.Blocking = false;
         SysConsole.Output(OutputType.INFO, "Connected to " + address.ToString() + " " + tport);
         IsAlive = true;
         LaunchTicker();
     }
     catch (Exception ex)
     {
         if (ex is ThreadAbortException)
         {
             throw ex;
         }
         TheClient.Schedule.ScheduleSyncTask(() =>
         {
             UIConsole.WriteLine("Connection failed: " + ex.Message);
         });
         SysConsole.Output(OutputType.ERROR, "Networking / connect internal: " + ex.ToString());
         if (ConnectionSocket != null)
         {
             ConnectionSocket.Close(5);
         }
         if (ChunkSocket != null)
         {
             ChunkSocket.Close(5);
         }
     }
 }
コード例 #20
0
ファイル: Player.cs プロジェクト: shuidong/Voxalia
        public override void Tick()
        {
            if (tdisco)
            {
                return;
            }
            if (!IsValid)
            {
                return;
            }
            int pc = PacketsToApply.Count;

            for (int i = 0; i < pc; i++)
            {
                PacketsToApply[i].Apply();
            }
            PacketsToApply.RemoveRange(0, pc);
            TickMovement(InWorld.Delta);
            // Manage Selection
            Location forward = Utilities.ForwardVector_Deg(Direction.X, Direction.Y);
            Location eye     = Position + new Location(0, 0, Maxes.Z);
            Location seltarg = eye + forward * 10;

            SelectedBlock = Collision.BoxRayTrace(InWorld, new Location(-0.001), new Location(0.001), eye, seltarg, -1);
            if (SelectedBlock == seltarg)
            {
                SelectedBlock = Location.NaN;
            }
            // Break
            if (Attack && !SelectedBlock.IsNaN())
            {
                if (ServerMain.GlobalTickTime - 0.5 >= LastBreak)
                {
                    LastBreak = ServerMain.GlobalTickTime;
                    Location sel_block = SelectedBlock.GetBlockLocation();
                    Chunk    ch        = InWorld.LoadChunk(World.GetChunkLocation(sel_block));
                    if (ch.Blocks[(int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30)].Type != 0)
                    {
                        ch.SetBlock((int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30), (ushort)Material.AIR);
                        InWorld.BroadcastBlock(sel_block);
                    }
                }
            }
            if (!Attack)
            {
                LastBreak = 0;
            }
            // Place
            Item HeldItem = GetItemForSlot(QuickBarPos);

            if (Secondary && HeldItem.Material != Material.AIR)
            {
                if (ServerMain.GlobalTickTime - 0.3 >= LastPlace)
                {
                    Location back_a_block = Collision.BoxRayTrace(InWorld, new Location(-0.001), new Location(0.001), eye, seltarg, 1);
                    LastPlace = ServerMain.GlobalTickTime;
                    Location sel_block = back_a_block.GetBlockLocation();
                    Chunk    ch        = InWorld.LoadChunk(World.GetChunkLocation(sel_block));
                    if (ch.Blocks[(int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30)].Type != (ushort)HeldItem.Material)
                    {
                        ch.SetBlock((int)(sel_block.X - ch.X * 30), (int)(sel_block.Y - ch.Y * 30), (int)(sel_block.Z - ch.Z * 30), (ushort)HeldItem.Material);
                        InWorld.BroadcastBlock(sel_block);
                    }
                }
            }
            if (!Secondary)
            {
                LastPlace = 0;
            }
            // TODO: Better tracking of what chunks to send
            List <Location> locs = GetChunksNear(World.GetChunkLocation(Position));

            foreach (Location loc in locs)
            {
                if (!ChunksAware.Contains(loc))
                {
                    ToSend.Add(loc);
                    ChunksAware.Add(loc);
                }
            }
            for (int i = 0; i < ChunksAware.Count; i++)
            {
                if (!locs.Contains(ChunksAware[i]))
                {
                    ToSend.Remove(ChunksAware[i]);
                    ChunksAware.RemoveAt(i--);
                }
            }
            sendtimer += InWorld.Delta;
            if (sendtimer >= 0.05f)
            {
                sendtimer = 0.05f;
                if (ToSend.Count > 0)
                {
                    Chunk ch = InWorld.LoadChunk(ToSend[0]);
                    SendToSecondary(new ChunkPacketOut(ch));
                    for (int i = 0; i < ch.Entities.Count; i++)
                    {
                        if (ch.Entities[i] != this)
                        {
                            Send(new NewEntityPacketOut(ch.Entities[i]));
                        }
                    }
                    ToSend.RemoveAt(0);
                }
            }
            // Handle networking
            lock (Packets)
            {
                for (int i = 0; i < Packets.Count; i++)
                {
                    try
                    {
                        Packets[i].Apply();
                    }
                    catch (Exception ex)
                    {
                        SysConsole.Output(OutputType.ERROR, "Networking / player / receive "
                                          + (Packets[i].IsChunkConnection ? "C-" : "") + "packet: " + ex.ToString());
                        Kick("Invalid packet " + Packets[i].GetType().Name); // TODO: Less internal-ish packet ID handling?
                    }
                }
                Packets.Clear();
            }
        }
コード例 #21
0
        /// <summary>
        /// Shuts down the server, saving any necessary data.
        /// </summary>
        public void ShutDown(Action callback = null)
        {
            ShutdownCallback = callback;
            if (CurThread != Thread.CurrentThread)
            {
                NeedShutdown.Cancel();
                return;
            }
            ShuttingDown = true;
            SysConsole.Output(OutputType.INFO, "[Shutdown] Starting to close server...");
            ConsoleHandler.OnCommandInput -= CommandInputHandle;
            Schedule.Tasks.Clear();
            foreach (PlayerEntity player in Players)
            {
                player.Kick("Server shutting down.");
            }
            Object tlock = new Object();
            int    t     = 0;
            int    c     = 0;

            foreach (World world in LoadedWorlds)
            {
                t++;
                SysConsole.Output(OutputType.INFO, "[Shutdown] Unloading world: " + world.Name);
                world.UnloadFully(() =>
                {
                    lock (tlock)
                    {
                        c++;
                    }
                });
            }
            while (true)
            {
                lock (tlock)
                {
                    if (c >= t)
                    {
                        break;
                    }
                }
                // TODO: Max timeout?
                Thread.Sleep(50);
            }
            LoadedWorlds.Clear();
            SysConsole.Output(OutputType.INFO, "[Shutdown] Clearing plugins...");
            Plugins.UnloadPlugins();
            SysConsole.Output(OutputType.INFO, "[Shutdown] Saving final data...");
            long cid;

            lock (CIDLock)
            {
                cid = cID;
            }
            lock (SaveFileLock)
            {
                Files.WriteText("server_eid.txt", cid.ToString());
            }
            // TODO: CVar save?
            SysConsole.Output(OutputType.INFO, "[Shutdown] Closing server...");
            ShutDownQuickly();
        }
コード例 #22
0
ファイル: ChunkVBO.cs プロジェクト: MoTo1496/Voxalia
        public void UpdateBuffer()
        {
            if (Vertices == null && verts == null)
            {
                SysConsole.Output(OutputType.ERROR, "Failed to update VBO, null vertices!");
                return;
            }
            LastVRAM = 0;
            Vector3[] vecs  = verts ?? Vertices.ToArray();
            uint[]    inds  = indices ?? Indices.ToArray();
            Vector3[] norms = normals ?? Normals.ToArray();
            Vector3[] texs  = texts ?? TexCoords.ToArray();
            Vector3[] tangs = Tangents != null?Tangents.ToArray() : (tangents ?? TangentsFor(vecs, norms, texs));

            Vector4[] cols = Colors != null?Colors.ToArray() : v4_colors;

            Vector4[] tcols = TCOLs != null?TCOLs.ToArray() : v4_tcolors;

            Vector4[] thvs = THVs != null?THVs.ToArray() : v4_thvs;

            Vector4[] thws = THWs != null?THWs.ToArray() : v4_thws;

            Vector4[] thvs2 = THVs2 != null?THVs2.ToArray() : v4_thvs2;

            Vector4[] thws2 = THWs2 != null?THWs2.ToArray() : v4_thws2;

            vC = vecs.Length;
            // Vertex buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, _VertexVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vecs.Length * Vector3.SizeInBytes), vecs, BufferMode);
            LastVRAM += vecs.Length * Vector3.SizeInBytes;
            // Normal buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, _NormalVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(norms.Length * Vector3.SizeInBytes), norms, BufferMode);
            LastVRAM += norms.Length * Vector3.SizeInBytes;
            // TexCoord buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TexCoordVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(texs.Length * Vector3.SizeInBytes), texs, BufferMode);
            LastVRAM += texs.Length * Vector3.SizeInBytes;
            // Tangent buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TangentVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(tangs.Length * Vector3.SizeInBytes), tangs, BufferMode);
            LastVRAM += tangs.Length * Vector3.SizeInBytes;
            // Color buffer
            if (cols != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _ColorVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(cols.Length * Vector4.SizeInBytes), cols, BufferMode);
                LastVRAM += cols.Length * Vector4.SizeInBytes;
            }
            // TCOL buffer
            if (tcols != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _TCOLVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(tcols.Length * Vector4.SizeInBytes), tcols, BufferMode);
                LastVRAM += tcols.Length * Vector4.SizeInBytes;
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THVVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(thvs.Length * Vector4.SizeInBytes), thvs, BufferMode);
                LastVRAM += thvs.Length * Vector4.SizeInBytes;
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THWVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(thws.Length * Vector4.SizeInBytes), thws, BufferMode);
                LastVRAM += thws.Length * Vector4.SizeInBytes;
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THV2VBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(thvs2.Length * Vector4.SizeInBytes), thvs2, BufferMode);
                LastVRAM += thvs2.Length * Vector4.SizeInBytes;
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THW2VBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(thws2.Length * Vector4.SizeInBytes), thws2, BufferMode);
                LastVRAM += thws2.Length * Vector4.SizeInBytes;
            }
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            // Index buffer
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, _IndexVBO);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(inds.Length * sizeof(uint)), inds, BufferMode);
            LastVRAM += inds.Length * sizeof(uint);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
        }
コード例 #23
0
        public override bool ParseBytesAndExecute(byte[] data)
        {
            int len = 1 + 8 + 8 + 8 + 24 + 4 + 4 + 4 + 4 + 24 + 4 + 4 + 4 + 4;

            if (data.Length < len)
            {
                SysConsole.Output(OutputType.WARNING, "Joint packet: Bad initial length!");
                return(false);
            }
            byte type = data[0];
            long EID1 = Utilities.BytesToLong(Utilities.BytesPartial(data, 1, 8));
            long EID2 = Utilities.BytesToLong(Utilities.BytesPartial(data, 1 + 8, 8));
            long JID  = Utilities.BytesToLong(Utilities.BytesPartial(data, 1 + 8 + 8, 8));

            if (TheClient.TheRegion.GetJoint(JID) != null)
            {
                // If we already know this joint, just keep on going.
                return(true);
            }
            Entity pe1 = TheClient.TheRegion.GetEntity(EID1);
            Entity pe2 = TheClient.TheRegion.GetEntity(EID2);

            if (pe1 == null)
            {
                SysConsole.Output(OutputType.WARNING, "Joint Packet: Invalid EID-1 " + EID1);
                return(false);
            }
            if (pe2 == null)
            {
                SysConsole.Output(OutputType.WARNING, "Joint Packet: Invalid EID-2 " + EID2);
                return(false);
            }
            Location pos1 = Location.FromDoubleBytes(data, 1 + 8 + 8 + 8);
            float    qx1  = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24, 4));
            float    qy1  = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4, 4));
            float    qz1  = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 4, 4));
            float    qw1  = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 4 + 4, 4));

            BEPUutilities.Quaternion quat1 = new BEPUutilities.Quaternion(qx1, qy1, qz1, qw1);
            pe1.SetPosition(pos1);
            pe1.SetOrientation(quat1);
            Location pos2 = Location.FromDoubleBytes(data, 1 + 8 + 8 + 8 + 24 + 4 + 4 + 4 + 4);
            float    qx2  = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 24 + 4 + 4 + 4 + 4, 4));
            float    qy2  = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 24 + 4 + 4 + 4 + 4, 4));
            float    qz2  = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 4 + 24 + 4 + 4 + 4 + 4, 4));
            float    qw2  = Utilities.BytesToFloat(Utilities.BytesPartial(data, 1 + 8 + 8 + 8 + 24 + 4 + 4 + 4 + 24 + 4 + 4 + 4 + 4, 4));

            BEPUutilities.Quaternion quat2 = new BEPUutilities.Quaternion(qx2, qy2, qz2, qw2);
            pe1.SetPosition(pos1);
            pe1.SetOrientation(quat1);
            pe2.SetPosition(pos2);
            pe2.SetOrientation(quat2);
            if (type == 0)
            {
                if (data.Length != len + 24)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                Location        pos = Location.FromDoubleBytes(data, len);
                JointBallSocket jbs = new JointBallSocket((PhysicsEntity)pe1, (PhysicsEntity)pe2, pos)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jbs);
                return(true);
            }
            else if (type == 1)
            {
                if (data.Length != len + 24)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                Location    dir = Location.FromDoubleBytes(data, len);
                JointSlider js  = new JointSlider((PhysicsEntity)pe1, (PhysicsEntity)pe2, dir)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(js);
                return(true);
            }
            else if (type == 2)
            {
                if (data.Length != len + 4 + 4 + 24 + 24)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                float         min     = Utilities.BytesToFloat(Utilities.BytesPartial(data, len, 4));
                float         max     = Utilities.BytesToFloat(Utilities.BytesPartial(data, len + 4, 4));
                Location      ent1pos = Location.FromDoubleBytes(data, len + 4 + 4);
                Location      ent2pos = Location.FromDoubleBytes(data, len + 4 + 4 + 24);
                JointDistance jd      = new JointDistance((PhysicsEntity)pe1, (PhysicsEntity)pe2, min, max, ent1pos, ent2pos)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jd);
                return(true);
            }
            else if (type == 3)
            {
                if (data.Length != len + 24 + 1)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                Location      axis = Location.FromDoubleBytes(data, len);
                bool          mode = data[len + 24] == 1;
                JointPullPush jpp  = new JointPullPush((PhysicsEntity)pe1, (PhysicsEntity)pe2, axis, mode)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jpp);
                return(true);
            }
            else if (type == 4)
            {
                if (data.Length != len)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                JointForceWeld jfw = new JointForceWeld(pe1, pe2)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jfw);
                return(true);
            }
            else if (type == 5)
            {
                if (data.Length != len + 24)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                Location     dir = Location.FromDoubleBytes(data, len);
                JointSpinner js  = new JointSpinner((PhysicsEntity)pe1, (PhysicsEntity)pe2, dir)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(js);
                return(true);
            }
            else if (type == 6)
            {
                if (data.Length != len + 24 + 24)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                Location   a1 = Location.FromDoubleBytes(data, len);
                Location   a2 = Location.FromDoubleBytes(data, len + 24);
                JointTwist jt = new JointTwist((PhysicsEntity)pe1, (PhysicsEntity)pe2, a1, a2)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jt);
                return(true);
            }
            else if (type == 7)
            {
                if (data.Length != len)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                JointWeld jw = new JointWeld((PhysicsEntity)pe1, (PhysicsEntity)pe2)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jw);
                return(true);
            }
            else if (type == 8)
            {
                if (data.Length != len + 24 + 1)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                Location          dir        = Location.FromDoubleBytes(data, len);
                bool              issteering = data[len + 24] == 1;
                JointVehicleMotor jm         = new JointVehicleMotor((PhysicsEntity)pe1, (PhysicsEntity)pe2, dir, issteering)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jm);
                return(true);
            }
            else if (type == 9)
            {
                if (data.Length != len + 24 + 24 + 24 + 4 + 4)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                Location        cpos1 = Location.FromDoubleBytes(data, len);
                Location        cpos2 = Location.FromDoubleBytes(data, len + 24);
                Location        axis  = Location.FromDoubleBytes(data, len + 24 + 24);
                float           min   = Utilities.BytesToFloat(Utilities.BytesPartial(data, len + 24 + 24 + 24, 4));
                float           max   = Utilities.BytesToFloat(Utilities.BytesPartial(data, len + 24 + 24 + 24 + 4, 4));
                JointLAxisLimit jlal  = new JointLAxisLimit((PhysicsEntity)pe1, (PhysicsEntity)pe2, min, max, cpos1, cpos2, axis)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jlal);
                return(true);
            }
            else if (type == 10)
            {
                if (data.Length != len + 24 + 24)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                Location         hinge = Location.FromDoubleBytes(data, len);
                Location         twist = Location.FromDoubleBytes(data, len + 24);
                JointSwivelHinge jlal  = new JointSwivelHinge((PhysicsEntity)pe1, (PhysicsEntity)pe2, hinge, twist)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jlal);
                return(true);
            }
            else if (type == 11)
            {
                if (data.Length != len + 4)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                float            height = Utilities.BytesToFloat(Utilities.BytesPartial(data, len, 4));
                ConstWheelStepUp cwsu   = new ConstWheelStepUp((PhysicsEntity)pe1, height)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(cwsu);
                return(true);
            }
            else if (type == 12)
            {
                if (data.Length != len + 4 + 1)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                ConnectorBeam cb = new ConnectorBeam()
                {
                    One   = pe1,
                    Two   = pe2,
                    color = System.Drawing.Color.FromArgb(Utilities.BytesToInt(Utilities.BytesPartial(data, len, 4))),
                    JID   = JID,
                    type  = (BeamType)data[len + 4]
                };
                TheClient.TheRegion.AddJoint(cb);
                return(true);
            }
            else if (type == 13)
            {
                if (data.Length != len)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                JointFlyingDisc jfd = new JointFlyingDisc((PhysicsEntity)pe1)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jfd);
                return(true);
            }
            else if (type == 14)
            {
                if (data.Length != len)
                {
                    SysConsole.Output(OutputType.WARNING, "Joint packet: Bad length!");
                    return(false);
                }
                JointNoCollide jnc = new JointNoCollide((PhysicsEntity)pe1, (PhysicsEntity)pe2)
                {
                    JID = JID
                };
                TheClient.TheRegion.AddJoint(jnc);
                return(true);
            }
            else
            {
                SysConsole.Output(OutputType.WARNING, "Unknown joint type " + type);
                return(false);
            }
        }
コード例 #24
0
ファイル: ChunkVBO.cs プロジェクト: MoTo1496/Voxalia
        public void GenerateVBO()
        {
            if (generated)
            {
                Destroy();
            }
            GL.BindVertexArray(0);
            if (Vertices == null && verts == null)
            {
                SysConsole.Output(OutputType.ERROR, "Failed to render VBO, null vertices!");
                return;
            }
            Vector3[] vecs = verts ?? Vertices.ToArray();
            if (vecs.Length == 0)
            {
                return;
            }
            LastVRAM = 0;
            uint[]    inds  = indices ?? Indices.ToArray();
            Vector3[] norms = normals ?? Normals.ToArray();
            Vector3[] texs  = texts ?? TexCoords.ToArray();
            Vector3[] tangs = Tangents != null?Tangents.ToArray() : (tangents ?? TangentsFor(vecs, norms, texs));

            Vector4[] cols = Colors != null?Colors.ToArray() : v4_colors;

            Vector4[] tcols = TCOLs != null?TCOLs.ToArray() : v4_tcolors;

            Vector4[] thvs = THVs != null?THVs.ToArray() : v4_thvs;

            Vector4[] thws = THWs != null?THWs.ToArray() : v4_thws;

            Vector4[] thvs2 = THVs2 != null?THVs2.ToArray() : v4_thvs2;

            Vector4[] thws2 = THWs2 != null?THWs2.ToArray() : v4_thws2;

            vC = inds.Length;
            // Vertex buffer
            GL.GenBuffers(1, out _VertexVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _VertexVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vecs.Length * Vector3.SizeInBytes), vecs, BufferMode);
            LastVRAM += vecs.Length * Vector3.SizeInBytes;
            // Normal buffer
            GL.GenBuffers(1, out _NormalVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _NormalVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(norms.Length * Vector3.SizeInBytes), norms, BufferMode);
            LastVRAM += norms.Length * Vector3.SizeInBytes;
            // TexCoord buffer
            GL.GenBuffers(1, out _TexCoordVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TexCoordVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(texs.Length * Vector3.SizeInBytes), texs, BufferMode);
            LastVRAM += texs.Length * Vector3.SizeInBytes;
            GL.GenBuffers(1, out _TangentVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TangentVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(tangs.Length * Vector3.SizeInBytes), tangs, BufferMode);
            LastVRAM += tangs.Length * Vector3.SizeInBytes;
            // Color buffer
            if (cols != null)
            {
                colors = true;
                GL.GenBuffers(1, out _ColorVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _ColorVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(cols.Length * Vector4.SizeInBytes), cols, BufferMode);
                LastVRAM += cols.Length * Vector4.SizeInBytes;
            }
            // TCOL buffer
            if (tcols != null)
            {
                this.tcols = true;
                GL.GenBuffers(1, out _TCOLVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _TCOLVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (tcols.Length * Vector4.SizeInBytes), tcols, BufferMode);
                LastVRAM += tcols.Length * Vector4.SizeInBytes;
                GL.GenBuffers(1, out _THVVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THVVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (thvs.Length * Vector4.SizeInBytes), thvs, BufferMode);
                LastVRAM += thvs.Length * Vector4.SizeInBytes;
                GL.GenBuffers(1, out _THWVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THWVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (thws.Length * Vector4.SizeInBytes), thws, BufferMode);
                LastVRAM += thws.Length * Vector4.SizeInBytes;
                GL.GenBuffers(1, out _THV2VBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THV2VBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (thvs2.Length * Vector4.SizeInBytes), thvs2, BufferMode);
                LastVRAM += thvs2.Length * Vector4.SizeInBytes;
                GL.GenBuffers(1, out _THW2VBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THW2VBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (thws2.Length * Vector4.SizeInBytes), thws2, BufferMode);
                LastVRAM += thws2.Length * Vector4.SizeInBytes;
            }
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            // Index buffer
            GL.GenBuffers(1, out _IndexVBO);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, _IndexVBO);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(inds.Length * sizeof(uint)), inds, BufferMode);
            LastVRAM += inds.Length * sizeof(uint);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            // VAO
            GL.GenVertexArrays(1, out _VAO);
            GL.BindVertexArray(_VAO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _VertexVBO);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, 0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _NormalVBO);
            GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 0, 0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TexCoordVBO);
            GL.VertexAttribPointer(2, 3, VertexAttribPointerType.Float, false, 0, 0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, _TangentVBO);
            GL.VertexAttribPointer(3, 3, VertexAttribPointerType.Float, false, 0, 0);
            if (cols != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _ColorVBO);
                GL.VertexAttribPointer(4, 4, VertexAttribPointerType.Float, false, 0, 0);
            }
            if (tcols != null)
            {
                GL.BindBuffer(BufferTarget.ArrayBuffer, _TCOLVBO);
                GL.VertexAttribPointer(5, 4, VertexAttribPointerType.Float, false, 0, 0);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THVVBO);
                GL.VertexAttribPointer(6, 4, VertexAttribPointerType.Float, false, 0, 0);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THWVBO);
                GL.VertexAttribPointer(7, 4, VertexAttribPointerType.Float, false, 0, 0);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THV2VBO);
                GL.VertexAttribPointer(8, 4, VertexAttribPointerType.Float, false, 0, 0);
                GL.BindBuffer(BufferTarget.ArrayBuffer, _THW2VBO);
                GL.VertexAttribPointer(9, 4, VertexAttribPointerType.Float, false, 0, 0);
            }
            GL.EnableVertexAttribArray(0);
            GL.EnableVertexAttribArray(1);
            GL.EnableVertexAttribArray(2);
            GL.EnableVertexAttribArray(3);
            if (cols != null)
            {
                GL.EnableVertexAttribArray(4);
            }
            if (tcols != null)
            {
                GL.EnableVertexAttribArray(5);
                GL.EnableVertexAttribArray(6);
                GL.EnableVertexAttribArray(7);
                GL.EnableVertexAttribArray(8);
                GL.EnableVertexAttribArray(9);
            }
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, _IndexVBO);
            // Clean up
            GL.BindVertexArray(0);
            generated = true;
        }
コード例 #25
0
ファイル: World.cs プロジェクト: shuidong/Voxalia
        /// <summary>
        /// The entry point for world threads.
        /// </summary>
        public void Run()
        {
            SysConsole.Output(OutputType.INIT, "Preparing to tick world " + Name + "...");
            // Tick
            double    TARGETFPS    = 20d;
            Stopwatch Counter      = new Stopwatch();
            Stopwatch DeltaCounter = new Stopwatch();

            DeltaCounter.Start();
            double TotalDelta   = 0;
            double CurrentDelta = 0d;
            double TargetDelta  = 0d;
            int    targettime   = 0;

            while (true)
            {
                // Update the tick time usage counter
                Counter.Reset();
                Counter.Start();
                // Update the tick delta counter
                DeltaCounter.Stop();
                // Delta time = Elapsed ticks * (ticks/second)
                CurrentDelta = ((double)DeltaCounter.ElapsedTicks) / ((double)Stopwatch.Frequency);
                // How much time should pass between each tick ideally

                /*TARGETFPS = WorldSettings[FPS];
                 * if (TARGETFPS < 1 || TARGETFPS > 100)
                 * {
                 *  WorldSettings[FPS] = 20;
                 *  TARGETFPS = 20;
                 * }*/
                TargetDelta = (1d / TARGETFPS);
                // How much delta has been built up
                TotalDelta += CurrentDelta;
                if (TotalDelta > TargetDelta * 10)
                {
                    // Lagging - cheat to catch up!
                    TargetDelta *= 3;
                }
                if (TotalDelta > TargetDelta * 10)
                {
                    // Lagging a /lot/ - cheat /extra/ to catch up!
                    TargetDelta *= 3;
                }
                if (TotalDelta > TargetDelta * 10)
                {
                    // At this point, the server's practically dead.
                    TargetDelta *= 3;
                }
                // Give up on acceleration at this point. 50 * 27 = 1.35 seconds / tick under a default tickrate.
                // As long as there's more delta built up than delta wanted, tick
                while (TotalDelta > TargetDelta)
                {
                    Tick(TargetDelta);
                    TotalDelta -= TargetDelta;
                }
                // Begin the delta counter to find out how much time is /really/ slept for
                DeltaCounter.Reset();
                DeltaCounter.Start();
                // The tick is done, stop measuring it
                Counter.Stop();
                // Only sleep for target milliseconds/tick minus how long the tick took... this is imprecise but that's okay
                targettime = (int)((1000d / TARGETFPS) - Counter.ElapsedMilliseconds);
                // Only sleep at all if we're not lagging
                if (targettime > 0)
                {
                    // Try to sleep for the target time - very imprecise, thus we deal with precision inside the tick code
                    Thread.Sleep(targettime);
                }
            }
        }
コード例 #26
0
ファイル: UIConsole.cs プロジェクト: BlackCoyote/Voxalia
 /// <summary>
 /// Writes a line of text to the console.
 /// </summary>
 /// <param name="text">The text to be written.</param>
 public static void WriteLine(string text)
 {
     Write(FreneticScript.TextStyle.Default + text + "\n");
     SysConsole.Output(OutputType.CLIENTINFO, text);
 }
コード例 #27
0
        public override TemplateObject Handle(TagData data)
        {
            if (data.Remaining == 0)
            {
                return(this);
            }
            switch (data[0])
            {
            // <--[tag]
            // @Name ColorTag.red
            // @Group General Information
            // @ReturnType NumberTag
            // @Returns the red value of this color.
            // @Example "0.1,0.2,0.3,1" .red returns "0.1".
            // -->
            case "red":
                return(new NumberTag(Internal.r).Handle(data.Shrink()));

            // <--[tag]
            // @Name ColorTag.green
            // @Group General Information
            // @ReturnType NumberTag
            // @Returns the green value of this color.
            // @Example "0.1,0.2,0.3,1" .green returns "0.2".
            // -->
            case "green":
                return(new NumberTag(Internal.g).Handle(data.Shrink()));

            // <--[tag]
            // @Name ColorTag.blue
            // @Group General Information
            // @ReturnType NumberTag
            // @Returns the blue value of this color.
            // @Example "0.1,0.2,0.3,1" .red returns "0.3".
            // -->
            case "blue":
                return(new NumberTag(Internal.b).Handle(data.Shrink()));

            // <--[tag]
            // @Name ColorTag.alpha
            // @Group General Information
            // @ReturnType NumberTag
            // @Returns the alpha value of this color.
            // @Example "0.1,0.2,0.3,1" .red returns "1".
            // -->
            case "alpha":
                return(new NumberTag(Internal.a).Handle(data.Shrink()));

            // <--[tag]
            // @Name ColorTag.mix[<ColorTag>|...]
            // @Group Mathematics
            // @ReturnType ColorTag
            // @Returns the result of mixing the specified color(s) with this one.
            // @Example "blue" .mix[red] returns "0.5,0,0.5,1"
            // -->
            case "mix":
            {
                ListTag list       = ListTag.For(data.GetModifierObject(0));
                Color   mixedColor = Internal;
                foreach (TemplateObject tcolor in list.ListEntries)
                {
                    ColorTag color = ColorTag.For(tcolor);
                    if (color == null)
                    {
                        SysConsole.Output(OutputType.ERROR, "Invalid color: " + TagParser.Escape(tcolor.ToString()));
                        continue;
                    }
                    mixedColor += color.Internal;
                }
                return(new ColorTag(mixedColor / list.ListEntries.Count).Handle(data.Shrink()));
            }

            default:
                return(new TextTag(ToString()).Handle(data));
            }
        }
コード例 #28
0
        public void Update(Location position, Location forward, Location up, Location velocity, bool selected)
        {
            CPosition = position;
            if (AudioInternal == null)
            {
                ALError err = AL.GetError();
                if (err != ALError.NoError)
                {
                    SysConsole.Output(OutputType.WARNING, "Found audio error " + err + "!");
                    //init(TheClient, CVars);
                    return;
                }
            }
            bool sel = CVars.a_quietondeselect.ValueB ? selected : true;

            Selected = sel;
            if (DeafenTime > 0.0)
            {
                TimeDeaf   += TheClient.Delta;
                DeafenTime -= TheClient.Delta;
                if (DeafNoise == null)
                {
                    DeafNoise = PlaySimpleInternal(DeafLoop, true);
                    if (DeafNoise == null)
                    {
                        DeafenTime = 0;
                        TimeDeaf   = 0;
                    }
                }
                if (DeafenTime < 0)
                {
                    TimeDeaf   = 0;
                    DeafenTime = 0;
                    DeafNoise.Stop();
                    DeafNoise.Destroy();
                    DeafNoise = null;
                }
            }
            if (TimeDeaf > 0.001 && DeafenTime > 0.001)
            {
                float weaken = (float)Math.Min(DeafenTime, TimeDeaf);
                if (weaken < 1.0)
                {
                    DeafNoise.Gain = (float)weaken * 0.5f;
                    DeafNoise.UpdateGain();
                }
                else
                {
                    DeafNoise.Gain = 0.5f;
                    DeafNoise.UpdateGain();
                }
            }
            DeafLoop.LastUse = TheClient.GlobalTickTimeLocal;
            for (int i = 0; i < PlayingNow.Count; i++)
            {
                if (!PlayingNow[i].Exists || PlayingNow[i].Src < 0 || (AudioInternal == null ? AL.GetSourceState(PlayingNow[i].Src) == ALSourceState.Stopped : PlayingNow[i].AudioInternal.State == AudioState.DONE))
                {
                    PlayingNow[i].Destroy();
                    if (AudioInternal == null)
                    {
                        CheckError("Destroy:" + PlayingNow[i].Effect.Name);
                    }
                    PlayingNow.RemoveAt(i);
                    i--;
                    continue;
                }
                PlayingNow[i].Effect.LastUse = TheClient.GlobalTickTimeLocal;
                if ((TimeDeaf > 0.0) && sel && !PlayingNow[i].IsBackground)
                {
                    PlayingNow[i].IsDeafened = true;
                    float lesser = (float)Math.Min(DeafenTime, TimeDeaf);
                    if (lesser < 0.999)
                    {
                        if (AudioInternal == null)
                        {
                            AL.Source(PlayingNow[i].Src, ALSourcef.Gain, PlayingNow[i].Gain * (1.0f - lesser));
                        }
                        else
                        {
                            PlayingNow[i].AudioInternal.Gain = PlayingNow[i].Gain * (1.0f - lesser);
                        }
                    }
                    else
                    {
                        if (AudioInternal == null)
                        {
                            AL.Source(PlayingNow[i].Src, ALSourcef.Gain, 0.0001f);
                        }
                        else
                        {
                            PlayingNow[i].AudioInternal.Gain = 0.0001f;
                        }
                    }
                }
                else if ((TimeDeaf <= 0.0) && sel && !PlayingNow[i].IsBackground)
                {
                    if (AudioInternal == null)
                    {
                        AL.Source(PlayingNow[i].Src, ALSourcef.Gain, PlayingNow[i].Gain);
                    }
                    else
                    {
                    }
                    PlayingNow[i].IsDeafened = false;
                }
                if ((TimeDeaf <= 0.0) && !sel && PlayingNow[i].IsBackground && !PlayingNow[i].Backgrounded)
                {
                    if (AudioInternal == null)
                    {
                        AL.Source(PlayingNow[i].Src, ALSourcef.Gain, 0.0001f);
                    }
                    else
                    {
                        PlayingNow[i].AudioInternal.Gain = 0.0001f;
                    }
                    PlayingNow[i].Backgrounded = true;
                }
                else if ((TimeDeaf <= 0.0) && sel && PlayingNow[i].Backgrounded)
                {
                    if (AudioInternal == null)
                    {
                        AL.Source(PlayingNow[i].Src, ALSourcef.Gain, PlayingNow[i].Gain);
                    }
                    else
                    {
                        PlayingNow[i].AudioInternal.Gain = PlayingNow[i].Gain;
                    }
                    PlayingNow[i].Backgrounded = false;
                    PlayingNow[i].IsDeafened   = false;
                }
            }
            CheckError("Setup");
            if (Microphone != null)
            {
                Microphone.Tick();
            }
            CheckError("Microphone");
            float globvol = CVars.a_globalvolume.ValueF;

            globvol = globvol <= 0 ? 0.001f : (globvol > 1 ? 1 : globvol);
            if (AudioInternal == null)
            {
                Vector3 pos   = ClientUtilities.Convert(position);
                Vector3 forw  = ClientUtilities.Convert(forward);
                Vector3 upvec = ClientUtilities.Convert(up);
                Vector3 vel   = ClientUtilities.Convert(velocity);
                AL.Listener(ALListener3f.Position, ref pos);
                AL.Listener(ALListenerfv.Orientation, ref forw, ref upvec);
                AL.Listener(ALListener3f.Velocity, ref vel);
                CheckError("Positioning");
                AL.Listener(ALListenerf.Gain, globvol);
                CheckError("Gain");
            }
            else
            {
                // TODO: vel
                AudioInternal.Left             = CVars.a_left.ValueB;
                AudioInternal.Right            = CVars.a_right.ValueB;
                AudioInternal.Position         = position;
                AudioInternal.ForwardDirection = forward;
                AudioInternal.UpDirection      = up;
                AudioInternal.Volume           = globvol;
            }
            TimeTowardsNextClean += TheClient.Delta;
            if (TimeTowardsNextClean > 10.0)
            {
                CleanTick();
                TimeTowardsNextClean = 0.0;
            }
        }
コード例 #29
0
 public void LoadSkin(TextureEngine texs)
 {
     if (Skinned)
     {
         return;
     }
     Skinned = true;
     if (Engine.TheClient.Files.Exists("models/" + Name + ".skin"))
     {
         string[] data = Engine.TheClient.Files.ReadText("models/" + Name + ".skin").SplitFast('\n');
         foreach (string datum in data)
         {
             if (datum.Length > 0)
             {
                 string[] datums = datum.SplitFast('=');
                 if (datums.Length == 2)
                 {
                     Texture tex     = texs.GetTexture(datums[1]);
                     bool    success = false;
                     string  typer;
                     string  datic = datums[0].BeforeAndAfter(":::", out typer);
                     typer = typer.ToLowerFast();
                     for (int i = 0; i < Meshes.Count; i++)
                     {
                         if (Meshes[i].Name == datic)
                         {
                             if (typer == "specular")
                             {
                                 Meshes[i].vbo.Tex_Specular = tex;
                             }
                             else if (typer == "reflectivity")
                             {
                                 Meshes[i].vbo.Tex_Reflectivity = tex;
                             }
                             else if (typer == "normal")
                             {
                                 Meshes[i].vbo.Tex_Normal = tex;
                             }
                             else if (typer == "")
                             {
                                 Meshes[i].vbo.Tex = tex;
                             }
                             else
                             {
                                 SysConsole.Output(OutputType.WARNING, "Unknown skin entry typer: '" + typer + "', expected reflectivity, specular, or simply no specification!");
                             }
                             success = true;
                         }
                     }
                     if (!success)
                     {
                         SysConsole.Output(OutputType.WARNING, "Unknown skin entry " + datums[0]);
                         StringBuilder all = new StringBuilder(Meshes.Count * 100);
                         for (int i = 0; i < Meshes.Count; i++)
                         {
                             all.Append(Meshes[i].Name + ", ");
                         }
                         SysConsole.Output(OutputType.WARNING, "Available: " + all.ToString());
                     }
                 }
             }
         }
     }
     else
     {
         SysConsole.Output(OutputType.WARNING, "Can't find models/" + Name + ".skin!");
     }
 }
コード例 #30
0
 private static void PackageWarningMethod(string warning)
 {
     SysConsole.Output(OutputType.WARNING, "[FileEngine/PackageHandler] " + warning);
 }