Example #1
0
        public DX11Renderer(IntPtr windowHandle, Size2 size, Device dev = null)
        {
            RenderSize = size;
            _windowHandle = windowHandle;
            if(dev != null)
            {
                _dxDevice = dev;
            }
            else
            {
                var swapchainDesc = new SwapChainDescription()
                {
                    BufferCount = 2,
                    ModeDescription =
                        new ModeDescription(size.Width, size.Height,
                                            new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    OutputHandle = windowHandle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect = SwapEffect.Discard,
                    Usage = Usage.RenderTargetOutput
                };

                // Create Device and SwapChain
                Device.CreateWithSwapChain(DriverType.Hardware,
                   DeviceCreationFlags.None, swapchainDesc, out _dxDevice, out _swapChain);

                // Ignore all windows events
                //    var factory = _swapChain.GetParent<Factory>();
                //    factory.MakeWindowAssociation(windowHandle, WindowAssociationFlags.None);

                Reset(size.Width, size.Height);
            }
        }
Example #2
0
        protected override void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback)
        {
            try
            {
                using (var image = NSImage.FromStream(stream))
                {
                    var rep = image.Representations()[0];
                    int width = rep.PixelsWide;
                    int height = rep.PixelsHigh;
                    Mipmaps = new Mipmap[1];
                    Size = new Size2(width, height);

                    var data = new byte[width * height * 4];
                    var emptyRect = RectangleF.Empty;
                    using (CGContext imageContext = new CGBitmapContext(data, width, height, 8, width*4, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast))
                    using (var cgImage = image.AsCGImage(ref emptyRect, null, null))
                    {
                        imageContext.DrawImage(new RectangleF(0, 0, width, height), cgImage);

                        Mipmaps[0] = new Mipmap(data, width, height, 1, 4);
                        if (flip) Mipmaps[0].FlipVertical();
                    }
                }
            }
            catch (Exception e)
            {
                FailedToLoad = true;
                Loader.AddLoadableException(e);
                if (loadedCallback != null) loadedCallback(this, false);
                return;
            }

            Loaded = true;
            if (loadedCallback != null) loadedCallback(this, true);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MemoryMappedTexture32bpp"/> class.
 /// </summary>
 /// <param name="size">The total size of the texture.</param>
 public MemoryMappedTexture32bpp(Size2 size)
 {
     m_pointer = Marshal.AllocHGlobal(size.Width * size.Height * 4);
     m_pointerNative = (int*)m_pointer.ToPointer();
     m_size = size;
     m_countInts = m_size.Width * m_size.Height;
 }
Example #4
0
        public ProgressBar(GUIControl parent)
            : base("", parent)
        {
            size=	new Size2(120, 32);
            pHorizontal=	true;
            pProgress=	0f;
            pAutoLabel=	true;
            pProgressColors=	new GUIColorPacket
            (
                new Color(0, 200, 0),
                new Color(230, 230, 230),
                new Color(0, 200, 150),
                new Color(0, 150, 150)
            );
            pProgressLeftColors=	new GUIColorPacket
            (
                new Color(200, 0, 0),
                new Color(100, 100, 100),
                new Color(200, 100, 50),
                new Color(200, 0, 0)
            );

            pAutoAdjustSize=	false;
            pBGColors.normal=	new Color(25, 25, 25);
            pBGColors.disabled=	new Color(0, 0, 0);

            addEvent("onProgressChanged");
            addEvent("onProgressColorsChanged");
            addEvent("onProgressLeftColorsChanged");
        }
Example #5
0
        protected override void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback)
        {
            try
            {
                using (var imageData = NSData.FromStream(stream))
                using (var image = UIImage.LoadFromData(imageData))
                {
                    int width = (int)image.Size.Width;
                    int height = (int)image.Size.Height;
                    Mipmaps = new Mipmap[1];
                    Size = new Size2(width, height);

                    var data = new byte[width * height * 4];
                    using (CGContext imageContext = new CGBitmapContext(data, width, height, 8, width*4, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast))
                    {
                        imageContext.DrawImage(new RectangleF(0, 0, width, height), image.CGImage);

                        Mipmaps[0] = new Mipmap(data, width, height, 1, 4);
                        if (flip) Mipmaps[0].FlipVertical();
                    }
                }
            }
            catch (Exception e)
            {
                FailedToLoad = true;
                Loader.AddLoadableException(e);
                if (loadedCallback != null) loadedCallback(this, false);
                return;
            }

            Loaded = true;
            if (loadedCallback != null) loadedCallback(this, true);
        }
        private SharpDX.Direct2D1.Bitmap SDXBitmapFromSysBitmap(WindowRenderTarget device, System.Drawing.Bitmap bitmap)
        {
            var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
            var bitmapProperties = new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
            var size = new Size2(bitmap.Width, bitmap.Height);

            // Transform pixels from BGRA to RGBA
            int stride = bitmap.Width * sizeof(int);
            using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
            {
                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                // Convert all pixels 
                for (int y = 0; y < bitmap.Height; y++)
                {
                    int offset = bitmapData.Stride * y;
                    for (int x = 0; x < bitmap.Width; x++)
                    {
                        // Not optimized 
                        byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = R | (G << 8) | (B << 16) | (A << 24);
                        tempStream.Write(rgba);
                    }

                }
                bitmap.UnlockBits(bitmapData);
                tempStream.Position = 0;

                return new SharpDX.Direct2D1.Bitmap(device, size, tempStream, stride, bitmapProperties);
            }
        }
Example #7
0
        public void Size2_IsConstructedProperly()
        {
            var result = new Size2(123, 456);

            TheResultingValue(result)
                .ShouldBe(123, 456);
        }
Example #8
0
 public Rectangle2(Point2 point, Size2 sizeF)
 {
     X = point.X;
     Y = point.Y;
     Width = sizeF.Width;
     Height = sizeF.Height;
 }
Example #9
0
        public static IViewPort New(VideoTypes videoType, IDisposableResource parent, Point2 location, Size2 size)
        {
            IViewPort api = null;

            #if WIN32
            if (videoType == VideoTypes.D3D9) api = new D3D9.ViewPort(parent, location, size);
            #endif

            #if WIN32 || WINRT || WP8
            if (videoType == VideoTypes.D3D11) api = new D3D11.ViewPort(parent, location, size);
            #endif

            #if WIN32 || OSX || LINUX || iOS || ANDROID || NaCl
            if (videoType == VideoTypes.OpenGL) api = new OpenGL.ViewPort(parent, location, size);
            #endif

            #if XNA
            if (videoType == VideoTypes.XNA) api = new XNA.ViewPort(parent, location, size);
            #endif

            #if VITA
            if (videoType == VideoTypes.Vita) api = new Vita.ViewPort(parent, location, size);
            #endif

            if (api == null) Debug.ThrowError("ViewPortAPI", "Unsuported InputType: " + videoType);
            return api;
        }
Example #10
0
        /// <summary>
        /// Initializes a new DirectXTexture class.
        /// </summary>
        /// <param name="bmp">The Bitmap.</param>
        internal DirectXTexture(System.Drawing.Bitmap bmp)
        {
            RawBitmap = (System.Drawing.Bitmap) bmp.Clone();
            _width = bmp.Width;
            _height = bmp.Height;
            var sourceArea = new Rectangle(0, 0, bmp.Width, bmp.Height);
            var bitmapProperties = new BitmapProperties(
                new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96);
            var size = new Size2(bmp.Width, bmp.Height);

            int stride = bmp.Width*sizeof (int);
            using (var tempStream = new DataStream(bmp.Height*stride, true, true))
            {
                BitmapData bitmapData = bmp.LockBits(sourceArea, ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                for (int y = 0; y < bmp.Height; y++)
                {
                    int offset = bitmapData.Stride*y;
                    for (int x = 0; x < bmp.Width; x++)
                    {
                        byte b = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte g = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte r = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte a = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = r | (g << 8) | (b << 16) | (a << 24);
                        tempStream.Write(rgba);
                    }
                }
                bmp.UnlockBits(bitmapData);
                tempStream.Position = 0;
                _bmp = new Bitmap(DirectXHelper.RenderTarget, size, tempStream, stride, bitmapProperties);
            }
        }
Example #11
0
        /// <summary>Initializes the specified view.</summary>
        /// <param name="view">The view.</param>
        /// <exception cref="System.ArgumentException">Expecting argument to be a ShaderResourceView or RenderTargetView;view</exception>
        protected override void Initialize(DeviceChild view)
        {
            // The initialize method will override the view.Tag, so we are setting it back
            base.Initialize(view);

            IsRenderView = view is RenderTargetView;

            var shaderResourceView = view as ShaderResourceView;
            int mipLevel = 0;
            if (shaderResourceView != null)
            {
                var description = shaderResourceView.Description;
                mipLevel = description.Texture1D.MostDetailedMip;
            }
            else
            {
                var renderTargetView = view as RenderTargetView;
                if (renderTargetView == null)
                {
                    throw new ArgumentException("Expecting argument to be a ShaderResourceView or RenderTargetView", "view");
                }
                mipLevel = renderTargetView.Description.Texture1D.MipSlice;
            }
            Size = new Size2(Math.Max(1, Texture.Width >> mipLevel), Math.Max(1, Texture.Height >> mipLevel));

            TexelSize = new Size2F
            {
                Width = 1.0f / Size.Width,
                Height = 1.0f / Size.Height
            };
        }
 public static Vector2[] WorldToScreen(Matrix4x4 viewMatrix, Size2 screenSize, params Vector3[] points)
 {
     Vector2[] worlds = new Vector2[points.Length];
     for (int i = 0; i < worlds.Length; i++)
         worlds[i] = WorldToScreen(viewMatrix, screenSize, points[i]);
     return worlds;
 }
Example #13
0
        public void Size2_EqualsObject()
        {
            var size1 = new Size2(123, 456);
            var size2 = new Size2(123, 456);

            TheResultingValue(size1.Equals((Object)size2)).ShouldBe(true);
            TheResultingValue(size1.Equals("This is a test")).ShouldBe(false);
        }
Example #14
0
        public void Size2_Area_IsCalculatedCorrectly()
        {
            var size1 = new Size2(123, 456);
            TheResultingValue(size1.Area).ShouldBe(123 * 456);

            var size2 = new Size2(222, 55555);
            TheResultingValue(size2.Area).ShouldBe(222 * 55555);
        }
Example #15
0
 public SharpDX.RectangleF GetTextureClip(Size2 outputSize)
 {
   lock (_imageSync)
   {
     Size imageSize = ImageSize;
     SharpDX.RectangleF textureClip = _animator.GetZoomRect(new Size2(imageSize.Width, imageSize.Height), outputSize, DateTime.Now);
     return new SharpDX.RectangleF(textureClip.X * _textureMaxUv.Width, textureClip.Y * _textureMaxUv.Height, textureClip.Width * _textureMaxUv.Width, textureClip.Height * _textureMaxUv.Height);
   }
 }
Example #16
0
        public DepthStencil(IDisposableResource parent, int width, int height, DepthStencilFormats depthStencilFormats)
            : base(parent)
        {
            try
            {
                var video = parent.FindParentOrSelfWithException<Video>();
                Size = new Size2(width, height);
                SizeF = Size.ToVector2();

                int depthBit = 16, stencilBit = 0;
                switch (depthStencilFormats)
                {
                    case DepthStencilFormats.Defualt:
                        depthBit = 24;
                        stencilBit = 0;
                        break;

                    case DepthStencilFormats.Depth24Stencil8:
                        depthBit = 24;
                        stencilBit = 8;
                        break;

                    case DepthStencilFormats.Depth16:
                        depthBit = 16;
                        stencilBit = 0;
                        break;

                    case DepthStencilFormats.Depth24:
                        depthBit = 24;
                        stencilBit = 0;
                        break;

                    case DepthStencilFormats.Depth32:
                        depthBit = 32;
                        stencilBit = 0;
                        break;

                    default:
                        Debug.ThrowError("Video", "Unsuported DepthStencilFormat type");
                        break;
                }

                com = new DepthStencilCom();
                var error = com.Init(video.com, width, height, depthBit, stencilBit);

                switch (error)
                {
                    case DepthStencilErrors.Textrue: Debug.ThrowError("DepthStencil", "Failed to create Texture2D"); break;
                    case DepthStencilErrors.DepthStencilView: Debug.ThrowError("DepthStencil", "Failed to create DepthStencilView"); break;
                }
            }
            catch (Exception e)
            {
                Dispose();
                throw e;
            }
        }
Example #17
0
        public void Init(ApplicationDesc desc)
        {
            OS.CurrentApplication = this;
            CurrentApplication = this;
            theEvent = new ApplicationEvent();

            if (desc.FrameSize.Width == 0 || desc.FrameSize.Height == 0) FrameSize = new Size2(512, 512);
            else FrameSize = desc.FrameSize;
        }
Example #18
0
 internal Font()
 {
     glyphs=	new Dictionary<char, FontGlyphCollection>();
     maxSize=	Size2.NO_SIZE;
     bitmap=	null;
     wordSpacing=	10f;
     size=	14f;
     pOriginalSize=	14f;
     pName=	"";
     texture=	Texture.NULL;
 }
Example #19
0
        public void Size2_OpInequality()
        {
            var size1 = new Size2(123, 456);
            var size2 = new Size2(123, 456);
            var size3 = new Size2(123, 555);
            var size4 = new Size2(222, 456);

            TheResultingValue(size1 != size2).ShouldBe(false);
            TheResultingValue(size1 != size3).ShouldBe(true);
            TheResultingValue(size1 != size4).ShouldBe(true);
        }
Example #20
0
        public void Size2_EqualsSize2()
        {
            var size1 = new Size2(123, 456);
            var size2 = new Size2(123, 456);
            var size3 = new Size2(123, 555);
            var size4 = new Size2(222, 456);

            TheResultingValue(size1.Equals(size2)).ShouldBe(true);
            TheResultingValue(size1.Equals(size3)).ShouldBe(false);
            TheResultingValue(size1.Equals(size4)).ShouldBe(false);
        }
Example #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GameForm"/> class.
 /// </summary>
 /// <param name="text">The text.</param>
 public GameFormSdl(String text) : base(text)
 {
     Size = new Size2(800, 600);
     ResizeBeginActions += GameForm_ResizeBeginActions;
     ResizeEndActions += GameForm_ResizeEndActions;
     ActivateActions += GameForm_ActivateActions;
     DeActivateActions += GameForm_DeActivateActions;
     previousWindowState = FormWindowState.Normal;
     MinimizedActions += GameForm_MinimizedActions;
     MaximizedActions += GameForm_MaximizedActions;
     RestoredActions += GameForm_RestoredActions;
 }
 protected override void CreateMediaTarget(SinkWriter sinkWriter, Size2 videoPixelSize, out int streamIndex)
 {
     using (MF.MediaType mediaTypeOut = new MF.MediaType())
     {
         mediaTypeOut.Set<Guid>(MF.MediaTypeAttributeKeys.MajorType, MF.MediaTypeGuids.Video);
         mediaTypeOut.Set<Guid>(MF.MediaTypeAttributeKeys.Subtype, VIDEO_ENCODING_FORMAT);
         mediaTypeOut.Set<int>(MF.MediaTypeAttributeKeys.AvgBitrate, Bitrate);
         mediaTypeOut.Set<int>(MF.MediaTypeAttributeKeys.InterlaceMode, (int)MF.VideoInterlaceMode.Progressive);
         mediaTypeOut.Set<long>(MF.MediaTypeAttributeKeys.FrameSize, MFHelper.GetMFEncodedIntsByValues(videoPixelSize.Width, videoPixelSize.Height));
         mediaTypeOut.Set<long>(MF.MediaTypeAttributeKeys.FrameRate, MFHelper.GetMFEncodedIntsByValues(Framerate, 1));
         sinkWriter.AddStream(mediaTypeOut, out streamIndex);
     }
 }
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="textureFormat">The desired type of format for the output texture</param>
        /// <param name="platform">The graphics platform</param>
        /// <param name="graphicsProfile">The graphics profile</param>
        /// <param name="textureSizeInput">The texture size input.</param>
        /// <param name="textureSizeRequested">The texture size requested.</param>
        /// <param name="generateMipmaps">Indicate if mipmaps should be generated for the output texture</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindBestTextureSize(TextureFormat textureFormat, GraphicsPlatform platform, GraphicsProfile graphicsProfile, Size2 textureSizeInput, Size2 textureSizeRequested, bool generateMipmaps, ILogger logger)
        {
            var textureSize = textureSizeRequested;

            // compressed DDS files has to have a size multiple of 4.
            if (platform == GraphicsPlatform.Direct3D11 && textureFormat == TextureFormat.Compressed
                && ((textureSizeRequested.Width % 4) != 0 || (textureSizeRequested.Height % 4) != 0))
            {
                textureSize.Width = unchecked((int)(((uint)(textureSizeRequested.Width + 3)) & ~(uint)3));
                textureSize.Height = unchecked((int)(((uint)(textureSizeRequested.Height + 3)) & ~(uint)3));
            }

            var maxTextureSize = 0;

            // determine if the desired size if valid depending on the graphics profile
            switch (graphicsProfile)
            {
                case GraphicsProfile.Level_9_1:
                case GraphicsProfile.Level_9_2:
                case GraphicsProfile.Level_9_3:
                    if (generateMipmaps && (!IsPowerOfTwo(textureSize.Width) || !IsPowerOfTwo(textureSize.Height)))
                    {
                        // TODO: TEMPORARY SETUP A MAX TEXTURE OF 1024. THIS SHOULD BE SPECIFIED DONE IN THE ASSET INSTEAD
                        textureSize.Width = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Width), 1024);
                        textureSize.Height = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Height), 1024);
                        logger.Warning("Graphic profiles 9.1/9.2/9.3 do not support mipmaps with textures that are not power of 2. Asset is automatically resized to " + textureSize);
                    }
                    maxTextureSize = graphicsProfile >= GraphicsProfile.Level_9_3 ? 4096 : 2048;
                    break;
                case GraphicsProfile.Level_10_0:
                case GraphicsProfile.Level_10_1:
                    maxTextureSize = 8192;
                    break;
                case GraphicsProfile.Level_11_0:
                case GraphicsProfile.Level_11_1:
                case GraphicsProfile.Level_11_2:
                    maxTextureSize = 16384;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("graphicsProfile");
            }

            if (textureSize.Width > maxTextureSize || textureSize.Height > maxTextureSize)
            {
                logger.Error("Graphic profile {0} do not support texture with resolution {2} x {3} because it is larger than {1}. " +
                             "Please reduce texture size or upgrade your graphic profile.", graphicsProfile, maxTextureSize, textureSize.Width, textureSize.Height);
                return new Size2(Math.Min(textureSize.Width, maxTextureSize), Math.Min(textureSize.Height, maxTextureSize));
            }

            return textureSize;
        }
Example #24
0
        public static Rectangle2 CalcWin(Size2 overview, SizeI2 totalSize, RectangleI2 visibleWin, float zoomFactorX,
			float zoomFactorY)
        {
            float winX = visibleWin.X*overview.Width/totalSize.Width;
            float winWidth = visibleWin.Width*overview.Width/totalSize.Width/zoomFactorX;
            if (winWidth > overview.Width - winX){
                winWidth = overview.Width - winX;
            }
            float winY = visibleWin.Y*overview.Height/totalSize.Height;
            float winHeight = visibleWin.Height*overview.Height/totalSize.Height/zoomFactorY;
            if (winHeight > overview.Height - winY){
                winHeight = overview.Height - winY;
            }
            return new Rectangle2(winX, winY, winWidth, winHeight);
        }
Example #25
0
 public Button(LogicGraph game, string back, string text, Vector2 position, Size2 size, SpriteFont font, Color color)
     : base(game)
 {
     backName = back;
     Text = text;
     Position = position;
     Size = size;
     Font = font;
     Color = color;
     this.OnButtonDown += Button_OnButtonDown;
     this.OnButtonUp += Button_OnButtonUp;
     this.OnHover += Button_OnHover;
     this.OnLeave += Button_OnLeave;
     this.DrawOrder = 10;
 }
Example #26
0
        // Clamps the given value between the given minimum value and maximum value
        public static Size2 clamp(Size2 value, Size2 min, Size2 max)
        {
            correctMinMax(min, max, out min, out max);

            if(value.width< min.width)
                value.width=	min.width;
            else if(value.width> max.width)
                value.width=	max.width;

            if(value.height< min.height)
                value.height=	min.height;
            else if(value.height> max.height)
                value.height=	max.height;

            return value;
        }
Example #27
0
        // Corrects the min and max if they are switched around
        public static void correctMinMax(Size2 inMin, Size2 inMax, out Size2 outMin, out Size2 outMax)
        {
            outMin=	inMin;
            outMax=	inMax;

            if(inMin.width> inMax.width)
            {
                outMin.width=	inMax.width;
                outMax.width=	inMin.width;
            }
            if(inMin.height> inMax.height)
            {
                outMin.height=	inMax.height;
                outMax.height=	inMin.height;
            }
        }
Example #28
0
 public ImportParameters(TextureConvertParameters textureParameters)
 {
     var asset = textureParameters.Texture;
     IsSRgb = asset.SRgb;
     DesiredSize = new Size2((int)asset.Width, (int)asset.Height);
     IsSizeInPercentage = asset.IsSizeInPercentage;
     DesiredFormat = asset.Format;
     DesiredAlpha = asset.Alpha;
     TextureHint = asset.Hint;
     GenerateMipmaps = asset.GenerateMipmaps;
     PremultiplyAlpha = asset.PremultiplyAlpha;
     ColorKeyColor  = asset.ColorKeyColor;
     ColorKeyEnabled = asset.ColorKeyEnabled;
     TextureQuality = textureParameters.TextureQuality;
     GraphicsPlatform = textureParameters.GraphicsPlatform;
     GraphicsProfile = textureParameters.GraphicsProfile;
     Platform = textureParameters.Platform;
 }
Example #29
0
 public ImportParameters(SpriteSheetAssetCompiler.SpriteSheetParameters spriteSheetParameters)
 {
     var asset = spriteSheetParameters.SheetAsset;
     IsSRgb = asset.SRgb;
     DesiredSize = new Size2(100, 100);
     IsSizeInPercentage = true;
     DesiredFormat = asset.Format;
     DesiredAlpha = asset.Alpha;
     TextureHint = TextureHint.Color;
     GenerateMipmaps = asset.GenerateMipmaps;
     PremultiplyAlpha = asset.PremultiplyAlpha;
     ColorKeyColor = asset.ColorKeyColor;
     ColorKeyEnabled = asset.ColorKeyEnabled;
     TextureQuality = spriteSheetParameters.TextureQuality;
     GraphicsPlatform = spriteSheetParameters.GraphicsPlatform;
     GraphicsProfile = spriteSheetParameters.GraphicsProfile;
     Platform = spriteSheetParameters.Platform;
 }
 public static Vector2 HeightVector(this Size2 size) => new Vector2(0, size.Height);
Example #31
0
 public BasicCollisionBody(Size2 size, Vector2 origin)
 {
     Size     = size;
     Origin   = origin;
     IsStatic = false;
 }
 public RectangleTexture(Size2 size, Color color) : this(size.Width, size.Height, color)
 {
 }
Example #33
0
 public Hive(Vector2 location, Size2 size)
 {
     Location = location;
     Size     = size;
 }
Example #34
0
        public unsafe DepthStencil(IDisposableResource parent, int width, int height, DepthStencilFormats depthStencilFormats)
            : base(parent)
        {
            try
            {
                uint depthBit = GL.DEPTH_COMPONENT16, stencilBit = 0;
                switch (depthStencilFormats)
                {
                case DepthStencilFormats.Defualt:
                                                #if iOS || ANDROID || NaCl || RPI
                    depthBit   = GL.DEPTH_COMPONENT16;
                    stencilBit = 0;
                                                #else
                    depthBit   = GL.DEPTH_COMPONENT24;
                    stencilBit = 0;
                                                #endif
                    break;

                case DepthStencilFormats.Depth24Stencil8:
                    depthBit   = GL.DEPTH_COMPONENT24;
                    stencilBit = GL.STENCIL_INDEX8;
                    break;

                case DepthStencilFormats.Depth16:
                    depthBit   = GL.DEPTH_COMPONENT16;
                    stencilBit = 0;
                    break;

                case DepthStencilFormats.Depth24:
                    depthBit   = GL.DEPTH_COMPONENT24;
                    stencilBit = 0;
                    break;

                case DepthStencilFormats.Depth32:
                    depthBit   = GL.DEPTH_COMPONENT32;
                    stencilBit = 0;
                    break;

                default:
                    Debug.ThrowError("DepthStencil", "Unsuported DepthStencilFormat type");
                    break;
                }

                Size  = new Size2(width, height);
                SizeF = Size.ToVector2();

                // create depth
                uint surfaceTEMP = 0;
                GL.GenRenderbuffers(1, &surfaceTEMP);
                if (surfaceTEMP == 0)
                {
                    Debug.ThrowError("DpethStencil", "Failed to create DepthBuffer");
                }
                depthBuffer = surfaceTEMP;

                GL.BindRenderbuffer(GL.RENDERBUFFER, depthBuffer);
                GL.RenderbufferStorage(GL.RENDERBUFFER, depthBit, width, height);

                // create stencil
                if (stencilBit != 0)
                {
                    surfaceTEMP = 0;
                    GL.GenRenderbuffers(1, &surfaceTEMP);
                    if (surfaceTEMP == 0)
                    {
                        Debug.ThrowError("DpethStencil", "Failed to create StencilBuffer");
                    }
                    stencilBuffer = surfaceTEMP;

                    GL.BindRenderbuffer(GL.RENDERBUFFER, stencilBuffer);
                    GL.RenderbufferStorage(GL.RENDERBUFFER, stencilBit, width, height);
                }

                uint   error;
                string errorName;
                if (Video.checkForError(out error, out errorName))
                {
                    Debug.ThrowError("DepthStencil", string.Format("{0} {1}: Failed to create DepthStencil", error, errorName));
                }
            }
            catch (Exception e)
            {
                Dispose();
                throw e;
            }
        }
 public static Vector2 WidthVector(this Size2 size) => new Vector2(size.Width, 0);
Example #36
0
        private Vector2 DrawMod(ModValue item, Vector2 position)
        {
            const float EPSILON = 0.001f;
            const int   MARGIN_BOTTOM = 4, MARGIN_LEFT = 50;

            Vector2          oldPosition = position;
            ItemModsSettings settings    = Settings.ItemMods;

            string affix = item.AffixType == ModsDat.ModType.Prefix ? "[P]"
                : item.AffixType == ModsDat.ModType.Suffix ? "[S]" : "[?]";

            Dictionary <int, Color> TColors = new Dictionary <int, Color>
            {
                { 1, settings.T1Color },
                { 2, settings.T2Color },
                { 3, settings.T3Color }
            };

            if (item.AffixType != ModsDat.ModType.Hidden)
            {
                if (item.CouldHaveTiers())
                {
                    affix += $" T{item.Tier} ";
                }

                if (item.AffixType == ModsDat.ModType.Prefix)
                {
                    Graphics.DrawText(affix, settings.ModTextSize, position.Translate(5 - MARGIN_LEFT, 0), settings.PrefixColor);
                    if (!TColors.TryGetValue(item.Tier, out TColor))
                    {
                        TColor = settings.PrefixColor;
                    }
                }

                if (item.AffixType == ModsDat.ModType.Suffix)
                {
                    Graphics.DrawText(affix, settings.ModTextSize, position.Translate(5 - MARGIN_LEFT, 0), settings.SuffixColor);
                    if (!TColors.TryGetValue(item.Tier, out TColor))
                    {
                        TColor = settings.SuffixColor;
                    }
                }
                Size2 textSize = Graphics.DrawText(item.AffixText, settings.ModTextSize, position, TColor);
                if (textSize != new Size2())
                {
                    position.Y += textSize.Height;
                }
            }

            for (int i = 0; i < 4; i++)
            {
                IntRange range = item.Record.StatRange[i];
                if (range.Min == 0 && range.Max == 0)
                {
                    continue;
                }
                StatsDat.StatRecord stat = item.Record.StatNames[i];
                int value = item.StatValue[i];
                if (value <= -1000 || stat == null)
                {
                    continue;
                }
                bool   noSpread = !range.HasSpread();
                string line2    = string.Format(noSpread ? "{0}" : "{0} [{1}]", stat, range);
                Graphics.DrawText(line2, settings.ModTextSize, position, Color.Gainsboro);
                string  statText     = stat.ValueToString(value);
                Vector2 statPosition = position.Translate(-5, 0);
                Size2   txSize       = Graphics.DrawText(statText, settings.ModTextSize, statPosition, Color.Gainsboro, FontDrawFlags.Right);
                position.Y += txSize.Height;
            }
            return(Math.Abs(position.Y - oldPosition.Y) > EPSILON?position.Translate(0, MARGIN_BOTTOM) : oldPosition);
        }
Example #37
0
        /// <summary>
        /// Determine the output format of the texture depending on the platform and asset properties.
        /// </summary>
        /// <param name="parameters">The conversion request parameters</param>
        /// <param name="imageSize">The texture output size</param>
        /// <param name="inputImageFormat">The pixel format of the input image</param>
        /// <returns>The pixel format to use as output</returns>
        public static PixelFormat DetermineOutputFormat(ImportParameters parameters, Size2 imageSize, PixelFormat inputImageFormat)
        {
            var hint      = parameters.TextureHint;
            var alphaMode = parameters.DesiredAlpha;

            // Default output format
            var outputFormat = PixelFormat.R8G8B8A8_UNorm;

            switch (parameters.ShouldCompress)
            {
            case true:
                switch (parameters.Platform)
                {
                case PlatformType.Windows:
                    switch (parameters.GraphicsPlatform)
                    {
                    case GraphicsPlatform.Direct3D11:
                    case GraphicsPlatform.Direct3D12:

                        // https://msdn.microsoft.com/en-us/library/windows/desktop/hh308955%28v=vs.85%29.aspx
                        // http://www.reedbeta.com/blog/2012/02/12/understanding-bcn-texture-compression-formats/
                        // ----------------------------------------------    ----------------------------------------------------                        ---    ---------------------------------
                        // Source data                                       Minimum required data compression resolution                     Recommended format	Minimum supported feature level
                        // ----------------------------------------------    ----------------------------------------------------                        ---    ---------------------------------
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits), with 0 or 1 bit(s) of alpha    BC1    Direct3D 9.1     (color maps, cutout color maps - 1 bit alpha, normal maps if memory is tight)
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits), with 4 bits of alpha           BC2    Direct3D 9.1     (idem)
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits) with 8 bits of alpha            BC3    Direct3D 9.1     (color maps with alpha, packing color and mono maps together)
                        // One-channel color                                 One color channel (8 bits)                                                  BC4    Direct3D 10      (Height maps, gloss maps, font atlases, any gray scales image)
                        // Two-channel color	                             Two color channels (8 bits:8 bits)                                          BC5    Direct3D 10      (Tangent space normal maps)
                        // Three-channel high dynamic range (HDR) color      Three color channels (16 bits:16 bits:16 bits) in "half" floating point*    BC6H   Direct3D 11      (HDR images)
                        // Three-channel color, alpha channel optional       Three color channels (4 to 7 bits per channel) with 0 to 8 bits of alpha    BC7    Direct3D 11      (High quality color maps, Color maps with full alpha)

                        switch (alphaMode)
                        {
                        case AlphaFormat.None:
                        case AlphaFormat.Mask:
                            // DXT1 handles 1-bit alpha channel
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC1_UNorm_SRgb : PixelFormat.BC1_UNorm;
                            break;

                        case AlphaFormat.Explicit:
                            // DXT3 is good at sharp alpha transitions
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC2_UNorm_SRgb : PixelFormat.BC2_UNorm;
                            break;

                        case AlphaFormat.Interpolated:
                            // DXT5 is good at alpha gradients
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC3_UNorm_SRgb : PixelFormat.BC3_UNorm;
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }

                        // Overrides the format when profile is >= 11.0
                        // Support some specific optimized formats based on the hint or input type
                        if (hint == TextureHint.NormalMap)
                        {
                            outputFormat = PixelFormat.BC5_UNorm;
                        }
                        else if (hint == TextureHint.Grayscale)
                        {
                            outputFormat = PixelFormat.BC4_UNorm;
                        }
                        else if (inputImageFormat.IsHDR())
                        {
                            // BC6H is too slow to compile
                            //outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.BC6H_Uf16 : inputImageFormat;
                            outputFormat = inputImageFormat;
                        }
                        // TODO support the BC6/BC7 but they are so slow to compile that we can't use them right now
                        break;

                    default:
                        outputFormat = parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                        break;
                    }
                    break;

                default:
                    throw new NotSupportedException("Platform " + parameters.Platform + " is not supported by TextureTool");
                }
                break;

            case false:
                outputFormat = inputImageFormat;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(outputFormat);
        }
Example #38
0
 /// <summary>
 /// size
 /// </summary>
 public GroupLayer(Layer bk, Size2 Size, DeviceContext DC) : base(DC)
 {
     this.Size = Size;
     _father   = bk;
 }
Example #39
0
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="parameters">The import parameters</param>
        /// <param name="outputFormat">The output format</param>
        /// <param name="textureSize">The texture size requested.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindBestTextureSize(ImportParameters parameters, PixelFormat outputFormat, Size2 textureSize, ILogger logger = null)
        {
            bool isBlockCompressed =
                (outputFormat >= PixelFormat.BC1_Typeless && outputFormat <= PixelFormat.BC5_SNorm) ||
                (outputFormat >= PixelFormat.BC6H_Typeless && outputFormat <= PixelFormat.BC7_UNorm_SRgb);

            // compressed DDS files has to have a size multiple of 4.
            if (parameters.ShouldCompress && isBlockCompressed &&
                ((textureSize.Width % 4) != 0 || (textureSize.Height % 4) != 0))
            {
                textureSize.Width  = unchecked ((int)(((uint)(textureSize.Width + 3)) & ~(uint)3));
                textureSize.Height = unchecked ((int)(((uint)(textureSize.Height + 3)) & ~(uint)3));
            }

            return(FindMaximumTextureSize(parameters, textureSize, logger));
        }
Example #40
0
            /// <inheritdoc />
            protected override async Task <ResultStatus> DoCommandOverride(ICommandContext commandContext)
            {
                VideoAsset videoAsset = Parameters.Video;

                try
                {
                    // Get path to ffmpeg
                    var ffmpeg = ToolLocator.LocateTool("ffmpeg.exe")?.ToWindowsPath() ?? throw new AssetException("Failed to compile a video asset, ffmpeg was not found.");

                    // Get absolute path of asset source on disk
                    var assetDirectory = videoAsset.Source.GetParent();
                    var assetSource    = UPath.Combine(assetDirectory, videoAsset.Source);

                    //=====================================================================================
                    //Get the info from the video codec

                    //Check if we need to reencode the video
                    var mustReEncodeVideo    = false;
                    var sidedataStripCommand = "";

                    // check that the video file format is supported
                    if (Parameters.Platform == PlatformType.Windows && videoAsset.Source.GetFileExtension() != ".mp4")
                    {
                        mustReEncodeVideo = true;
                    }

                    //Use FFmpegMedia object (need to check more details first before I can use it)
                    VideoStream videoStream = null;
                    AudioStream audioStream = null;
                    FFmpegUtils.PreloadLibraries();
                    FFmpegUtils.Initialize();
                    using (var media = new FFmpegMedia())
                    {
                        media.Open(assetSource.ToWindowsPath());

                        // Get the first video stream
                        videoStream = media.Streams.OfType <VideoStream>().FirstOrDefault();
                        if (videoStream == null)
                        {
                            throw new AssetException("Failed to compile a video asset. Did not find the VideoStream from the media.");
                        }

                        // On windows MediaEngineEx player only decode the first video if the video is detected as a stereoscopic video,
                        // so we remove the tags inside the video in order to ensure the same behavior as on other platforms (side by side decoded texture)
                        // Unfortunately it does seem possible to disable this behavior from the MediaEngineEx API.
                        if (Parameters.Platform == PlatformType.Windows && media.IsStereoscopicVideo(videoStream))
                        {
                            mustReEncodeVideo    = true;
                            sidedataStripCommand = "-vf sidedata=delete";
                        }

                        // Get the first audio stream
                        audioStream = media.Streams.OfType <AudioStream>().FirstOrDefault();
                    }
                    Size2 videoSize = new Size2(videoStream.Width, videoStream.Height);

                    //check the format
                    if (ListSupportedCodecNames != null)
                    {
                        if (Array.IndexOf(ListSupportedCodecNames, videoStream.Codec) < 0)
                        {
                            mustReEncodeVideo = true;
                        }
                    }

                    // check if video need to be trimmed
                    var videoDuration = videoAsset.VideoDuration;
                    if (videoDuration.Enabled && (videoDuration.StartTime != TimeSpan.Zero ||
                                                  videoDuration.EndTime.TotalSeconds < videoStream.Duration.TotalSeconds - MathUtil.ZeroToleranceDouble))
                    {
                        mustReEncodeVideo = true;
                    }

                    //check the video target and source resolution
                    Size2 targetSize;
                    if (videoAsset.IsSizeInPercentage)
                    {
                        targetSize = new Size2((int)(videoSize.Width * videoAsset.Width / 100.0f), (int)(videoSize.Height * videoAsset.Height / 100.0f));
                    }
                    else
                    {
                        targetSize = new Size2((int)(videoAsset.Width), (int)(videoAsset.Height));
                    }

                    // ensure that the size is a multiple of 2 (ffmpeg cannot output video not multiple of 2, at least with this codec)
                    if (targetSize.Width % 2 == 1)
                    {
                        targetSize.Width += 1;
                    }
                    if (targetSize.Height % 2 == 1)
                    {
                        targetSize.Height += 1;
                    }

                    if (targetSize.Width != videoSize.Width || targetSize.Height != videoSize.Height)
                    {
                        mustReEncodeVideo = true;
                    }

                    //check the audio settings
                    int  audioChannelsTarget       = audioStream == null? 0: audioStream.ChannelCount;
                    bool mustReEncodeAudioChannels = false;
                    if (videoAsset.IsAudioChannelMono)
                    {
                        audioChannelsTarget = 1;
                        if (audioStream != null && audioStream.ChannelCount != audioChannelsTarget)
                        {
                            mustReEncodeAudioChannels = true;
                            mustReEncodeVideo         = true;
                        }
                    }

                    // Execute ffmpeg to convert source to H.264
                    string tempFile = null;
                    try
                    {
                        if (mustReEncodeVideo)
                        {
                            string targetCodecFormat = "h264";  //hardcodec for now
                            commandContext.Logger.Info(string.Format("Video Asset Compiler: \"{0}\". Re-encode the Video. Format:{1}, Size:{2}x{3}. Audio Channels:{4}",
                                                                     videoAsset.Source.GetFileName(), targetCodecFormat, targetSize.Width, targetSize.Height, audioChannelsTarget));

                            tempFile = Path.GetTempFileName();
                            string channelFlag = "";
                            if (mustReEncodeAudioChannels)
                            {
                                channelFlag = string.Format(" -ac {0}", audioChannelsTarget);
                            }

                            var startTime       = videoDuration.StartTime;
                            var duration        = videoDuration.EndTime - videoDuration.StartTime;
                            var trimmingOptions = videoDuration.Enabled ?
                                                  $" -ss {startTime.Hours:D2}:{startTime.Minutes:D2}:{startTime.Seconds:D2}.{startTime.Milliseconds:D3}" +
                                                  $" -t {duration.Hours:D2}:{duration.Minutes:D2}:{duration.Seconds:D2}.{duration.Milliseconds:D3}":
                                                  "";

                            var commandLine = "  -hide_banner -loglevel error" +                       // hide most log output
                                              "  -nostdin" +                                           // no interaction (background process)
                                              $" -i \"{assetSource.ToWindowsPath()}\"" +               // input file
                                              $"{trimmingOptions}" +
                                              "  -f mp4 -vcodec " + targetCodecFormat +                // codec
                                              channelFlag +                                            // audio channels
                                              $"  -vf scale={targetSize.Width}:{targetSize.Height} " + // adjust the resolution
                                              sidedataStripCommand +                                   // strip of stereoscopic sidedata tag
                                                                                                       //" -an" + // no audio
                                                                                                       //" -pix_fmt yuv422p" + // pixel format (planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples))
                                              $" -y \"{tempFile}\"";                                   // output file (always overwrite)
                            var ret = await ShellHelper.RunProcessAndGetOutputAsync(ffmpeg, commandLine, commandContext.Logger);

                            if (ret != 0 || commandContext.Logger.HasErrors)
                            {
                                throw new AssetException($"Failed to compile a video asset. ffmpeg failed to convert {assetSource}.");
                            }
                        }
                        else
                        {
                            commandContext.Logger.Info(string.Format("Video Asset Compiler: \"{0}\". No Re-encoding necessary",
                                                                     videoAsset.Source.GetFileName()));

                            // Use temporary file
                            tempFile = assetSource.ToWindowsPath();
                        }

                        var dataUrl = Url + "_Data";
                        var video   = new Video.Video
                        {
                            CompressedDataUrl = dataUrl,
                        };

                        // Make sure we don't compress h264 data
                        commandContext.AddTag(new ObjectUrl(UrlType.Content, dataUrl), Builder.DoNotCompressTag);

                        // Write the data
                        using (var reader = new BinaryReader(new FileStream(tempFile, FileMode.Open, FileAccess.Read)))
                            using (var outputStream = MicrothreadLocalDatabases.DatabaseFileProvider.OpenStream(dataUrl, VirtualFileMode.Create, VirtualFileAccess.Write, VirtualFileShare.Read, StreamFlags.Seekable))
                            {
                                // For now write everything at once, 1MB at a time
                                var length = reader.BaseStream.Length;
                                for (var position = 0L; position < length; position += 2 << 20)
                                {
                                    var buffer = reader.ReadBytes(2 << 20);
                                    outputStream.Write(buffer, 0, buffer.Length);
                                }
                            }

                        var assetManager = new ContentManager(MicrothreadLocalDatabases.ProviderService);
                        assetManager.Save(Url, video);

                        return(ResultStatus.Successful);
                    }
                    finally
                    {
                        if (mustReEncodeVideo)
                        {
                            if (tempFile != null)
                            {
                                File.Delete(tempFile);
                            }
                        }
                    }
                }
                catch (AssetException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new AssetException("Failed to compile a video asset. Unexpected exception.", ex);
                }
            }
 public void Size2_Parse_FailsForInvalidStrings()
 {
     Assert.That(() => Size2.Parse("foo"),
                 Throws.TypeOf <FormatException>());
 }
Example #42
0
        public Video(IDisposableResource parent, IApplication application, DepthStencilFormats depthStencilFormats, bool vSync)
            : base(parent)
        {
            try
            {
                int depthBit = 16, stencilBit = 0;
                switch (depthStencilFormats)
                {
                case DepthStencilFormats.None:
                    depthBit   = 0;
                    stencilBit = 0;
                    break;

                case DepthStencilFormats.Defualt:
                                                #if iOS || ANDROID || NaCl || RPI
                    depthBit   = 16;
                    stencilBit = 0;
                                                #else
                    depthBit   = 24;
                    stencilBit = 0;
                                                #endif
                    break;

                case DepthStencilFormats.Depth24Stencil8:
                    depthBit   = 24;
                    stencilBit = 8;
                    break;

                case DepthStencilFormats.Depth16:
                    depthBit   = 16;
                    stencilBit = 0;
                    break;

                case DepthStencilFormats.Depth24:
                    depthBit   = 24;
                    stencilBit = 0;
                    break;

                case DepthStencilFormats.Depth32:
                    depthBit   = 32;
                    stencilBit = 0;
                    break;

                default:
                    Debug.ThrowError("Video", "Unsuported DepthStencilFormat type");
                    break;
                }

                currentTextures      = new Texture2D[8];
                currentSamplerStates = new SamplerState[8];

                                #if WIN32 || OSX || LINUX || NaCl
                BackBufferSize   = application.FrameSize;
                this.application = application;
                                #else
                BackBufferSize   = application.FrameSize;
                this.application = application;
                                #endif

                                #if WIN32
                //Get DC
                handle = application.Handle;
                dc     = WGL.GetDC(handle);
                WGL.SwapBuffers(dc);

                //Set BackBuffer format
                WGL.PIXELFORMATDESCRIPTOR pfd = new WGL.PIXELFORMATDESCRIPTOR();
                WGL.ZeroPixelDescriptor(ref pfd);
                pfd.nVersion   = 1;
                pfd.dwFlags    = WGL.PFD_DRAW_TO_WINDOW | WGL.PFD_SUPPORT_OPENGL | WGL.PFD_DOUBLEBUFFER;
                pfd.iPixelType = (byte)WGL.PFD_TYPE_RGBA;
                //pfd.cColorBits = 24;
                //pfd.cAlphaBits = 8;
                pfd.cDepthBits   = (byte)depthBit;
                pfd.cStencilBits = (byte)stencilBit;
                pfd.iLayerType   = (byte)WGL.PFD_MAIN_PLANE;
                unsafe { pfd.nSize = (ushort)sizeof(WGL.PIXELFORMATDESCRIPTOR); }

                int pixelFormatIndex          = WGL.ChoosePixelFormat(dc, ref pfd);
                if (pixelFormatIndex == 0)
                {
                    Debug.ThrowError("Video", "ChoosePixelFormat failed");
                }
                if (WGL.SetPixelFormat(dc, pixelFormatIndex, ref pfd) == 0)
                {
                    Debug.ThrowError("Video", "Failed to set PixelFormat");
                }

                ctx = WGL.CreateContext(dc);
                if (ctx == IntPtr.Zero)
                {
                    Debug.ThrowError("Video", "Failed to create GL context");
                }
                if (WGL.MakeCurrent(dc, ctx) == 0)
                {
                    Debug.ThrowError("Video", "Failed to make GL context current");
                }

                WGL.Init();
                WGL.SwapInterval(vSync ? 1 : 0);                // -1 for smart vsync
                                #endif

                                #if RPI
                unsafe
                {
                    // Init Pi video
                    RaspberryPi.bcm_host_init();

                    const int piDisplay = 0;
                    uint      piWidth = 0, piHeight = 0;
                    if (RaspberryPi.graphics_get_display_size(piDisplay, &piWidth, &piHeight) < 0)
                    {
                        Debug.ThrowError("Video", "Failed to get display size");
                    }
                    Console.WriteLine("piWidth - " + piWidth);
                    Console.WriteLine("piHeight - " + piHeight);
                    BackBufferSize = new Size2((int)piWidth, (int)piHeight);

                    IntPtr dispman_display = RaspberryPi.vc_dispmanx_display_open(piDisplay);
                    if (dispman_display == IntPtr.Zero)
                    {
                        Debug.ThrowError("Video", "Failed: vc_dispmanx_display_open");
                    }

                    IntPtr dispman_update = RaspberryPi.vc_dispmanx_update_start(0);
                    if (dispman_update == IntPtr.Zero)
                    {
                        Debug.ThrowError("Video", "Failed: vc_dispmanx_update_start");
                    }

                    var dstRect = new RaspberryPi.VC_RECT_T()
                    {
                        x      = 0,
                        y      = 0,
                        width  = (int)piWidth,
                        height = (int)piHeight
                    };
                    var srcRect = new RaspberryPi.VC_RECT_T()
                    {
                        x          = 0,
                        y          = 0,
                        width      = ((int)piWidth) << 16,
                            height = ((int)piHeight) << 16
                    };
                    IntPtr dispman_element = RaspberryPi.vc_dispmanx_element_add(dispman_update, dispman_display, 0, &dstRect, IntPtr.Zero, &srcRect, RaspberryPi.DISPMANX_PROTECTION_NONE, IntPtr.Zero, IntPtr.Zero, 0);
                    if (dispman_element == IntPtr.Zero)
                    {
                        Debug.ThrowError("Video", "Failed: vc_dispmanx_element_add");
                    }

                    nativeWindow = new RaspberryPi.DISPMANX_WINDOW_T()
                    {
                        element = dispman_element,
                        width   = (int)piWidth,
                        height  = (int)piHeight
                    };
                    windowHandle = GCHandle.Alloc(nativeWindow, GCHandleType.Pinned);
                    RaspberryPi.vc_dispmanx_update_submit_sync(dispman_update);

                    // Init EGL
                    handle = application.Handle;
                    GL.GetError();                    //NOTE: THIS MUST BE HERE SO THAT libGLES LOADS BEFORE libEGL
                    dc = EGL.GetDisplay(IntPtr.Zero);

                    int major, minor;
                    if (!EGL.Initialize(dc, out major, out minor))
                    {
                        Debug.ThrowError("Video", string.Format("Failed to initialize display connection, Error {0}", EGL.GetError()));
                    }

                    int[] pixelFormat = new int[]
                    {
                        //EGL.RENDERABLE_TYPE, EGL.OPENGL_ES2_BIT,

                        //EGL.RED_SIZE, 5,
                        //EGL.GREEN_SIZE, 6,
                        //EGL.BLUE_SIZE, 5,
                        //EGL.ALPHA_SIZE, 0,//EGL.DONT_CARE,
                        EGL.SURFACE_TYPE, EGL.WINDOW_BIT,

                        EGL.DEPTH_SIZE, depthBit,
                        //EGL.STENCIL_SIZE, stencilBit,//EGL.DONT_CARE,//<<<<<<<<<< Test enabling this!

                        //EGL.SAMPLE_BUFFERS, 0,
                        //EGL.SAMPLES, 0,

                        //EGL.MIN_SWAP_INTERVAL, 0,
                        //EGL.MAX_SWAP_INTERVAL, 1,

                        EGL.NONE,
                    };

                    int num_configs;
                    var configs = new IntPtr();
                    if (EGL.ChooseConfig(dc, pixelFormat, &configs, 1, &num_configs) == 0 || num_configs == 0)
                    {
                        Debug.ThrowError("Video", string.Format("Failed to retrieve GraphicsMode, error {0}", EGL.GetError()));
                    }

                    if (EGL.BindAPI(EGL.OPENGL_ES_API) == 0)
                    {
                        Debug.ThrowError("Video", "Failed to bind GLES API");
                    }
                    ;

                    int[] attrib_list = new int[]
                    {
                        EGL.CONTEXT_CLIENT_VERSION, 2,
                        EGL.NONE
                    };

                    ctx = EGL.CreateContext(dc, configs, IntPtr.Zero, attrib_list);
                    if (ctx == IntPtr.Zero)
                    {
                        Debug.ThrowError("Video", "Failed to create context");
                    }

                    surface = EGL.CreateWindowSurface(dc, configs, windowHandle.AddrOfPinnedObject(), null);
                    //surface = EGL.CreateWindowSurface(dc, configs[0], handle, null);// <<<<<<<<<<<<<<<<<<<<<<<<<<<< used in x11
                    if (surface == IntPtr.Zero)
                    {
                        Debug.ThrowError("Video", "Failed to create window surface");
                    }

                    if (EGL.MakeCurrent(dc, surface, surface, ctx) == 0)
                    {
                        Debug.ThrowError("Video", "Failed to make EGL context current");
                    }
                    //if (EGL.SwapInterval(dc, vSync ? 1 : 0) == 0) Debug.ThrowError("Video", "Failed to set vSync");
                    checkForEGLError();
                }
                                #elif LINUX
                //Get DC
                handle = application.Handle;
                dc     = X11.XOpenDisplay(IntPtr.Zero);
                int screen = X11.XDefaultScreen(dc);

                //Set Pixel format
                int[] attrbs =
                {
                    GLX.RGBA,
                    GLX.DOUBLEBUFFER,// 1,
                    //GLX.RED_SIZE, 8,
                    //GLX.GREEN_SIZE, 8,
                    //GLX.BLUE_SIZE, 8,
                    //GLX.ALPHA_SIZE, 8,
                    GLX.DEPTH_SIZE,depthBit,
                    GLX.NONE
                };

                IntPtr visual = GLX.ChooseVisual(dc, screen, attrbs);
                if (visual == IntPtr.Zero)
                {
                    Debug.ThrowError("Video", "Failed to get visual");
                }

                ctx = GLX.CreateContext(dc, visual, new IntPtr(0), true);
                GLX.MakeCurrent(dc, handle, ctx);

                bool failed = false;
                try { GLX.SwapIntervalSGI(vSync ? 1 : 0); }
                catch { failed = true; }

                if (failed)
                {
                    GLX.Init();
                    GLX.SwapIntervalMesa(vSync ? 1 : 0);
                }
                                #endif

                                #if OSX
                var attribs = new object[]
                {
                    NSOpenGLPixelFormatAttribute.Window,
                    NSOpenGLPixelFormatAttribute.Accelerated,
                    NSOpenGLPixelFormatAttribute.NoRecovery,
                    NSOpenGLPixelFormatAttribute.DoubleBuffer,
                    NSOpenGLPixelFormatAttribute.ColorSize, 24,
                    NSOpenGLPixelFormatAttribute.AlphaSize, 8,
                    NSOpenGLPixelFormatAttribute.DepthSize, depthBit
                };

                var pixelFormat = new NSOpenGLPixelFormat(attribs);
                if (pixelFormat == null)
                {
                    Debug.ThrowError("Video", "NSOpenGLPixelFormat failed");
                }

                NSContext = new NSOpenGLContext(pixelFormat, null);
                if (NSContext == null)
                {
                    Debug.ThrowError("Video", "Failed to create GL context");
                }
                NSContext.MakeCurrentContext();
                NSContext.SwapInterval = vSync;
                NSContext.View         = application.View;
                ctx          = NSContext.CGLContext.Handle;
                OS.NSContext = NSContext;

                /*//Get DC
                 * dc = CGL.DisplayIDToOpenGLDisplayMask(CGL.MainDisplayID());
                 * if (dc == IntPtr.Zero) Debug.ThrowError("Video", "Failed to get DC");
                 *
                 * //Set BackBuffer format
                 * int[] attributes =
                 * {
                 *      //(int)CGL.PixelFormatAttribute.kCGLPFADoubleBuffer,
                 *      //(int)CGL.PixelFormatAttribute.kCGLPFADisplayMask, dc.ToInt32(),
                 *      //(int)CGL.PixelFormatAttribute.kCGLPFAWindow,
                 *      (int)CGL.PixelFormatAttribute.kCGLPFAAccelerated,
                 *      (int)CGL.PixelFormatAttribute.kCGLPFAColorSize, 32,
                 *      (int)CGL.PixelFormatAttribute.kCGLPFADepthSize, depthBit,
                 *      0
                 * };
                 *
                 * IntPtr pixelFormat = IntPtr.Zero;
                 * int pixelFormatCount = 0;
                 * int error = CGL.ChoosePixelFormat(attributes, ref pixelFormat, ref pixelFormatCount);
                 * if (error != 0 || pixelFormat == IntPtr.Zero)
                 * {
                 *      Debug.ThrowError("Video", "ChoosePixelFormat failed");
                 * }
                 *
                 * error = CGL.CreateContext(pixelFormat, IntPtr.Zero, ref ctx);
                 * if (error != 0 || ctx == IntPtr.Zero)
                 * {
                 *      Debug.ThrowError("Video", "Failed to create GL fullscreen context");
                 * }
                 *
                 * CGL.SetCurrentContext(ctx);*/
                                #endif

                                #if iOS
                // GL will be created by the Application
                                #endif

                                #if ANDROID
                // GL will be created by the Application
                                #endif

                                #if NaCl
                var   frame   = application.FrameSize;
                int[] attribs =
                {
                    (int)PPAPI.Graphics3DAttrib.PP_GRAPHICS3DATTRIB_ALPHA_SIZE,                8,// Try to disable this to see if it gets rid of alpha blending presintation issues
                    (int)PPAPI.Graphics3DAttrib.PP_GRAPHICS3DATTRIB_DEPTH_SIZE,     depthBit,
                    (int)PPAPI.Graphics3DAttrib.PP_GRAPHICS3DATTRIB_STENCIL_SIZE,   stencilBit,
                    (int)PPAPI.Graphics3DAttrib.PP_GRAPHICS3DATTRIB_SAMPLES,                   0,
                    (int)PPAPI.Graphics3DAttrib.PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS,            0,
                    (int)PPAPI.Graphics3DAttrib.PP_GRAPHICS3DATTRIB_WIDTH,          frame.Width,
                    (int)PPAPI.Graphics3DAttrib.PP_GRAPHICS3DATTRIB_HEIGHT,         frame.Height,
                    (int)PPAPI.Graphics3DAttrib.PP_GRAPHICS3DATTRIB_NONE
                };

                graphics = OS.GetGraphics();
                if (graphics == IntPtr.Zero)
                {
                    Debug.ThrowError("Video", "Failed to get Graphics object");
                }

                IntPtr pbbInstance = OS.GetPBBInstance();
                if (graphics == IntPtr.Zero)
                {
                    Debug.ThrowError("Video", "Failed to get PBBInstance object");
                }

                IntPtr gles = OS.GetGlES();
                if (gles == IntPtr.Zero)
                {
                    Debug.ThrowError("Video", "Failed to get GLES object");
                }

                context = PPAPI.InitOpenGL(OS.GetInstance(), graphics, pbbInstance, attribs, gles);
                if (context == 0)
                {
                    Debug.ThrowError("Video", "Failed to create GL context");
                }

                PPAPI.SetCurrentContextPPAPI(context);
                PPAPI.StartSwapBufferLoop(graphics, context);
                                #endif

                checkForError();

                //Setup defualt OpenGL characteristics
                GL.FrontFace(GL.CCW);

                // Get Caps
                Caps = new Caps();
                Caps.MaxShaderVersion = ShaderVersions.Unknown;
                unsafe
                {
                    int max = 0;
                    GL.GetIntegerv(GL.MAX_TEXTURE_SIZE, &max);
                    Caps.MaxTextureSize = max;

                    // SEEMS TO MESS UP ON OSX
                    //GL.GetIntegerv(GL.MAX_VERTEX_UNIFORM_VECTORS, &max);
                    //Caps.MaxVertexConstants = max;

                    //GL.GetIntegerv(GL.MAX_FRAGMENT_UNIFORM_VECTORS, &max);
                    //Caps.MaxPixelConstants = max;

                                        #if RPI
                    byte *shaderVersionPtr = null;
                                        #else
                    byte *shaderVersionPtr = GL.GetString(GL.SHADING_LANGUAGE_VERSION);
                                        #endif
                    string shaderVersion = "";
                    while (shaderVersionPtr != null && shaderVersionPtr[0] != 0)
                    {
                        shaderVersion += (char)shaderVersionPtr[0];
                        shaderVersionPtr++;
                    }

                                        #if iOS || RPI
                    shaderVersion = "1.0";
                                        #elif ANDROID
                    shaderVersion = shaderVersion.Substring(shaderVersion.Length - 4, 4);
                                        #elif NaCl
                    shaderVersion = shaderVersion.Substring(18, 3);
                                        #else
                    shaderVersion = shaderVersion.Substring(0, 4);
                                        #endif
                    float shaderValue = Convert.ToSingle(shaderVersion);

                    Caps.Version = Versions.GL1;
                    FileTag      = "";
                                        #if iOS || ANDROID || NaCl || RPI
                    if (shaderValue >= 1.0f)
                    {
                        Caps.Version          = Versions.GL2;
                        FileTag               = "GLES2_";
                        Caps.MaxShaderVersion = ShaderVersions.GLSL_1_00;
                    }
                                        #else
                    if (shaderValue >= 1.1f)
                    {
                        Caps.Version          = Versions.GL2;
                        FileTag               = "GL2_";
                        Caps.MaxShaderVersion = ShaderVersions.GLSL_1_10;
                    }
                    if (shaderValue >= 1.2f)
                    {
                        Caps.Version          = Versions.GL2;
                        FileTag               = "GL2_";
                        Caps.MaxShaderVersion = ShaderVersions.GLSL_1_20;
                    }
                    // GL3 not supported in GLSL 1.30 becuase 'gl_InstanceID' only exists in GLSL 1.40

                    /*if (shaderValue >= 1.3f)
                     * {
                     *      Caps.Version = Versions.GL3;
                     *      IShader.FileTag = "GL3_";
                     *      Caps.MaxShaderVersion = ShaderVersions.GLSL_1_30;
                     * }*/
                    if (shaderValue >= 1.4f)
                    {
                        Caps.Version          = Versions.GL3;
                        FileTag               = "GL3_";
                        Caps.MaxShaderVersion = ShaderVersions.GLSL_1_40;
                    }
                    if (shaderValue >= 1.5f)
                    {
                        Caps.Version          = Versions.GL3;
                        FileTag               = "GL3_";
                        Caps.MaxShaderVersion = ShaderVersions.GLSL_1_50;
                    }
                    if (shaderValue >= 3.3f)
                    {
                        Caps.Version          = Versions.GL3;
                        FileTag               = "GL3_";
                        Caps.MaxShaderVersion = ShaderVersions.GLSL_3_30;
                    }
                    //if (shaderValue >= 4.0f) Caps.MaxShaderVersion = ShaderVersions.GLSL_4_00;
                    //if (shaderValue >= 4.1f) Caps.MaxShaderVersion = ShaderVersions.GLSL_4_10;
                    //if (shaderValue >= 4.2f) Caps.MaxShaderVersion = ShaderVersions.GLSL_4_20;
                                        #endif

                    if (Caps.Version == Versions.GL1)
                    {
                        Debug.ThrowError("Video", "OpenGL 2 or higher is required.\nAre your video card drivers up to date?");
                    }

                    byte * extensionsPtr   = GL.GetString(GL.EXTENSIONS);
                    string extensionValues = "";
                    while (extensionsPtr != null && extensionsPtr[0] != 0)
                    {
                        extensionValues += (char)extensionsPtr[0];
                        extensionsPtr++;
                    }

                    var extensions = extensionValues.Split(' ');
                    foreach (var ext in extensions)
                    {
                        switch (ext)
                        {
                        case "GL_instanced_arrays": Caps.HardwareInstancing = true; break;

                        case "GL_ARB_instanced_arrays": Caps.HardwareInstancing = true; break;

                        case "GL_EXT_texture_compression_s3tc": Caps.TextureCompression_S3TC = true; break;

                        case "GL_AMD_compressed_ATC_texture": Caps.TextureCompression_ATC = true; break;

                        case "GL_ATI_texture_compression_atitc": Caps.TextureCompression_ATC = true; break;

                        case "GL_IMG_texture_compression_pvrtc": Caps.TextureCompression_PVR = true; break;
                        }
                        //Console.WriteLine(ext);
                    }
                }

                checkForError();

                // Init Ext
                GL.Init();
            }
            catch (Exception e)
            {
                Dispose();
                throw e;
            }
        }
Example #43
0
 public MainGame(string title, string startingViewName, Size2 defaultGameSize, SceneFactory sceneFactory, IController controller)
     : this(title, startingViewName, sceneFactory, controller)
 {
     _areScreenSettingsPreCalculated = false;
     _defaultScreenSize = defaultGameSize;
 }
Example #44
0
    /// <summary>
    /// Loads a Direct2D Bitmap from a file using System.Drawing.Image.FromFile(...)
    /// </summary>
    /// <param name="renderTarget">The render target.</param>
    /// <param name="file">The file.</param>
    /// <returns>A D2D1 Bitmap</returns>
    public static Bitmap LoadFromFile(RenderTarget renderTarget, System.Drawing.Size newSize, string file)
    {
        // Loads from file using System.Drawing.Image
        System.Drawing.Bitmap bitmap;

        int width, height;

        if (newSize.IsEmpty)
        {
            bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(file));
        }
        else if (newSize.Width == 0)
        {
            //scale to height
            bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(file));
            height = newSize.Height;
            float ratio = bitmap.Width / (float)bitmap.Height;
            width  = (int)(height * ratio);
            bitmap = new System.Drawing.Bitmap(bitmap, width, height);
        }
        else if (newSize.Height == 0)
        {
            bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(file));
            width  = newSize.Width;
            float ratio = bitmap.Height / (float)bitmap.Width;
            height = (int)(width * ratio);
            bitmap = new System.Drawing.Bitmap(bitmap, width, height);
        }
        else
        {
            bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(file), newSize);
        }

        var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
        var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
        var size             = new Size2(bitmap.Width, bitmap.Height);

        // Transform pixels from BGRA to RGBA
        int stride = bitmap.Width * sizeof(int);

        using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
        {
            // Lock System.Drawing.Bitmap
            var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            // Convert all pixels
            for (int y = 0; y < bitmap.Height; y++)
            {
                int offset = bitmapData.Stride * y;
                for (int x = 0; x < bitmap.Width; x++)
                {
                    // Not optimized
                    byte B    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte G    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte R    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    byte A    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                    int  rgba = R | (G << 8) | (B << 16) | (A << 24);
                    tempStream.Write(rgba);
                }
            }
            bitmap.UnlockBits(bitmapData);
            tempStream.Position = 0;

            return(new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties));
        }
    }
Example #45
0
 /// <summary>
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.
 /// </summary>
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="dataStream">A pointer to the memory location of the image data, or NULL to create an uninitialized bitmap.</param>
 /// <param name="pitch">The byte count of each scanline, which is equal to (the image width in pixels * the number of bytes per pixel) + memory padding. If srcData is NULL, this value is ignored. (Note that pitch is also sometimes called stride.)</param>
 /// <param name="bitmapProperties">The pixel format and dots per inch (DPI) of the bitmap to create.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>
 public Bitmap1(DeviceContext deviceContext, Size2 size, DataStream dataStream, int pitch, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : base(IntPtr.Zero)
 {
     deviceContext.CreateBitmap(size, dataStream == null ? IntPtr.Zero : dataStream.PositionPointer, pitch, bitmapProperties, this);
 }
Example #46
0
        private void DrawWeaponDps(RectangleF clientRect)
        {
            var   weapon            = itemEntity.GetComponent <Weapon>();
            float aSpd              = (float)Math.Round(1000f / weapon.AttackTime, 2);
            int   cntDamages        = Enum.GetValues(typeof(DamageType)).Length;
            var   doubleDpsPerStat  = new float[cntDamages];
            float physDmgMultiplier = 1;
            int   PhysHi            = weapon.DamageMax;
            int   PhysLo            = weapon.DamageMin;

            foreach (ModValue mod in mods)
            {
                for (int iStat = 0; iStat < 4; iStat++)
                {
                    IntRange range = mod.Record.StatRange[iStat];
                    if (range.Min == 0 && range.Max == 0)
                    {
                        continue;
                    }

                    StatsDat.StatRecord theStat = mod.Record.StatNames[iStat];
                    int value = mod.StatValue[iStat];
                    switch (theStat.Key)
                    {
                    case "physical_damage_+%":
                    case "local_physical_damage_+%":
                        physDmgMultiplier += value / 100f;
                        break;

                    case "local_attack_speed_+%":
                        aSpd *= (100f + value) / 100;
                        break;

                    case "local_minimum_added_physical_damage":
                        PhysLo += value;
                        break;

                    case "local_maximum_added_physical_damage":
                        PhysHi += value;
                        break;

                    case "local_minimum_added_fire_damage":
                    case "local_maximum_added_fire_damage":
                    case "unique_local_minimum_added_fire_damage_when_in_main_hand":
                    case "unique_local_maximum_added_fire_damage_when_in_main_hand":
                        doubleDpsPerStat[(int)DamageType.Fire] += value;
                        break;

                    case "local_minimum_added_cold_damage":
                    case "local_maximum_added_cold_damage":
                    case "unique_local_minimum_added_cold_damage_when_in_off_hand":
                    case "unique_local_maximum_added_cold_damage_when_in_off_hand":
                        doubleDpsPerStat[(int)DamageType.Cold] += value;
                        break;

                    case "local_minimum_added_lightning_damage":
                    case "local_maximum_added_lightning_damage":
                        doubleDpsPerStat[(int)DamageType.Lightning] += value;
                        break;

                    case "unique_local_minimum_added_chaos_damage_when_in_off_hand":
                    case "unique_local_maximum_added_chaos_damage_when_in_off_hand":
                    case "local_minimum_added_chaos_damage":
                    case "local_maximum_added_chaos_damage":
                        doubleDpsPerStat[(int)DamageType.Chaos] += value;
                        break;
                    }
                }
            }
            WeaponDpsSettings settings = Settings.WeaponDps;

            Color[] elementalDmgColors = { Color.White,
                                           settings.DmgFireColor,
                                           settings.DmgColdColor,
                                           settings.DmgLightningColor,
                                           settings.DmgChaosColor };
            physDmgMultiplier += itemEntity.GetComponent <Quality>().ItemQuality / 100f;
            PhysLo             = (int)Math.Round(PhysLo * physDmgMultiplier);
            PhysHi             = (int)Math.Round(PhysHi * physDmgMultiplier);
            doubleDpsPerStat[(int)DamageType.Physical] = PhysLo + PhysHi;

            aSpd = (float)Math.Round(aSpd, 2);
            float pDps     = doubleDpsPerStat[(int)DamageType.Physical] / 2 * aSpd;
            float eDps     = 0;
            int   firstEmg = 0;
            Color DpsColor = settings.pDamageColor;

            for (int i = 1; i < cntDamages; i++)
            {
                eDps += doubleDpsPerStat[i] / 2 * aSpd;
                if (doubleDpsPerStat[i] > 0)
                {
                    if (firstEmg == 0)
                    {
                        firstEmg = i;
                        DpsColor = elementalDmgColors[i];
                    }
                    else
                    {
                        DpsColor = settings.eDamageColor;
                    }
                }
            }

            var   textPosition = new Vector2(clientRect.Right - 2, clientRect.Y + 1);
            Size2 pDpsSize     = pDps > 0
                ? Graphics.DrawText(pDps.ToString("#.#"), settings.DpsTextSize, textPosition, FontDrawFlags.Right)
                : new Size2();
            Size2 eDpsSize = eDps > 0
                ? Graphics.DrawText(eDps.ToString("#.#"), settings.DpsTextSize,
                                    textPosition.Translate(0, pDpsSize.Height), DpsColor, FontDrawFlags.Right)
                : new Size2();
            Vector2 dpsTextPosition = textPosition.Translate(0, pDpsSize.Height + eDpsSize.Height);

            Graphics.DrawText("dps", settings.DpsNameTextSize, dpsTextPosition, settings.TextColor, FontDrawFlags.Right);
            Graphics.DrawImage("preload-end.png", new RectangleF(textPosition.X - 86, textPosition.Y - 6, 90, 65), settings.BackgroundColor);
        }
Example #47
0
        /// <summary>
        /// Determine the output format of the texture depending on the platform and asset properties.
        /// </summary>
        /// <param name="parameters">The conversion request parameters</param>
        /// <param name="imageSize">The texture output size</param>
        /// <param name="inputImageFormat">The pixel format of the input image</param>
        /// <returns>The pixel format to use as output</returns>
        public static PixelFormat DetermineOutputFormat(ImportParameters parameters, Size2 imageSize, PixelFormat inputImageFormat)
        {
            var hint      = parameters.TextureHint;
            var alphaMode = parameters.DesiredAlpha;

            // Default output format
            var outputFormat = PixelFormat.R8G8B8A8_UNorm;

            switch (parameters.ShouldCompress)
            {
            case true:
                switch (parameters.Platform)
                {
                case PlatformType.Android:
                case PlatformType.iOS:
                    if (inputImageFormat.IsHDR())
                    {
                        outputFormat = inputImageFormat;
                    }
                    else
                    {
                        switch (parameters.GraphicsProfile)
                        {
                        case GraphicsProfile.Level_9_1:
                        case GraphicsProfile.Level_9_2:
                        case GraphicsProfile.Level_9_3:
                            outputFormat = alphaMode == AlphaFormat.None && !parameters.IsSRgb ? PixelFormat.ETC1 : parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                            break;

                        case GraphicsProfile.Level_10_0:
                        case GraphicsProfile.Level_10_1:
                        case GraphicsProfile.Level_11_0:
                        case GraphicsProfile.Level_11_1:
                        case GraphicsProfile.Level_11_2:
                            // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android
                            switch (alphaMode)
                            {
                            case AlphaFormat.None:
                                outputFormat = parameters.IsSRgb ? PixelFormat.ETC2_RGB_SRgb : PixelFormat.ETC2_RGB;
                                break;

                            case AlphaFormat.Mask:
                                // DXT1 handles 1-bit alpha channel
                                // TODO: Not sure about the equivalent here?
                                outputFormat = parameters.IsSRgb ? PixelFormat.ETC2_RGBA_SRgb : PixelFormat.ETC2_RGB_A1;
                                break;

                            case AlphaFormat.Explicit:
                            case AlphaFormat.Interpolated:
                                // DXT3 is good at sharp alpha transitions
                                // TODO: Not sure about the equivalent here?
                                outputFormat = parameters.IsSRgb ? PixelFormat.ETC2_RGBA_SRgb : PixelFormat.ETC2_RGBA;
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                            break;

                        default:
                            throw new ArgumentOutOfRangeException("GraphicsProfile");
                        }
                    }
                    break;

                case PlatformType.Windows:
                case PlatformType.UWP:
                case PlatformType.Linux:
                case PlatformType.macOS:
                    switch (parameters.GraphicsPlatform)
                    {
                    case GraphicsPlatform.Direct3D11:
                    case GraphicsPlatform.Direct3D12:
                    case GraphicsPlatform.OpenGL:
                    case GraphicsPlatform.Vulkan:

                        // https://msdn.microsoft.com/en-us/library/windows/desktop/hh308955%28v=vs.85%29.aspx
                        // http://www.reedbeta.com/blog/2012/02/12/understanding-bcn-texture-compression-formats/
                        // ----------------------------------------------    ----------------------------------------------------                        ---    ---------------------------------
                        // Source data                                       Minimum required data compression resolution                     Recommended format	Minimum supported feature level
                        // ----------------------------------------------    ----------------------------------------------------                        ---    ---------------------------------
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits), with 0 or 1 bit(s) of alpha    BC1    Direct3D 9.1     (color maps, cutout color maps - 1 bit alpha, normal maps if memory is tight)
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits), with 4 bits of alpha           BC2    Direct3D 9.1     (idem)
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits) with 8 bits of alpha            BC3    Direct3D 9.1     (color maps with alpha, packing color and mono maps together)
                        // One-channel color                                 One color channel (8 bits)                                                  BC4    Direct3D 10      (Height maps, gloss maps, font atlases, any gray scales image)
                        // Two-channel color	                             Two color channels (8 bits:8 bits)                                          BC5    Direct3D 10      (Tangent space normal maps)
                        // Three-channel high dynamic range (HDR) color      Three color channels (16 bits:16 bits:16 bits) in "half" floating point*    BC6H   Direct3D 11      (HDR images)
                        // Three-channel color, alpha channel optional       Three color channels (4 to 7 bits per channel) with 0 to 8 bits of alpha    BC7    Direct3D 11      (High quality color maps, Color maps with full alpha)

                        switch (alphaMode)
                        {
                        case AlphaFormat.None:
                        case AlphaFormat.Mask:
                            // DXT1 handles 1-bit alpha channel
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC1_UNorm_SRgb : PixelFormat.BC1_UNorm;
                            break;

                        case AlphaFormat.Explicit:
                            // DXT3 is good at sharp alpha transitions
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC2_UNorm_SRgb : PixelFormat.BC2_UNorm;
                            break;

                        case AlphaFormat.Interpolated:
                            // DXT5 is good at alpha gradients
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC3_UNorm_SRgb : PixelFormat.BC3_UNorm;
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }

                        // Overrides the format when profile is >= 10.0
                        // Support some specific optimized formats based on the hint or input type
                        if (parameters.GraphicsProfile >= GraphicsProfile.Level_10_0)
                        {
                            if (parameters.GraphicsPlatform != GraphicsPlatform.OpenGL && hint == TextureHint.NormalMap)
                            {
                                outputFormat = PixelFormat.BC5_UNorm;
                            }
                            else if (parameters.GraphicsPlatform != GraphicsPlatform.OpenGL && hint == TextureHint.Grayscale)
                            {
                                outputFormat = PixelFormat.BC4_UNorm;
                            }
                            else if (inputImageFormat.IsHDR())
                            {
                                // BC6H is too slow to compile
                                //outputFormat = parameters.GraphicsProfile >= GraphicsProfile.Level_11_0 && alphaMode == AlphaFormat.None ? PixelFormat.BC6H_Uf16 : inputImageFormat;
                                outputFormat = inputImageFormat;
                            }
                            // TODO support the BC6/BC7 but they are so slow to compile that we can't use them right now
                        }
                        break;

                    case GraphicsPlatform.OpenGLES:             // OpenGLES on Windows
                        if (inputImageFormat.IsHDR())
                        {
                            outputFormat = inputImageFormat;
                        }
                        else if (parameters.IsSRgb)
                        {
                            outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb;
                        }
                        else
                        {
                            switch (parameters.GraphicsProfile)
                            {
                            case GraphicsProfile.Level_9_1:
                            case GraphicsProfile.Level_9_2:
                            case GraphicsProfile.Level_9_3:
                                outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.R8G8B8A8_UNorm;
                                break;

                            case GraphicsProfile.Level_10_0:
                            case GraphicsProfile.Level_10_1:
                            case GraphicsProfile.Level_11_0:
                            case GraphicsProfile.Level_11_1:
                            case GraphicsProfile.Level_11_2:
                                // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android
                                outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.ETC2_RGBA;
                                break;

                            default:
                                throw new ArgumentOutOfRangeException("GraphicsProfile");
                            }
                        }
                        break;

                    default:
                        // OpenGL on Windows
                        // TODO: Need to handle OpenGL Desktop compression
                        outputFormat = parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                        break;
                    }
                    break;

                default:
                    throw new NotSupportedException("Platform " + parameters.Platform + " is not supported by TextureTool");
                }
                break;

            case false:
                outputFormat = inputImageFormat;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            // OpenGLES: avoid BGRA (optional extension)
            if (parameters.GraphicsPlatform == GraphicsPlatform.OpenGLES)
            {
                switch (outputFormat)
                {
                case PixelFormat.B8G8R8A8_UNorm:
                    outputFormat = PixelFormat.R8G8B8A8_UNorm;
                    break;

                case PixelFormat.B8G8R8A8_UNorm_SRgb:
                    outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb;
                    break;
                }
            }

            // OpenGL and OpenGLES: avoid R5G6B5 (not implemented)
            if (parameters.GraphicsPlatform == GraphicsPlatform.OpenGLES || parameters.GraphicsPlatform == GraphicsPlatform.OpenGL)
            {
                switch (outputFormat)
                {
                case PixelFormat.B5G5R5A1_UNorm:
                case PixelFormat.B5G6R5_UNorm:
                    outputFormat = PixelFormat.R8G8B8A8_UNorm;
                    break;
                }
            }

            return(outputFormat);
        }
    public void Dilate(MultiUvTextureMask mask, Size2 size, bool isLinear, DataBox imageData)
    {
        //set every alpha value to 0
        for (int i = 0; i < imageData.SlicePitch; i += 4)
        {
            var rgba = Utilities.Read <uint>(imageData.DataPointer + i);
            rgba &= 0xffffff;
            Utilities.Write <uint>(imageData.DataPointer + i, ref rgba);
        }

        var sourceTextureDesc = new Texture2DDescription {
            Width             = size.Width,
            Height            = size.Height,
            MipLevels         = 0,
            ArraySize         = 1,
            Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget | BindFlags.UnorderedAccess,
            OptionFlags       = ResourceOptionFlags.GenerateMipMaps
        };
        var sourceTexture        = new Texture2D(device, sourceTextureDesc);
        var sourceTextureInView  = new ShaderResourceView(device, sourceTexture);
        var sourceTextureOutView = new UnorderedAccessView(device, sourceTexture);

        var destTextureDesc = new Texture2DDescription {
            Width             = size.Width,
            Height            = size.Height,
            MipLevels         = 1,
            ArraySize         = 1,
            Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            BindFlags         = BindFlags.UnorderedAccess
        };
        var destTexture        = new Texture2D(device, destTextureDesc);
        var destTextureOutView = new UnorderedAccessView(device, destTexture);

        var stagingTextureDesc = new Texture2DDescription {
            Width             = size.Width,
            Height            = size.Height,
            MipLevels         = 1,
            ArraySize         = 1,
            Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
            SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            Usage             = ResourceUsage.Staging,
            CpuAccessFlags    = CpuAccessFlags.Read
        };
        var stagingTexture = new Texture2D(device, stagingTextureDesc);

        var context = device.ImmediateContext;

        context.UpdateSubresource(imageData, sourceTexture, 0);

        foreach (var perUvMask in mask.PerUvMasks)
        {
            maskRenderer.RenderMaskToAlpha(perUvMask, size, sourceTexture);
        }

        context.ClearState();
        context.ComputeShader.Set(alphaPremultiplerShader);
        context.ComputeShader.SetUnorderedAccessView(0, sourceTextureOutView);
        context.Dispatch(
            IntegerUtils.RoundUp(size.Width, ShaderNumThreadsPerDim),
            IntegerUtils.RoundUp(size.Height, ShaderNumThreadsPerDim),
            1);
        context.ClearState();

        context.GenerateMips(sourceTextureInView);

        context.ClearState();
        context.ComputeShader.Set(dilatorShader);
        context.ComputeShader.SetShaderResources(0, sourceTextureInView);
        context.ComputeShader.SetUnorderedAccessView(0, destTextureOutView);
        context.Dispatch(
            IntegerUtils.RoundUp(size.Width, ShaderNumThreadsPerDim),
            IntegerUtils.RoundUp(size.Height, ShaderNumThreadsPerDim),
            1);
        context.ClearState();

        context.CopyResource(destTexture, stagingTexture);

        var resultImageData = context.MapSubresource(stagingTexture, 0, MapMode.Read, MapFlags.None);

        CopyDataBox(resultImageData, imageData);
        context.UnmapSubresource(stagingTexture, 0);

        stagingTexture.Dispose();

        destTexture.Dispose();
        destTextureOutView.Dispose();

        sourceTexture.Dispose();
        sourceTextureInView.Dispose();
        sourceTextureOutView.Dispose();
    }
Example #49
0
 public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror)
 {
     ActualRenderFrameSize = optimalRenderFrameSize = new Size2(2560, 1440);
     MirrorTexture         = Texture.New2D(device, ActualRenderFrameSize.Width, ActualRenderFrameSize.Height, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.RenderTarget | TextureFlags.ShaderResource);
 }
Example #50
0
 public IconManager()
 {
     IconSize = new Size2(42, 42);
 }
Example #51
0
 /// <summary>
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.
 /// </summary>
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="bitmapProperties">The pixel format and dots per inch (DPI) of the bitmap to create.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>
 public Bitmap1(DeviceContext deviceContext, Size2 size, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : this(deviceContext, size, null, 0, bitmapProperties)
 {
 }
Example #52
0
 /// <summary>
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.
 /// </summary>
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="dataStream">A pointer to the memory location of the image data, or NULL to create an uninitialized bitmap.</param>
 /// <param name="pitch">The byte count of each scanline, which is equal to (the image width in pixels * the number of bytes per pixel) + memory padding. If srcData is NULL, this value is ignored. (Note that pitch is also sometimes called stride.)</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>
 public Bitmap1(DeviceContext deviceContext, Size2 size, DataStream dataStream, int pitch)
     : this(deviceContext, size, dataStream, pitch, new BitmapProperties1(new PixelFormat(Format.Unknown, AlphaMode.Unknown)))
 {
 }
Example #53
0
        public static ResultStatus ImportTextureImageRaw(TextureTool textureTool, TexImage texImage, ImportParameters parameters, CancellationToken cancellationToken, Logger logger)
        {
            // Apply transformations
            textureTool.Decompress(texImage, parameters.IsSRgb);

            // Special case when the input texture is monochromatic but it is supposed to be a color and we are working in SRGB
            // In that case, we need to transform it to a supported SRGB format (R8G8B8A8_UNorm_SRgb)
            // TODO: As part of a conversion phase, this code may be moved to a dedicated method in this class at some point
            if (parameters.TextureHint == TextureHint.Color && parameters.IsSRgb && (texImage.Format == PixelFormat.R8_UNorm || texImage.Format == PixelFormat.A8_UNorm))
            {
                textureTool.Convert(texImage, PixelFormat.R8G8B8A8_UNorm_SRgb);
            }

            if (parameters.TextureHint == TextureHint.NormalMap && parameters.InvertY)
            {
                textureTool.InvertY(texImage);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
            {
                return(ResultStatus.Cancelled);
            }

            var fromSize   = new Size2(texImage.Width, texImage.Height);
            var targetSize = parameters.DesiredSize;

            // Resize the image
            if (parameters.IsSizeInPercentage)
            {
                targetSize = new Size2((int)(fromSize.Width * targetSize.Width / 100.0f), (int)(fromSize.Height * targetSize.Height / 100.0f));
            }

            // determine the alpha format of the texture when set to Auto
            // Note: this has to be done before the ColorKey transformation in order to be able to take advantage of image file AlphaDepth information
            if (parameters.DesiredAlpha == AlphaFormat.Auto)
            {
                var colorKey   = parameters.ColorKeyEnabled ? (Color?)parameters.ColorKeyColor : null;
                var alphaLevel = textureTool.GetAlphaLevels(texImage, new Rectangle(0, 0, texImage.Width, texImage.Height), colorKey, logger);
                parameters.DesiredAlpha = alphaLevel.ToAlphaFormat();
            }

            // Find the target size
            var outputFormat = DetermineOutputFormat(parameters, targetSize, texImage.Format);

            targetSize = FindBestTextureSize(parameters, outputFormat, targetSize, logger);

            // Resize the image only if needed
            if (targetSize != fromSize)
            {
                textureTool.Resize(texImage, targetSize.Width, targetSize.Height, Filter.Rescaling.Lanczos3);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
            {
                return(ResultStatus.Cancelled);
            }

            // Apply the color key
            if (parameters.ColorKeyEnabled)
            {
                textureTool.ColorKey(texImage, parameters.ColorKeyColor);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
            {
                return(ResultStatus.Cancelled);
            }

            // Pre-multiply alpha only for relevant formats
            if (parameters.PremultiplyAlpha && texImage.Format.HasAlpha32Bits())
            {
                textureTool.PreMultiplyAlpha(texImage);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
            {
                return(ResultStatus.Cancelled);
            }


            // Generate mipmaps
            if (parameters.GenerateMipmaps)
            {
                var boxFilteringIsSupported = !texImage.Format.IsSRgb() || (MathUtil.IsPow2(targetSize.Width) && MathUtil.IsPow2(targetSize.Height));
                textureTool.GenerateMipMaps(texImage, boxFilteringIsSupported? Filter.MipMapGeneration.Box: Filter.MipMapGeneration.Linear);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
            {
                return(ResultStatus.Cancelled);
            }


            // Convert/Compress to output format
            // TODO: Change alphaFormat depending on actual image content (auto-detection)?
            outputFormat = DetermineOutputFormat(parameters, targetSize, texImage.Format);
            textureTool.Compress(texImage, outputFormat, (TextureConverter.Requests.TextureQuality)parameters.TextureQuality);

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
            {
                return(ResultStatus.Cancelled);
            }

            return(ResultStatus.Successful);
        }
Example #54
0
        protected override void DrawCore(RenderDrawContext context)
        {
            // Inputs:
            Texture colorBuffer             = GetSafeInput(0);
            Texture depthBuffer             = GetSafeInput(1);
            Texture normalsBuffer           = GetSafeInput(2);
            Texture specularRoughnessBuffer = GetSafeInput(3);

            // Output:
            Texture outputBuffer = GetSafeOutput(0);

            // Prepare
            var temporalCache = Prepare(context, outputBuffer);

            FlushCache(context.RenderContext.Time.FrameCount);

            // Get temporary buffers
            var     rayTraceBuffersSize = GetBufferResolution(outputBuffer, RayTracePassResolution);
            var     resolveBuffersSize  = GetBufferResolution(outputBuffer, ResolvePassResolution);
            Texture rayTraceBuffer      = NewScopedRenderTarget2D(rayTraceBuffersSize.Width, rayTraceBuffersSize.Height, RayTraceTargetFormat, 1);
            Texture resolveBuffer       = NewScopedRenderTarget2D(resolveBuffersSize.Width, resolveBuffersSize.Height, ReflectionsFormat, 1);

            // Check if resize depth
            Texture smallerDepthBuffer = depthBuffer;

            if (DepthResolution != ResolutionMode.Full)
            {
                // Smaller depth buffer improves ray tracing performance.

                var depthBuffersSize = GetBufferResolution(depthBuffer, DepthResolution);
                smallerDepthBuffer = NewScopedRenderTarget2D(depthBuffersSize.Width, depthBuffersSize.Height, PixelFormat.R32_Float, 1);

                depthPassShader.SetInput(0, depthBuffer);
                depthPassShader.SetOutput(smallerDepthBuffer);
                depthPassShader.Draw(context, "Downscale Depth");
            }

            // Blur Pass
            Texture blurPassBuffer;

            if (UseColorBufferMips)
            {
                // Note: using color buffer mips maps helps with reducing artifacts
                // and improves resolve pass performance (faster color texture lookups, less cache misses)
                // Also for high surface roughness values it adds more blur to the reflection tail which looks more realistic.

                // Get temp targets
                var     colorBuffersSize      = new Size2(outputBuffer.Width / 2, outputBuffer.Height / 2);
                int     colorBuffersMips      = Texture.CalculateMipMapCount(MipMapCount.Auto, colorBuffersSize.Width, colorBuffersSize.Height);
                Texture colorBuffer0          = NewScopedRenderTarget2D(colorBuffersSize.Width, colorBuffersSize.Height, ReflectionsFormat, colorBuffersMips);
                Texture colorBuffer1          = NewScopedRenderTarget2D(colorBuffersSize.Width / 2, colorBuffersSize.Height / 2, ReflectionsFormat, colorBuffersMips - 1);
                int     colorBuffer1MipOffset = 1; // For colorBuffer1 we could use one mip less (optimized)

                // Cache per color buffer mip views
                int colorBuffer0Mips = colorBuffer0.MipLevels;
                if (cachedColorBuffer0Mips == null || cachedColorBuffer0Mips.Length != colorBuffer0Mips || cachedColorBuffer0Mips[0].ParentTexture != colorBuffer0)
                {
                    cachedColorBuffer0Mips?.ForEach(view => view?.Dispose());
                    cachedColorBuffer0Mips = new Texture[colorBuffer0Mips];
                    for (int mipIndex = 0; mipIndex < colorBuffer0Mips; mipIndex++)
                    {
                        cachedColorBuffer0Mips[mipIndex] = colorBuffer0.ToTextureView(ViewType.Single, 0, mipIndex);
                    }
                }
                int colorBuffer1Mips = colorBuffer1.MipLevels;
                if (cachedColorBuffer1Mips == null || cachedColorBuffer1Mips.Length != colorBuffer1Mips || cachedColorBuffer1Mips[0].ParentTexture != colorBuffer1)
                {
                    cachedColorBuffer1Mips?.ForEach(view => view?.Dispose());
                    cachedColorBuffer1Mips = new Texture[colorBuffer1Mips];
                    for (int mipIndex = 0; mipIndex < colorBuffer1Mips; mipIndex++)
                    {
                        cachedColorBuffer1Mips[mipIndex] = colorBuffer1.ToTextureView(ViewType.Single, 0, mipIndex);
                    }
                }

                // Clone scene frame to mip 0 of colorBuffer0
                Scaler.SetInput(0, colorBuffer);
                Scaler.SetOutput(cachedColorBuffer0Mips[0]);
                Scaler.Draw(context, "Copy frame");

                // Downscale with gaussian blur
                for (int mipLevel = 1; mipLevel < colorBuffersMips; mipLevel++)
                {
                    // Blur H
                    var srcMip = cachedColorBuffer0Mips[mipLevel - 1];
                    var dstMip = cachedColorBuffer1Mips[mipLevel - colorBuffer1MipOffset];
                    blurPassShaderH.SetInput(0, srcMip);
                    blurPassShaderH.SetOutput(dstMip);
                    blurPassShaderH.Draw(context, "Blur H");

                    // Blur V
                    srcMip = dstMip;
                    dstMip = cachedColorBuffer0Mips[mipLevel];
                    blurPassShaderV.SetInput(0, srcMip);
                    blurPassShaderV.SetOutput(dstMip);
                    blurPassShaderV.Draw(context, "Blur V");
                }

                blurPassBuffer = colorBuffer0;
            }
            else
            {
                // Don't use color buffer with mip maps
                blurPassBuffer = colorBuffer;

                cachedColorBuffer0Mips?.ForEach(view => view?.Dispose());
                cachedColorBuffer1Mips?.ForEach(view => view?.Dispose());
            }

            // Ray Trace Pass
            rayTracePassShader.SetInput(0, colorBuffer);
            rayTracePassShader.SetInput(1, smallerDepthBuffer);
            rayTracePassShader.SetInput(2, normalsBuffer);
            rayTracePassShader.SetInput(3, specularRoughnessBuffer);
            rayTracePassShader.SetOutput(rayTraceBuffer);
            rayTracePassShader.Draw(context, "Ray Trace");

            // Resolve Pass
            resolvePassShader.SetInput(0, blurPassBuffer);
            resolvePassShader.SetInput(1, ResolvePassResolution == ResolutionMode.Full ? depthBuffer : smallerDepthBuffer);
            resolvePassShader.SetInput(2, normalsBuffer);
            resolvePassShader.SetInput(3, specularRoughnessBuffer);
            resolvePassShader.SetInput(4, rayTraceBuffer);
            resolvePassShader.SetOutput(resolveBuffer);
            resolvePassShader.Draw(context, "Resolve");

            // Temporal Pass
            Texture reflectionsBuffer = resolveBuffer;

            if (TemporalEffect)
            {
                var temporalSize = outputBuffer.Size;
                temporalCache.Resize(GraphicsDevice, ref temporalSize);
                Texture temporalBuffer0 = NewScopedRenderTarget2D(temporalSize.Width, temporalSize.Height, ReflectionsFormat, 1);

                temporalPassShader.SetInput(0, resolveBuffer);
                temporalPassShader.SetInput(1, temporalCache.TemporalBuffer);
                temporalPassShader.SetInput(2, depthBuffer);
                temporalPassShader.SetOutput(temporalBuffer0);
                temporalPassShader.Draw(context, "Temporal");

                context.CommandList.Copy(temporalBuffer0, temporalCache.TemporalBuffer); // TODO: use Texture.Swap from ContentStreaming branch to make it faster!

                reflectionsBuffer = temporalCache.TemporalBuffer;
            }

            // Combine Pass
            combinePassShader.SetInput(0, colorBuffer);
            combinePassShader.SetInput(1, depthBuffer);
            combinePassShader.SetInput(2, normalsBuffer);
            combinePassShader.SetInput(3, specularRoughnessBuffer);
            combinePassShader.SetInput(4, reflectionsBuffer);
            combinePassShader.SetOutput(outputBuffer);
            combinePassShader.Draw(context, "Combine");

#if SSLR_DEBUG
            if (DebugMode != DebugModes.None)
            {
                // Debug preview of temp targets
                switch (DebugMode)
                {
                case DebugModes.RayTrace:
                    Scaler.SetInput(0, rayTraceBuffer);
                    break;

                case DebugModes.Resolve:
                    Scaler.SetInput(0, resolveBuffer);
                    break;

                case DebugModes.Temporal:
                    if (temporalCache != null)
                    {
                        Scaler.SetInput(0, temporalCache.TemporalBuffer);
                    }
                    break;
                }
                Scaler.SetOutput(outputBuffer);
                Scaler.Draw(context);
            }
#endif
        }
Example #55
0
 private void GameForm_ResizeBeginActions(WindowEvent e)
 {
     isUserResizing = true;
     cachedSize     = Size;
     PauseRendering?.Invoke(this, EventArgs.Empty);
 }
 public virtual void Update()
 {
     TextSize = SessionStatisticsCore.SettingsInstance.TextSize;
     BoxSize  = Graphics.MeasureText(TextToDraw, TextSize);
 }
Example #57
0
 /// <summary>
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.
 /// </summary>
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>
 public Bitmap1(DeviceContext deviceContext, Size2 size)
     : this(deviceContext, size, null, 0, new BitmapProperties1(new PixelFormat(Format.Unknown, AlphaMode.Unknown)))
 {
 }
Example #58
0
        public override void Render()
        {
            base.Render();
            if (!Settings.Enable || WinApi.IsKeyDown(Keys.F10) || (GameController.Player != null &&
                                                                   GameController.Player.GetComponent <Player>().Level >= 100))
            {
                return;
            }

            DateTime nowTime     = DateTime.Now;
            TimeSpan elapsedTime = nowTime - lastTime;

            if (elapsedTime.TotalSeconds > 1)
            {
                CalculateXp(nowTime);
                partyXpPenalty = PartyXpPenalty();
                lastTime       = nowTime;
            }

            bool showInTown =
                !Settings.ShowInTown && GameController.Area.CurrentArea.IsTown ||
                !Settings.ShowInTown && GameController.Area.CurrentArea.IsHideout;
            Vector2 position         = StartDrawPointFunc();
            string  fps              = $"fps:({GameController.Game.IngameState.CurFps})";
            string  areaName         = $"{GameController.Area.CurrentArea.DisplayName}";
            Color   hasCorruptedArea = PreloadAlertPlugin.hasCorruptedArea;

            if (Settings.OnlyAreaName)
            {
                if (!showInTown)
                {
                    var    areaNameSize = Graphics.MeasureText(areaName, Settings.TextSize);
                    float  boxHeight    = areaNameSize.Height;
                    float  boxWidth     = MathHepler.Max(areaNameSize.Width);
                    var    bounds       = new RectangleF(position.X - 84 - boxWidth, position.Y - 5, boxWidth + 90, boxHeight + 12);
                    string latency      = $"({GameController.Game.IngameState.CurLatency})";
                    Graphics.DrawText(areaName, Settings.TextSize, new Vector2(bounds.X + 84, position.Y), hasCorruptedArea);
                    Graphics.DrawImage("preload-start.png", bounds, Settings.BackgroundColor);
                    Graphics.DrawImage("preload-end.png", bounds, Settings.BackgroundColor);
                    if (Settings.ShowLatency)
                    {
                        Graphics.DrawText(latency, Settings.TextSize, new Vector2(bounds.X + 35, position.Y), Settings.LatencyTextColor);
                    }
                    Size   = bounds.Size;
                    Margin = new Vector2(0, 5);
                }
            }

            if (!Settings.OnlyAreaName)
            {
                if (!showInTown)
                {
                    var     xpReceiving     = levelXpPenalty * partyXpPenalty;
                    var     xpReceivingText = $"{xpRate}  *{xpReceiving:p0}";
                    string  ping            = $"ping:({GameController.Game.IngameState.CurLatency})";
                    Size2   areaNameSize    = Graphics.DrawText(areaName, Settings.TextSize, position - 1, hasCorruptedArea, FontDrawFlags.Right);
                    Vector2 secondLine      = position.Translate(-1, areaNameSize.Height + 2);
                    Size2   xpRateSize      = Graphics.DrawText(timeLeft, Settings.TextSize, secondLine, Settings.TimeLeftColor, FontDrawFlags.Right);
                    Vector2 thirdLine       = secondLine.Translate(-1, xpRateSize.Height + 2);
                    Size2   xpLeftSize      = Graphics.DrawText(xpReceivingText, Settings.TextSize, thirdLine, Settings.TimeLeftColor, FontDrawFlags.Right);
                    string  timer           = AreaInstance.GetTimeString(nowTime - GameController.Area.CurrentArea.TimeEntered);
                    Size2   timerSize       = Graphics.MeasureText(timer, Settings.TextSize);

                    float boxWidth  = MathHepler.Max(xpRateSize.Width + 40, xpLeftSize.Width + 40, areaNameSize.Width + 20, timerSize.Width);
                    float boxHeight = xpRateSize.Height + xpLeftSize.Height + areaNameSize.Height;
                    var   bounds    = new RectangleF(position.X - boxWidth - 104, position.Y - 7, boxWidth + 110, boxHeight + 18);

                    Size2 timeFpsSize = Graphics.MeasureText(fps, Settings.TextSize);
                    var   dif         = bounds.Width - (12 + timeFpsSize.Width + xpRateSize.Width);
                    if (dif < 0)
                    {
                        bounds.X += dif; bounds.Width -= dif;
                    }

                    Graphics.DrawText(timer, Settings.TextSize, new Vector2(bounds.X + 70, position.Y), Settings.TimerTextColor);
                    Graphics.DrawText(fps, Settings.TextSize, new Vector2(bounds.X + 70, secondLine.Y), Settings.FpsTextColor);
                    Graphics.DrawText(ping, Settings.TextSize, new Vector2(bounds.X + 70, thirdLine.Y), Settings.LatencyTextColor);
                    Graphics.DrawImage("preload-start.png", bounds, Settings.BackgroundColor);
                    Graphics.DrawImage("preload-end.png", bounds, Settings.BackgroundColor);
                    Size   = bounds.Size;
                    Margin = new Vector2(0, 5);
                }
            }
        }
Example #59
0
        public void SDXThread(object sender)
        {
            float progress = 0.0f;

            while (IsRunning)
            {
                GameHandle = GameProcess.MainWindowHandle;

                if (GameProcess.HasExited)
                {
                    IsRunning = false;
                }

                // get the coords of the csgo window
                GetWindowRect(GameHandle, out WindowBounds);

                // set the location of the form overlay
                try
                {
                    if (WindowBounds.X != Location.X || WindowBounds.Width != Size.Width)
                    {
                        Location = new System.Drawing.Point(WindowBounds.X, WindowBounds.Y);
                        Size     = new System.Drawing.Size(WindowBounds.Width, WindowBounds.Height);
                    }
                }
                catch { }

                // set the size of the form overlay
                WindowSize = new Size2(WindowBounds.Width, WindowBounds.Height);

                RenderDevice.BeginDraw();
                RenderDevice.Clear(Color.Transparent);
                RenderDevice.TextAntialiasMode = TextAntialiasMode.Aliased; // you can set another text mode

                //place your rendering things here
                if (GetActiveWindowTitle() == "Counter-Strike: Global Offensive" || GetActiveWindowTitle() == "Dolphin")
                {
                    Mem.StartProcess();

                    // Create Local Entity
                    LocalEntity LE = new LocalEntity();

                    // update viewmatrix
                    ViewMatrix = Matrix4x4.ReadMatrix(Mem, dwClient + dwViewMatrix);

                    // Update radar image (in case of map change)
                    if (RadarEnabled)
                    {
                        RadarImageUpdate();
                    }

                    // perform this loop for every entity in the game
                    for (int i = 0; i < 32; i++)
                    {
                        // increment rainbow cycle colour
                        progress += 0.00001f;

                        // create new entity instance
                        Entity Entity = new Entity(i);

                        // Call Radar if enabled on GUI
                        if (RadarEnabled)
                        {
                            RadarLoop(Entity, LE);
                        }

                        // Call ESP if enabled on GUI
                        if (BoxESPEnabledFriendly || BoxESPEnabledOpposition || SkeletonsEnabledFriendly || SkeletonsEnabledOpposition)
                        {
                            ESPLoop(Entity, LE, progress);
                        }

                        // Draw HP Label if enabled on GUI
                        if (IsEnabled_EnemyHPLabel && Entity.Entity_Team != LE.LocalEntity_Team && Entity.Entity_isAlive())
                        {
                            Drawing2D.DrawShadowText(Entity.Entity_Position_W2S.X - 20, Entity.Entity_Position_W2S.Y, 12.0f, Color.Lime, ("《 ❤ " + Entity.Entity_Health + " 》"));
                        }

                        // Draw Glow if enabled on GUI
                        if (GlowEnabledOpposition || GlowEnabledFriendly)
                        {
                            DoGlow(Mem, Entity, LE, progress);
                        }

                        // Call trigger if enabled on GUI
                        if (IsEnabled_TriggerBot)
                        {
                            TriggerbotLoop(LE);
                        }
                    }
                    Thread.Sleep(1);
                }
                RenderDevice.EndDraw();
            }
        }
Example #60
-1
        private static List<Vector3> generateTreePositions(Texture2D treeMap, GroundMap groundMap, ColorSurface normals)
        {
            var treeMapColors = new Color[treeMap.Description.Width*treeMap.Description.Height];
            treeMap. GetData(treeMapColors);

            var sz = new Size2(treeMap.Description.Width, treeMap.Description.Height);
            var noiseData = new int[sz.Width,sz.Height];
            for (var x = 0; x < sz.Width; x++)
                for (var y = 0; y < sz.Height; y++)
                    noiseData[x, y] = treeMapColors[y + x*sz.Height].R;

            var treeList = new List<Vector3>();
            var random = new Random();

            var minFlatness = (float) Math.Cos(MathUtil.DegreesToRadians(15));
            for (var y = normals.Height - 2; y > 0; y--)
                for (var x = normals.Width - 2; x > 0; x--)
                {
                    var terrainHeight = groundMap[x, y];
                    if ((terrainHeight <= 8) || (terrainHeight >= 14))
                        continue;
                    var flatness1 = Vector3.Dot(normals.AsVector3(x, y), Vector3.Up);
                    var flatness2 = Vector3.Dot(normals.AsVector3(x + 1, y + 1), Vector3.Up);
                    if (flatness1 <= minFlatness || flatness2 <= minFlatness)
                        continue;
                    var relx = (float) x/normals.Width;
                    var rely = (float) y/normals.Height;

                    float noiseValueAtCurrentPosition = noiseData[(int) (relx*sz.Width), (int) (rely*sz.Height)];
                    float treeDensity;
                    if (noiseValueAtCurrentPosition > 200)
                        treeDensity = 3;
                    else if (noiseValueAtCurrentPosition > 150)
                        treeDensity = 2;
                    else if (noiseValueAtCurrentPosition > 100)
                        treeDensity = 1;
                    else
                        treeDensity = 0;

                    for (var currDetail = 0; currDetail < treeDensity; currDetail++)
                    {
                        var rand1 = (float) random.NextDouble();
                        var rand2 = (float) random.NextDouble();
                        treeList.Add(new Vector3(
                                         x + rand1,
                                         groundMap.GetExactHeight(x, y, rand1, rand2),
                                         y + rand2));
                    }
                }

            return treeList;
        }