Example #1
0
 public SharpDX.DXGI.SwapChain CreateSwapChain(SharpDX.DXGI.SwapChainDescription desc)
 {
     using (var factory = new SharpDX.DXGI.Factory1())
     {
         return(new SharpDX.DXGI.SwapChain(factory, _dx11Device, desc));
     }
 }
Example #2
0
        private void InitializeDeviceResources()
        {
            SharpDX.DXGI.ModeDescription      backBufferDesc = new SharpDX.DXGI.ModeDescription(Width, Height, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm);
            SharpDX.DXGI.SwapChainDescription swapChainDesc  = new SharpDX.DXGI.SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = renderForm.Handle,
                IsWindowed        = true
            };
            SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            var factory = swapChain.GetParent <SharpDX.DXGI.Factory>();

            factory.MakeWindowAssociation(renderForm.Handle, SharpDX.DXGI.WindowAssociationFlags.IgnoreAll);
            d3dDeviceContext = d3dDevice.ImmediateContext;
            using (SharpDX.Direct3D11.Texture2D backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
            {
                renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            // Set viewport
            viewport = new SharpDX.Viewport(0, 0, Width, Height);
            d3dDeviceContext.Rasterizer.SetViewport(viewport);
        }
        private void InitializeDirectXResources()
        {
            var clientSize     = ClientSize;
            var backBufferDesc = new SharpDX.DXGI.ModeDescription(clientSize.Width, clientSize.Height,
                                                                  new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm);

            var swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = Handle,
                SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                IsWindowed        = false
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport,
                                                          new[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, swapChainDesc,
                                                          out _d3DDevice, out var swapChain);
            _d3DDeviceContext = _d3DDevice.ImmediateContext;

            _swapChain = new SharpDX.DXGI.SwapChain1(swapChain.NativePointer);

            _d2DFactory = new SharpDX.Direct2D1.Factory();

            using (var backBuffer = _swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
            {
                _renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3DDevice, backBuffer);
                _renderTarget     = new SharpDX.Direct2D1.RenderTarget(_d2DFactory, backBuffer.QueryInterface <SharpDX.DXGI.Surface>(),
                                                                       new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)))
                {
                    TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype
                };
            }

            _solidColorBrush = new SharpDX.Direct2D1.SolidColorBrush(_renderTarget, Color.White);

            _dwFactory  = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);
            _textFormat = new SharpDX.DirectWrite.TextFormat(_dwFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold,
                                                             SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 84 * (float)GraphicsUtils.Scale)
            {
                TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center,
                ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center
            };
            //                var rectangleGeometry = new D2D1.RoundedRectangleGeometry(_d2DFactory,
            //                    new D2D1.RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, Width - 128 * 2, Height - 128 * 2) });
        }
Example #4
0
        public GpuSwapChain(
            IntPtr handle,
            Size <int> size,
            GpuPixelFormat pixelFormat,
            GpuDevice device)
        {
            //size property
            Size        = size;
            PixelFormat = pixelFormat;
            GpuDevice   = device;

            //get factory
            using (var factory = GpuDevice.Adapter.Adapter.GetParent <SharpDX.DXGI.Factory>())
            {
                //set swapchain desc
                var swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount     = 1,
                    Flags           = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed      = true,
                    ModeDescription = new SharpDX.DXGI.ModeDescription()
                    {
                        Format           = GpuConvert.ToPixelFormat(PixelFormat),
                        Height           = Size.Height,
                        Width            = Size.Width,
                        RefreshRate      = new SharpDX.DXGI.Rational(60, 1),
                        Scaling          = SharpDX.DXGI.DisplayModeScaling.Unspecified,
                        ScanlineOrdering = SharpDX.DXGI.DisplayModeScanlineOrder.Unspecified
                    },
                    OutputHandle      = handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.RenderTargetOutput
                };

                mSwapChain = new SharpDX.DXGI.SwapChain(factory, GpuDevice.Device, swapChainDesc);

                //report error, if create swapchain failed
                LogEmitter.Assert(mSwapChain != null, LogLevel.Error,
                                  "[Create SwapChain Failed] [Width = {0}] [Height = {1}] [Format = {2}]", Size.Width, Size.Height, PixelFormat);

                RenderTarget = new GpuRenderTarget(GpuDevice, this);
            }
        }
Example #5
0
        public void Init(IntPtr hWnd, ApplicationInfo appInfo)
        {
            if (m_ApplicationInfo != null)
            {
                throw new InvalidOperationException("context already initialized");
            }

            m_ApplicationInfo = appInfo;

            var swapChainDesc = new SharpDX.DXGI.SwapChainDescription
            {
                ModeDescription = new SharpDX.DXGI.ModeDescription
                {
                    Width       = m_ApplicationInfo.Width,
                    Height      = m_ApplicationInfo.Height,
                    RefreshRate = new SharpDX.DXGI.Rational(60, 1),
                    Format      = SharpDX.DXGI.Format.R8G8B8A8_UNorm
                },
                SampleDescription = new SharpDX.DXGI.SampleDescription
                {
                    Count = 4
                },
                BufferCount  = 1,
                Usage        = SharpDX.DXGI.Usage.RenderTargetOutput,
                OutputHandle = hWnd,
                IsWindowed   = !m_ApplicationInfo.FullScreen,
                SwapEffect   = SharpDX.DXGI.SwapEffect.Discard,
                Flags        = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch
            };

            Device.CreateWithSwapChain(DriverType.Hardware,
                                       DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, new[] { m_FeatureLevel },
                                       swapChainDesc, out Device dev, out SharpDX.DXGI.SwapChain swapChain);
            Dev       = dev;
            DevCon    = Dev.ImmediateContext;
            SwapChain = swapChain;

            m_MSAAQuality = Dev.CheckMultisampleQualityLevels(SharpDX.DXGI.Format.R8G8B8A8_UNorm, 4);

            Resize();
        }
Example #6
0
 public DUIDeviceContext3(IntPtr handle)
 {
     this.d3d11Device    = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport);
     this.dxgiDevice     = d3d11Device.QueryInterface <SharpDX.Direct3D11.Device1>().QueryInterface <SharpDX.DXGI.Device>();
     this.d2dDevice3     = new SharpDX.Direct2D1.Device3(dxgiDevice);
     this.deviceContext3 = new SharpDX.Direct2D1.DeviceContext3(d2dDevice3, SharpDX.Direct2D1.DeviceContextOptions.None);
     // 创建 DXGI SwapChain。
     SharpDX.DXGI.SwapChainDescription swapChainDescription = new SharpDX.DXGI.SwapChainDescription()
     {
         BufferCount  = 1,
         Usage        = SharpDX.DXGI.Usage.RenderTargetOutput,
         OutputHandle = handle,
         IsWindowed   = true,
         // 这里宽度和高度都是 0,表示自动获取。
         ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.B8G8R8A8_UNorm),
         SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
         SwapEffect        = SharpDX.DXGI.SwapEffect.Discard
     };
     this.swapChain             = new SharpDX.DXGI.SwapChain(dxgiDevice.GetParent <SharpDX.DXGI.Adapter>().GetParent <SharpDX.DXGI.Factory>(), d3d11Device, swapChainDescription);
     this.swapChainBuffer       = SharpDX.DXGI.Surface.FromSwapChain(this.swapChain, 0);
     this.targetBitmap          = new SharpDX.Direct2D1.Bitmap1(this.deviceContext3, this.swapChainBuffer);
     this.deviceContext3.Target = targetBitmap;
 }
Example #7
0
        private bool InitDevice()
        {
            var mode = new SharpDX.DXGI.ModeDescription()
            {
                Width            = Width,
                Height           = Height,
                RefreshRate      = new SharpDX.DXGI.Rational(60, 1),
                Format           = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                ScanlineOrdering = SharpDX.DXGI.DisplayModeScanlineOrder.Unspecified,
                Scaling          = SharpDX.DXGI.DisplayModeScaling.Unspecified,
            };

            var swapDesc = new SharpDX.DXGI.SwapChainDescription()
            {
                BufferCount       = 1,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                ModeDescription   = mode,
                OutputHandle      = Handle,
                IsWindowed        = true,
                SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
            };

            Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None, swapDesc, out device, out swapChain);

            Texture2D backbuffer = swapChain.GetBackBuffer <Texture2D>(0);

            renderTarget = new RenderTargetView(device, backbuffer);

            deviceContext = device.ImmediateContext;

            deviceContext.OutputMerger.SetRenderTargets(renderTarget);

            deviceContext.Rasterizer.SetViewport(0, 0, Width, Height);

            return(true);
        }
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - Simple Text");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = device.ImmediateContext;

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }


            fontFactory = new SharpFontWrapper.Factory();

            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            colorStyle = fontFactory.CreateColor(SharpDX.Color.Green);

            textFormat = new SharpDX.DirectWrite.TextFormat(fontWrapper.DWriteFactory, "Consolas", 32.0f);
            textFormat.TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center;
            textFormat.ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near;



            textLayout = new SharpDX.DirectWrite.TextLayout(fontWrapper.DWriteFactory,
                                                            "DirectWrite Text Layout with formatting and color", textFormat, 1000.0f, 1000.0f);

            textLayout.SetFontStyle(SharpDX.DirectWrite.FontStyle.Italic, new SharpDX.DirectWrite.TextRange(0, 11));

            textLayout.SetFontFamilyName("Arial", new SharpDX.DirectWrite.TextRange(24, 4));
            textLayout.SetFontSize(72.0f, new SharpDX.DirectWrite.TextRange(29, 10));

            //Stylistic typeography
            SharpDX.DirectWrite.Typography typoGraphy = new SharpDX.DirectWrite.Typography(fontWrapper.DWriteFactory);
            typoGraphy.AddFontFeature(new SharpDX.DirectWrite.FontFeature(SharpDX.DirectWrite.FontFeatureTag.StylisticSet7, 1));
            textLayout.SetFontFamilyName("Gabriola", new SharpDX.DirectWrite.TextRange(12, 4));
            textLayout.SetTypography(typoGraphy, new SharpDX.DirectWrite.TextRange(12, 4));

            //Note : to pass color, make sure to use native pointer, as in that case we do not need sharpdx/.net to build com wrapper, colorStyle is already one
            textLayout.SetDrawingEffect(colorStyle.NativePointer, new SharpDX.DirectWrite.TextRange(44, 5));

            RenderLoop.Run(renderForm, () =>
            {
                float t = (float)watch.Elapsed.TotalMilliseconds;
                float x = ((float)Math.Sin(t * 0.002f) * 100.0f) + (renderForm.Width * 0.5f);

                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);
                deviceContext.ClearRenderTargetView(renderView, Color.Black);

                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center;

                fontWrapper.DrawString(deviceContext, "Hello SharpFontWrapper", 64.0f, new Vector2(x, renderForm.Height * 0.25f), Color.Yellow, flags);

                fontWrapper.DrawString(deviceContext, "This is another text", 64.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.25f + 100.0f), Color.White, flags);

                fontWrapper.DrawTextLayout(deviceContext, textLayout, new Vector2(0, renderForm.Height * 0.25f + 200.0f), Color.White, flags);

                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });

            typoGraphy.Dispose();

            colorStyle.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();

            fontWrapper.Dispose();
            fontFactory.Dispose();

            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - Simple Text");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = new DeviceContext2(device.ImmediateContext.NativePointer);

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }

            //Pixel shader and custom cbuffer
            using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("PixelShader.hlsl", "PS", "ps_5_0", ShaderFlags.OptimizationLevel3))
            {
                customPixelShader = new PixelShader(device, byteCode);
            }

            BufferDescription cbufferDesc = new BufferDescription()
            {
                BindFlags           = BindFlags.ConstantBuffer,
                CpuAccessFlags      = CpuAccessFlags.Write,
                OptionFlags         = ResourceOptionFlags.None,
                SizeInBytes         = 16, //Need to be 16 aligned
                StructureByteStride = 0,
                Usage = ResourceUsage.Dynamic
            };

            cBuffer = new Buffer(device, cbufferDesc);


            fontFactory = new SharpFontWrapper.Factory();
            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            renderStates = fontWrapper.RenderStates;

            RenderLoop.Run(renderForm, () =>
            {
                float t = (float)watch.Elapsed.TotalSeconds;

                deviceContext.ClearRenderTargetView(renderView, Color.Black);
                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);

                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center
                                                   | SharpFontWrapper.TextFlags.StatePrepared; //Make sure this is on,otherwise pixelshader will be reverted to default

                //Custom cbuffer is not overriden, we can set it anywhere
                DataStream ds;
                deviceContext.MapSubresource(cBuffer, MapMode.WriteDiscard, MapFlags.None, out ds);
                ds.Write <float>(-t * 5.0f);
                deviceContext.UnmapSubresource(cBuffer, 0);


                deviceContext.PixelShader.SetConstantBuffer(1, cBuffer);

                //Set default render states
                renderStates.SetStates(deviceContext, 0);

                deviceContext.PixelShader.Set(customPixelShader);

                fontWrapper.DrawString(deviceContext, "SharpFontWrapper", 96.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.5f), Color.White, flags);

                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });



            renderStates.Dispose();
            fontWrapper.Dispose();
            fontFactory.Dispose();

            cBuffer.Dispose();
            customPixelShader.Dispose();
            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
Example #10
0
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - Transformed Text");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = device.ImmediateContext;

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }


            fontFactory = new SharpFontWrapper.Factory();

            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            Matrix view       = Matrix.Translation(0.0f, 0.0f, 2.0f);
            Matrix projection = Matrix.PerspectiveFovLH(1.57f, 1024.0f / 768.0f, 0.01f, 100.0f);


            int objectCount = 128;

            Matrix[] mats = new Matrix[objectCount];

            Random r = new Random();

            for (int i = 0; i < objectCount; i++)
            {
                mats[i] = Matrix.Translation(r.NextVector3(new Vector3(-5.0f), new Vector3(5.0f)));
            }

            RenderLoop.Run(renderForm, () =>
            {
                float t = (float)watch.Elapsed.TotalMilliseconds;

                deviceContext.ClearRenderTargetView(renderView, Color.Black);
                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);

                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center;

                Matrix rotation = Matrix.RotationY(t * 0.0001f);

                for (int i = 0; i < objectCount; i++)
                {
                    //Please note that font wrapper defaults to inverted Y
                    Matrix world = Matrix.Scaling(0.002f, -0.002f, 0.002f);
                    world        = world * mats[i] * rotation;

                    Matrix twvp = world * view * projection;

                    fontWrapper.DrawString(deviceContext, "SharpFontWrapper", "Arial", 64.0f, twvp, null, Color.White, flags);
                }



                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });


            fontWrapper.Dispose();
            fontFactory.Dispose();

            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
Example #11
0
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - View glyph sheets");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = new DeviceContext2(device.ImmediateContext.NativePointer);

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }

            //Vertex/Pixel shaders
            using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("GlyphSheetView.hlsl", "VS", "vs_5_0", ShaderFlags.OptimizationLevel3))
            {
                vsGlyphView = new VertexShader(device, byteCode);
            }
            using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("GlyphSheetView.hlsl", "PS", "ps_5_0", ShaderFlags.OptimizationLevel3))
            {
                psGlyphView = new PixelShader(device, byteCode);
            }

            fontFactory = new SharpFontWrapper.Factory();
            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            renderStates = fontWrapper.RenderStates;

            bool showGlyphMode = false;

            renderForm.KeyDown += (sender, args) =>
            {
                if (args.KeyCode == System.Windows.Forms.Keys.Space)
                {
                    showGlyphMode = !showGlyphMode;
                }
            };

            RenderLoop.Run(renderForm, () =>
            {
                renderForm.Text = string.Format("SharpFontWrapper - Glyph Sheets view - {0} sheets built", fontWrapper.GlyphAtlas.SheetCount);

                float t = (float)watch.Elapsed.TotalSeconds;

                deviceContext.ClearRenderTargetView(renderView, Color.Black);
                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);

                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center;


                if (showGlyphMode)
                {
                    deviceContext.VertexShader.Set(vsGlyphView);
                    deviceContext.GeometryShader.Set(null); //Text uses GS, so it might still be bound, ensure to remove it
                    deviceContext.PixelShader.Set(psGlyphView);

                    deviceContext.PixelShader.SetShaderResource(0, fontWrapper.GlyphAtlas.GetSheet(0).SheetTexture);


                    deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
                    deviceContext.Draw(3, 0);
                }
                else
                {
                    fontWrapper.DrawString(deviceContext, "SharpFontWrapper, space to toggle glyph view", 32.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.5f), Color.White, flags);
                }
                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });



            renderStates.Dispose();
            fontWrapper.Dispose();
            fontFactory.Dispose();

            vsGlyphView.Dispose();
            psGlyphView.Dispose();
            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
Example #12
0
        /// <summary>
        /// deviceを作成します。
        /// </summary>
        /// <param name="control">レンダリング先となるcontrol</param>
        /// <param name="tso_config">設定</param>
        /// <returns>deviceの作成に成功したか</returns>
        public bool InitializeApplication(Control control, TSOConfig tso_config)
        {
            this.tso_config = tso_config;
            SetControl(control);

            control.MouseDown += new MouseEventHandler(form_OnMouseDown);
            control.MouseMove += new MouseEventHandler(form_OnMouseMove);

            {
            device = new Device(DriverType.Hardware, DeviceCreationFlags.None);

            var desc = new SharpDX.DXGI.SwapChainDescription()
            {
                BufferCount = 1,
                Usage = SharpDX.DXGI.Usage.RenderTargetOutput,
                OutputHandle = control.Handle,
                IsWindowed = true,
                ModeDescription = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                SampleDescription = DetectSampleDescription(device, SharpDX.DXGI.Format.D32_Float),
                Flags = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch,
                SwapEffect = SharpDX.DXGI.SwapEffect.Discard
            };
            dxgi_factory = new SharpDX.DXGI.Factory();
            swap_chain = new SharpDX.DXGI.SwapChain(dxgi_factory, device, desc);
            }

            ctx = device.ImmediateContext;

            Stopwatch sw = new Stopwatch();
            sw.Start();

            string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin");
            if (! File.Exists(effect_file))
            {
            Console.WriteLine("File not found: " + effect_file);
            return false;
            }
            try
            {
            var shader_bytecode = ShaderBytecode.FromFile(effect_file);
            effect = new Effect(device, shader_bytecode);
            }
            catch (SharpDX.CompilationException e)
            {
            Console.WriteLine(e.Message + ": " + effect_file);
            return false;
            }

            sw.Stop();
            Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed);

            string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt");
            if (! File.Exists(techmap_file))
            {
            Console.WriteLine("File not found: " + techmap_file);
            return false;
            }
            techmap.Load(techmap_file);

            World_variable = effect.GetVariableBySemantic("World").AsMatrix();
            WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix();
            WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix();
            /* for HUD */
            Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix();

            LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix();
            LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector();
            UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector();

            cb_variable = effect.GetConstantBufferByName("cb");

            ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource();
            ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource();

            figures.Camera = camera;
            figures.TSOFileOpen += delegate(TSOFile tso)
            {
            tso.Open(device, effect);
            techmap.AssignTechniqueIndices(tso);
            };

            // Define an input layout to be passed to the vertex shader.
            var technique = effect.GetTechniqueByIndex(0);
            il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie);

            // Setup the immediate context to use the shaders and model we defined.
            ctx.InputAssembler.InputLayout = il;

            camera.Update();

            DefineBlendState();
            DefineDepthStencilState();
            DefineRasterizerState();

            return true;
        }
Example #13
0
        /// <summary>
        /// deviceを作成します。
        /// </summary>
        /// <param name="control">レンダリング先となるcontrol</param>
        /// <param name="tso_config">設定</param>
        /// <returns>deviceの作成に成功したか</returns>
        public bool InitializeApplication(Control control, TSOConfig tso_config)
        {
            this.tso_config = tso_config;
            SetControl(control);

            control.MouseDown += new MouseEventHandler(form_OnMouseDown);
            control.MouseMove += new MouseEventHandler(form_OnMouseMove);

            var desc = new SharpDX.DXGI.SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                OutputHandle      = control.Handle,
                IsWindowed        = true,
                ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.B8G8R8A8_UNorm),
                SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                Flags             = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SharpDX.DXGI.SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swap_chain);

            //DetectSampleDescription(device, SharpDX.DXGI.Format.D32_Float);

            ctx = device.ImmediateContext;

            Stopwatch sw = new Stopwatch();

            sw.Start();

            string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin");

            if (!File.Exists(effect_file))
            {
                Console.WriteLine("File not found: " + effect_file);
                return(false);
            }
            try
            {
                var shader_bytecode = ShaderBytecode.FromFile(effect_file);
                effect = new Effect(device, shader_bytecode);
            }
            catch (SharpDX.CompilationException e)
            {
                Console.WriteLine(e.Message + ": " + effect_file);
                return(false);
            }

            sw.Stop();
            Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed);

            string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt");

            if (!File.Exists(techmap_file))
            {
                Console.WriteLine("File not found: " + techmap_file);
                return(false);
            }
            techmap.Load(techmap_file);

            World_variable               = effect.GetVariableBySemantic("World").AsMatrix();
            WorldView_variable           = effect.GetVariableBySemantic("WorldView").AsMatrix();
            WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix();
            /* for normal in view */
            View_variable = effect.GetVariableBySemantic("View").AsMatrix();
            /* for HUD */
            Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix();

            LocalBoneMats_variable  = effect.GetVariableByName("LocalBoneMats").AsMatrix();
            LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector();
            UVSCR_variable          = effect.GetVariableByName("UVSCR").AsVector();

            cb_variable = effect.GetConstantBufferByName("cb");

            ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource();
            ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource();

            figures.Camera       = camera;
            figures.TSOFileOpen += delegate(TSOFile tso)
            {
                tso.Open(device, effect);
                techmap.AssignTechniqueIndices(tso);
            };

            // Define an input layout to be passed to the vertex shader.
            var technique = effect.GetTechniqueByIndex(0);

            il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie);

            // Setup the immediate context to use the shaders and model we defined.
            ctx.InputAssembler.InputLayout = il;

            camera.Update();

            DefineBlendState();
            DefineDepthStencilState();
            DefineRasterizerState();

            return(true);
        }
Example #14
0
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - Simple Text");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = new DeviceContext2(device.ImmediateContext.NativePointer);

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }


            fontFactory = new SharpFontWrapper.Factory();
            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            RenderLoop.Run(renderForm, () =>
            {
                float t = (float)watch.Elapsed.TotalMilliseconds;

                deviceContext.ClearRenderTargetView(renderView, Color.Black);
                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);


                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center;

                RectangleF layoutRect = new RectangleF(renderForm.Width * 0.5f, renderForm.Height * 0.5f, 0, 0);

                var rect = fontWrapper.MeasureString("Hello SharpFontWrapper", "Arial", 64.0f, layoutRect, flags);

                SharpDX.Rectangle r = new Rectangle((int)rect.Left, (int)rect.Top, (int)rect.Right - (int)rect.Left, (int)rect.Bottom - (int)rect.Top);

                deviceContext.ClearView(renderView, Color.Blue, new SharpDX.Mathematics.Interop.RawRectangle[] { r }, 1);


                fontWrapper.DrawString(deviceContext, "Hello SharpFontWrapper", 64.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.5f), Color.White, flags);

                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });



            fontWrapper.Dispose();
            fontFactory.Dispose();

            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
Example #15
0
        public Pipeline(int frameCount, System.Drawing.Size size, System.IntPtr windowHandle)
        {
            // Fields
            FrameCount = frameCount;
            Size       = size;

            // Pipeline
            var d3d12Device = new SharpDX.Direct3D12.Device(null, SharpDX.Direct3D.FeatureLevel.Level_12_1);

            var queueDescription     = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct);
            var commandQueue         = d3d12Device.CreateCommandQueue(queueDescription);
            var swapChainDescription = new SharpDX.DXGI.SwapChainDescription()
            {
                BufferCount       = frameCount,
                ModeDescription   = new SharpDX.DXGI.ModeDescription(Size.Width, Size.Height, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                SwapEffect        = SharpDX.DXGI.SwapEffect.FlipDiscard,
                OutputHandle      = windowHandle,
                Flags             = SharpDX.DXGI.SwapChainFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                IsWindowed        = true
            };
            var rtvHeapDescription = new SharpDX.Direct3D12.DescriptorHeapDescription()
            {
                DescriptorCount = frameCount,
                Flags           = SharpDX.Direct3D12.DescriptorHeapFlags.None,
                Type            = SharpDX.Direct3D12.DescriptorHeapType.RenderTargetView
            };
            var renderTargetViewHeap = d3d12Device.CreateDescriptorHeap(rtvHeapDescription);
            var rtvHandle            = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            var dxgiFactory          = new SharpDX.DXGI.Factory4();
            var swapChain            = new SharpDX.DXGI.SwapChain(dxgiFactory, commandQueue, swapChainDescription);
            var swapChain3           = swapChain.QueryInterface <SharpDX.DXGI.SwapChain3>();
            var frameIndex           = swapChain3.CurrentBackBufferIndex;
            var renderTargets        = new SharpDX.Direct3D12.Resource[frameCount];
            var commandAllocators    = new SharpDX.Direct3D12.CommandAllocator[frameCount];
            var rtvDescriptorSize    = d3d12Device.GetDescriptorHandleIncrementSize(SharpDX.Direct3D12.DescriptorHeapType.RenderTargetView);

            var d2d1Factory        = new SharpDX.Direct2D1.Factory();
            var d3d11Device        = SharpDX.Direct3D11.Device.CreateFromDirect3D12(d3d12Device, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, commandQueue);
            var d3d11On12Device    = d3d11Device.QueryInterface <SharpDX.Direct3D11.Device11On12>();
            var wrappedBackBuffers = new SharpDX.Direct3D11.Resource[frameCount];
            var d2dRenderTargets   = new SharpDX.Direct2D1.RenderTarget[frameCount];

            for (int i = 0; i < frameCount; i++)
            {
                renderTargets[i]     = swapChain3.GetBackBuffer <SharpDX.Direct3D12.Resource>(i);
                commandAllocators[i] = d3d12Device.CreateCommandAllocator(SharpDX.Direct3D12.CommandListType.Direct);
                d3d12Device.CreateRenderTargetView(renderTargets[i], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;

                var format = new SharpDX.Direct3D11.D3D11ResourceFlags()
                {
                    BindFlags      = (int)SharpDX.Direct3D11.BindFlags.RenderTarget,
                    CPUAccessFlags = (int)SharpDX.Direct3D11.CpuAccessFlags.None
                };
                d3d11On12Device.CreateWrappedResource(renderTargets[i], format, (int)SharpDX.Direct3D12.ResourceStates.Present, (int)SharpDX.Direct3D12.ResourceStates.RenderTarget, typeof(SharpDX.Direct3D11.Resource).GUID, out wrappedBackBuffers[i]);
                var surface = wrappedBackBuffers[i].QueryInterface <SharpDX.DXGI.Surface>();
                d2dRenderTargets[i] = new SharpDX.Direct2D1.RenderTarget(d2d1Factory, surface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
            }

            // Assets
            var fenceEvent  = new System.Threading.AutoResetEvent(false);
            var fence       = d3d12Device.CreateFence(0, SharpDX.Direct3D12.FenceFlags.None);
            var fenceValues = new int[frameCount];

            for (int i = 0; i < frameCount; i++)
            {
                fenceValues[i] = 1;
            }

            var commandList = d3d12Device.CreateCommandList(SharpDX.Direct3D12.CommandListType.Direct, commandAllocators[frameIndex], pipelineState);

            commandList.Close();

            D3D12Device          = d3d12Device;
            CommandAllocators    = commandAllocators;
            RenderTargetViewHeap = renderTargetViewHeap;
            RenderTargets        = renderTargets;
            CommandQueue         = commandQueue;
            SwapChain3           = swapChain3;
            Fence              = fence;
            FenceEvent         = fenceEvent;
            D3D11Device        = d3d11Device;
            D3D11On12Device    = d3d11On12Device;
            WrappedBackBuffers = wrappedBackBuffers;
            D2DRenderTargets   = d2dRenderTargets;
            CommandList        = commandList;
            FenceValues        = fenceValues;
            RtvDescriptorSize  = rtvDescriptorSize;
            FrameIndex         = frameIndex;
        }