Пример #1
0
        public override IntPtr WndProc(
            IntPtr hWnd, User32.WindowMessage msg,
            IntPtr wParam, IntPtr lParam)
        {
            switch (msg)
            {
            case User32.WindowMessage.WM_PAINT:
                _swap?.Present(1, PresentFlags.None);
                break;

            case User32.WindowMessage.WM_CLOSE:
                Environment.Exit(0);
                return(IntPtr.Zero);
            }

            return(base.WndProc(hWnd, msg, wParam, lParam));
        }
Пример #2
0
        public void Update(Camera camera)
        {
            if (userResized)
            {
                // Dispose all previous allocated resources
                Utilities.Dispose(ref backBuffer);
                Utilities.Dispose(ref renderView);
                Utilities.Dispose(ref depthBuffer);
                Utilities.Dispose(ref depthView);

                // Resize the backbuffer
                swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None);

                // Get the backbuffer from the swapchain
                backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);

                // Renderview on the backbuffer
                renderView = new RenderTargetView(device, backBuffer);

                // Create the depth buffer
                depthBuffer = new Texture2D(device, new Texture2DDescription()
                {
                    Format            = Format.D32_Float_S8X24_UInt,
                    ArraySize         = 1,
                    MipLevels         = 1,
                    Width             = form.ClientSize.Width,
                    Height            = form.ClientSize.Height,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                });

                // Create the depth buffer view
                depthView = new DepthStencilView(device, depthBuffer);

                // Setup targets and viewport for rendering
                context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
                context.OutputMerger.SetTargets(depthView, renderView);

                // Setup new projection matrix with correct aspect ratio
//                projMatrix = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, camera.near, camera.far);

                // We are done resizing
                userResized = false;
            }
            Color4 col = new Color4(0.5f, 0.5f, 0.5f, 1.0f);

            unsafe
            {
                context.ClearRenderTargetView(renderTarget, *(RawColor4 *)&col);
            }
            swapChain.Present(0, PresentFlags.None);
//            Matrix.Translation(0.0f, 0.0f, 5.0f, out viewMatrix);
            //Camera.Current.Update();
//            Matrix.Multiply(ref camera.Parent.transform.worldMatrix, ref camera.projectionMatrix, out viewProjMatrix);
            //Matrix.Multiply(ref viewMatrix, ref Camera.Current.projectionMatrix, out viewProjMatrix);
            Matrix.Multiply(ref Camera.Current.Entity.Transform.worldMatrix, ref Camera.Current.projectionMatrix, out viewProjMatrix);
            context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
            context.ClearRenderTargetView(renderView, Color.Black);

            var time = clock.ElapsedMilliseconds / 1000.0f;

            // Update WorldViewProj Matrix
            var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProjMatrix;

            worldViewProj.Transpose();
            context.UpdateSubresource(ref worldViewProj, contantBuffer);

            // Draw the cube
            context.Draw(36, 0);

            // Present!
            swapChain.Present(0, PresentFlags.None);
        }
Пример #3
0
 public void End()
 {
     //Present the backbuffer to the screen
     SwapChain.Present(true);
 }
Пример #4
0
        public override void DrawScene()
        {
            ImmediateContext.ClearRenderTargetView(RenderTargetView, Color.LightSteelBlue);
            ImmediateContext.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);

            ImmediateContext.InputAssembler.InputLayout       = InputLayouts.PosNormal;
            ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            var viewProj = _view * _proj;

            _fx.SetDirLights(_dirLights);
            _fx.SetEyePosW(_eyePosW);

            var activeTech = _fx.Light1Tech;

            switch (_lightCount)
            {
            case 1:
                activeTech = _fx.Light1Tech;
                break;

            case 2:
                activeTech = _fx.Light2Tech;
                break;

            case 3:
                activeTech = _fx.Light3Tech;
                break;
            }
            for (var p = 0; p < activeTech.Description.PassCount; p++)
            {
                var pass = activeTech.GetPassByIndex(p);
                ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_shapesVB, VertexPN.Stride, 0));
                ImmediateContext.InputAssembler.SetIndexBuffer(_shapesIB, Format.R32_UInt, 0);

                var world             = _gridWorld;
                var worldInvTranspose = MathF.InverseTranspose(world);
                var wvp = world * viewProj;
                _fx.SetWorld(world);
                _fx.SetWorldInvTranspose(worldInvTranspose);
                _fx.SetWorldViewProj(wvp);
                _fx.SetMaterial(_gridMat);
                pass.Apply(ImmediateContext);
                ImmediateContext.DrawIndexed(_gridIndexCount, _gridIndexOffset, _gridVertexOffset);

                world             = _boxWorld;
                worldInvTranspose = MathF.InverseTranspose(world);
                wvp = world * viewProj;
                _fx.SetWorld(world);
                _fx.SetWorldInvTranspose(worldInvTranspose);
                _fx.SetWorldViewProj(wvp);
                _fx.SetMaterial(_boxMat);
                pass.Apply(ImmediateContext);
                ImmediateContext.DrawIndexed(_boxIndexCount, _boxIndexOffset, _boxVertexOffset);

                foreach (var matrix in _cylWorld)
                {
                    world             = matrix;
                    worldInvTranspose = MathF.InverseTranspose(world);
                    wvp = world * viewProj;
                    _fx.SetWorld(world);
                    _fx.SetWorldInvTranspose(worldInvTranspose);
                    _fx.SetWorldViewProj(wvp);
                    _fx.SetMaterial(_cylinderMat);
                    pass.Apply(ImmediateContext);
                    ImmediateContext.DrawIndexed(_cylinderIndexCount, _cylinderIndexOffset, _cylinderVertexOffset);
                }
                foreach (var matrix in _sphereWorld)
                {
                    world             = matrix;
                    worldInvTranspose = MathF.InverseTranspose(world);
                    wvp = world * viewProj;
                    _fx.SetWorld(world);
                    _fx.SetWorldInvTranspose(worldInvTranspose);
                    _fx.SetWorldViewProj(wvp);
                    _fx.SetMaterial(_sphereMat);
                    pass.Apply(ImmediateContext);
                    ImmediateContext.DrawIndexed(_sphereIndexCount, _sphereIndexOffset, _sphereVertexOffset);
                }
                ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_skullVB, VertexPN.Stride, 0));
                ImmediateContext.InputAssembler.SetIndexBuffer(_skullIB, Format.R32_UInt, 0);

                world             = _skullWorld;
                worldInvTranspose = MathF.InverseTranspose(world);
                wvp = world * viewProj;
                _fx.SetWorld(world);
                _fx.SetWorldInvTranspose(worldInvTranspose);
                _fx.SetWorldViewProj(wvp);
                _fx.SetMaterial(_skullMat);
                pass.Apply(ImmediateContext);
                ImmediateContext.DrawIndexed(_skullIndexCount, 0, 0);
            }
            SwapChain.Present(0, PresentFlags.None);
        }
Пример #5
0
        static void Main(string[] args)
        {
            // Select a File to play
            var openFileDialog = new OpenFileDialog { Title = "Select a file", Filter = "Media Files(*.WMV;*.MP4;*.AVI)|*.WMV;*.MP4;*.AVI" };
            var result = openFileDialog.ShowDialog();
            if (result == DialogResult.Cancel)
            {
                return;
            }

            // Initialize MediaFoundation
            MediaManager.Startup();

            var renderForm = new SharpDX.Windows.RenderForm();

            device = CreateDeviceForVideo(out dxgiManager);

            // Creates the MediaEngineClassFactory
            var mediaEngineFactory = new MediaEngineClassFactory();
            
            //Assign our dxgi manager, and set format to bgra
            MediaEngineAttributes attr = new MediaEngineAttributes();
            attr.VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            attr.DxgiManager = dxgiManager;

            // Creates MediaEngine for AudioOnly 
            var mediaEngine = new MediaEngine(mediaEngineFactory, attr, MediaEngineCreateFlags.None);

            // Register our PlayBackEvent
            mediaEngine.PlaybackEvent += OnPlaybackCallback;

            // Query for MediaEngineEx interface
            mediaEngineEx = mediaEngine.QueryInterface<MediaEngineEx>();

            // Opens the file
            var fileStream = openFileDialog.OpenFile();
            
            // Create a ByteStream object from it
            var stream = new ByteStream(fileStream);

            // Creates an URL to the file
            var url = new Uri(openFileDialog.FileName, UriKind.RelativeOrAbsolute);

            // Set the source stream
            mediaEngineEx.SetSourceFromByteStream(stream, url.AbsoluteUri);

            // Wait for MediaEngine to be ready
            if (!eventReadyToPlay.WaitOne(1000))
            {
                Console.WriteLine("Unexpected error: Unable to play this file");
            }

            //Create our swapchain
            swapChain = CreateSwapChain(device, renderForm.Handle);

            //Get DXGI surface to be used by our media engine
            var texture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var surface = texture.QueryInterface<SharpDX.DXGI.Surface>();

            //Get our video size
            int w, h;
            mediaEngine.GetNativeVideoSize(out w, out h);

            // Play the music
            mediaEngineEx.Play();

            long ts;

            RenderLoop.Run(renderForm, () =>
            {
                //Transfer frame if a new one is available
                if (mediaEngine.OnVideoStreamTick(out ts))
                {
                    mediaEngine.TransferVideoFrame(surface, null, new SharpDX.Rectangle(0, 0, w, h), null);
                }

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

            mediaEngine.Shutdown();
            swapChain.Dispose();
            device.Dispose();
        }
Пример #6
0
 /// <summary>
 /// Render the frame
 /// </summary>
 protected void RenderScene()
 {
     // Just clear the backbuffer
     device.ClearRenderTargetView(renderTargetView, backColor);
     swapChain.Present(0, PresentOptions.None);
 }
Пример #7
0
 protected override void EndDraw()
 {
     base.EndDraw();
     // present the foreground swapchain
     _foregroundChain.Present(1, PresentFlags.None);
 }
Пример #8
0
        protected override void Draw(GameTimer gt)
        {
            CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc;

            // Reuse the memory associated with command recording.
            // We can only reset when the associated command lists have finished execution on the GPU.
            cmdListAlloc.Reset();

            // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
            // Reusing the command list reuses memory.
            CommandList.Reset(cmdListAlloc, _psos["opaque"]);

            CommandList.SetViewport(Viewport);
            CommandList.SetScissorRectangles(ScissorRectangle);

            // Indicate a state transition on the resource usage.
            CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget);

            // Clear the back buffer and depth buffer.
            CommandList.ClearRenderTargetView(CurrentBackBufferView, Color.LightSteelBlue);
            CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0);

            // Specify the buffers we are going to render to.
            CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView);

            CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps);

            CommandList.SetGraphicsRootSignature(_rootSignature);

            Resource passCB = CurrFrameResource.PassCB.Resource;

            CommandList.SetGraphicsRootConstantBufferView(1, passCB.GPUVirtualAddress);

            // Bind all the materials used in this scene. For structured buffers, we can bypass the heap and
            // set as a root descriptor.
            Resource matBuffer = CurrFrameResource.MaterialBuffer.Resource;

            CommandList.SetGraphicsRootShaderResourceView(2, matBuffer.GPUVirtualAddress);

            // Bind the sky cube map. For our demos, we just use one "world" cube map representing the environment
            // from far away, so all objects will use the same cube map and we only need to set it once per-frame.
            // If we wanted to use "local" cube maps, we would have to change them per-object, or dynamically
            // index into an array of cube maps.
            GpuDescriptorHandle skyTexDescriptor = _srvDescriptorHeap.GPUDescriptorHandleForHeapStart;

            skyTexDescriptor += _skyTexHeapIndex * CbvSrvUavDescriptorSize;
            CommandList.SetGraphicsRootDescriptorTable(3, skyTexDescriptor);

            // Bind all the textures used in this scene. Observe
            // that we only have to specify the first descriptor in the table.
            // The root signature knows how many descriptors are expected in the table.
            CommandList.SetGraphicsRootDescriptorTable(4, _srvDescriptorHeap.GPUDescriptorHandleForHeapStart);

            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]);

            CommandList.PipelineState = _psos["sky"];
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Sky]);

            // Indicate a state transition on the resource usage.
            CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present);

            // Done recording commands.
            CommandList.Close();

            // Add the command list to the queue for execution.
            CommandQueue.ExecuteCommandList(CommandList);

            // Present the buffer to the screen. Presenting will automatically swap the back and front buffers.
            SwapChain.Present(0, PresentFlags.None);

            // Advance the fence value to mark commands up to this fence point.
            CurrFrameResource.Fence = ++CurrentFence;

            // Add an instruction to the command queue to set a new fence point.
            // Because we are on the GPU timeline, the new fence point won't be
            // set until the GPU finishes processing all the commands prior to this Signal().
            CommandQueue.Signal(Fence, CurrentFence);
        }
        protected override void Draw(GameTimer gt)
        {
            CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc;

            // Reuse the memory associated with command recording.
            // We can only reset when the associated command lists have finished execution on the GPU.
            cmdListAlloc.Reset();

            // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
            // Reusing the command list reuses memory.
            CommandList.Reset(cmdListAlloc, _psos["opaque"]);

            CommandList.SetViewport(Viewport);
            CommandList.SetScissorRectangles(ScissorRectangle);

            // Indicate a state transition on the resource usage.
            CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget);

            // Clear the back buffer and depth buffer.
            CommandList.ClearRenderTargetView(CurrentBackBufferView, new Color(_mainPassCB.FogColor));
            CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0);

            // Specify the buffers we are going to render to.
            CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView);

            CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps);

            CommandList.SetGraphicsRootSignature(_rootSignature);

            var passCBByteSize = D3DUtil.CalcConstantBufferByteSize <PassConstants>();

            // Draw opaque items--floors, walls, skull.
            Resource passCB = CurrFrameResource.PassCB.Resource;

            CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress);
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]);

            // Mark the visible mirror pixels in the stencil buffer with the value 1
            CommandList.StencilReference = 1;
            CommandList.PipelineState    = _psos["markStencilMirrors"];
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Mirrors]);

            // Draw the reflection into the mirror only (only for pixels where the stencil buffer is 1).
            // Note that we must supply a different per-pass constant buffer--one with the lights reflected.
            CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress + passCBByteSize);
            CommandList.PipelineState = _psos["drawStencilReflections"];
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Reflected]);

            // Restore main pass constants and stencil ref.
            CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress);
            CommandList.StencilReference = 0;

            // Draw mirror with transparency so reflection blends through.
            CommandList.PipelineState = _psos["transparent"];
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Transparent]);

            // Draw shadows
            CommandList.PipelineState = _psos["shadow"];
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Shadow]);

            // Indicate a state transition on the resource usage.
            CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present);

            // Done recording commands.
            CommandList.Close();

            // Add the command list to the queue for execution.
            CommandQueue.ExecuteCommandList(CommandList);

            // Present the buffer to the screen. Presenting will automatically swap the back and front buffers.
            SwapChain.Present(0, PresentFlags.None);

            // Advance the fence value to mark commands up to this fence point.
            CurrFrameResource.Fence = ++CurrentFence;

            // Add an instruction to the command queue to set a new fence point.
            // Because we are on the GPU timeline, the new fence point won't be
            // set until the GPU finishes processing all the commands prior to this Signal().
            CommandQueue.Signal(Fence, CurrentFence);
        }
Пример #10
0
 /// <summary>
 /// Present scene to screen
 /// </summary>
 public void Present()
 {
     SwapChain.Present(0, PresentFlags.None);
 }
Пример #11
0
 public override void Present()
 {
     swapChain.Present((int)PresentInterval, PresentFlags.None);
 }
        internal static void Present()
        {
            if (m_swapchain != null)
            {
                GetRenderProfiler().StartProfilingBlock("Screenshot");
                if (m_screenshot.HasValue)
                {
                    if (m_screenshot.Value.SizeMult == VRageMath.Vector2.One)
                    {
                        MyCopyToRT.ClearAlpha(Backbuffer);
                        SaveScreenshotFromResource(Backbuffer.Resource);
                    }
                    else
                    {
                        TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                    }
                }
                GetRenderProfiler().EndProfilingBlock();

                try
                {
                    MyManagers.OnFrameEnd();
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                    GetRenderProfiler().StartProfilingBlock("Waiting for present");
                    m_swapchain.Present(m_settings.VSync ? 1 : 0, 0);
                    GetRenderProfiler().EndProfilingBlock();
                    MyGpuProfiler.IC_EndBlock();

                    MyStatsUpdater.Timestamps.Update(ref MyStatsUpdater.Timestamps.Present, ref MyStatsUpdater.Timestamps.PreviousPresent);

                    if (VRage.OpenVRWrapper.MyOpenVR.Static != null)
                    {
                        MyGpuProfiler.IC_BeginBlock("OpenVR.FrameDone");
                        GetRenderProfiler().StartProfilingBlock("OpenVR.FrameDone");

                        /*var handle=MyOpenVR.GetOverlay("menu");
                         * MyOpenVR.SetOverlayTexture(handle, MyRender11.Backbuffer.m_resource.NativePointer);
                         */
                        VRage.OpenVRWrapper.MyOpenVR.FrameDone();
                        GetRenderProfiler().EndProfilingBlock();
                        MyGpuProfiler.IC_EndBlock();
                    }

                    m_consecutivePresentFails = 0;

                    GetRenderProfiler().StartProfilingBlock("Stopwatch");
                    if (m_presentTimer == null)
                    {
                        m_presentTimer = new Stopwatch();
                    }
                    else
                    {
                        m_presentTimer.Stop();

                        if (m_presentTimes.Count >= PresentTimesStored)
                        {
                            m_presentTimes.Dequeue();
                        }
                        m_presentTimes.Enqueue(m_presentTimer.ElapsedMilliseconds);
                    }

                    m_presentTimer.Restart();
                    GetRenderProfiler().EndProfilingBlock();
                }
                catch (SharpDXException e)
                {
                    Log.WriteLine("Device removed - resetting device; reason: " + e.Message);
                    HandleDeviceReset();
                    Log.WriteLine("Device removed - resetting completed");

                    m_consecutivePresentFails++;

                    if (m_consecutivePresentFails == 5)
                    {
                        Log.WriteLine("Present failed");
                        Log.IncreaseIndent();

                        if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                        {
                            Log.WriteLine("Device removed: " + Device.DeviceRemovedReason);
                        }

                        var timings = "";
                        while (m_presentTimes.Count > 0)
                        {
                            timings += m_presentTimes.Dequeue();
                            if (m_presentTimes.Count > 0)
                            {
                                timings += ", ";
                            }
                        }

                        Log.WriteLine("Last present timings = [ " + timings + " ]");
                        Log.DecreaseIndent();
                    }
                }

                GetRenderProfiler().StartProfilingBlock("GPU profiler");
                MyGpuProfiler.EndFrame();
                MyGpuProfiler.StartFrame();
                m_profilingStarted = true;
                GetRenderProfiler().EndProfilingBlock();

                // waiting for change to fullscreen - window migh overlap or some other dxgi excuse to fail :(
                GetRenderProfiler().StartProfilingBlock("TryChangeToFullscreen");
                TryChangeToFullscreen();
                GetRenderProfiler().EndProfilingBlock();
            }
        }
 /// <summary>
 /// Finish render.
 /// Derived methods must call base.EndRender()
 /// </summary>
 protected virtual void EndRender()
 {
     _swapChain.Present(0, PresentFlags.None);
 }
Пример #14
0
        /// <summary>
        /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling (anti-aliasing)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="syncInterval"></param>
        /// <param name="flags"></param>
        /// <returns>The HRESULT of the original method</returns>
        int PresentHook(IntPtr swapChainPtr, int syncInterval, SlimDX.DXGI.PresentFlags flags)
        {
            if (swapChainPtr != _swapChainPointer)
            {
                _swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr);
            }
            SwapChain swapChain = _swapChain;

            //using (SlimDX.DXGI.SwapChain swapChain = SlimDX.DXGI.SwapChain.FromPointer(swapChainPtr))
            {
                try
                {
                    #region Screenshot Request
                    if (this.Request != null)
                    {
                        this.DebugMessage("PresentHook: Request Start");
                        DateTime startTime = DateTime.Now;
                        using (Texture2D texture = Texture2D.FromSwapChain <Texture2D>(swapChain, 0))
                        {
                            #region Determine region to capture
                            System.Drawing.Rectangle regionToCapture = new System.Drawing.Rectangle(0, 0, texture.Description.Width, texture.Description.Height);

                            //if (this.Request.RegionToCapture.Width > 0)
                            //{
                            //    regionToCapture = this.Request.RegionToCapture;
                            //}
                            #endregion

                            var theTexture = texture;

                            // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture
                            Texture2D textureResolved = null;
                            if (texture.Description.SampleDescription.Count > 1)
                            {
                                this.DebugMessage("PresentHook: resolving multi-sampled texture");
                                // texture is multi-sampled, lets resolve it down to single sample
                                textureResolved = new Texture2D(texture.Device, new Texture2DDescription()
                                {
                                    CpuAccessFlags    = CpuAccessFlags.None,
                                    Format            = texture.Description.Format,
                                    Height            = texture.Description.Height,
                                    Usage             = ResourceUsage.Default,
                                    Width             = texture.Description.Width,
                                    ArraySize         = 1,
                                    SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // Ensure single sample
                                    BindFlags         = BindFlags.None,
                                    MipLevels         = 1,
                                    OptionFlags       = texture.Description.OptionFlags
                                });
                                // Resolve into textureResolved
                                texture.Device.ImmediateContext.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format);

                                // Make "theTexture" be the resolved texture
                                theTexture = textureResolved;
                            }

                            // Create destination texture
                            Texture2D textureDest = new Texture2D(texture.Device, new Texture2DDescription()
                            {
                                CpuAccessFlags    = CpuAccessFlags.None,                     // CpuAccessFlags.Write | CpuAccessFlags.Read,
                                Format            = SlimDX.DXGI.Format.R8G8B8A8_UNorm,       // Supports BMP/PNG
                                Height            = regionToCapture.Height,
                                Usage             = ResourceUsage.Default,                   // ResourceUsage.Staging,
                                Width             = regionToCapture.Width,
                                ArraySize         = 1,                                       //texture.Description.ArraySize,
                                SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0), // texture.Description.SampleDescription,
                                BindFlags         = BindFlags.None,
                                MipLevels         = 1,                                       //texture.Description.MipLevels,
                                OptionFlags       = texture.Description.OptionFlags
                            });

                            // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index
                            theTexture.Device.ImmediateContext.CopySubresourceRegion(theTexture, 0, new ResourceRegion()
                            {
                                Top    = regionToCapture.Top,
                                Bottom = regionToCapture.Bottom,
                                Left   = regionToCapture.Left,
                                Right  = regionToCapture.Right,
                                Front  = 0,
                                Back   = 1 // Must be 1 or only black will be copied
                            }, textureDest, 0, 0, 0, 0);

                            // Note: it would be possible to capture multiple frames and process them in a background thread

                            // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline
                            Guid   requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread
                            String FileName  = this.Request.FileName;

                            //int width = textureDest.Description.Width;
                            //int height = textureDest.Description.Height;


                            //if (bitmap != null)
                            //{
                            //    bitmap.Dispose();
                            //    bitmap = null;
                            //}

                            /*if (bitmap == null)
                             * {
                             *  bitmap = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
                             * }*/


                            /*Surface s=textureDest.AsSurface();
                             * DataRectangle r=s.Map();
                             *
                             *
                             *
                             *              //Bitmap bitmap = new Bitmap(width, height, 4 * width, PixelFormat.Format32bppRgb, stream.DataPointer);
                             *
                             *
                             */
                            //using (MemoryStream ms = new MemoryStream())
                            //{
                            //    Texture2D.ToStream(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Bmp, ms);
                            //    ms.Position = 0;
                            //    bitmap = new Bitmap(ms);
                            //}
                            //Texture2D.ToFile(textureDest.Device.ImmediateContext, textureDest, GetImageFileFormat(this.Request.Format), FileName);
                            Texture2D.ToFile(textureDest.Device.ImmediateContext, textureDest, GetImageFileFormat(this.Request.Format), PrepareFile(this.Request.FileName));



                            textureDest.Dispose();
                            textureDest = null;
                            //ImageFormat f = Request.ImageFormat;
                            //bitmap.Save(Request.FileName, GetImageFormat(Request.Format));
                            //SaveFile();

                            this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString());

                            //ThreadPool.QueueUserWorkItem(delegate
                            //{
                            //    //FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create);
                            //    //Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs);

                            //    DateTime startCopyToSystemMemory = DateTime.Now;
                            //    using (MemoryStream ms = new MemoryStream())
                            //    {
                            //        //Texture2D.ToStream(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Bmp, ms);
                            //        //ms.Position = 0;
                            //        Texture2D.ToFile(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Jpg, FileName);
                            //        this.DebugMessage("PresentHook: Copy to File time: " + (DateTime.Now - startCopyToSystemMemory).ToString());

                            //        //DateTime startSendResponse = DateTime.Now;
                            //        //SendResponse(ms, requestId);
                            //        //this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString());
                            //    }

                            //    // Free the textureDest as we no longer need it.
                            //    textureDest.Dispose();
                            //    textureDest = null;
                            //    this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString());
                            //});

                            // Prevent the request from being processed a second time
                            this.Request = null;

                            // Make sure we free up the resolved texture if it was created
                            if (textureResolved != null)
                            {
                                textureResolved.Dispose();
                                textureResolved = null;
                            }
                        }
                        //this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString());
                        //this.DebugMessage("PresentHook: Request End");
                    }
                    #endregion

                    #region TODO: Draw overlay (after screenshot so we don't capture overlay as well)
                    if (this.ShowOverlay)
                    {
                        // Note: Direct3D 11 doesn't have font support, so I believe the approach is to use
                        //       a Direct3D 10.1 device with Direct2d, render to a texture, and then blend
                        //       this into the Direct3D 11 backbuffer - hmm sounds like fun.
                        // http://forums.create.msdn.com/forums/t/38961.aspx
                        // http://www.gamedev.net/topic/547920-how-to-use-d2d-with-d3d11/
                    }
                    #endregion
                }
                catch (Exception e)
                {
                    // If there is an error we do not want to crash the hooked application, so swallow the exception
                    this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.ToString());
                    //return unchecked((int)0x8000FFFF); //E_UNEXPECTED
                }

                // As always we need to call the original method, note that EasyHook has already repatched the original method
                // so calling it here will not cause an endless recursion to this function
                return(swapChain.Present(syncInterval, flags).Code);
            }
        }
Пример #15
0
        public static void Render()
        {
            // initial directx before
            InitialDirectX();
            // call render loop
            RenderLoop.Run(renderForm, () =>
            {
                if (renderForm.WindowState == FormWindowState.Minimized)
                {
                    return;
                }

                try
                {
                    Culc();
                    // clear all data in graphic card
                    renderTarget.BeginDraw();
                    renderTarget.Transform = Matrix3x2.Identity;
                    renderTarget.Clear(SharpDX.Color.White);

                    // ---- begin draw ----
                    InvalidatePictureBox();
                    using (var brush = new SolidColorBrush(renderTarget, SharpDX.Color.Black))
                    {
                        renderTarget.DrawText("Слитков золота найден: " + (5 - items.Count), textFormat, new RawRectangleF(650, 15, renderTarget.Size.Width, renderTarget.Size.Height), brush);
                        if (items.Count != 0)
                        {
                            renderTarget.DrawText("Найдите 5\nслитков золота", textFormat, new RawRectangleF(650, 410, renderTarget.Size.Width, renderTarget.Size.Height), brush);
                        }
                        if (items.Count == 0 && Math.Abs(exit.Position.X - player.X) < 40 && Math.Abs(exit.Position.Y - player.Y) < 40)
                        {
                            renderTarget.DrawText("Вы победили!", textFormat, new RawRectangleF(650, 410, renderTarget.Size.Width, renderTarget.Size.Height), brush);
                        }
                        else if (items.Count == 0)
                        {
                            renderTarget.DrawText("Найдите выход!.", textFormat, new RawRectangleF(650, 410, renderTarget.Size.Width, renderTarget.Size.Height), brush);
                        }
                    }
                    // ---- end draw ----
                    try
                    {
                        renderTarget.Flush();
                    }
                    catch (SharpDXException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    renderTarget.EndDraw();
                    swapChain.Present(0, PresentFlags.None);
                }
                catch (Exception ex)
                {
                    renderForm.Close();
                }
            });

            swapChain.IsFullScreen = false;
            textFormat.Dispose();
            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();
        }
Пример #16
0
        public override void DrawScene()
        {
            ImmediateContext.Rasterizer.State = null;

            ImmediateContext.ClearDepthStencilView(
                DepthStencilView,
                DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil,
                1.0f, 0
                );
            ImmediateContext.Rasterizer.SetViewports(Viewport);

            _ssao.SetNormalDepthRenderTarget(DepthStencilView);

            DrawSceneToSsaoNormalDepthMap();

            _ssao.ComputeSsao(_camera);
            _ssao.BlurAmbientMap(4);


            ImmediateContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
            ImmediateContext.Rasterizer.SetViewports(Viewport);

            ImmediateContext.ClearRenderTargetView(RenderTargetView, Color.Silver);
            ImmediateContext.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);

            var viewProj = _camera.ViewProj;
            var view     = _camera.View;
            var proj     = _camera.Proj;

            Effects.BasicFX.SetDirLights(_dirLights);
            Effects.BasicFX.SetEyePosW(_camera.Position);
            //Effects.BasicFX.SetCubeMap(_sky.CubeMapSRV);

            Effects.NormalMapFX.SetDirLights(_dirLights);
            Effects.NormalMapFX.SetEyePosW(_camera.Position);
            //Effects.NormalMapFX.SetCubeMap(_sky.CubeMapSRV);

            if (!Util.IsKeyDown(Keys.S))
            {
                Effects.BasicFX.SetSsaoMap(_ssao.AmbientSRV);
                Effects.NormalMapFX.SetSsaoMap(_ssao.AmbientSRV);
            }
            else
            {
                Effects.BasicFX.SetSsaoMap(_texMgr.CreateTexture("Textures/white.dds"));
                Effects.NormalMapFX.SetSsaoMap(_texMgr.CreateTexture("Textures/white.dds"));
            }
            var toTexSpace = Matrix.Scaling(0.5f, -0.5f, 1.0f) * Matrix.Translation(0.5f, 0.5f, 0);

            var activeTech       = Effects.NormalMapFX.Light3Tech;
            var activeSphereTech = Effects.BasicFX.Light3ReflectTech;
            var activeSkullTech  = Effects.BasicFX.Light3ReflectTech;

            ImmediateContext.InputAssembler.InputLayout       = InputLayouts.PosNormalTexTan;
            ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            if (Util.IsKeyDown(Keys.W))
            {
                ImmediateContext.Rasterizer.State = RenderStates.WireframeRS;
            }
            for (var p = 0; p < activeTech.Description.PassCount; p++)
            {
                // draw grid
                var pass = activeTech.GetPassByIndex(p);
                _grid.ToTexSpace = toTexSpace;
                _grid.Draw(ImmediateContext, pass, view, proj);
                // draw box
                _box.ToTexSpace = toTexSpace;
                _box.Draw(ImmediateContext, pass, view, proj);

                // draw columns
                foreach (var cylinder in _cylinders)
                {
                    cylinder.ToTexSpace = toTexSpace;
                    cylinder.Draw(ImmediateContext, pass, view, proj);
                }
            }
            ImmediateContext.HullShader.Set(null);
            ImmediateContext.DomainShader.Set(null);
            ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            for (var p = 0; p < activeSphereTech.Description.PassCount; p++)
            {
                var pass = activeSphereTech.GetPassByIndex(p);

                foreach (var sphere in _spheres)
                {
                    sphere.ToTexSpace = toTexSpace;
                    sphere.Draw(ImmediateContext, pass, view, proj, RenderMode.Basic);
                }
            }

            ImmediateContext.Rasterizer.State = null;

            ImmediateContext.InputAssembler.InputLayout = InputLayouts.Basic32;

            for (var p = 0; p < activeSkullTech.Description.PassCount; p++)
            {
                _skull.ToTexSpace = toTexSpace;
                _skull.Draw(ImmediateContext, activeSkullTech.GetPassByIndex(p), view, proj, RenderMode.Basic);
            }
            ImmediateContext.OutputMerger.DepthStencilState     = null;
            ImmediateContext.OutputMerger.DepthStencilReference = 0;

            DrawScreenQuad(_ssao.AmbientSRV);
            DrawScreenQuad2(_ssao.NormalDepthSRV);

            _sky.Draw(ImmediateContext, _camera);

            ImmediateContext.Rasterizer.State = null;
            ImmediateContext.OutputMerger.DepthStencilState     = null;
            ImmediateContext.OutputMerger.DepthStencilReference = 0;

            var srvs = new List <ShaderResourceView>();

            for (var i = 0; i < 16; i++)
            {
                srvs.Add(null);
            }

            ImmediateContext.PixelShader.SetShaderResources(srvs.ToArray(), 0, 16);

            SwapChain.Present(0, PresentFlags.None);
        }
Пример #17
0
        static void Main()
        {
            for (int i = 0; i < Diagnostics.Length; i++)
            {
                Diagnostics[i] = 0;
            }
            // Create render target window
            form = new RenderForm();
            form.StartPosition = FormStartPosition.CenterScreen;
            form.ClientSize    = new System.Drawing.Size(160 * 4, 144 * 4);

            form.WindowState = FormWindowState.Minimized;
            form.Show();
            form.Focus();
            form.WindowState = FormWindowState.Normal;


            // Create swap chain description
            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(160, 144, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            // Create swap chain and Direct3D device
            // The BgraSupport flag is needed for Direct2D compatibility otherwise new RenderTarget() will fail!
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, swapChainDesc, out Device device, out swapChain);

            // Get back buffer in a Direct2D-compatible format (DXGI surface)
            backBuffer = Surface.FromSwapChain(swapChain, 0);

            // Create Direct2D factory
            using (var factory = new FactoryD2D()) {
                var dpi = factory.DesktopDpi;

                // Create bitmap render target from DXGI surface
                renderTarget = new RenderTarget(factory, backBuffer, new RenderTargetProperties()
                {
                    DpiX        = 0,
                    DpiY        = 0,
                    MinLevel    = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT,
                    PixelFormat = new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Ignore),
                    Type        = RenderTargetType.Hardware,
                    Usage       = RenderTargetUsage.None
                });
            }

            backBufferBMP = new Bitmap(renderTarget, new Size2(160, 144), new BitmapProperties(renderTarget.PixelFormat));


            Color[] palette = new Color[4];
            palette[0] = Color.White;
            palette[1] = Color.LightGray;
            palette[2] = Color.DarkGray;
            palette[3] = Color.Black;

            Color[] bitmap = new Color[160 * 144];



            while (true)
            {
                STOP = false;
                OpenFileDialog of = new OpenFileDialog {
                    Filter           = "Game Boy Files (*.gb)|*.gb|Game Boy Color Files (*.gbc)|*.gbc",
                    RestoreDirectory = true
                };
                of.ShowDialog();
                DMGBoard Board = DMGBoard.Builder(of.FileName);

                AddKeyListeners(form, Board);
                Debugger d = new Debugger(Board);
                //d.Show();
                //Application.Run();

                RenderLoop rl = new RenderLoop(form);
                while (rl.NextFrame() && !STOP)
                {
                    int[] temp = Board.RunOneFrame();
                    for (int i = 0; i < temp.Length; i++)
                    {
                        bitmap[i] = palette[temp[i]];
                    }

                    renderTarget.BeginDraw();
                    renderTarget.Transform = Matrix3x2.Identity;
                    renderTarget.Clear(Color.Black);
                    backBufferBMP.CopyFromMemory(bitmap, 160 * 4);
                    renderTarget.DrawBitmap(backBufferBMP, 1f, BitmapInterpolationMode.NearestNeighbor);

                    renderTarget.EndDraw();
                    swapChain.Present(1, PresentFlags.Restart);
                }
                d.Dispose();
            }

            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();



            //Application.Run();
        }
Пример #18
0
 public void SwapBuffers()
 {
     swapChain.Present(syncInterval, PresentFlags.None);
 }
Пример #19
0
        protected override void Draw(GameTimer gt)
        {
            CommandAllocator cmdListAlloc = CurrFrameResource.CmdListAlloc;

            // Reuse the memory associated with command recording.
            // We can only reset when the associated command lists have finished execution on the GPU.
            cmdListAlloc.Reset();

            // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
            // Reusing the command list reuses memory.
            CommandList.Reset(cmdListAlloc, _psos["opaque"]);

            CommandList.SetViewport(Viewport);
            CommandList.SetScissorRectangles(ScissorRectangle);

            // Indicate a state transition on the resource usage.
            CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.Present, ResourceStates.RenderTarget);

            // Clear the back buffer and depth buffer.
            CommandList.ClearRenderTargetView(CurrentBackBufferView, new Color(_mainPassCB.FogColor));
            CommandList.ClearDepthStencilView(DepthStencilView, ClearFlags.FlagsDepth | ClearFlags.FlagsStencil, 1.0f, 0);

            // Specify the buffers we are going to render to.
            CommandList.SetRenderTargets(CurrentBackBufferView, DepthStencilView);

            CommandList.SetDescriptorHeaps(_descriptorHeaps.Length, _descriptorHeaps);

            CommandList.SetGraphicsRootSignature(_rootSignature);

            Resource passCB = CurrFrameResource.PassCB.Resource;

            CommandList.SetGraphicsRootConstantBufferView(2, passCB.GPUVirtualAddress);
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Opaque]);

            CommandList.PipelineState = _psos["alphaTested"];
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.AlphaTested]);

            CommandList.PipelineState = _psos["treeSprites"];
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.AlphaTestedTreeSprites]);

            CommandList.PipelineState = _psos["transparent"];
            DrawRenderItems(CommandList, _ritemLayers[RenderLayer.Transparent]);

            // Indicate a state transition on the resource usage.
            CommandList.ResourceBarrierTransition(CurrentBackBuffer, ResourceStates.RenderTarget, ResourceStates.Present);

            // Done recording commands.
            CommandList.Close();

            // Add the command list to the queue for execution.
            CommandQueue.ExecuteCommandList(CommandList);

            // Present the buffer to the screen. Presenting will automatically swap the back and front buffers.
            SwapChain.Present(0, PresentFlags.None);

            // Advance the fence value to mark commands up to this fence point.
            CurrFrameResource.Fence = ++CurrentFence;

            // Add an instruction to the command queue to set a new fence point.
            // Because we are on the GPU timeline, the new fence point won't be
            // set until the GPU finishes processing all the commands prior to this Signal().
            CommandQueue.Signal(Fence, CurrentFence);
        }
Пример #20
0
        internal static void Present()
        {
            if (m_swapchain != null)
            {
                GetRenderProfiler().StartProfilingBlock("Screenshot");
                if (m_screenshot.HasValue)
                {
                    if (m_screenshot.Value.SizeMult == VRageMath.Vector2.One)
                    {
                        MyCopyToRT.ClearAlpha(Backbuffer);
                        SaveScreenshotFromResource(Backbuffer);
                    }
                    else
                    {
                        TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                    }
                }
                GetRenderProfiler().EndProfilingBlock();

                try
                {
                    MyManagers.OnFrameEnd();
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                    GetRenderProfiler().StartProfilingBlock("Waiting for present");
                    m_swapchain.Present(m_settings.VSync ? 1 : 0, 0);
                    GetRenderProfiler().EndProfilingBlock();
                    MyGpuProfiler.IC_EndBlock();

                    MyStatsUpdater.Timestamps.Update(ref MyStatsUpdater.Timestamps.Present, ref MyStatsUpdater.Timestamps.PreviousPresent);

                    MyManagers.OnUpdate();

                    if (VRage.OpenVRWrapper.MyOpenVR.Static != null)
                    {
                        MyGpuProfiler.IC_BeginBlock("OpenVR.FrameDone");
                        GetRenderProfiler().StartProfilingBlock("OpenVR.FrameDone");

                        /*var handle=MyOpenVR.GetOverlay("menu");
                         * MyOpenVR.SetOverlayTexture(handle, MyRender11.Backbuffer.m_resource.NativePointer);
                         */
                        VRage.OpenVRWrapper.MyOpenVR.FrameDone();
                        GetRenderProfiler().EndProfilingBlock();
                        MyGpuProfiler.IC_EndBlock();
                    }
                }
                catch (SharpDXException e)
                {
                    Log.WriteLine("Graphics device error! Reason:\n" + e.Message);

                    if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                    {
                        Log.WriteLine("Device removed reason:\n" + Device.DeviceRemovedReason);
                    }

                    Log.WriteLine("Exception stack trace:\n" + e.StackTrace);

                    StringBuilder sb = new StringBuilder();

                    foreach (var column in MyRenderStats.m_stats.Values)
                    {
                        foreach (var stats in column)
                        {
                            sb.Clear();
                            stats.WriteTo(sb);
                            Log.WriteLine(sb.ToString());
                        }
                    }

                    MyStatsUpdater.UpdateStats();
                    MyStatsDisplay.WriteTo(sb);
                    Log.WriteLine(sb.ToString());

                    throw;
                }

                GetRenderProfiler().StartProfilingBlock("GPU profiler");
                MyGpuProfiler.EndFrame();
                MyGpuProfiler.StartFrame();
                GetRenderProfiler().EndProfilingBlock();

                // waiting for change to fullscreen - window migh overlap or some other dxgi excuse to fail :(
                GetRenderProfiler().StartProfilingBlock("TryChangeToFullscreen");
                TryChangeToFullscreen();
                GetRenderProfiler().EndProfilingBlock();
            }
        }
Пример #21
0
 public void EndScene()
 {
     swapChain.Present(vSyncEnabled ? 1 : 0, PresentFlags.None);
 }
Пример #22
0
 protected override void EndDraw()
 {
     SwapChain.Present(Configuration.WaitVerticalBlanking ? 1 : 0, PresentFlags.None);
 }
Пример #23
0
 protected virtual void EndFrame()
 {
     Sprite.Flush();
     SwapChain.Present(0, PresentFlags.None);
 }
Пример #24
0
 public void Present()
 {
     swapChain.Present(1, PresentFlags.None);
     //swapChain.Present(1, PresentFlags.None, new PresentParameters());
 }
Пример #25
0
		public void Present()
		{
			swapChain?.Present(0, PresentFlags.None);
		}
Пример #26
0
        private void InitializeOculus()
        {
            RenderForm form = new RenderForm("OculusWrap SharpDX demo");

			Wrap	oculus	= new Wrap();
			Hmd		hmd;

            form.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Window_KeyUp);

            //form.moused

            //form.Activate();
            //form.Show();

            int textureWidth = 0, textureHeight = 0;
            newTextureArrived = false;

            //zoom == 2 is not implemented, because the visual quality would be too low.
            //zoom == 4 will be implemented in the future.
            if (zoom == 3)
            {
                textureWidth = 3328;
                textureHeight = 1664;
            }

            bool success = oculus.Initialize();
            if (!success)
            {
                System.Windows.Forms.MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Use the head mounted display, if it's available, otherwise use the debug HMD.
            int numberOfHeadMountedDisplays = oculus.Hmd_Detect();
            if (numberOfHeadMountedDisplays > 0)
                hmd = oculus.Hmd_Create(0);
            else
                hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2);

            if (hmd == null)
            {
                System.Windows.Forms.MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (hmd.ProductName == string.Empty)
                System.Windows.Forms.MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error);

            // Specify which head tracking capabilities to enable.
            hmd.SetEnabledCaps(OVR.HmdCaps.LowPersistence | OVR.HmdCaps.DynamicPrediction);

            // Start the sensor which informs of the Rift's pose and motion
            hmd.ConfigureTracking(OVR.TrackingCaps.ovrTrackingCap_Orientation | OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OVR.TrackingCaps.ovrTrackingCap_Position, OVR.TrackingCaps.None);

            // Create a set of layers to submit.
            EyeTexture[] eyeTextures = new EyeTexture[2];
            OVR.ovrResult result;

            // Create DirectX drawing device.
            SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug);

            // Create DirectX Graphics Interface factory, used to create the swap chain.
            Factory factory = new Factory();

            DeviceContext immediateContext = device.ImmediateContext;

            // Define the properties of the swap chain.
            SwapChainDescription swapChainDescription = new SwapChainDescription();
            swapChainDescription.BufferCount = 1;
            swapChainDescription.IsWindowed = true;
            swapChainDescription.OutputHandle = form.Handle;
            swapChainDescription.SampleDescription = new SampleDescription(1, 0);
            swapChainDescription.Usage = Usage.RenderTargetOutput | Usage.ShaderInput;
            swapChainDescription.SwapEffect = SwapEffect.Sequential;
            swapChainDescription.Flags = SwapChainFlags.AllowModeSwitch;
            swapChainDescription.ModeDescription.Width = form.Width;
            swapChainDescription.ModeDescription.Height = form.Height;
            swapChainDescription.ModeDescription.Format = Format.R8G8B8A8_UNorm;
            swapChainDescription.ModeDescription.RefreshRate.Numerator = 0;
            swapChainDescription.ModeDescription.RefreshRate.Denominator = 1;

            // Create the swap chain.
            SharpDX.DXGI.SwapChain swapChain = new SwapChain(factory, device, swapChainDescription);

            // Retrieve the back buffer of the swap chain.
            Texture2D backBuffer = swapChain.GetBackBuffer<Texture2D>(0);
            RenderTargetView backBufferRenderTargetView = new RenderTargetView(device, backBuffer);

            // Create a depth buffer, using the same width and height as the back buffer.
            Texture2DDescription depthBufferDescription = new Texture2DDescription();
            depthBufferDescription.Format = Format.D32_Float;
            depthBufferDescription.ArraySize = 1;
            depthBufferDescription.MipLevels = 1;
            depthBufferDescription.Width = form.Width;
            depthBufferDescription.Height = form.Height;
            depthBufferDescription.SampleDescription = new SampleDescription(1, 0);
            depthBufferDescription.Usage = ResourceUsage.Default;
            depthBufferDescription.BindFlags = BindFlags.DepthStencil;
            depthBufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            depthBufferDescription.OptionFlags = ResourceOptionFlags.None;

            // Define how the depth buffer will be used to filter out objects, based on their distance from the viewer.
            DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription();
            depthStencilStateDescription.IsDepthEnabled = true;
            depthStencilStateDescription.DepthComparison = Comparison.Less;
            depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero;

            // Create the depth buffer.
            Texture2D depthBuffer = new Texture2D(device, depthBufferDescription);
            DepthStencilView depthStencilView = new DepthStencilView(device, depthBuffer);
            DepthStencilState depthStencilState = new DepthStencilState(device, depthStencilStateDescription);
            Viewport viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f);

            immediateContext.OutputMerger.SetDepthStencilState(depthStencilState);
            immediateContext.OutputMerger.SetRenderTargets(depthStencilView, backBufferRenderTargetView);
            immediateContext.Rasterizer.SetViewport(viewport);

            // Retrieve the DXGI device, in order to set the maximum frame latency.
            using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>())
            {
                dxgiDevice.MaximumFrameLatency = 1;
            }

            Layers layers = new Layers();
            LayerEyeFov layerEyeFov = layers.AddLayerEyeFov();

            for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
            {
                OVR.EyeType eye = (OVR.EyeType)eyeIndex;
                EyeTexture eyeTexture = new EyeTexture();
                eyeTextures[eyeIndex] = eyeTexture;

                // Retrieve size and position of the texture for the current eye.
                eyeTexture.FieldOfView = hmd.DefaultEyeFov[eyeIndex];
                eyeTexture.TextureSize = hmd.GetFovTextureSize(eye, hmd.DefaultEyeFov[eyeIndex], 1.0f);
                eyeTexture.RenderDescription = hmd.GetRenderDesc(eye, hmd.DefaultEyeFov[eyeIndex]);
                eyeTexture.HmdToEyeViewOffset = eyeTexture.RenderDescription.HmdToEyeViewOffset;
                eyeTexture.ViewportSize.Position = new OVR.Vector2i(0, 0);
                eyeTexture.ViewportSize.Size = eyeTexture.TextureSize;
                eyeTexture.Viewport = new Viewport(0, 0, eyeTexture.TextureSize.Width, eyeTexture.TextureSize.Height, 0.0f, 1.0f);

                // Define a texture at the size recommended for the eye texture.
                eyeTexture.Texture2DDescription = new Texture2DDescription();
                eyeTexture.Texture2DDescription.Width = eyeTexture.TextureSize.Width;
                eyeTexture.Texture2DDescription.Height = eyeTexture.TextureSize.Height;
                eyeTexture.Texture2DDescription.ArraySize = 1;
                eyeTexture.Texture2DDescription.MipLevels = 1;
                eyeTexture.Texture2DDescription.Format = Format.R8G8B8A8_UNorm;
                eyeTexture.Texture2DDescription.SampleDescription = new SampleDescription(1, 0);
                eyeTexture.Texture2DDescription.Usage = ResourceUsage.Default;
                eyeTexture.Texture2DDescription.CpuAccessFlags = CpuAccessFlags.None;
                eyeTexture.Texture2DDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget;

                // Convert the SharpDX texture description to the native Direct3D texture description.
                OVR.D3D11.D3D11_TEXTURE2D_DESC swapTextureDescriptionD3D11 = SharpDXHelpers.CreateTexture2DDescription(eyeTexture.Texture2DDescription);

                // Create a SwapTextureSet, which will contain the textures to render to, for the current eye.
                result = hmd.CreateSwapTextureSetD3D11(device.NativePointer, ref swapTextureDescriptionD3D11, out eyeTexture.SwapTextureSet);
                WriteErrorDetails(oculus, result, "Failed to create swap texture set.");

                // Create room for each DirectX texture in the SwapTextureSet.
                eyeTexture.Textures = new Texture2D[eyeTexture.SwapTextureSet.TextureCount];
                eyeTexture.RenderTargetViews = new RenderTargetView[eyeTexture.SwapTextureSet.TextureCount];

                // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet.
                for (int textureIndex = 0; textureIndex < eyeTexture.SwapTextureSet.TextureCount; textureIndex++)
                {
                    // Retrieve the current textureData object.
                    OVR.D3D11.D3D11TextureData textureData = eyeTexture.SwapTextureSet.Textures[textureIndex];

                    // Create a managed Texture2D, based on the unmanaged texture pointer.
                    eyeTexture.Textures[textureIndex] = new Texture2D(textureData.Texture);

                    // Create a render target view for the current Texture2D.
                    eyeTexture.RenderTargetViews[textureIndex] = new RenderTargetView(device, eyeTexture.Textures[textureIndex]);
                }

                // Define the depth buffer, at the size recommended for the eye texture.
                eyeTexture.DepthBufferDescription = new Texture2DDescription();
                eyeTexture.DepthBufferDescription.Format = Format.D32_Float;
                eyeTexture.DepthBufferDescription.Width = eyeTexture.TextureSize.Width;
                eyeTexture.DepthBufferDescription.Height = eyeTexture.TextureSize.Height;
                eyeTexture.DepthBufferDescription.ArraySize = 1;
                eyeTexture.DepthBufferDescription.MipLevels = 1;
                eyeTexture.DepthBufferDescription.SampleDescription = new SampleDescription(1, 0);
                eyeTexture.DepthBufferDescription.Usage = ResourceUsage.Default;
                eyeTexture.DepthBufferDescription.BindFlags = BindFlags.DepthStencil;
                eyeTexture.DepthBufferDescription.CpuAccessFlags = CpuAccessFlags.None;
                eyeTexture.DepthBufferDescription.OptionFlags = ResourceOptionFlags.None;

                // Create the depth buffer.
                eyeTexture.DepthBuffer = new Texture2D(device, eyeTexture.DepthBufferDescription);
                eyeTexture.DepthStencilView = new DepthStencilView(device, eyeTexture.DepthBuffer);

                // Specify the texture to show on the HMD.
                layerEyeFov.ColorTexture[eyeIndex] = eyeTexture.SwapTextureSet.SwapTextureSetPtr;
                layerEyeFov.Viewport[eyeIndex].Position = new OVR.Vector2i(0, 0);
                layerEyeFov.Viewport[eyeIndex].Size = eyeTexture.TextureSize;
                layerEyeFov.Fov[eyeIndex] = eyeTexture.FieldOfView;
                layerEyeFov.Header.Flags = OVR.LayerFlags.TextureOriginAtBottomLeft;
            }

            // Define the texture used to display the rendered result on the computer monitor.
            Texture2DDescription mirrorTextureDescription = new Texture2DDescription();
            mirrorTextureDescription.Width = form.Width;
            mirrorTextureDescription.Height = form.Height;
            mirrorTextureDescription.ArraySize = 1;
            mirrorTextureDescription.MipLevels = 1;
            mirrorTextureDescription.Format = Format.R8G8B8A8_UNorm;
            mirrorTextureDescription.SampleDescription = new SampleDescription(1, 0);
            mirrorTextureDescription.Usage = ResourceUsage.Default;
            mirrorTextureDescription.CpuAccessFlags = CpuAccessFlags.None;
            mirrorTextureDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget;

            SamplerStateDescription samplerStateDescription = new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.Anisotropic
            };

            RasterizerStateDescription rasterizerStateDescription = RasterizerStateDescription.Default();
            rasterizerStateDescription.IsFrontCounterClockwise = true;

            // Convert the SharpDX texture description to the native Direct3D texture description.
            OVR.D3D11.D3D11_TEXTURE2D_DESC mirrorTextureDescriptionD3D11 = SharpDXHelpers.CreateTexture2DDescription(mirrorTextureDescription);

            OculusWrap.D3D11.MirrorTexture mirrorTexture;

            // Create the texture used to display the rendered result on the computer monitor.
            result = hmd.CreateMirrorTextureD3D11(device.NativePointer, ref mirrorTextureDescriptionD3D11, out mirrorTexture);
            WriteErrorDetails(oculus, result, "Failed to create mirror texture.");

            Texture2D mirrorTextureD3D11 = new Texture2D(mirrorTexture.Texture.Texture);

            #region Vertex and pixel shader
            // Create vertex shader.
            ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderMain", "vs_4_0");
            VertexShader vertexShader = new VertexShader(device, vertexShaderByteCode);

            // Create pixel shader.
            ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderMain", "ps_4_0");
            PixelShader pixelShader = new PixelShader(device, pixelShaderByteCode);

            ShaderSignature shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);



            Texture2D myTexture = new Texture2D(device, new Texture2DDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                ArraySize = 1,
                MipLevels = 1,
                Width = textureWidth,
                Height = textureHeight,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
            });


            ShaderResourceView textureView = new ShaderResourceView(device, myTexture);


            //set sampler for texture
            SamplerState samplerState = new SamplerState(device, samplerStateDescription);

            //initialize rasterizer
            RasterizerState rasterizerState = new RasterizerState(device, rasterizerStateDescription);

            // Specify that each vertex consists of a single vertex position and color.

            int[] indices = null;
            Vertex[] vertices = null;
            CreateGeometry(out indices, out vertices);

            InputElement[] inputElements = new InputElement[]
            {
                new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),
                /*new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),*/
            };

            // Define an input layout to be passed to the vertex shader.
            InputLayout inputLayout = new InputLayout(device, shaderSignature, inputElements);

            // Create a vertex buffer, containing our 3D model.
            Buffer vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, vertices);//m_vertices);

            // Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader.
            Buffer constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            Buffer indexBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.IndexBuffer, indices);

            // Setup the immediate context to use the shaders and model we defined.
            immediateContext.InputAssembler.InputLayout = inputLayout;
            immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            immediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0));
            immediateContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);

            immediateContext.VertexShader.SetConstantBuffer(0, constantBuffer);

            immediateContext.VertexShader.Set(vertexShader);
            immediateContext.PixelShader.Set(pixelShader);

            immediateContext.PixelShader.SetShaderResource(0, textureView);
            immediateContext.PixelShader.SetSampler(0, samplerState);
            #endregion

            DateTime startTime = DateTime.Now;
            Vector3 position = new Vector3(0, 0, 0);

            oculusReady = true;

            #region Render loop
            RenderLoop.Run(form, () =>
            {
                OVR.Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset };
                OVR.FrameTiming frameTiming = hmd.GetFrameTiming(0);
                OVR.TrackingState trackingState = hmd.GetTrackingState(frameTiming.DisplayMidpointSeconds);
                OVR.Posef[] eyePoses = new OVR.Posef[2];

                // Calculate the position and orientation of each eye.
                oculus.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses);

                float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds;

                for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
                {
                    OVR.EyeType eye = (OVR.EyeType)eyeIndex;
                    EyeTexture eyeTexture = eyeTextures[eyeIndex];

                    layerEyeFov.RenderPose[eyeIndex] = eyePoses[eyeIndex];

                    // Retrieve the index of the active texture and select the next texture as being active next.
                    int textureIndex = eyeTexture.SwapTextureSet.CurrentIndex++;

                    immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]);
                    immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black);
                    immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                    immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport);
                    //added a custom rasterizer
                    immediateContext.Rasterizer.State = rasterizerState;

                    // Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction.
                    Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation);
                    Matrix rotationMatrix = Matrix.RotationQuaternion(rotationQuaternion);
                    Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3();
                    Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3();

                    Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3();

                    //use this to get the first rotation to goal
                    Matrix world = Matrix.Scaling(1.0f) /** Matrix.RotationX(timeSinceStart*0.2f) */* Matrix.RotationY(timeSinceStart * 2 / 10f) /** Matrix.RotationZ(timeSinceStart*3/10f)*/;
                    Matrix viewMatrix = Matrix.LookAtRH(viewPosition, viewPosition + lookAt, lookUp);

                    Matrix projectionMatrix = OVR.ovrMatrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 10.0f, OVR.ProjectionModifier.None).ToMatrix();
                    projectionMatrix.Transpose();

                    Matrix worldViewProjection = world * viewMatrix * projectionMatrix;
                    worldViewProjection.Transpose();

                    // Update the transformation matrix.
                    immediateContext.UpdateSubresource(ref worldViewProjection, constantBuffer);

                    // Draw the cube
                    //immediateContext.Draw(vertices.Length/2, 0);
                    immediateContext.DrawIndexed(indices.Length, 0, 0);
                }

                hmd.SubmitFrame(0, layers);

                immediateContext.CopyResource(mirrorTextureD3D11, backBuffer);
                swapChain.Present(0, PresentFlags.None);


                if (newTextureArrived == true)
                {
                    newTextureArrived = false;
                    DataBox map = device.ImmediateContext.MapSubresource(myTexture, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);

                    //load the BitMapSource with appropriate formating (Format32bppPRGBA)
                    SharpDX.WIC.BitmapSource bitMap = LoadBitmap(new SharpDX.WIC.ImagingFactory(), streamTexture);
                    //string newFile = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\img_merged.jpg";
                    //SharpDX.WIC.BitmapSource bitMap = LoadBitmapFromFile(new SharpDX.WIC.ImagingFactory(), newFile);

                    int width = bitMap.Size.Width;
                    int height = bitMap.Size.Height;
                    int stride = bitMap.Size.Width * 4;

                    bitMap.CopyPixels(stride, map.DataPointer, height * stride);

                    device.ImmediateContext.UnmapSubresource(myTexture, 0);

                    //bitMap.Dispose();
                    streamTexture.Seek(0, SeekOrigin.Begin);
                }


            });
            #endregion
            // Release all resources
            inputLayout.Dispose();
            constantBuffer.Dispose();
            indexBuffer.Dispose();
            vertexBuffer.Dispose();
            inputLayout.Dispose();
            shaderSignature.Dispose();
            pixelShader.Dispose();
            pixelShaderByteCode.Dispose();
            vertexShader.Dispose();
            vertexShaderByteCode.Dispose();
            mirrorTextureD3D11.Dispose();
            layers.Dispose();
            eyeTextures[0].Dispose();
            eyeTextures[1].Dispose();
            immediateContext.ClearState();
            immediateContext.Flush();
            immediateContext.Dispose();
            depthStencilState.Dispose();
            depthStencilView.Dispose();
            depthBuffer.Dispose();
            backBufferRenderTargetView.Dispose();
            backBuffer.Dispose();
            swapChain.Dispose();
            factory.Dispose();

            // Disposing the device, before the hmd, will cause the hmd to fail when disposing.
            // Disposing the device, after the hmd, will cause the dispose of the device to fail.
            // It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down.
            // device.Dispose();

            hmd.Dispose();
            oculus.Dispose();
        }