Example #1
0
        public void DrawRectangle(Rectangle bounds, Color color, int thicknessLeft, int thicknessTop, int thicknessRight, int thicknessBottom)
        {
            var texture = GpuResourceManager.GetTexture2D(this, Graphics, 1, 1, false, SurfaceFormat.Color);

            texture.SetData(new Color[] { color });

            // MinY
            if (thicknessTop > 0)
            {
                SpriteBatch.Draw(texture, new Rectangle(bounds.X, bounds.Y, bounds.Width, thicknessTop), color);
            }

            // MaxX
            if (thicknessRight > 0)
            {
                SpriteBatch.Draw(texture,
                                 new Rectangle(bounds.X + bounds.Width - thicknessRight, bounds.Y, thicknessRight, bounds.Height),
                                 color);
            }

            // MaxY
            if (thicknessBottom > 0)
            {
                SpriteBatch.Draw(texture,
                                 new Rectangle(bounds.X, bounds.Y + bounds.Height - thicknessBottom, bounds.Width, thicknessBottom),
                                 color);
            }

            // MinX
            if (thicknessLeft > 0)
            {
                SpriteBatch.Draw(texture, new Rectangle(bounds.X, bounds.Y, thicknessLeft, bounds.Height), color);
            }
        }
Example #2
0
        private void SetupClouds(GraphicsDevice device, int planeDistance)
        {
            CloudsPlaneEffect            = new AlphaTestEffect(device);
            CloudsPlaneEffect.Texture    = CloudTexture;
            CloudsPlaneEffect.FogEnabled = true;
            CloudsPlaneEffect.FogEnd     = 64 * 0.8f;
            CloudsPlaneEffect.FogStart   = 0f;
            //CloudsPlaneEffect.FogEnabled = false;
            //CloudsPlaneEffect.DiffuseColor
            //CloudsPlaneEffect.TextureEnabled = true;
            //CloudsPlaneEffect.Alpha = 0.5f;

            var cloudVertices = new[]
            {
                new VertexPositionTexture(new Vector3(-planeDistance, 0, -planeDistance), new Vector2(0, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, 1)),

                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, planeDistance), new Vector2(1, 1)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, 1))
            };


            CloudsPlane = GpuResourceManager.GetBuffer(this, device, VertexPositionTexture.VertexDeclaration,
                                                       cloudVertices.Length, BufferUsage.WriteOnly);
            CloudsPlane.SetData <VertexPositionTexture>(cloudVertices);
        }
Example #3
0
        private PooledTexture2D GetMipMappedTexture2D(GraphicsDevice device, Image <Rgba32> image)
        {
            //device.VertexSamplerStates.
            PooledTexture2D texture = GpuResourceManager.GetTexture2D(this, device, image.Width, image.Height, true, SurfaceFormat.Color);

            // Directory.CreateDirectory(name);
            // var resampler = new BicubicResampler();
            // var encoder = new PngEncoder();
            for (int level = 0; level < Alex.MipMapLevel; level++)
            {
                int mipWidth  = (int)System.Math.Max(1, image.Width >> level);
                int mipHeight = (int)System.Math.Max(1, image.Height >> level);

                var bmp = image.CloneAs <Rgba32>();            //.CloneAs<Rgba32>();
                bmp.Mutate(x => x.Resize(mipWidth, mipHeight, KnownResamplers.NearestNeighbor, true));

                uint[] colorData;

                if (bmp.TryGetSinglePixelSpan(out var pixelSpan))
                {
                    colorData = pixelSpan.ToArray().Select(x => x.Rgba).ToArray();
                }
                else
                {
                    throw new Exception("Could not get image data!");
                }

                //TODO: Resample per texture instead of whole texture map.

                texture.SetData(level, null, colorData, 0, colorData.Length);
            }

            return(texture);
        }
Example #4
0
        public static bool TryGetSkin(Uri skinUri, GraphicsDevice graphics, out PooledTexture2D texture)
        {
            try
            {
                byte[] data;
                using (WebClient wc = new WebClient())
                {
                    data = wc.DownloadData(skinUri);
                }

                using (MemoryStream ms = new MemoryStream(data))
                {
                    texture = GpuResourceManager.GetTexture2D("SkinUtils", graphics, ms);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Warn(ex, $"Could not retrieve skin: {ex.ToString()}");
            }

            texture = null;
            return(false);
        }
Example #5
0
            private void UpdateVertexBuffer(GraphicsDevice device)
            {
                if (_disposed || _updateQueued)
                {
                    return;
                }

                var indices = Indices;
                PooledIndexBuffer currentBuffer = Buffer;

                if (indices.Length > 0 && (Buffer == null || currentBuffer.IndexCount != indices.Length))
                {
                    _updateQueued = true;

                    Alex.Instance.UIThreadQueue.Enqueue(
                        () =>
                    {
                        if (_disposed)
                        {
                            return;
                        }

                        PooledIndexBuffer buffer = GpuResourceManager.GetIndexBuffer(
                            this, device, IndexElementSize.SixteenBits, indices.Length, BufferUsage.None);

                        buffer.SetData(indices);
                        Buffer = buffer;

                        currentBuffer?.MarkForDisposal();

                        _updateQueued = false;
                    });
                }
            }
Example #6
0
 public PooledVertexBuffer(GpuResourceManager parent, long id, object owner, GraphicsDevice graphicsDevice, VertexDeclaration vertexDeclaration, int vertexCount, BufferUsage bufferUsage) : base(graphicsDevice, vertexDeclaration, vertexCount, bufferUsage)
 {
     Parent      = parent;
     PoolId      = id;
     CreatedTime = DateTime.UtcNow;
     Owner       = owner;
 }
Example #7
0
 public PooledTexture2D(GpuResourceManager parent, long id, object owner, GraphicsDevice graphicsDevice, int width, int height) : base(graphicsDevice, width, height)
 {
     Parent      = parent;
     PoolId      = id;
     CreatedTime = DateTime.UtcNow;
     Owner       = owner;
 }
Example #8
0
 public PooledTexture2D(GpuResourceManager parent, long id, object owner, GraphicsDevice graphicsDevice, int width, int height, bool mipmap, SurfaceFormat format, int arraySize) : base(graphicsDevice, width, height, mipmap, format, arraySize)
 {
     Parent      = parent;
     PoolId      = id;
     CreatedTime = DateTime.UtcNow;
     Owner       = owner;
 }
Example #9
0
 public PooledIndexBuffer(GpuResourceManager parent, long id, object owner, GraphicsDevice graphicsDevice, IndexElementSize indexElementSize, int indexCount, BufferUsage bufferUsage) : base(graphicsDevice, indexElementSize, indexCount, bufferUsage)
 {
     Parent      = parent;
     PoolId      = id;
     CreatedTime = DateTime.UtcNow;
     Owner       = owner;
 }
Example #10
0
        public static PooledTexture2D BitmapToTexture2D(GraphicsDevice device, Image <Rgba32> image, out long byteSize)
        {
            var bmp       = image;//.CloneAs<Rgba32>();
            var pixels    = bmp.GetPixelSpan();
            var colorData = pixels.ToArray().Select(x => x.Rgba).ToArray();

            PooledTexture2D texture = GpuResourceManager.GetTexture2D("Image converter", device, image.Width, image.Height);

            texture.SetData(colorData);

            byteSize = texture.MemoryUsage;
            return(texture);

            /*for (int x = 0; x < bmp.Width; x++)
             * {
             *      for (int y = 0; y < bmp.Height; y++)
             *      {
             *
             *      }
             * }
             * using (MemoryStream ms = new MemoryStream())
             * {
             *      bmp.SaveAsPng(ms);
             *
             *      ms.Position = 0;
             *      byteSize = ms.Length;
             *      return GpuResourceManager.GetTexture2D("Alex.Api.Utils.TextureUtils.ImageToTexture2D", device, ms);
             * }*/
        }
Example #11
0
        public void FillRectangle(Rectangle bounds, Color color)
        {
            var texture = GpuResourceManager.GetTexture2D(this, Graphics, 1, 1, false, SurfaceFormat.Color);

            texture.SetData(new Color[] { color });

            SpriteBatch.Draw(texture, bounds, Color.White);
        }
Example #12
0
        private void Cache(EntityModel model, Dictionary <string, ModelBone> modelBones)
        {
            List <VertexPositionNormalTexture> vertices = new List <VertexPositionNormalTexture>();

            var textureSize = new Vector2(model.Texturewidth, model.Textureheight);
            var newSize     = new Vector2(Texture.Width, Texture.Height);

            if (textureSize.X == 0 && textureSize.Y == 0)
            {
                textureSize = newSize;
            }

            var uvScale = newSize / textureSize;

            foreach (var bone in model.Bones.Where(x => string.IsNullOrWhiteSpace(x.Parent)))
            {
                //if (bone.NeverRender) continue;
                if (modelBones.ContainsKey(bone.Name))
                {
                    continue;
                }

                ProcessBone(bone, vertices, uvScale, textureSize, modelBones);
            }

            foreach (var bone in model.Bones.Where(x => !string.IsNullOrWhiteSpace(x.Parent)))
            {
                //if (bone.NeverRender) continue;
                if (modelBones.ContainsKey(bone.Name))
                {
                    continue;
                }

                var newBone = ProcessBone(bone, vertices, uvScale, textureSize, modelBones);

                if (modelBones.TryGetValue(bone.Parent, out ModelBone parentBone))
                {
                    parentBone.Children = parentBone.Children.Concat(new[] { newBone }).ToArray();
                    newBone.Parent      = parentBone;

                    modelBones[bone.Parent] = parentBone;
                }
            }

            if (vertices.Count == 0)
            {
                //	Log.Warn($"No vertices. {JsonConvert.SerializeObject(model,Formatting.Indented)}");
                Valid     = true;
                CanRender = false;
                return;
            }

            VertexBuffer = GpuResourceManager.GetBuffer(this, Alex.Instance.GraphicsDevice,
                                                        VertexPositionNormalTexture.VertexDeclaration, vertices.Count, BufferUsage.None);
            VertexBuffer.SetData(vertices.ToArray());

            Valid = true;
        }
Example #13
0
        public static PooledTexture2D BitmapToTexture2D(GraphicsDevice device, Image <Rgba32> image, out long byteSize)
        {
            var bmp = image;    //.CloneAs<Rgba32>();

            uint[] colorData;
            if (bmp.TryGetSinglePixelSpan(out var pixelSpan))
            {
                colorData = pixelSpan.ToArray().Select(x => x.Rgba).ToArray();
            }
            else
            {
                throw new Exception("Could not get image data!");
            }
            // var colorData = pixels.ToArray().Select(x => x.Rgba).ToArray();

            PooledTexture2D result = null;

            if (Thread.CurrentThread != RenderThread)
            {
                AutoResetEvent resetEvent = new AutoResetEvent(false);
                QueueOnRenderThread(
                    () =>
                {
                    result = GpuResourceManager.GetTexture2D("Image converter", device, image.Width, image.Height);
                    result.SetData(colorData);

                    resetEvent.Set();
                });
                resetEvent.WaitOne();
            }
            else
            {
                result = GpuResourceManager.GetTexture2D("Image converter", device, image.Width, image.Height);
                result.SetData(colorData);
            }

            byteSize = result.MemoryUsage;
            return(result);

            /*for (int x = 0; x < bmp.Width; x++)
             * {
             *      for (int y = 0; y < bmp.Height; y++)
             *      {
             *
             *      }
             * }
             * using (MemoryStream ms = new MemoryStream())
             * {
             *      bmp.SaveAsPng(ms);
             *
             *      ms.Position = 0;
             *      byteSize = ms.Length;
             *      return GpuResourceManager.GetTexture2D("Alex.Api.Utils.TextureUtils.ImageToTexture2D", device, ms);
             * }*/
        }
Example #14
0
        private IndexBuffer RenewIndexBuffer(GraphicsDevice graphicsDevice, int[] vertices)
        {
            IndexBuffer buffer = GpuResourceManager.GetIndexBuffer(this, graphicsDevice, IndexElementSize.ThirtyTwoBits, vertices.Length, BufferUsage.WriteOnly);

            if (vertices.Length > 0)
            {
                buffer.SetData(vertices);
            }

            return(buffer);
        }
Example #15
0
            public bool GetIcon(GraphicsDevice device, out Texture2D icon)
            {
                if (!HasIcon)
                {
                    icon = null;
                    return(false);
                }

                icon = GpuResourceManager.GetTexture2D(this, device, Width, Height);
                icon.SetData(Icon);
                return(true);
            }
Example #16
0
        private Texture2D CreateTexture(GraphicsDevice graphics, Rectangle bounds, Color color)
        {
            var texture = GpuResourceManager.GetTexture2D(this, graphics, bounds.Width, bounds.Height, false, SurfaceFormat.Color);
            var data    = new Color[bounds.Width * bounds.Height];

            for (var i = 0; i < data.Length; i++)
            {
                data[i] = color;
            }
            texture.SetData(data);
            return(texture);
        }
Example #17
0
        private void Cache(PooledTexture2D texture, EntityModel model, Dictionary <string, ModelBone> modelBones)
        {
            List <VertexPositionColorTexture> vertices = new List <VertexPositionColorTexture>();

            //var modelTextureSize = model.Description != null ?
            //	new Vector2(model.Description.TextureWidth, model.Description.TextureHeight) :
            //	new Vector2(model.Texturewidth, model.Textureheight);

            var modelTextureSize = new Vector2(model.Description.TextureWidth, model.Description.TextureHeight);

            var actualTextureSize = new Vector2(texture.Width, texture.Height);

            if (modelTextureSize.X == 0 && modelTextureSize.Y == 0)
            {
                modelTextureSize = actualTextureSize;
            }

            var uvScale = actualTextureSize / modelTextureSize;            // / actualTextureSize;

            foreach (var bone in model.Bones.Where(x => string.IsNullOrWhiteSpace(x.Parent)))
            {
                //if (bone.NeverRender) continue;
                if (modelBones.ContainsKey(bone.Name))
                {
                    continue;
                }

                var processed = ProcessBone(texture, model, bone, vertices, uvScale, actualTextureSize, modelBones);

                if (!modelBones.TryAdd(bone.Name, processed))
                {
                    Log.Warn($"Failed to add bone! {bone.Name}");
                }
            }

            if (vertices.Count == 0)
            {
                //Log.Warn($"No vertices.");

                Valid     = true;
                CanRender = false;
                return;
            }

            VertexBuffer = GpuResourceManager.GetBuffer(this, Alex.Instance.GraphicsDevice,
                                                        VertexPositionColorTexture.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly);
            VertexBuffer.SetData(vertices.ToArray());

            Valid    = true;
            _texture = texture;
        }
Example #18
0
        public override Texture2D ReadJson(JsonReader reader, Type objectType, Texture2D existingValue, bool hasExistingValue,
                                           JsonSerializer serializer)
        {
            try
            {
                string base64Value = reader.Value.ToString();

                if (string.IsNullOrWhiteSpace(base64Value))
                {
                    return(null);
                }

                byte[] data = Convert.FromBase64String(base64Value);

                if (!Program.IsRunningOnStartupThread())
                {
                    ManualResetEvent resetEvent = new ManualResetEvent(false);

                    Texture2D result = null;

                    Alex.Instance.UIThreadQueue.Enqueue(
                        () =>
                    {
                        using (MemoryStream stream = new MemoryStream(data))
                        {
                            result = GpuResourceManager.GetTexture2D(
                                this, GraphicsDevice, stream);                                         //Texture2D.FromStream(GraphicsDevice, stream);
                        }

                        resetEvent.Set();
                    });

                    resetEvent.WaitOne();

                    return(result);
                }
                else
                {
                    using (MemoryStream stream = new MemoryStream(data))
                    {
                        return(GpuResourceManager.GetTexture2D(
                                   this, GraphicsDevice, stream));                     //Texture2D.FromStream(GraphicsDevice, stream);
                    }
                }
            }
            catch
            {
                return(null);
            }
        }
Example #19
0
        private DynamicVertexBuffer RenewVertexBuffer(GraphicsDevice graphicsDevice, VertexPositionNormalTextureColor[] vertices)
        {
            DynamicVertexBuffer buffer = GpuResourceManager.GetBuffer(this, graphicsDevice,
                                                                      VertexPositionNormalTextureColor.VertexDeclaration,
                                                                      vertices.Length,
                                                                      BufferUsage.WriteOnly);

            if (vertices.Length > 0)
            {
                buffer.SetData(vertices);
            }

            return(buffer);
        }
Example #20
0
        public static bool TryGetSkin(string json, GraphicsDevice graphics, out PooledTexture2D texture, out bool isSlim)
        {
            isSlim = false;
            try
            {
                TexturesResponse r = JsonConvert.DeserializeObject <TexturesResponse>(json);
                if (r != null)
                {
                    string url = r.textures?.SKIN?.url;
                    if (url != null)
                    {
                        byte[] data;
                        using (WebClient wc = new WebClient())
                        {
                            data = wc.DownloadData(url);
                        }

                        ManualResetEvent resetEvent = new ManualResetEvent(false);

                        PooledTexture2D text = null;
                        Alex.Instance.UIThreadQueue.Enqueue(
                            () =>
                        {
                            using (MemoryStream ms = new MemoryStream(data))
                            {
                                text = GpuResourceManager.GetTexture2D(
                                    "SkinUtils", graphics, ms);                                             // Texture2D.FromStream(graphics, ms);
                            }

                            resetEvent.Set();
                        });

                        resetEvent.WaitOne();

                        texture = text;
                        isSlim  = (r.textures.SKIN.metadata?.model == "slim");

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex, $"Could not retrieve skin: {ex.ToString()}");
            }

            texture = null;
            return(false);
        }
Example #21
0
        private void BuildModel(PooledTexture2D texture, EntityModel model, Dictionary <string, ModelBone> modelBones)
        {
            List <VertexPositionColorTexture> vertices = new List <VertexPositionColorTexture>();

            var actualTextureSize = new Vector2(texture.Width, texture.Height);

            int counter = 0;

            foreach (var bone in model.Bones.Where(x => string.IsNullOrWhiteSpace(x.Parent)))
            {
                //if (bone.NeverRender) continue;
                if (string.IsNullOrWhiteSpace(bone.Name))
                {
                    bone.Name = $"bone{counter++}";
                }

                if (modelBones.ContainsKey(bone.Name))
                {
                    continue;
                }

                var processed = ProcessBone(model, bone, ref vertices, actualTextureSize, modelBones);

                if (!modelBones.TryAdd(bone.Name, processed))
                {
                    Log.Warn($"Failed to add bone! {bone.Name}");
                }
            }

            if (vertices.Count == 0)
            {
                Valid = true;
                return;
            }

            VertexBuffer = GpuResourceManager.GetBuffer(this, Alex.Instance.GraphicsDevice,
                                                        VertexPositionColorTexture.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly);
            VertexBuffer.SetData(vertices.ToArray());

            Effect                    = new AlphaTestEffect(Alex.Instance.GraphicsDevice);
            Effect.Texture            = texture;
            Effect.VertexColorEnabled = true;

            Valid    = true;
            _texture = texture;
        }
Example #22
0
            private void UpdateVertexBuffer(GraphicsDevice device)
            {
                var indices = Parts.SelectMany(x => x.Indexes).ToArray();

                IndexBuffer currentBuffer = Buffer;

                if (indices.Length > 0 && (Buffer == null || currentBuffer.IndexCount != indices.Length))
                {
                    IndexBuffer buffer = GpuResourceManager.GetIndexBuffer(this, device, IndexElementSize.SixteenBits,
                                                                           indices.Length, BufferUsage.None);

                    buffer.SetData(indices);
                    Buffer = buffer;

                    currentBuffer?.Dispose();
                }
            }
Example #23
0
            private void UpdateVertexBuffer(GraphicsDevice device)
            {
                var indices = Indices;

                PooledIndexBuffer currentBuffer = Buffer;

                if (indices.Length > 0 && (Buffer == null || currentBuffer.IndexCount != indices.Length))
                {
                    PooledIndexBuffer buffer = GpuResourceManager.GetIndexBuffer(this, device, IndexElementSize.SixteenBits,
                                                                                 indices.Length, BufferUsage.None);

                    buffer.SetData(indices);
                    Buffer = buffer;

                    currentBuffer?.MarkForDisposal();
                }
            }
Example #24
0
        public static bool TryGetSkin(Uri skinUri, GraphicsDevice graphics, out PooledTexture2D texture)
        {
            if (!Program.IsRunningOnStartupThread())
            {
                AutoResetEvent  resetEvent = new AutoResetEvent(false);
                bool            result     = false;
                PooledTexture2D rTexture   = null;
                Alex.Instance.UIThreadQueue.Enqueue(
                    () =>
                {
                    result = TryGetSkin(skinUri, graphics, out rTexture);
                    resetEvent.Set();
                });

                resetEvent.WaitOne();

                texture = rTexture;
                return(result);
            }

            try
            {
                byte[] data;
                using (WebClient wc = new WebClient())
                {
                    data = wc.DownloadData(skinUri);
                }

                using (MemoryStream ms = new MemoryStream(data))
                {
                    texture = GpuResourceManager.GetTexture2D("SkinUtils", graphics, ms);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Warn(ex, $"Could not retrieve skin: {ex.ToString()}");
            }

            texture = null;
            return(false);
        }
Example #25
0
        private void SetVertices()
        {
            var b = _blockStates[_index];

            var vertices = b.Model
                           .GetVertices(World
                                        , Vector3.Zero, _blockStates[_index].Block);

            if (vertices.vertices.Length > 0 && vertices.indexes.Length > 0)
            {
                var oldBuffer      = _buffer;
                var oldIndexBuffer = _indexBuffer;

                var newBuffer = GpuResourceManager.GetBuffer(this, Alex.GraphicsDevice,
                                                             VertexPositionNormalTextureColor.VertexDeclaration,
                                                             vertices.vertices.Length, BufferUsage.None);

                var newIndexBuffer = GpuResourceManager.GetIndexBuffer(this, Alex.GraphicsDevice,
                                                                       IndexElementSize.ThirtyTwoBits,
                                                                       vertices.indexes.Length, BufferUsage.None);

                newBuffer.SetData(vertices.vertices);

                newIndexBuffer.SetData(vertices.indexes);

                _buffer      = newBuffer;
                _indexBuffer = newIndexBuffer;

                oldIndexBuffer?.MarkForDisposal();
                oldBuffer?.MarkForDisposal();

                GraphicsDevice.Indices = _indexBuffer;
                GraphicsDevice.SetVertexBuffer(_buffer);

                _canRender = true;
            }

            // _vertices = vertices.vertices;
            // _indices = vertices.indexes;
        }
Example #26
0
        public static bool TryGetSkin(Uri skinUri, GraphicsDevice graphics, out PooledTexture2D texture)
        {
            try
            {
                byte[] data;
                using (WebClient wc = new WebClient())
                {
                    data = wc.DownloadData(skinUri);
                }

                ManualResetEvent resetEvent = new ManualResetEvent(false);

                PooledTexture2D text = null;
                Alex.Instance.UIThreadQueue.Enqueue(
                    () =>
                {
                    using (MemoryStream ms = new MemoryStream(data))
                    {
                        text = GpuResourceManager.GetTexture2D(
                            "SkinUtils", graphics, ms);                                     // Texture2D.FromStream(graphics, ms);
                    }

                    resetEvent.Set();
                });

                resetEvent.WaitOne();

                texture = text;

                return(true);
            }
            catch (Exception ex)
            {
                Log.Warn(ex, $"Could not retrieve skin: {ex.ToString()}");
            }

            texture = null;
            return(false);
        }
Example #27
0
        public SkyBox(IServiceProvider serviceProvider, GraphicsDevice device, World world)
        {
            World = world;
            //Game = alex;
            var alex = serviceProvider.GetRequiredService <Alex>();

            OptionsProvider = serviceProvider.GetRequiredService <IOptionsProvider>();

            if (alex.Resources.ResourcePack.TryGetBitmap("environment/sun", out var sun))
            {
                SunTexture = TextureUtils.BitmapToTexture2D(device, sun);
            }
            else
            {
                CanRender = false;
                return;
            }

            if (alex.Resources.ResourcePack.TryGetBitmap("environment/moon_phases", out var moonPhases))
            {
                MoonTexture = TextureUtils.BitmapToTexture2D(device, moonPhases);
            }
            else
            {
                CanRender = false;
                return;
            }

            if (alex.Resources.ResourcePack.TryGetBitmap("environment/clouds", out var cloudTexture))
            {
                CloudTexture = TextureUtils.BitmapToTexture2D(device, cloudTexture);
                EnableClouds = false;
            }
            else
            {
                EnableClouds = false;
            }

            //var d = 144;

            CelestialPlaneEffect = new BasicEffect(device);
            CelestialPlaneEffect.VertexColorEnabled = false;
            CelestialPlaneEffect.LightingEnabled    = false;
            CelestialPlaneEffect.TextureEnabled     = true;

            SkyPlaneEffect = new BasicEffect(device);
            SkyPlaneEffect.VertexColorEnabled = false;
            SkyPlaneEffect.FogEnabled         = true;
            SkyPlaneEffect.FogStart           = 0;
            SkyPlaneEffect.FogEnd             = 64 * 0.8f;
            SkyPlaneEffect.LightingEnabled    = true;

            var planeDistance = 64;
            var plane         = new[]
            {
                new VertexPositionColor(new Vector3(-planeDistance, 0, -planeDistance), Color.White),
                new VertexPositionColor(new Vector3(planeDistance, 0, -planeDistance), Color.White),
                new VertexPositionColor(new Vector3(-planeDistance, 0, planeDistance), Color.White),

                new VertexPositionColor(new Vector3(planeDistance, 0, -planeDistance), Color.White),
                new VertexPositionColor(new Vector3(planeDistance, 0, planeDistance), Color.White),
                new VertexPositionColor(new Vector3(-planeDistance, 0, planeDistance), Color.White)
            };

            SkyPlane = GpuResourceManager.GetBuffer(this, device, VertexPositionColor.VertexDeclaration,
                                                    plane.Length, BufferUsage.WriteOnly);
            SkyPlane.SetData <VertexPositionColor>(plane);

            planeDistance = 60;
            var celestialPlane = new[]
            {
                new VertexPositionTexture(new Vector3(-planeDistance, 0, -planeDistance), new Vector2(0, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, 1)),

                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, planeDistance), new Vector2(1, 1)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, 1))
            };

            CelestialPlane = GpuResourceManager.GetBuffer(this, device, VertexPositionTexture.VertexDeclaration,
                                                          celestialPlane.Length, BufferUsage.WriteOnly);
            CelestialPlane.SetData <VertexPositionTexture>(celestialPlane);

            _moonPlaneVertices = new[]
            {
                new VertexPositionTexture(new Vector3(-planeDistance, 0, -planeDistance), new Vector2(0, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(MoonX, 0)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, MoonY)),

                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(MoonX, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, planeDistance), new Vector2(MoonX, MoonY)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, MoonY)),
            };
            MoonPlane = GpuResourceManager.GetBuffer(this, device, VertexPositionTexture.VertexDeclaration,
                                                     _moonPlaneVertices.Length, BufferUsage.WriteOnly);
            MoonPlane.SetData <VertexPositionTexture>(_moonPlaneVertices);

            if (EnableClouds)
            {
                SetupClouds(device, planeDistance);
            }

            RenderSkybox = Options.VideoOptions.Skybox.Value;
            Options.VideoOptions.Skybox.Bind(SkyboxSettingUpdated);
        }
        private void QueryCompleted(ServerQueryResponse response)
        {
            //   var response = queryTask.Result;
            SetConnectingState(false);

            if (response.Success)
            {
                var s = response.Status;
                var q = s.Query;
                _pingStatus.SetPlayerCount(q.Players.Online, q.Players.Max);

                ConnectionEndpoint = s.EndPoint;

                if (!s.WaitingOnPing)
                {
                    _pingStatus.SetPing(s.Delay);
                }

                if (q.Version.Protocol < (SavedServerEntry.ServerType == ServerType.Java ? JavaProtocol.ProtocolVersion : McpeProtocolInfo.ProtocolVersion))
                {
                    if (SavedServerEntry.ServerType == ServerType.Java)
                    {
                        _pingStatus.SetOutdated(q.Version.Name);
                    }
                }
                else if (q.Version.Protocol > (SavedServerEntry.ServerType == ServerType.Java ? JavaProtocol.ProtocolVersion : McpeProtocolInfo.ProtocolVersion))
                {
                    _pingStatus.SetOutdated($"multiplayer.status.client_out_of_date", true);
                }

                if (q.Description.Extra != null)
                {
                    StringBuilder builder = new StringBuilder();
                    foreach (var extra in q.Description.Extra)
                    {
                        if (extra.Color != null)
                        {
                            builder.Append(API.Utils.TextColor.GetColor(extra.Color).ToString());
                        }

                        if (extra.Bold.HasValue)
                        {
                            builder.Append(ChatFormatting.Bold);
                        }

                        if (extra.Italic.HasValue)
                        {
                            builder.Append(ChatFormatting.Italic);
                        }

                        if (extra.Underlined.HasValue)
                        {
                            builder.Append(ChatFormatting.Underline);
                        }

                        if (extra.Strikethrough.HasValue)
                        {
                            builder.Append(ChatFormatting.Strikethrough);
                        }

                        if (extra.Obfuscated.HasValue)
                        {
                            builder.Append(ChatFormatting.Obfuscated);
                        }

                        builder.Append(extra.Text);
                    }

                    _serverMotd.Text = builder.ToString();
                }
                else
                {
                    _serverMotd.Text = q.Description.Text;
                }

                if (!string.IsNullOrWhiteSpace(q.Favicon))
                {
                    var match = FaviconRegex.Match(q.Favicon);
                    if (match.Success && _graphicsDevice != null)
                    {
                        AutoResetEvent reset = new AutoResetEvent(false);
                        Alex.Instance.UIThreadQueue.Enqueue(() =>
                        {
                            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(match.Groups["data"].Value)))
                            {
                                ServerIcon = GpuResourceManager.GetTexture2D(this, _graphicsDevice, ms);
                            }

                            reset.Set();
                        });

                        reset.WaitOne();

                        SavedServerEntry.CachedIcon = ServerIcon;
                        _serverIcon.Texture         = ServerIcon;
                    }
                }
            }
            else
            {
                SetErrorMessage(response.ErrorMessage);
            }
        }
Example #29
0
        protected override void OnLoad(IRenderArgs args)
        {
            Skin skin = _playerProfileService?.CurrentProfile?.Skin;

            if (skin == null)
            {
                Alex.Resources.ResourcePack.TryGetBitmap("entity/alex", out var rawTexture);
                skin = new Skin()
                {
                    Slim    = true,
                    Texture = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, rawTexture)
                };
            }

            var entity = new RemotePlayer("", null, null, skin.Texture);

            AddChild(_playerView =
                         new GuiEntityModelView(
                             entity /*new PlayerMob("", null, null, skin.Texture, skin.Slim)*/)                    /*"geometry.humanoid.customSlim"*/
            {
                BackgroundOverlay = new Color(Color.Black, 0.15f),

                Margin = new Thickness(15, 15, 5, 40),

                Width  = 92,
                Height = 128,

                Anchor = Alignment.BottomRight,
            });

            AddChild(new GuiButton("Change Skin", ChangeSKinBtnPressed)
            {
                Anchor         = Alignment.BottomRight,
                Modern         = false,
                TranslationKey = "",
                Margin         = new Thickness(15, 15, 6, 15),
                Width          = 90,
                //Enabled = false
            });

            AutoResetEvent reset = new AutoResetEvent(false);

            Alex.UIThreadQueue.Enqueue(() =>
            {
                using (MemoryStream ms =
                           new MemoryStream(ResourceManager.ReadResource("Alex.Resources.GradientBlur.png")))
                {
                    BackgroundOverlay = (TextureSlice2D)GpuResourceManager.GetTexture2D(this, args.GraphicsDevice, ms);
                }

                BackgroundOverlay.RepeatMode = TextureRepeatMode.Stretch;
                reset.Set();
            });
            reset.WaitOne();
            reset.Dispose();

            BackgroundOverlay.Mask = new Color(Color.White, 0.5f);

            _splashText.Text    = SplashTexts.GetSplashText();
            Alex.IsMouseVisible = true;

            Alex.GameStateManager.AddState("serverlist", new MultiplayerServerSelectionState(_backgroundSkyBox));
            //Alex.GameStateManager.AddState("profileSelection", new ProfileSelectionState(_backgroundSkyBox));
        }
Example #30
0
        public static void Init(GraphicsDevice gd)
        {
            WhiteTexture = GpuResourceManager.GetTexture2D("Alex.Extensions", gd, 1, 1);
            WhiteTexture.SetData(new Color[] { Color.White });

            var size = Vector3.One;

            // Calculate the position of the vertices on the top face.
            Vector3 topLeftFront  = new Vector3(size.X, size.Y, size.Z);
            Vector3 topLeftBack   = new Vector3(0, size.Y, size.Z);
            Vector3 topRightFront = new Vector3(size.X, size.Y, 0);
            Vector3 topRightBack  = new Vector3(0, size.Y, 0);

            // Calculate the position of the vertices on the bottom face.
            Vector3 btmLeftFront  = new Vector3(size.X, 0, size.Z);
            Vector3 btmLeftBack   = new Vector3(0, 0, size.Z);
            Vector3 btmRightFront = new Vector3(size.X, 0, 0);
            Vector3 btmRightBack  = Vector3.Zero;

            // UV texture coordinates
            Color textureTopLeft     = Color.White;
            Color textureTopRight    = Color.White;
            Color textureBottomLeft  = Color.White;
            Color textureBottomRight = Color.White;

            // Add the vertices for the FRONT face.
            CubeVertices[0] = new VertexPositionColor(topLeftFront, textureTopLeft);
            CubeVertices[1] = new VertexPositionColor(btmLeftFront, textureBottomLeft);
            CubeVertices[2] = new VertexPositionColor(topRightFront, textureTopRight);
            CubeVertices[3] = new VertexPositionColor(btmLeftFront, textureBottomLeft);
            CubeVertices[4] = new VertexPositionColor(btmRightFront, textureBottomRight);
            CubeVertices[5] = new VertexPositionColor(topRightFront, textureTopRight);

            // Add the vertices for the BACK face.
            CubeVertices[6]  = new VertexPositionColor(topLeftBack, textureTopRight);
            CubeVertices[7]  = new VertexPositionColor(topRightBack, textureTopLeft);
            CubeVertices[8]  = new VertexPositionColor(btmLeftBack, textureBottomRight);
            CubeVertices[9]  = new VertexPositionColor(btmLeftBack, textureBottomRight);
            CubeVertices[10] = new VertexPositionColor(topRightBack, textureTopLeft);
            CubeVertices[11] = new VertexPositionColor(btmRightBack, textureBottomLeft);

            // Add the vertices for the TOP face.
            CubeVertices[12] = new VertexPositionColor(topLeftFront, textureBottomLeft);
            CubeVertices[13] = new VertexPositionColor(topRightBack, textureTopRight);
            CubeVertices[14] = new VertexPositionColor(topLeftBack, textureTopLeft);
            CubeVertices[15] = new VertexPositionColor(topLeftFront, textureBottomLeft);
            CubeVertices[16] = new VertexPositionColor(topRightFront, textureBottomRight);
            CubeVertices[17] = new VertexPositionColor(topRightBack, textureTopRight);

            // Add the vertices for the BOTTOM face.
            CubeVertices[18] = new VertexPositionColor(btmLeftFront, textureTopLeft);
            CubeVertices[19] = new VertexPositionColor(btmLeftBack, textureBottomLeft);
            CubeVertices[20] = new VertexPositionColor(btmRightBack, textureBottomRight);
            CubeVertices[21] = new VertexPositionColor(btmLeftFront, textureTopLeft);
            CubeVertices[22] = new VertexPositionColor(btmRightBack, textureBottomRight);
            CubeVertices[23] = new VertexPositionColor(btmRightFront, textureTopRight);

            // Add the vertices for the LEFT face.
            CubeVertices[24] = new VertexPositionColor(topLeftFront, textureTopRight);
            CubeVertices[25] = new VertexPositionColor(btmLeftBack, textureBottomLeft);
            CubeVertices[26] = new VertexPositionColor(btmLeftFront, textureBottomRight);
            CubeVertices[27] = new VertexPositionColor(topLeftBack, textureTopLeft);
            CubeVertices[28] = new VertexPositionColor(btmLeftBack, textureBottomLeft);
            CubeVertices[29] = new VertexPositionColor(topLeftFront, textureTopRight);

            // Add the vertices for the RIGHT face.
            CubeVertices[30] = new VertexPositionColor(topRightFront, textureTopLeft);
            CubeVertices[31] = new VertexPositionColor(btmRightFront, textureBottomLeft);
            CubeVertices[32] = new VertexPositionColor(btmRightBack, textureBottomRight);
            CubeVertices[33] = new VertexPositionColor(topRightBack, textureTopRight);
            CubeVertices[34] = new VertexPositionColor(topRightFront, textureTopLeft);
            CubeVertices[35] = new VertexPositionColor(btmRightBack, textureBottomRight);
        }