public void Initialize()
 {
     Viewport = new ViewportF()
     {
         Width = Form.ClientSize.Width,
         Height = Form.ClientSize.Height,
         MaxDepth = 1.0f
     };
     ScissorRect = new Rectangle()
     {
         Right = Form.ClientSize.Width,
         Bottom = Form.ClientSize.Height
     };
     EnableDebug();
     Device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
     GraphicCommandQueue = Device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));
     SwapChain = DxHelper.CreateSwapchain(Form, GraphicCommandQueue, Config);
     FrameIndex = SwapChain.CurrentBackBufferIndex;
     Resource[] tempRenderTargets;
     RenderTargetViewHeap = DxHelper.CreateRenderTargetViewHeap(Config, SwapChain, out tempRenderTargets);
     RenderTargets = tempRenderTargets;
     RootSignature = DxHelper.CreateRootSignature();
     Fence = Device.CreateFence(0, FenceFlags.None);
     FenceValue = 1;
     FenceEvent = new AutoResetEvent(false);
 }
        /// <summary>
        /// Setup resources for rendering
        /// </summary>
        private void LoadAssets()
        {
            // Create the descriptor heap for the render target view
            descriptorHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type            = DescriptorHeapType.RenderTargetView,
                DescriptorCount = 1
            });

            // Create the main command list
            commandList = device.CreateCommandList(CommandListType.Direct, commandListAllocator, null);

            // Get the backbuffer and creates the render target view
            renderTarget = swapChain.GetBackBuffer <Resource>(0);
            device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart);

            // Create the viewport
            viewPort = new ViewportF(0, 0, width, height);

            // Create the scissor
            scissorRectangle = new Rectangle(0, 0, width, height);

            // Create a fence to wait for next frame
            fence        = device.CreateFence(0, FenceFlags.None);
            currentFence = 1;

            // Close command list
            commandList.Close();

            // Create an event handle use for VTBL
            eventHandle = new AutoResetEvent(false);

            // Wait the command list to complete
            WaitForPrevFrame();
        }
示例#3
0
        /// <summary>
        /// Resizes the current presenter, by resizing the back buffer and the depth stencil buffer.
        /// </summary>
        /// <param name="width">New backbuffer width</param>
        /// <param name="height">New backbuffer height</param>
        /// <param name="format">Backbuffer display format.</param>
        /// <param name="refreshRate"></param>
        /// <returns><c>true</c> if the presenter was resized, <c>false</c> otherwise</returns>
        public virtual bool Resize(int width, int height, Format format, Rational?refreshRate = null)
        {
            if (Description.BackBufferWidth == width && Description.BackBufferHeight == height &&
                Description.BackBufferFormat == format)
            {
                return(false);
            }

            if (DepthStencilBuffer != null)
            {
                RemoveAndDispose(ref depthStencilBuffer);
            }

            Description.BackBufferWidth  = width;
            Description.BackBufferHeight = height;
            Description.BackBufferFormat = format;
            if (refreshRate.HasValue)
            {
                Description.RefreshRate = refreshRate.Value;
            }

            DefaultViewport = new ViewportF(0, 0, Description.BackBufferWidth, Description.BackBufferHeight);

            CreateDepthStencilBuffer();
            return(true);
        }
示例#4
0
 /// <summary>
 /// Binds a single viewport to the rasterizer stage.
 /// </summary>
 /// <param name="viewport">The viewport.</param>
 /// <remarks>
 /// <p></p><p>All viewports must be set atomically as one operation. Any viewports not defined by the call are disabled.</p><p>Which viewport to use is determined by the SV_ViewportArrayIndex semantic output by a geometry shader; if a geometry shader does not specify the semantic, Direct3D will use the first viewport in the array.</p>
 /// </remarks>
 /// <msdn-id>ff476480</msdn-id>
 /// <unmanaged>void ID3D11DeviceContext::RSSetViewports([In] unsigned int NumViewports,[In, Buffer, Optional] const void* pViewports)</unmanaged>
 /// <unmanaged-short>ID3D11DeviceContext::RSSetViewports</unmanaged-short>
 public void SetViewport(ViewportF viewport)
 {
     unsafe
     {
         SetViewports(1, new IntPtr(&viewport));
     }
 }
示例#5
0
        private void InitRenderTarget(IntPtr surface)
        {
            IntPtr sharedHandle;

            var c = new SharpDX.ComObject(surface);
            var D3DImageResource = c.QueryInterface <SharpDX.DXGI.Resource>();


            sharedHandle = D3DImageResource.SharedHandle;

            var tempResource    = D3DDevice.OpenSharedResource <SharpDX.Direct3D11.Resource>(sharedHandle);
            var d3DImageTexture = tempResource.QueryInterface <Texture2D>();

            RenderTarget = new RenderTargetView(D3DDevice, d3DImageTexture);

            var vp = new ViewportF {
                Width    = (float)host.ActualWidth,
                Height   = (float)host.ActualHeight,
                MinDepth = 0.0f,
                MaxDepth = 1.0f
            };

            D3DContext.Rasterizer.SetViewport(vp);
            D3DContext.OutputMerger.SetRenderTargets(RenderTarget);

            ////Cleanup
            tempResource.Dispose();
            d3DImageTexture.Dispose();
        }
示例#6
0
 public void Initialize()
 {
     Viewport = new ViewportF()
     {
         Width    = Form.ClientSize.Width,
         Height   = Form.ClientSize.Height,
         MaxDepth = 1.0f
     };
     ScissorRect = new Rectangle()
     {
         Right  = Form.ClientSize.Width,
         Bottom = Form.ClientSize.Height
     };
     EnableDebug();
     Device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_11_0);
     GraphicCommandQueue = Device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));
     SwapChain           = DxHelper.CreateSwapchain(Form, GraphicCommandQueue, Config);
     FrameIndex          = SwapChain.CurrentBackBufferIndex;
     Resource[] tempRenderTargets;
     RenderTargetViewHeap = DxHelper.CreateRenderTargetViewHeap(Config, SwapChain, out tempRenderTargets);
     RenderTargets        = tempRenderTargets;
     RootSignature        = DxHelper.CreateRootSignature();
     Fence      = Device.CreateFence(0, FenceFlags.None);
     FenceValue = 1;
     FenceEvent = new AutoResetEvent(false);
 }
            private void RenderRelativeScreenSpaced(RenderContext context, DeviceContextProxy deviceContext)
            {
                IsRightHand = !context.Camera.CreateLeftHandSystem;
                var viewportSize = Size * SizeScale * context.DpiScale;
                var globalTrans  = context.GlobalTransform;

                UpdateParameters(context, (float)context.ActualWidth, (float)context.ActualHeight);
                globalTrans.View           = CreateViewMatrix(context, out globalTrans.EyePos);
                globalTrans.Projection     = projectionMatrix;
                globalTrans.ViewProjection = globalTrans.View * globalTrans.Projection;
                globalTrans.Viewport       = new Vector4(viewportSize, viewportSize, 1 / viewportSize, 1 / viewportSize);
                GlobalTransform            = globalTrans;
                var offX = 0;
                var offY = 0;

                offX = (int)(Width / 2 * (1 + RelativeScreenLocationX) - viewportSize / 2);
                offY = (int)(Height / 2 * (1 - RelativeScreenLocationY) - viewportSize / 2);
                offX = Math.Max(0, Math.Min(offX, (int)(Width - viewportSize)));
                offY = Math.Max(0, Math.Min(offY, (int)(Height - viewportSize)));
                var viewport = new ViewportF(offX, offY, viewportSize, viewportSize);

                context.Set(ref globalTrans, ref viewport);
                context.UpdatePerFrameData(true, false, deviceContext);
                deviceContext.SetViewport(ref viewport);
                deviceContext.SetScissorRectangle(offX, offY, (int)viewportSize + offX, (int)viewportSize + offY);
            }
示例#8
0
        //Resize, place the components depending of the viewport size
        protected override void UpdateLayout(ViewportF viewport, Texture2DDescription newBackBufferDescr)
        {
            base.UpdateLayout(viewport, newBackBufferDescr);

            if (Updatable)
            {
                int _headerHeight = (int)(viewport.Height * 0.1f);
                int btPlacementY  = _headerHeight;

                btPlacementY        += 20;
                _btGraphic.Bounds    = new UniRectangle(5, btPlacementY, _leftMenuPanel.Bounds.Size.X.Offset - 10, 50);
                btPlacementY        += 50;
                _btSound.Bounds      = new UniRectangle(5, btPlacementY, _leftMenuPanel.Bounds.Size.X.Offset - 10, 50);
                btPlacementY        += 50;
                _btCoreEngine.Bounds = new UniRectangle(5, btPlacementY, _leftMenuPanel.Bounds.Size.X.Offset - 10, 50);
                btPlacementY        += 50;
                _btKeyBinding.Bounds = new UniRectangle(5, btPlacementY, _leftMenuPanel.Bounds.Size.X.Offset - 10, 50);

                _settingsStateLabel.Bounds = new UniRectangle(10, new UniScalar(1f, -75.0f), 0, 0);
                if (_graphSettingsPanel != null)
                {
                    _graphSettingsPanel.Resize();
                }
                if (_coreEngineSetingsPanel != null)
                {
                    _coreEngineSetingsPanel.Resize();
                }
            }
        }
示例#9
0
        public override bool Resize(int width, int height, Format format, Rational?refreshRate = null)
        {
            if (!base.Resize(width, height, format, refreshRate))
            {
                return(false);
            }

            RemoveAndDispose(ref backBuffer);

#if DIRECTX11_2 && (WIN8METRO || WINDOWS_UWP)
            var swapChainPanel = Description.DeviceWindowHandle as SwapChainPanel;
            if (swapChainPanel != null && swapChain2 != null)
            {
                swapChain2.MatrixTransform = Matrix3x2.Scaling(1f / swapChainPanel.CompositionScaleX, 1f / swapChainPanel.CompositionScaleY);
            }
#endif

            swapChain.ResizeBuffers(bufferCount, width, height, format, Description.Flags);

            // Recreate the back buffer
            backBuffer = ToDispose(RenderTarget2D.New(GraphicsDevice, swapChain.GetBackBuffer <Direct3D11.Texture2D>(0)));

            // Reinit the Viewport
            DefaultViewport = new ViewportF(0, 0, backBuffer.Width, backBuffer.Height);

            return(true);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            for (int i = 0; i < this._textures.Length; ++i)
            {
                _textures[i].RTView.Dispose();
                _textures[i].SRView.Dispose();

                if (_textures[i].DepthBuffer != null)
                {
                    _textures[i].DepthBuffer.Dispose();
                }

                if (_textures[i].DepthStencilView != null)
                {
                    _textures[i].DepthStencilView.Dispose();
                }
            }

            _textures     = null;
            _currentIndex = -1;

            _size     = new Sizei();
            _viewport = new ViewportF();

            _ovr                 = null;
            _sessionPtr          = IntPtr.Zero;
            _textureSwapChainPtr = IntPtr.Zero;
        }
示例#11
0
        public override bool BeginDraw()
        {
            if (GraphicsDevice != null && Window.Visible)
            {
                savedPresenter = GraphicsDevice.Presenter;
                savedViewport  = GraphicsDevice.Viewport;

                CreateOrUpdatePresenter();

                if (isBackBufferToResize || windowUserResized)
                {
                    PixelFormat resizeFormat;
                    var         size = GetRequestedSize(out resizeFormat);
                    Presenter.Resize(size.Width, size.Height, resizeFormat);

                    isBackBufferToResize = false;
                    windowUserResized    = false;
                }

                GraphicsDevice.Presenter = Presenter;
                GraphicsDevice.SetViewport(Presenter.DefaultViewport);
                GraphicsDevice.SetRenderTargets(Presenter.DepthStencilBuffer, Presenter.BackBuffer);

                beginDrawOk = true;
                return(true);
            }

            beginDrawOk = false;
            return(false);
        }
示例#12
0
 private void UpdateLayout(ViewportF viewport, Texture2DDescription newBackBufferDescr)
 {
     _helloLabel.Bounds    = new UniRectangle((_engine.ViewPort.Width - 212) / 2 - 250, _headerHeight + 90, 50, 40);
     _nicknameLabel.Bounds = new UniRectangle((_engine.ViewPort.Width - 212) / 2 - 195, _headerHeight + 90, 200, 40);
     _mainMenuLabel.Bounds = new UniRectangle((_engine.ViewPort.Width - 212) / 2 + 65, _headerHeight + 96, 85, 50);
     _buttonsGroup.Bounds  = new UniRectangle((_engine.ViewPort.Width - 212) / 2, _headerHeight + 137, 212, 400);
 }
示例#13
0
        public void OnWindowResize(DXManager dxman)
        {
            DisposeBuffers();

            var device = dxman.device;



            int uw = Width = dxman.backbuffer.Description.Width * SSAASampleCount;
            int uh = Height = dxman.backbuffer.Description.Height * SSAASampleCount;

            Viewport          = new ViewportF();
            Viewport.Width    = (float)uw;
            Viewport.Height   = (float)uh;
            Viewport.MinDepth = 0.0f;
            Viewport.MaxDepth = 1.0f;
            Viewport.X        = 0.0f;
            Viewport.Y        = 0.0f;


            GBuffers             = new GpuMultiTexture(device, uw, uh, 4, Format.R8G8B8A8_UNorm, true, Format.D32_Float, MSAASampleCount);
            WindowSizeVramUsage += GBuffers.VramUsage;

            SceneColour          = new GpuTexture(device, uw, uh, Format.R32G32B32A32_Float, 1, 0, true, Format.D32_Float);
            WindowSizeVramUsage += SceneColour.VramUsage;
        }
            private void RenderAbsolutePositionPerspective(RenderContext context, DeviceContextProxy deviceContext)
            {
                var globalTrans = context.GlobalTransform;

                UpdateParameters(context, (float)context.ActualWidth, (float)context.ActualHeight);
                var distance = Size / 2 / SizeScale;
                var viewInv  = globalTrans.View.PsudoInvert();
                //Determine new camera position. So the size of the object keeps the same. Decouple it from global zooming
                var pos    = Vector3.Normalize(absolutePosition - globalTrans.EyePos);
                var newPos = absolutePosition - pos * distance;

                newPos            -= absolutePosition; // Need to do additional translation, since translation is not in model matrix.
                viewInv.M41        = newPos.X;
                viewInv.M42        = newPos.Y;
                viewInv.M43        = newPos.Z;
                globalTrans.View   = viewInv.PsudoInvert();
                globalTrans.EyePos = newPos;
                // Create new projection matrix with proper near/far field.
                globalTrans.Projection     = projectionMatrix;
                globalTrans.ViewProjection = globalTrans.View * globalTrans.Projection;
                GlobalTransform            = globalTrans;
                var viewport = new ViewportF(0, 0, context.ActualWidth, context.ActualHeight);

                context.Set(ref globalTrans, ref viewport);
                context.UpdatePerFrameData(true, false, deviceContext);

                deviceContext.SetViewport(ref viewport);
                deviceContext.SetScissorRectangle(0, 0, (int)context.ActualWidth, (int)context.ActualHeight);
            }
示例#15
0
 /// <summary>
 /// Converts a SharpDX Viewport to a library-independent viewport.
 /// </summary>
 /// <param name="vp">The SharpDX viewport</param>
 /// <returns>The library-independent viewport</returns>
 public static STRViewport ToSTRViewport(this ViewportF vp)
 {
     return(new STRViewport()
     {
         Width = vp.Width, Height = vp.Height
     });
 }
示例#16
0
        public void Push(ViewportF vp, Rectangle scissor, IDxDepthStencil dsv, bool rodsv = false, params IDxRenderTarget[] rts)
        {
            RenderTargetStackElement elem = new RenderTargetStackElement(vp, scissor, dsv, rodsv, rts);

            stack.Push(elem);
            this.Apply();
        }
        public void Render(string path)
        {
            if (GetContext == null)
            {
                return;
            }

            CurrentState = RenderState.CubeMap;
            SetViewPoint(Vector3.Zero);
            OutputResolution = OutputMapSize;
            Viewport         = new Viewport(0, 0, OutputResolution, OutputResolution);
            CreateRenderTargetsFromMap(ConvertedCubeMap, false);
            UpdateThreaded(path);

            CurrentState     = RenderState.IrradianceMap;
            Viewport         = new Viewport(0, 0, IrradianceSize, IrradianceSize);
            OutputResolution = IrradianceSize;
            CreateRenderTargetsFromMap(IrradianceCubeMap, false);
            UpdateThreaded(path);

            CurrentState     = RenderState.PreFilteredMap;
            Viewport         = new Viewport(0, 0, PreFilteredSize, PreFilteredSize);
            OutputResolution = PreFilteredSize;
            CreateRenderTargetsFromMap(PreFilteredCubeMap, true);
            UpdateThreaded(path);
        }
示例#18
0
        public RenderTarget(string name, RenderTargetView rt, DepthStencilView ds, ViewportF v) : this()
        {
            renderTargetView = rt;
            depthStencil     = ds;
            viewport         = v;

            Name = name;
        }
示例#19
0
 private void UpdateLayout(ViewportF viewport, Texture2DDescription newBackBufferDescr)
 {
     _serversLabel.Bounds           = new UniRectangle(200, _headerHeight + 107, 200, 20);
     _serverList.Bounds             = new UniRectangle(200, _headerHeight + 137, 400, _engine.ViewPort.Height - _headerHeight - 200);
     _connectButton.Bounds          = new UniRectangle(_engine.ViewPort.Width - 300, _engine.ViewPort.Height - 140, 212, 40);
     _backButton.Bounds             = new UniRectangle(_engine.ViewPort.Width - 300, _engine.ViewPort.Height - 100, 212, 40);
     _serverDescriptionLabel.Bounds = new UniRectangle(620, _headerHeight + 137, 300, 100);
 }
示例#20
0
            /// <summary>
            /// Runs the blur procedure
            /// </summary>
            /// <param name="context">The context.</param>
            /// <param name="deviceContext">The device context.</param>
            /// <param name="source">The source.</param>
            /// <param name="depth">The depth.</param>
            /// <param name="sourceViewport"></param>
            /// <param name="modelStruct"></param>
            public virtual void Run(RenderContext context, DeviceContextProxy deviceContext,
                                    ShaderResourceViewProxy source, ref ViewportF sourceViewport, BlurDepth depth, ref BorderEffectStruct modelStruct)
            {
                deviceContext.SetSampler(PixelShader.Type, samplerSlot, sampler);
                if ((depth & BlurDepth.One) != 0)
                {
                    using (var target1 = context.GetOffScreenRT(OffScreenTextureSize.Half,
                                                                global::SharpDX.DXGI.Format.R8G8B8A8_UNorm, out var width, out var height))
                    {
                        modelStruct.ViewportScale = (int)OffScreenTextureSize.Half;
                        modelCB.Upload(deviceContext, ref modelStruct);
                        //Full -> Half Vertical
                        deviceContext.SetRenderTarget(target1);
                        deviceContext.SetViewport(0, 0, width, height);
                        deviceContext.SetScissorRectangle(0, 0, width, height);
                        screenBlurPassVertical.BindShader(deviceContext);
                        screenBlurPassVertical.BindStates(deviceContext, StateType.All);
                        screenBlurPassVertical.PixelShader.BindTexture(deviceContext, textureSlot, source);
                        deviceContext.Draw(4, 0);

                        if ((depth & BlurDepth.Two) != 0)
                        {
                            using (var target2 = context.GetOffScreenRT(OffScreenTextureSize.Quarter,
                                                                        global::SharpDX.DXGI.Format.R8G8B8A8_UNorm, out var width2, out var height2))
                            {
                                // Half to Quater Vertical
                                modelStruct.ViewportScale = (int)OffScreenTextureSize.Quarter;
                                modelCB.Upload(deviceContext, ref modelStruct);
                                deviceContext.SetRenderTarget(target2);
                                deviceContext.SetViewport(0, 0, width2, height2);
                                deviceContext.SetScissorRectangle(0, 0, width2, height2);
                                screenBlurPassVertical.BindShader(deviceContext);
                                screenBlurPassVertical.PixelShader.BindTexture(deviceContext, textureSlot, target1);
                                deviceContext.Draw(4, 0);

                                // Quater to Half Horizontal
                                modelStruct.ViewportScale = (int)OffScreenTextureSize.Half;
                                modelCB.Upload(deviceContext, ref modelStruct);
                                deviceContext.SetRenderTarget(target1);
                                deviceContext.SetViewport(0, 0, width, height);
                                deviceContext.SetScissorRectangle(0, 0, width, height);
                                screenBlurPassHorizontal.BindShader(deviceContext);
                                screenBlurPassHorizontal.PixelShader.BindTexture(deviceContext, textureSlot, target2);
                                deviceContext.Draw(4, 0);
                            }
                        }
                        // Half to Full Horizontal
                        modelStruct.ViewportScale = (int)OffScreenTextureSize.Full;
                        modelCB.Upload(deviceContext, ref modelStruct);
                        deviceContext.SetRenderTarget(source);
                        deviceContext.SetViewport(ref sourceViewport);
                        deviceContext.SetScissorRectangle(ref sourceViewport);
                        screenBlurPassHorizontal.BindShader(deviceContext);
                        screenBlurPassHorizontal.PixelShader.BindTexture(deviceContext, textureSlot, target1);
                        deviceContext.Draw(4, 0);
                    }
                }
            }
示例#21
0
        /// <summary>
        /// Binds a single viewport to the rasterizer stage.
        /// </summary>
        /// <param name="x">The x coord of the viewport.</param>
        /// <param name="y">The x coord of the viewport.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="minZ">The min Z.</param>
        /// <param name="maxZ">The max Z.</param>
        /// <remarks>
        /// <p></p><p>All viewports must be set atomically as one operation. Any viewports not defined by the call are disabled.</p><p>Which viewport to use is determined by the SV_ViewportArrayIndex semantic output by a geometry shader; if a geometry shader does not specify the semantic, Direct3D will use the first viewport in the array.</p>
        /// </remarks>
        /// <msdn-id>ff476480</msdn-id>
        /// <unmanaged>void ID3D11DeviceContext::RSSetViewports([In] unsigned int NumViewports,[In, Buffer, Optional] const void* pViewports)</unmanaged>
        /// <unmanaged-short>ID3D11DeviceContext::RSSetViewports</unmanaged-short>
        public void SetViewport(float x, float y, float width, float height, float minZ = 0.0f, float maxZ = 1.0f)
        {
            var viewport = new ViewportF(x, y, width, height, minZ, maxZ);

            unsafe
            {
                SetViewports(1, new IntPtr(&viewport));
            }
        }
示例#22
0
        private void engine_ScreenSize_Updated(ViewportF viewport, Texture2DDescription newBackBuffer)
        {
            CreateRenderTargets(newBackBuffer);

            if (OnStaggingBackBufferChanged != null)
            {
                OnStaggingBackBufferChanged(_renderTextureView);
            }
        }
示例#23
0
        /// <summary>
        /// Gets the screen coordinates from the specified 3D point
        /// </summary>
        /// <param name="point">3D point</param>
        /// <param name="viewPort">View port</param>
        /// <param name="wvp">World * View * Projection</param>
        /// <param name="isInsideScreen">Returns true if the resulting point is inside the screen</param>
        /// <returns>Returns the resulting screen coordinates</returns>
        public static Vector2 UnprojectToScreen(Vector3 point, ViewportF viewPort, Matrix wvp, out bool isInsideScreen)
        {
            isInsideScreen = true;

            // Go to projection space
            Vector3.Transform(ref point, ref wvp, out Vector4 projected);

            // Clip
            //
            //  -Wp < Xp <= Wp
            //  -Wp < Yp <= Wp
            //  0 < Zp <= Wp
            //
            if (projected.X < -projected.W)
            {
                projected.X    = -projected.W;
                isInsideScreen = false;
            }
            if (projected.X > projected.W)
            {
                projected.X    = projected.W;
                isInsideScreen = false;
            }
            if (projected.Y < -projected.W)
            {
                projected.Y    = -projected.W;
                isInsideScreen = false;
            }
            if (projected.Y > projected.W)
            {
                projected.Y    = projected.W;
                isInsideScreen = false;
            }
            if (projected.Z < 0)
            {
                projected.Z    = 0;
                isInsideScreen = false;
            }
            if (projected.Z > projected.W)
            {
                projected.Z    = projected.W;
                isInsideScreen = false;
            }

            // Divide by w, to move from homogeneous coordinates to 3D coordinates again
            projected.X = projected.X / projected.W;
            projected.Y = projected.Y / projected.W;
            projected.Z = projected.Z / projected.W;

            // Perform the viewport scaling, to get the appropiate coordinates inside the viewport
            projected.X = ((float)(((projected.X + 1.0) * 0.5) * viewPort.Width)) + viewPort.X;
            projected.Y = ((float)(((1.0 - projected.Y) * 0.5) * viewPort.Height)) + viewPort.Y;
            projected.Z = (projected.Z * (viewPort.MaxDepth - viewPort.MinDepth)) + viewPort.MinDepth;

            return(projected.XY());
        }
示例#24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsPresenter" /> class.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="presentationParameters"> </param>
        protected GraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters)
        {
            GraphicsDevice = device.MainDevice;
            Description    = presentationParameters.Clone();

            DefaultViewport = new ViewportF(0, 0, Description.BackBufferWidth, Description.BackBufferHeight);

            // Creates a default DepthStencilBuffer.
            CreateDepthStencilBuffer();
        }
示例#25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsPresenter" /> class.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="presentationParameters"> </param>
        protected GraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters)
        {
            GraphicsDevice = device.MainDevice;
            Description = presentationParameters.Clone();

            DefaultViewport = new ViewportF(0, 0, Description.BackBufferWidth, Description.BackBufferHeight);

            // Creates a default DepthStencilBuffer.
            CreateDepthStencilBuffer();
        }
示例#26
0
 private void UpdateLayout(ViewportF viewport, Texture2DDescription newBackBufferDescr)
 {
     if (Updatable)
     {
         _creditsLabel.Bounds = new UniRectangle((_engine.ViewPort.Width - 200) / 2,
                                                 (_engine.ViewPort.Height - 200) / 2, 600, 200);
         _backButton.Bounds = new UniRectangle(_engine.ViewPort.Width - 200, _engine.ViewPort.Height - 60, 120,
                                               24);
     }
     //_buttonsGroup.Bounds = new UniRectangle(_engine.ViewPort.Width - 200, _engine.ViewPort.Height - 200, 200, 200);
 }
示例#27
0
        public void OnWindowResize(DXManager dxman)
        {
            DisposeBuffers();

            var device = dxman.device;


            int sc = dxman.multisamplecount;
            int sq = dxman.multisamplequality;

            Multisampled = (sc > 1);

            int uw = Width = dxman.backbuffer.Description.Width;
            int uh = Height = dxman.backbuffer.Description.Height;

            Viewport          = new ViewportF();
            Viewport.Width    = (float)uw;
            Viewport.Height   = (float)uh;
            Viewport.MinDepth = 0.0f;
            Viewport.MaxDepth = 1.0f;
            Viewport.X        = 0.0f;
            Viewport.Y        = 0.0f;


            Format f  = Format.R32G32B32A32_Float;
            Format df = Format.D32_Float;


            Primary              = new GpuTexture(device, uw, uh, f, sc, sq, true, df);
            WindowSizeVramUsage += Primary.VramUsage;


            int rc = (int)(Math.Ceiling(uw / 8.0f) * Math.Ceiling(uh / 8.0f));

            Reduction0           = new GpuBuffer <float>(device, 1, rc);
            Reduction1           = new GpuBuffer <float>(device, 1, rc);
            WindowSizeVramUsage += sizeof(float) * rc * 2;

            LumBlendResult       = new GpuBuffer <float>(device, 1, 1);
            WindowSizeVramUsage += sizeof(float); //because 4 bytes matter

            int tw = uw / 8;
            int th = uh / 8;

            rc = tw * th;
            f  = Format.R8G8B8A8_UNorm;

            Bloom0 = new GpuBuffer <Vector4>(device, 1, rc);
            Bloom1 = new GpuBuffer <Vector4>(device, 1, rc);
            WindowSizeVramUsage += /*sizeof(V4F)*/ 16 * rc * 2;

            Bloom = new GpuTexture(device, tw, th, f, 1, 0, false, df);
            WindowSizeVramUsage += Bloom.VramUsage;
        }
示例#28
0
            private void DrawOutline(RenderContext context, DeviceContextProxy deviceContext,
                                     ShaderResourceViewProxy depthStencilBuffer, ShaderResourceViewProxy source)
            {
                var buffer         = context.RenderHost.RenderBuffer;
                var sourceViewport = new ViewportF(0, 0, buffer.FullResPPBuffer.Width, buffer.FullResPPBuffer.Height);

                deviceContext.SetViewport(ref sourceViewport);
                deviceContext.SetScissorRectangle(ref sourceViewport);
                #region Do Blur Pass
                if (useBlurCore)
                {
                    for (var i = 0; i < numberOfBlurPass; ++i)
                    {
                        blurCore.Run(context, deviceContext, source, ref sourceViewport, PostEffectBlurCore.BlurDepth.One, ref modelStruct);
                    }
                }
                else
                {
                    blurPassHorizontal.PixelShader.BindSampler(deviceContext, samplerSlot, sampler);
                    for (var i = 0; i < numberOfBlurPass; ++i)
                    {
                        deviceContext.SetRenderTarget(context.RenderHost.RenderBuffer.FullResPPBuffer.NextRTV);
                        blurPassHorizontal.PixelShader.BindTexture(deviceContext, textureSlot, source);
                        blurPassHorizontal.BindShader(deviceContext);
                        blurPassHorizontal.BindStates(deviceContext, StateType.All);
                        deviceContext.Draw(4, 0);

                        deviceContext.SetRenderTarget(source);
                        blurPassVertical.PixelShader.BindTexture(deviceContext, textureSlot, context.RenderHost.RenderBuffer.FullResPPBuffer.NextRTV);
                        blurPassVertical.BindShader(deviceContext);
                        blurPassVertical.BindStates(deviceContext, StateType.All);
                        deviceContext.Draw(4, 0);
                    }
                }

                #region Draw back with stencil test
                deviceContext.SetRenderTarget(depthStencilBuffer, context.RenderHost.RenderBuffer.FullResPPBuffer.NextRTV,
                                              true, global::SharpDX.Color.Transparent, false);
                screenQuadPass.PixelShader.BindTexture(deviceContext, textureSlot, source);
                screenQuadPass.BindShader(deviceContext);
                screenQuadPass.BindStates(deviceContext, StateType.All);
                deviceContext.Draw(4, 0);
                #endregion

                #region Draw outline onto original target
                deviceContext.SetRenderTarget(buffer.FullResPPBuffer.CurrentRTV);
                screenOutlinePass.PixelShader.BindTexture(deviceContext, textureSlot, context.RenderHost.RenderBuffer.FullResPPBuffer.NextRTV);
                screenOutlinePass.BindShader(deviceContext);
                screenOutlinePass.BindStates(deviceContext, StateType.All);
                deviceContext.Draw(4, 0);
                screenOutlinePass.PixelShader.BindTexture(deviceContext, textureSlot, null);
                #endregion
                #endregion
            }
        public ShadowMap(Device device, int width, int height)
        {
            _device = device;

            Width  = width;
            Height = height;

            Viewport         = new ViewportF(0, 0, width, height);
            ScissorRectangle = new RectangleF(0, 0, width, height);

            BuildResource();
        }
示例#30
0
        public Vector3 UnprojectScreenCoord(Vector3 screenCoords)
        {
            // expand coord to fit the view
            screenCoords.X *= _graphicsDevice.BackBuffer.Width;
            screenCoords.Y *= _graphicsDevice.BackBuffer.Height;

            // translate vectors into world space by unprojecting them.
            var customViewport = new ViewportF(0, 0, _graphicsDevice.BackBuffer.Width, _graphicsDevice.BackBuffer.Height, _nearZClip, _farZClip);
            var worldCoord     = customViewport.Unproject(screenCoords, ProjectionMatrix, ViewMatrix, Matrix.Identity);

            return(worldCoord);
        }
        public CubeRenderTarget(Device device, int width, int height, Format format)
        {
            _device = device;
            _format = format;

            Width  = width;
            Height = height;

            Viewport         = new ViewportF(0, 0, Width, Height);
            ScissorRectangle = new RectangleF(0, 0, width, height);

            BuildResource();
        }
示例#32
0
        public Shadowmap(Device device)
        {
            TextureSize         = 1024;                                         //todo: make this a setting...
            CascadeCount        = Math.Min(Settings.Default.ShadowCascades, 8); // 6; //use setting
            PCFSize             = 3;
            PCFOffset           = 0.000125f;                                    //0.002f
            BlurBetweenCascades = 0.05f;

            ShadowVars = new GpuVarsBuffer <ShadowmapVars>(device);


            DepthTexture    = DXUtility.CreateTexture2D(device, TextureSize * CascadeCount, TextureSize, 1, 1, Format.R32_Typeless, 1, 0, ResourceUsage.Default, BindFlags.DepthStencil | BindFlags.ShaderResource, 0, 0);
            DepthTextureSS  = DXUtility.CreateSamplerState(device, TextureAddressMode.Border, new Color4(0.0f), Comparison.Less, Filter.ComparisonMinMagLinearMipPoint, 0, 0.0f, 0.0f, 0.0f);
            DepthTextureSRV = DXUtility.CreateShaderResourceView(device, DepthTexture, Format.R32_Float, ShaderResourceViewDimension.Texture2D, 1, 0, 0, 0);
            DepthTextureDSV = DXUtility.CreateDepthStencilView(device, DepthTexture, Format.D32_Float, DepthStencilViewDimension.Texture2D);

            Cascades = new List <ShadowmapCascade>(CascadeCount);
            for (int i = 0; i < CascadeCount; i++)
            {
                ShadowmapCascade c = new ShadowmapCascade();
                c.Owner         = this;
                c.Index         = i;
                c.ZNear         = 0.0f;
                c.ZFar          = 1.0f;
                c.IntervalNear  = 0.0f;
                c.IntervalFar   = 1.0f;
                c.DepthRenderVP = new ViewportF()
                {
                    Height   = (float)TextureSize,
                    Width    = (float)TextureSize,
                    MaxDepth = 1.0f,
                    MinDepth = 0.0f,
                    X        = (float)(TextureSize * i),
                    Y        = 0,
                };
                Cascades.Add(c);
            }

            DepthRenderRS = DXUtility.CreateRasterizerState(device, FillMode.Solid, CullMode.None, true, false, true, 0, 0.0f, 1.0f);
            DepthRenderDS = DXUtility.CreateDepthStencilState(device, true, DepthWriteMask.All);

            DepthRenderVP          = new ViewportF();
            DepthRenderVP.Height   = (float)TextureSize;
            DepthRenderVP.Width    = (float)TextureSize;
            DepthRenderVP.MaxDepth = 1.0f;
            DepthRenderVP.MinDepth = 0.0f;
            DepthRenderVP.X        = 0;
            DepthRenderVP.Y        = 0;

            graphicsMemoryUsage = (long)(TextureSize * TextureSize * CascadeCount * 4);
        }
        public void Initialize()
        {
            if(_window.Form.WindowState == FormWindowState.Minimized)
                return;

            if(!DeviceManager.IsInitialized)
                throw new InvalidOperationException("Device manager is not initialized");

            DestroyResources();

            _depthBuffer.Resize(Window.ClientWidth, Window.ClientHeight);
            _windowTextureBuffer.Resize(Window.ClientWidth, Window.ClientHeight);

            _depthBuffer.Initialize();
            _windowTextureBuffer.Initialize();

            var viewport = new ViewportF(0, 0, Window.ClientWidth, Window.ClientHeight);
            DeviceManager.Context.Rasterizer.SetViewport(viewport);
        }
示例#34
0
        public void Update(float deltaT)
        {            
            InputManager.Update();
            _Camera.Update(deltaT,(float)_RenderControl.ActualWidth, (float)_RenderControl.ActualHeight);

            //Get the position of the mouse on the rendercanvas
            System.Windows.Point mousePos = _RenderControl.PointFromScreen(InputManager.GetMousePosition());
            
            // Create a viewportfrustum for Ray.GetPickRay
            ViewportF viewFrustum = new ViewportF(0, 0, (float)(_RenderControl.ActualWidth), (float)(_RenderControl.ActualHeight), Camera.NearPlane, 2);

            HandlePicking(viewFrustum, mousePos);

            if (GameObjectManager.Instance().SelectedObject != null)
            {
                _Gizmo.Update(_Camera, viewFrustum, mousePos, GameObjectManager.Instance().SelectedObject);
                _Gizmo.Position = GameObjectManager.Instance().SelectedObject.Transform.WorldPosition.Vector3;                
            }

            GameObjectManager.Instance().Update(deltaT, Camera);

        }
        /// <summary>
        /// Called when the host request a new frame.
        /// </summary>
        /// <param name="device">Direct3D11 device.</param>
        /// <param name="context">Direct3D11 device context.</param>
        /// <param name="renderTargetView">Render target used for drawing.</param>
        public override void Draw(Device device, DeviceContext context, RenderTargetView renderTargetView)
        {
            bool deviceReset = false;

            if (device != this.sharpDXContext.D3DDevice)
            {
                this.sharpDXContext.OnDeviceReset(device, context);
                deviceReset = true;
            }

            this.sharpDXContext.D3DContext.ClearState();
            this.sharpDXContext.BackBufferView = renderTargetView;

            using (Texture2D backBufferTexture = new Texture2D(this.sharpDXContext.BackBufferView.Resource.NativePointer))
            {
                int currentWidth = (int)this.sharpDXContext.BackBufferSize.Width;
                int currentHeight = (int)this.sharpDXContext.BackBufferSize.Height;

                this.sharpDXContext.BackBuffer = backBufferTexture;

                if ((currentWidth != backBufferTexture.Description.Width && currentHeight != backBufferTexture.Description.Height)
                    || deviceReset)
                {
                    this.sharpDXContext.BackBufferSize = new Size(backBufferTexture.Description.Width, backBufferTexture.Description.Height);

                    this.sharpDXContext.RecreateDepthStencil(this.sharpDXContext.BackBufferSize);
                }
            }

            ViewportF viewport = new ViewportF(0, 0, (float)this.sharpDXContext.BackBufferSize.Width, (float)this.sharpDXContext.BackBufferSize.Height);
            sharpDXContext.D3DContext.Rasterizer.SetViewport(viewport);

            this.sharpDXContext.OnRender();

            this.runtimeHost.RequestAdditionalFrame();
        }
示例#36
0
        public bool IsHit(Camera camera, ViewportF view, System.Windows.Point mousePos)
        {
            bool result = false;
            float distance = float.MaxValue;
            float closestDistance = float.MaxValue;

            if (GetCurrentGizmoModels() == null)
                return false;
            for (int i = 0; i < GetCurrentGizmoModels().Count; i++)
            {
                // Create the worldViewProjectionMatrix
                Matrix worldViewProjectionMatrix = GetCurrentGizmoModels()[i].GetWorldMatrix() * camera.ViewMatrix * camera.ProjectionMatrix;

                //Create a Ray from the mouse position
                Ray ray = Ray.GetPickRay((int)(mousePos.X), (int)(mousePos.Y), view, worldViewProjectionMatrix);

                if (GetCurrentGizmoModels()[i].IsHitByRay(ray, out distance))
                {
                    if (distance < closestDistance)
                    {
                        closestDistance = distance;
                        SelectedAxis = i;

                        var rotate = Matrix.Identity;
                        
                        rotate = Matrix.RotationYawPitchRoll(MathUtil.DegreesToRadians(GetCurrentGizmoModels()[i].Rotation.Y),
                                                                   MathUtil.DegreesToRadians(GetCurrentGizmoModels()[i].Rotation.X),
                                                                   MathUtil.DegreesToRadians(GetCurrentGizmoModels()[i].Rotation.Z));
                        
                        _HitPosition = camera.Position + Vector3.TransformCoordinate(ray.Direction * distance, rotate);
                        
                        _lastMousePos = mousePos;
                    }

                    result = true;
                }
            }                    
            return result;
        }
示例#37
0
        public MyGame(MapControl3D mainHost)
        {
            //SharpDX.Configuration.EnableObjectTracking = true;

            this.Camera = new Camera();
            this.Camera.LookAt(new Vector3(4, 0, 0), new Vector3(0, 0, 0), Vector3.UnitZ);

            this.CameraMoveService = new CameraMoveService(this.Camera);
            base.Updatables.Add(this.CameraMoveService);

            this.ViewGridAdjusterService = new ViewGridAdjusterService(this, mainHost);
            base.Updatables.Add(this.ViewGridAdjusterService);

            this.ViewGridProvider = new ViewGridProvider(this);

            this.CameraKeyHandler = new CameraKeyHandler(this, mainHost);
            base.Updatables.Add(this.CameraKeyHandler);

            m_fpsCounter = new FPSCounter(this);
            base.Updatables.Add(m_fpsCounter);

            this.CursorService = new CursorService(this, mainHost);

            var mainView = new GameSurfaceView(this.GraphicsDevice)
            {
                Camera = this.Camera,
            };

            var axesView = new GameSurfaceView(this.GraphicsDevice)
            {
                Camera = this.Camera,
            };

            var surface = ToDispose(new GameSurface(this.GraphicsDevice, mainHost));

            surface.Views.Add(mainView);
            surface.Views.Add(axesView);

            surface.SizeChanged += (w, h) =>
            {
                var vp = new ViewportF(0, 0, w, h);
                mainView.ViewPort = vp;
                mainView.Camera.SetAspect(vp.AspectRatio);

                axesView.ViewPort = new ViewportF(0, 0, 50, 50);
            };

            base.Surfaces.Add(surface);

            this.MousePositionService = new MousePositionService(this, mainHost, mainView);
            base.Updatables.Add(this.MousePositionService);

            this.SelectionService = new Client.SelectionService(this, mainHost, this.Camera);

            this.TerrainRenderer = ToDispose(new TerrainRenderer(this, this.Camera, this.ViewGridProvider));
            base.Updatables.Add(this.TerrainRenderer);
            mainView.Drawables.Add(this.TerrainRenderer);

            m_symbolRenderer = ToDispose(new SymbolRenderer(this, this.ViewGridProvider));
            base.Updatables.Add(m_symbolRenderer);
            mainView.Drawables.Add(m_symbolRenderer);

            m_selectionRenderer = ToDispose(new SelectionRenderer(this));
            base.Updatables.Add(m_selectionRenderer);
            mainView.Drawables.Add(m_selectionRenderer);

            m_designationRenderer = ToDispose(new DesignationRenderer(this));
            base.Updatables.Add(m_designationRenderer);
            mainView.Drawables.Add(m_designationRenderer);

            m_debugAxesRenderer = ToDispose(new DebugAxesRenderer(this));
            base.Updatables.Add(m_debugAxesRenderer);
            axesView.Drawables.Add(m_debugAxesRenderer);

            #if OUTLINERENDERER
            m_outlineRenderer = ToDispose(new ChunkOutlineRenderer(this, this.TerrainRenderer.ChunkManager));
            base.Updatables.Add(m_outlineRenderer);
            mainView.Drawables.Add(m_outlineRenderer);
            #endif

            #if TESTCUBERENDERER
            m_testCubeRenderer = ToDispose(new TestCubeRenderer(this));
            base.Updatables.Add(m_testCubeRenderer);
            mainView.Drawables.Add(m_testCubeRenderer);
            #endif

            this.RasterizerState = this.GraphicsDevice.RasterizerStates.CullBack;
        }
示例#38
0
 public static RawViewportF Convert( ViewportF v )
 {
     return new RawViewportF { X = v.X, Y = v.Y, Width = v.Width, Height = v.Height, MinDepth = v.MinDepth, MaxDepth = v.MaxDepth };
 }
示例#39
0
        /// <summary>
        /// Resizes the current presenter, by resizing the back buffer and the depth stencil buffer.
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public virtual void Resize(int width, int height, DXGI.Format format)
        {
            if (DepthStencilBuffer != null)
            {
                RemoveAndDispose(ref depthStencilBuffer);
            }

            Description.BackBufferWidth = width;
            Description.BackBufferHeight = height;
            Description.BackBufferFormat = format;

            DefaultViewport = new ViewportF(0, 0, Description.BackBufferWidth, Description.BackBufferHeight);

            CreateDepthStencilBuffer();
        }
示例#40
0
        private void ZeroPad(Device device, DeviceContext context, SurfacePass pass, ShaderResourceView source, UnorderedAccessView target, String channel)
        {
            ViewportF viewport = new ViewportF(0, 0, resolution.Width, resolution.Height);

            DataStream cbuffer = new DataStream(8, true, true);
            cbuffer.Write<uint>((uint)resolution.Width);
            cbuffer.Write<uint>((uint)resolution.Height);
            cbuffer.Position = 0;

            pass.Pass(context, "#define CHANNEL " + channel + "\n" + Encoding.ASCII.GetString(Resources.ConvolutionZeroPad), viewport, null, new[] { source }, new[] { target }, cbuffer);

            cbuffer.Dispose();
        }
        public void BeginDraw()
        {
            // Unlike the original C++ sample, we don't have smart pointers so we need to
            // dispose Direct3D objects explicitly
            Utilities.Dispose(ref renderTargetView);
            Utilities.Dispose(ref depthStencilView);

            // Express target area as a native RECT type.
            var updateRectNative = new Rectangle(0, 0, width, height);

            // Query for ISurfaceImageSourceNative interface.
            using (var sisNative = ComObject.QueryInterface<ISurfaceImageSourceNative>(this))
            {
                // Begin drawing - returns a target surface and an offset to use as the top left origin when drawing.
                try
                {
                    RawPoint offset;
                    using (var surface = sisNative.BeginDraw(updateRectNative, out offset))
                    {
                        // QI for target texture from DXGI surface.
                        using (var d3DTexture = surface.QueryInterface<Texture2D>())
                        {
                            renderTargetView = new RenderTargetView(d3dDevice, d3DTexture);
                        }

                        // Set viewport to the target area in the surface, taking into account the offset returned by BeginDraw.
                        var viewport = new ViewportF(offset.X, offset.Y, width, height);
                        d3dContext.Rasterizer.SetViewport(viewport);

                        // Get the surface description in order to determine its size. The size of the depth/stencil buffer and the RenderTargetView must match, so the 
                        // depth/stencil buffer must be the same size as the surface. Since the whole surface returned by BeginDraw can potentially be much larger than 
                        // the actual update rect area passed into BeginDraw, it may be preferable for some apps to include an intermediate step which instead creates a 
                        // separate smaller D3D texture and renders into it before calling BeginDraw, then simply copies that texture into the surface returned by BeginDraw. 
                        // This would prevent needing to create a depth/stencil buffer which is potentially much larger than required, thereby saving memory at the cost of 
                        // additional overhead due to the copy operation.
                        var surfaceDesc = surface.Description;

                        // Create depth/stencil buffer descriptor.
                        var depthStencilDesc = new Texture2DDescription()
                        {
                            Format = Format.D24_UNorm_S8_UInt,
                            Width = surfaceDesc.Width,
                            Height = surfaceDesc.Height,
                            ArraySize = 1,
                            MipLevels = 1,
                            BindFlags = BindFlags.DepthStencil,
                            SampleDescription = new SampleDescription(1, 0),
                            Usage = ResourceUsage.Default,
                        };

                        // Allocate a 2-D surface as the depth/stencil buffer.
                        using (var depthStencil = new Texture2D(d3dDevice, depthStencilDesc))
                        {
                            depthStencilView = new DepthStencilView(d3dDevice, depthStencil);
                        }
                    }
                }
                catch (SharpDXException ex)
                {
                    if (ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceRemoved ||
                        ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceReset)
                    {
                        // If the device has been removed or reset, attempt to recreate it and continue drawing.
                        CreateDeviceResources();
                        BeginDraw();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
示例#42
0
        public void Init(IntPtr windowHandle)
        {
            // Factory de interfaces de DirectX
            Factory factory = new Factory();

            // Factory para crear el adaptador a la tarjeta grafica (la primera)
            Adapter adapter = factory.GetAdapter(0);

            // Obtengo la salida a monitor primario del adaptador
            Output monitor = adapter.Outputs[0];

            //Obtengo mis posibilidades de salida que soporto que utilicen el formato R8G8B8A8_UNorm
            ModeDescription[] displayModes = monitor.GetDisplayModeList(swapChainFormat, DisplayModeEnumerationFlags.Interlaced);

            //Si utilizo VSync, busco la taza de refresco para la resolución deseada que soporta el monitor
            Rational refreshRate = new Rational(0, 1);

            //if (VSyncEnabled)
                foreach (ModeDescription mode in displayModes)
                    if (mode.Width == SettingsManager.Current.ScreenSize.Width &&
                        mode.Height == SettingsManager.Current.ScreenSize.Height)
                    {
                        refreshRate = mode.RefreshRate;
                        break;
                    }


            // Obtengo los datos sobre la tarjeta de memoria
            AdapterDescription adapterDescription = adapter.Description;
            VideoCardDescription = adapterDescription.Description;
            VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // En MB

            DebugManager.LogNotice(VideoCardDescription + " con " + VideoCardMemory + " MB dedicados");

            // Creo el device y el devicecontext
            SharpDX.Direct3D11.Device temp_device;

            SharpDX.Direct3D.FeatureLevel[] features = new FeatureLevel[] { // Array de Feature Level soportados
            FeatureLevel.Level_11_0,
            FeatureLevel.Level_10_1,
            FeatureLevel.Level_10_0,
            FeatureLevel.Level_9_3 };

            DeviceCreationFlags creationFlags; // Creo al device en modo debug si estoy en modo debug
            if (DebugManager.DebugMode)
                creationFlags = DeviceCreationFlags.Debug;
            else
                creationFlags = DeviceCreationFlags.None;


            SampleDescription sampleDescription; // Info de MSAA
            sampleDescription = new SampleDescription(1, 0);


            // Creo swapchain
            SwapChain temp_swapchain;

            // Descripcion de SwapChain
            SwapChainDescription swapChainDesc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(SettingsManager.Current.ScreenSize.Width,
                    SettingsManager.Current.ScreenSize.Height,
                    refreshRate, swapChainFormat),
                Usage = Usage.RenderTargetOutput,
                OutputHandle = windowHandle,
                // Multisampling
                SampleDescription = sampleDescription,
                IsWindowed = SettingsManager.Current.IsWindowed,
                // Sin flags avanzados
                Flags = SwapChainFlags.None,
                // Descarto el backbuffer despues de presentarlo
                SwapEffect = SwapEffect.Discard
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(adapter, creationFlags, features, swapChainDesc, out temp_device, out temp_swapchain);

            DebugManager.LogNotice("DirectX11 Device creado");

            DXDevice = temp_device;
            DXDeviceContext = DXDevice.ImmediateContext;
            swapChain = temp_swapchain;
            DebugManager.LogNotice("Feature Level utilizado: " + DXDevice.FeatureLevel.ToString());
          

            // Libero la salida, el adaptador y el factory
            monitor.Dispose();
            adapter.Dispose();
            factory.Dispose();

            // Puntero al backbuffer
            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            // A partir del puntero creo el render target
            renderTargetView = new RenderTargetView(DXDevice, backBuffer);
            // Libero el backBuffer
            backBuffer.Dispose();

            // Descripcion del depth/stencil buffer
            Texture2DDescription depthBufferDesc = new Texture2DDescription()
            {
                Width = SettingsManager.Current.ScreenSize.Width,
                Height = SettingsManager.Current.ScreenSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = sampleDescription,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            // Creo el depth/stencil buffer a partir de la descripcion
            depthStencilBuffer = new Texture2D(DXDevice, depthBufferDesc);
            // Y creo el depth/stencil view
            depthStencilView = new DepthStencilView(DXDevice, depthStencilBuffer);

            DXDeviceContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);

            ViewportF viewport = new ViewportF()
            {
                X = 0,
                Y = 0,
                Width = SettingsManager.Current.ScreenSize.Width,
                Height = SettingsManager.Current.ScreenSize.Height,
                MinDepth = 0,
                MaxDepth = 1
            };

            DXDeviceContext.Rasterizer.SetViewport(viewport.X, viewport.Y, viewport.Width, viewport.Height, viewport.MinDepth, viewport.MaxDepth);
            DebugManager.LogNotice("DX11 inicilizado!");

        }
        public GameObject IsHitByMouseClick(System.Windows.Point mousePos, ViewportF viewFrustum, Camera camera, out float distance)
        {
            distance = float.MaxValue;

            if (!_isInitialized)
                return null;

            GameObject result = null;

            // Create the worldViewProjectionMatrix
            Matrix worldViewProjectionMatrix = GameObject.Transform.World * camera.ViewMatrix * camera.ProjectionMatrix;

            //Create a Ray from the mouse position
            Ray ray = Ray.GetPickRay((int)(mousePos.X), (int)(mousePos.Y), viewFrustum, worldViewProjectionMatrix);


            float closestHit = float.MaxValue;

            if (ray.Intersects(BoundingSphere))
            {
                //Check if the ray intersects with a triangle from the mesh
                for (int j = 0; j < IndexCount / 3; j++)
                {
                    Vector3 v0 = VertexList[(int)IndexList[j * 3]];
                    Vector3 v1 = VertexList[(int)IndexList[j * 3 + 1]];
                    Vector3 v2 = VertexList[(int)IndexList[j * 3 + 2]];

                    var ScaleMatrix = Matrix.Scaling(GetTransform().WorldScale.Vector3);

                    if (ray.Intersects(ref v0, ref v1, ref v2, out distance))
                    {
                        if (closestHit > distance * (ray.Direction * GetTransform().WorldScale.Vector3).Length())
                        {
                            closestHit = distance * (ray.Direction * GetTransform().WorldScale.Vector3).Length();
                            distance = float.MaxValue;
                        }
                        result = GameObject;
                    }
                }
            }

            distance = closestHit;
            return result;
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref EnvMap);
            RemoveAndDispose(ref EnvMapSRV);
            RemoveAndDispose(ref EnvMapRTV);
            RemoveAndDispose(ref EnvMapDSV);
            RemoveAndDispose(ref PerEnvMapBuffer);

            EnvMapRTVs.ToList().ForEach((rtv) => RemoveAndDispose(ref rtv));
            EnvMapDSVs.ToList().ForEach((dsv) => RemoveAndDispose(ref dsv));
            contextList.ToList().ForEach((ctx) => RemoveAndDispose(ref ctx));

            var device = this.DeviceManager.Direct3DDevice;

            // Create the cube map TextureCube (array of 6 textures)
            var textureDesc = new Texture2DDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                Height = Size,
                Width = Size,
                ArraySize = 6, // 6-sides of the cube
                BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
                OptionFlags = ResourceOptionFlags.GenerateMipMaps | ResourceOptionFlags.TextureCube,
                SampleDescription = new SampleDescription(1, 0),
                MipLevels = 0,
                Usage = ResourceUsage.Default,
                CpuAccessFlags = CpuAccessFlags.None,
            };
            EnvMap = ToDispose(new Texture2D(device, textureDesc));

            // Create the SRV for the texture cube
            var descSRV = new ShaderResourceViewDescription();
            descSRV.Format = textureDesc.Format;
            descSRV.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.TextureCube;
            descSRV.TextureCube.MostDetailedMip = 0;
            descSRV.TextureCube.MipLevels = -1;
            EnvMapSRV = ToDispose(new ShaderResourceView(device, EnvMap, descSRV));

            // Create the RTVs
            var descRTV = new RenderTargetViewDescription();
            descRTV.Format = textureDesc.Format;
            descRTV.Dimension = RenderTargetViewDimension.Texture2DArray;
            descRTV.Texture2DArray.MipSlice = 0;
            // 1. Single RTV for single pass rendering
            descRTV.Texture2DArray.FirstArraySlice = 0;
            descRTV.Texture2DArray.ArraySize = 6;
            EnvMapRTV = ToDispose(new RenderTargetView(device, EnvMap, descRTV));
            // 2. RTV for each of the 6 sides of the texture cube
            descRTV.Texture2DArray.ArraySize = 1;
            for (int i = 0; i < 6; i++)
            {
                descRTV.Texture2DArray.FirstArraySlice = i;
                EnvMapRTVs[i] = ToDispose(new RenderTargetView(device, EnvMap, descRTV));
            }

            // Create DSVs
            using (var depth = new Texture2D(device, new Texture2DDescription
            {
                Format = Format.D32_Float,
                BindFlags = BindFlags.DepthStencil,
                Height = Size,
                Width = Size,
                Usage = ResourceUsage.Default,
                SampleDescription = new SampleDescription(1, 0),
                CpuAccessFlags = CpuAccessFlags.None,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.TextureCube,
                ArraySize = 6 // 6-sides of the cube
            }))
            {
                var descDSV = new DepthStencilViewDescription();
                descDSV.Format = depth.Description.Format;
                descDSV.Dimension = DepthStencilViewDimension.Texture2DArray;
                descDSV.Flags = DepthStencilViewFlags.None;
                descDSV.Texture2DArray.MipSlice = 0;
                // 1. Single DSV for single pass rendering
                descDSV.Texture2DArray.FirstArraySlice = 0;
                descDSV.Texture2DArray.ArraySize = 6;
                EnvMapDSV = ToDispose(new DepthStencilView(device, depth, descDSV));
                // 2. Create DSV for each face
                descDSV.Texture2DArray.ArraySize = 1;
                for (var i = 0; i < 6; i++)
                {
                    descDSV.Texture2DArray.FirstArraySlice = i;
                    EnvMapDSVs[i] = ToDispose(new DepthStencilView(device, depth, descDSV));
                }
            }

            // Create the viewport
            Viewport = new Viewport(0, 0, Size, Size);

            // Initialize context List for threaded rendering
            // See UpdateCubeThreaded
            if (Threads == 1)
                contextList = null;
            else
            {
                contextList = new DeviceContext[Threads];
                for (var i = 0; i < Threads; i++)
                {
                    contextList[i] = ToDispose(new DeviceContext(device));
                }
            }

            // Create the per environment map buffer (to store the 6 ViewProjection matrices)
            PerEnvMapBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<Matrix>() * 6, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            PerEnvMapBuffer.DebugName = "PerEnvMapBuffer";
        }
        public override bool Resize(int width, int height, Format format, Rational? refreshRate = null)
        {
            if (!base.Resize(width, height, format, refreshRate)) return false;

            RemoveAndDispose(ref backBuffer);

#if DIRECTX11_2 && WIN8METRO
            var swapChainPanel = Description.DeviceWindowHandle as SwapChainPanel;
            if (swapChainPanel != null && swapChain2 != null)
            {

                swapChain2.MatrixTransform = Matrix3x2.Scaling(1f / swapChainPanel.CompositionScaleX, 1f / swapChainPanel.CompositionScaleY);
            }
#endif

            swapChain.ResizeBuffers(bufferCount, width, height, format, Description.Flags);

            // Recreate the back buffer
            backBuffer = ToDispose(RenderTarget2D.New(GraphicsDevice, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0)));

            // Reinit the Viewport
            DefaultViewport = new ViewportF(0, 0, backBuffer.Width, backBuffer.Height);

            return true;
        }
示例#46
0
        private void ConvolveChannel(Device device, DeviceContext context, SurfacePass pass, ShaderResourceView sourceA, ShaderResourceView sourceB, GraphicsResource target, String channel)
        {
            if ((channel != "x") && (channel != "y") && (channel != "z")) throw new ArgumentException("Invalid RGB channel specified.");

            ViewportF viewport = new ViewportF(0, 0, resolution.Width, resolution.Height);

            ZeroPad(device, context, pass, sourceA, lBuf.view, channel);
            ZeroPad(device, context, pass, sourceB, rBuf.view, channel);

            fft.ForwardTransform(lBuf.view, tBuf.view);
            fft.ForwardTransform(rBuf.view, lBuf.view);

            DataStream cbuffer = new DataStream(8, true, true);
            cbuffer.Write<uint>((uint)resolution.Width);
            cbuffer.Write<uint>((uint)resolution.Height);
            cbuffer.Position = 0;

            pass.Pass(context, Encoding.ASCII.GetString(Resources.ConvolutionMultiply), viewport, null, null, new[] { tBuf.view, lBuf.view }, cbuffer);

            cbuffer.Dispose();

            cbuffer = new DataStream(8, true, true);
            cbuffer.Write<uint>((uint)resolution.Width);
            cbuffer.Write<uint>((uint)resolution.Height);
            cbuffer.Position = 0;

            UnorderedAccessView fftView = fft.InverseTransform(tBuf.view);

            pass.Pass(context, Encoding.ASCII.GetString(Resources.ConvolutionOutput), target.Dimensions, target.RTV, null, new[] { fftView }, cbuffer);

            fftView.Dispose();
            cbuffer.Dispose();
        }
        public override bool Resize(int width, int height, Format format)
        {
            if (!base.Resize(width, height, format)) return false;

            RemoveAndDispose(ref backBuffer);

            swapChain.ResizeBuffers(bufferCount, width, height, format, Description.Flags);

            // Recreate the back buffer
            backBuffer = ToDispose(RenderTarget2D.New(GraphicsDevice, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0)));

            // Reinit the Viewport
            DefaultViewport = new ViewportF(0, 0, backBuffer.Width, backBuffer.Height);

            return true;
        }
示例#48
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="x"></param>
		/// <param name="y"></param>
		/// <param name="w"></param>
		/// <param name="h"></param>
		public void SetViewport ( ViewportF viewport )
		{
			lock (deviceContext) {
				deviceContext.Rasterizer.SetViewport( SharpDXHelper.Convert( viewport ) );
			}
		}
        public override bool BeginDraw()
        {
            if (GraphicsDevice != null && Window.Visible)
            {
                savedPresenter = GraphicsDevice.Presenter;
                savedViewport = GraphicsDevice.Viewport;

                CreateOrUpdatePresenter();

                if (isBackBufferToResize || windowUserResized)
                {
                    PixelFormat resizeFormat;
                    var size = GetRequestedSize(out resizeFormat);
                    Presenter.Resize(size.Width, size.Height, resizeFormat);

                    isBackBufferToResize = false;
                    windowUserResized = false;
                }

                GraphicsDevice.Presenter = Presenter;
                GraphicsDevice.SetViewport(Presenter.DefaultViewport);
                GraphicsDevice.SetRenderTargets(Presenter.DepthStencilBuffer, Presenter.BackBuffer);

                beginDrawOk = true;
                return true;
            }

            beginDrawOk = false;
            return false;
        }
 /// <summary>
 /// Binds a single viewport to the rasterizer stage.
 /// </summary>
 /// <param name="viewport">The viewport.</param>
 /// <remarks>	
 /// <p></p><p>All viewports must be set atomically as one operation. Any viewports not defined by the call are disabled.</p><p>Which viewport to use is determined by the SV_ViewportArrayIndex semantic output by a geometry shader; if a geometry shader does not specify the semantic, Direct3D will use the first viewport in the array.</p>	
 /// </remarks>	
 /// <msdn-id>ff476480</msdn-id>	
 /// <unmanaged>void ID3D11DeviceContext::RSSetViewports([In] unsigned int NumViewports,[In, Buffer, Optional] const void* pViewports)</unmanaged>	
 /// <unmanaged-short>ID3D11DeviceContext::RSSetViewports</unmanaged-short>	
 public void SetViewports(ViewportF viewport)
 {
     unsafe
     {
         SetViewports(1, new IntPtr(&viewport));
     }
 }
 /// <summary>
 /// Binds a set of viewports to the rasterizer stage.
 /// </summary>
 /// <param name="viewports">The set of viewports to bind.</param>
 /// <param name="count">The number of viewport to set.</param>
 /// <msdn-id>ff476480</msdn-id>
 ///   <unmanaged>void ID3D11DeviceContext::RSSetViewports([In] unsigned int NumViewports,[In, Buffer, Optional] const void* pViewports)</unmanaged>
 ///   <unmanaged-short>ID3D11DeviceContext::RSSetViewports</unmanaged-short>
 /// <remarks><p></p><p>All viewports must be set atomically as one operation. Any viewports not defined by the call are disabled.</p><p>Which viewport to use is determined by the SV_ViewportArrayIndex semantic output by a geometry shader; if a geometry shader does not specify the semantic, Direct3D will use the first viewport in the array.</p></remarks>
 public void SetViewports(ViewportF[] viewports, int count = 0)
 {
     unsafe
     {
         fixed (void* pBuffer = viewports)
             SetViewports(viewports == null ? 0 : count <= 0 ? viewports.Length : count, (IntPtr)pBuffer);
     }
 }
 private void SetScaling(float currentScale)
 {
     var sc = (SwapChain1)GraphicsDevice.Presenter.NativePresenter;
     // query DX11.2 swap chain
     using (var sc2 = sc.QueryInterface<SwapChain2>())
     {
         var w = (int)(GraphicsDevice.BackBuffer.Width * currentScale);
         var h = (int)(GraphicsDevice.BackBuffer.Height * currentScale);
         // set the swap chain scaling (new in DX11.2)
         sc2.SourceSize = new Size2(w, h);
         // we need to set the viewport to the same size as the swap chain scaling region
         _currentViewport = new ViewportF(0, 0, w, h);
         _scale = currentScale;
     }
 }
示例#53
0
        /// <summary>
        /// Resizes the current presenter, by resizing the back buffer and the depth stencil buffer.
        /// </summary>
        /// <param name="width">New backbuffer width</param>
        /// <param name="height">New backbuffer height</param>
        /// <param name="format">Backbuffer display format.</param>
        /// <param name="refreshRate"></param>
        /// <returns><c>true</c> if the presenter was resized, <c>false</c> otherwise</returns>
        public virtual bool Resize(int width, int height, Format format, Rational? refreshRate = null)
        {
            if (Description.BackBufferWidth == width && Description.BackBufferHeight == height && Description.BackBufferFormat == format)
            {
                return false;
            }

            if (DepthStencilBuffer != null)
            {
                RemoveAndDispose(ref depthStencilBuffer);
            }

            Description.BackBufferWidth = width;
            Description.BackBufferHeight = height;
            Description.BackBufferFormat = format;
            if(refreshRate.HasValue)
            {
                Description.RefreshRate = refreshRate.Value;
            }

            DefaultViewport = new ViewportF(0, 0, Description.BackBufferWidth, Description.BackBufferHeight);

            CreateDepthStencilBuffer();
            return true;
        }
        private void LoadStructures()
        {
            var device = _graphicsDeviceManager.GraphicsDevice;

            var vertexBufferData = new[]
                                   {
                                       new SamplingVertex(-1.0f, 1.0f, 0.0f, 0.0f),
                                       new SamplingVertex(1.0f, 1.0f, 1.0f, 0.0f),
                                       new SamplingVertex(-1.0f, -1.0f, 0.0f, 1.0f),
                                       new SamplingVertex(1.0f, -1.0f, 1.0f, 1.0f)
                                   };

            var indexBufferData = new[] { 0, 1, 2, 3, 2, 1 };

            _viewerGeometry = ToDispose(new SharpDX.Toolkit.Graphics.GeometricPrimitive<SamplingVertex>(device, vertexBufferData, indexBufferData, false));

            var screenViewport = new ViewportF(0f, 0f, device.BackBuffer.Width, device.BackBuffer.Height);
            var targetWidth = (int)(screenViewport.Width / SampleSettings.Sampling.Ratio);
            var targetHeight = (int)(screenViewport.Height / SampleSettings.Sampling.Ratio);

            _viewport = new ViewportF(0f, 0f, targetWidth, targetHeight, 0f, 1f);

            _colorTextureRenderTarget = ToDispose(SharpDX.Toolkit.Graphics.RenderTarget2D.New(device,
                                                                                              targetWidth,
                                                                                              targetHeight,
                                                                                              SharpDX.Toolkit.Graphics.PixelFormat.B8G8R8A8.UNorm));

            _depthStencilBuffer = ToDispose(SharpDX.Toolkit.Graphics.DepthStencilBuffer.New(device,
                                                                                            targetWidth,
                                                                                            targetHeight,
                                                                                            SharpDX.Toolkit.Graphics.DepthFormat.Depth24Stencil8));

            _viewerEffect = _contentManager.Load<SamplingViewerEffect>("SamplingViewer");

            _viewerEffect.Scale = new Vector2(_viewport.Width / screenViewport.Width,
                                              _viewport.Height / screenViewport.Height);

            _viewerEffect.Offset = new Vector2(2f * (48.0f + _viewport.Width / 2f) / screenViewport.Width - 1f,
                                               1f - 2f * (screenViewport.Height - _viewport.Height - 48.0f + _viewport.Height / 2f) / screenViewport.Height);

            _samplingEffect = _contentManager.Load<SamplingRendererEffect>("SamplingRenderer");

            _samplingEffect.EncodeConstants = new Vector2(SampleSettings.TileSizeInBytes / SampleSettings.Sampling.Ratio, 24f);
        }
        public void InitBase()
        {
            VIEWPORT = new ViewportF(0, 0, Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT);
            GAME_AREA_SIZE = new RectangleF(0, 0, Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT);
            ViewportIDMatrix = Matrix.Identity;
            ViewportIDMatrixMirror = new Matrix3x2();
            ViewportIDMatrixMirror.M11 = -1; ViewportIDMatrixMirror.M12 = 0;
            ViewportIDMatrixMirror.M21 = 0; ViewportIDMatrixMirror.M22 = 1;
            ViewportIDMatrixMirror.M31 = 0; ViewportIDMatrixMirror.M32 = 0;

            Entities = new List<BaseEntity>();
            VisibleEntities = new List<BaseEntity>();
            CollidableEntities = new List<BaseEntity>();
            Initialize();
            GameCamera = Camera.GetInstance();
            Quad = new QuadTree(0, GAME_AREA_SIZE);
        }
        /// <summary>
        /// Creates resources that depend on the current back buffer size.
        /// </summary>
        private void CreateSizeDependentResources()
        {
            this.ReleaseSizeDependentResources();

            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, (int)this.BackBufferSize.Width, (int)this.BackBufferSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
            }
            else
            {
                SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
                {
                    Width = (int)this.BackBufferSize.Width,
                    Height = (int)this.BackBufferSize.Height,
                    Format = Format.B8G8R8A8_UNorm,
                    Stereo = false,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                    BufferCount = 2,
                    Scaling = Scaling.Stretch,
                    SwapEffect = SwapEffect.FlipSequential,
                };

                using (SharpDX.DXGI.Device2 dxgiDevice2 = this.D3DDevice.QueryInterface<SharpDX.DXGI.Device2>())
                {
                    using (SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter)
                    {
                        using (SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
                        {
                            swapChain = new SwapChain1(dxgiFactory2, this.D3DDevice, ref swapChainDescription);

                            if (this.backgroundPanel != null)
                            {
                                nativeBackgroundPanel.SwapChain = swapChain;
                            }
                            else if (this.panel != null)
                            {
                                nativePanel.SwapChain = swapChain;
                            }

                            dxgiDevice2.MaximumFrameLatency = 1;
                        }
                    }
                }
            }

            this.BackBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            this.BackBufferView = new RenderTargetView(this.D3DDevice, this.BackBuffer);
            this.UpdateBackBufferSize();

            using (Texture2D depthBuffer = new Texture2D(this.D3DDevice, new Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)this.BackBufferSize.Width,
                Height = (int)this.BackBufferSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags = BindFlags.DepthStencil,
            }))
            {
                this.DepthStencilView = new DepthStencilView(this.D3DDevice, depthBuffer, new DepthStencilViewDescription()
                {
                    Dimension = DepthStencilViewDimension.Texture2D
                });
            }

            ViewportF viewport = new ViewportF(0, 0, (float)this.BackBufferSize.Width, (float)this.BackBufferSize.Height, 0.0f, 1.0f);
            this.D3DContext.Rasterizer.SetViewport(viewport);
        }
示例#57
0
        public void Update(Camera camera, ViewportF view, System.Windows.Point mousePos, GameObject linkedObject)
        {
             UpdateModels(camera);

            if (InputManager.IsLeftMouseButtonDown() && SelectedAxis != -1)
            {
                //Create a Ray from the mouse position
                Matrix worldViewProjectionMatrix = Matrix.Identity *  camera.ViewMatrix * camera.ProjectionMatrix;
                Ray ray = Ray.GetPickRay((int)(mousePos.X), (int)(mousePos.Y), view, worldViewProjectionMatrix);
                Plane plane;
                Matrix RotationMat = Matrix.Identity;
                switch (Mode)
                {
                    case GizmoMode.None:
                        break;
                    case GizmoMode.Translate:
                        if (_StartPosition == null)
                        {
                            _StartPosition = new MyVector3();
                            _StartPosition.Vector3 = linkedObject.Transform.Position.Vector3; ;
                        }
                        Vector3 translationDelta = Vector3.Zero;
                        switch (SelectedAxis)
                        {
                            case 0:
                                plane = new Plane(_HitPosition, camera.Forward);
                                translationDelta = CalculateTransformDelta(plane, ray, camera);
                                Console.WriteLine(_HitPosition);

                                translationDelta = new Vector3(translationDelta.X, 0, 0);
                                break;
                            case 1:
 
                                plane = new Plane(_HitPosition, camera.Forward);
                                translationDelta = CalculateTransformDelta(plane, ray, camera);
                                Console.WriteLine(_HitPosition);
                                translationDelta = new Vector3(0, translationDelta.Y, 0);
                                break;
                            case 2:
                                plane = new Plane(_HitPosition, Vector3.Up);
                                translationDelta = CalculateTransformDelta(plane, ray, camera);
                                translationDelta = new Vector3(0, 0, translationDelta.Z);
                                break;
                            default:
                                break;
                        }

                        var scaledTranslationDelta = new Vector3((int)(translationDelta.X / TranslationSnapValue) * TranslationSnapValue,
                                                                 (int)(translationDelta.Y / TranslationSnapValue) * TranslationSnapValue,
                                                                 (int)(translationDelta.Z / TranslationSnapValue) * TranslationSnapValue);

                        _LastIntersectionPosition += scaledTranslationDelta;
                        linkedObject.Transform.Position.Vector3 += scaledTranslationDelta;
                        break;

                    case GizmoMode.Rotate:
                        if (_StartRotation == null)
                        {
                            _StartRotation = new MyVector3();
                            _StartRotation.Vector3 = linkedObject.Transform.RotationEuler.Vector3; ;
                        }
                        Vector3 RotateDelta = Vector3.Zero;
                        Vector3 MouseDelta = Vector3.Zero;
                        switch (SelectedAxis)
                        {
                            case 0:
                                plane = new Plane(_HitPosition, camera.Forward);
                                RotateDelta = CalculateTransformDelta(plane, ray, camera);
                                MouseDelta = new Vector3(0, RotateDelta.Y, 0);
                                RotateDelta = new Vector3(RotateDelta.Y, 0, 0);

                                break;
                            case 1:
                                plane = new Plane(_HitPosition, camera.Forward);
                                RotateDelta = CalculateTransformDelta(plane, ray, camera);
                                MouseDelta = new Vector3(RotateDelta.X, 0, 0);
                                RotateDelta = new Vector3(0, -RotateDelta.X, 0);
                                break;
                            case 2:
                                plane = new Plane(_HitPosition, camera.Up);
                                RotateDelta = CalculateTransformDelta(plane, ray, camera);
                                MouseDelta = new Vector3(0, 0, RotateDelta.Z);
                                RotateDelta = new Vector3(0, 0, RotateDelta.Z);
                                break;
                            default:
                                break;
                        }

                        RotateDelta *= 10.0f;
                        var scaledRotationDelta = new Vector3((int)(RotateDelta.X / RotationSnapValue) * RotationSnapValue,
                                                                 (int)(RotateDelta.Y / RotationSnapValue) * RotationSnapValue,
                                                                 (int)(RotateDelta.Z / RotationSnapValue) * RotationSnapValue);
                        
                        _LastIntersectionPosition += MouseDelta;
                        linkedObject.Transform.RotationEuler.X += scaledRotationDelta.X;
                        linkedObject.Transform.RotationEuler.Y += scaledRotationDelta.Y;
                        linkedObject.Transform.RotationEuler.Z += scaledRotationDelta.Z;
                        break;
                    case GizmoMode.Scale:
                        Vector3 scaleDelta = Vector3.Zero;
                        if (_StartScale == null)
                        {
                            _StartScale = new MyVector3();
                            _StartScale.Vector3 = linkedObject.Transform.Scale.Vector3; ;
                        }
                        switch (SelectedAxis)
                        {
                            case 0:
                                plane = new Plane(_HitPosition, camera.Forward);
                                scaleDelta = CalculateTransformDelta(plane, ray, camera);
                                scaleDelta = new Vector3(scaleDelta.X, 0, 0);
                                break;
                            case 1:
                                plane = new Plane(_HitPosition, camera.Forward);
                                scaleDelta = CalculateTransformDelta(plane, ray, camera);
                                scaleDelta = new Vector3(0, scaleDelta.Y, 0);
                                break;
                            case 2:
                                plane = new Plane(_HitPosition, Vector3.Up);
                                scaleDelta = CalculateTransformDelta(plane, ray, camera);
                                scaleDelta = new Vector3(0, 0, scaleDelta.Z);
                                break;
                            default:
                                break;
                        }

                        var scaledScaleDelta = new Vector3((int)(scaleDelta.X / ScaleSnapValue) * ScaleSnapValue,
                                                           (int)(scaleDelta.Y / ScaleSnapValue) * ScaleSnapValue,
                                                           (int)(scaleDelta.Z / ScaleSnapValue) * ScaleSnapValue) ;

                        _LastIntersectionPosition += scaledScaleDelta;

                        RotationMat = Matrix.RotationQuaternion(linkedObject.Transform.Rotation);
                        scaledScaleDelta = Vector3.TransformCoordinate(scaledScaleDelta, RotationMat);

                        linkedObject.Transform.Scale.Vector3 += scaledScaleDelta * new Vector3(1,1,-1) ;
                        break;
                    default:
                        break;
                }

                
            }
            else 
            {
                if (SelectedAxis != -1 )
                {
                    switch (Mode)
                    {
                        case GizmoMode.None:
                            break;
                        case GizmoMode.Translate:
                                var UndoCommand = new RelayCommand<MyVector3>(linkedObject.Transform.SetPosition);
                                UndoRedoStack.AddUndoCommand(UndoCommand, _StartPosition);
                                UndoRedoStack.ClearRedoStack();
                                _StartPosition = null;
                            break;
                        case GizmoMode.Rotate:
                                var UndoRotateCommand = new RelayCommand<MyVector3>(linkedObject.Transform.SetRotation);
                                UndoRedoStack.AddUndoCommand(UndoRotateCommand, _StartRotation);
                                UndoRedoStack.ClearRedoStack();
                                _StartRotation = null;
                            break;
                        case GizmoMode.Scale:
                                var UndoScaleCommand = new RelayCommand<MyVector3>(linkedObject.Transform.SetScale);
                                UndoRedoStack.AddUndoCommand(UndoScaleCommand, _StartScale);
                                UndoRedoStack.ClearRedoStack();
                                _StartScale = null;
                            break;
                        default:
                            break;
                    }
                }
                SelectedAxis = -1;
                _LastIntersectionPosition = Vector3.Zero;
            }

        }
        /// <summary>
        /// Gets the synchronized texture used for drawing.
        /// </summary>
        /// <param name="surfaceSize">Size of the drawing surface.</param>
        /// <param name="synchronizedTexture">Synchronized texture object.</param>
        /// <param name="textureSubRectangle">Area of the texture that has changed.</param>
        public override void GetTexture(Size2F surfaceSize, out DrawingSurfaceSynchronizedTexture synchronizedTexture, out RectangleF textureSubRectangle)
        {
            if (this.synchronizedTexture == null)
            {
                this.sharpDXContext.BackBufferSize = new Size(surfaceSize.Width, surfaceSize.Height);

                this.sharpDXContext.RecreateBackBuffer(this.sharpDXContext.BackBufferSize);
                this.sharpDXContext.RecreateDepthStencil(this.sharpDXContext.BackBufferSize);

                ViewportF viewport = new ViewportF(0, 0, surfaceSize.Width, surfaceSize.Height);
                this.sharpDXContext.D3DContext.Rasterizer.SetViewport(viewport);

                this.synchronizedTexture = this.runtimeHost.CreateSynchronizedTexture(this.sharpDXContext.BackBuffer);
            }

            synchronizedTexture = this.synchronizedTexture;
            textureSubRectangle = new RectangleF(0, 0, surfaceSize.Width, surfaceSize.Height);

            this.synchronizedTexture.BeginDraw();
            this.sharpDXContext.OnRender();
            this.synchronizedTexture.EndDraw();

            this.runtimeHost.RequestAdditionalFrame();
        }
示例#59
0
        private void LoadAssets()
        {
            // Create the descriptor heap for the render target view
            descriptorHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                Type = DescriptorHeapType.RenderTargetView,
                DescriptorCount = 1
            });

            // Create the main command list
            commandList = device.CreateCommandList(CommandListType.Direct, commandListAllocator, null);

            // Get the backbuffer and creates the render target view
            renderTarget = swapChain.GetBackBuffer<Resource>(0);
            device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart);

            // Create the viewport
            viewPort = new ViewportF(0, 0, width, height);

            // Create the scissor
            scissorRectangle = new Rectangle(0, 0, width, height);

            // Create a fence to wait for next frame
            fence = device.CreateFence(0, FenceFlags.None);
            currentFence = 1;

            // Close command list
            commandList.Close();

            // Create an event handle use for VTBL
            eventHandle = new AutoResetEvent(false);

            // Wait the command list to complete
            WaitForPrevFrame();
        }
 /// <summary>
 /// Binds a single viewport to the rasterizer stage.
 /// </summary>
 /// <param name="x">The x coord of the viewport.</param>
 /// <param name="y">The x coord of the viewport.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="minZ">The min Z.</param>
 /// <param name="maxZ">The max Z.</param>
 /// <remarks>	
 /// <p></p><p>All viewports must be set atomically as one operation. Any viewports not defined by the call are disabled.</p><p>Which viewport to use is determined by the SV_ViewportArrayIndex semantic output by a geometry shader; if a geometry shader does not specify the semantic, Direct3D will use the first viewport in the array.</p>	
 /// </remarks>	
 /// <msdn-id>ff476480</msdn-id>	
 /// <unmanaged>void ID3D11DeviceContext::RSSetViewports([In] unsigned int NumViewports,[In, Buffer, Optional] const void* pViewports)</unmanaged>	
 /// <unmanaged-short>ID3D11DeviceContext::RSSetViewports</unmanaged-short>	
 public void SetViewport(float x, float y, float width, float height, float minZ = 0.0f, float maxZ = 1.0f)
 {
     var viewport = new ViewportF(x, y, width, height, minZ, maxZ);
     unsafe
     {
         SetViewports(1, new IntPtr(&viewport));
     }
 }