Example #1
0
        private void RenderDots()
        {
            LoadData();


            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 103, 178));
            swapChain.Present(1, PresentFlags.None);
            vertexBuffer = D3D11.Buffer.Create <Vector3>(d3dDevice, D3D11.BindFlags.VertexBuffer, dots.ToArray());

            //Shader Code
            using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug))
            {
                vertexShader   = new D3D11.VertexShader(d3dDevice, vertexShaderByteCode);
                inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug))
            {
                pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderByteCode);
            }

            inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements);
            d3dDeviceContext.InputAssembler.InputLayout = inputLayout;
            LoadData();

            //DRAW
            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 166, 178));

            d3dDeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vector3>(), 0));
            d3dDeviceContext.Draw(dotsArray.Count(), 0);

            swapChain.Present(1, PresentFlags.None);
        }
Example #2
0
        private void Render(D3D11.Device device, D3D11.RenderTargetView[] rtvs)
        {
            D3D11.DeviceContext deviceContext = device.ImmediateContext;


            for (int i = 0; i < 6; ++i)
            {
                deviceContext.OutputMerger.SetRenderTargets(rtvs[i]);
                deviceContext.ClearRenderTargetView(rtvs[i], Color.Red);

                //if (i == 5)
                //    continue;
                KDX_SKYBOX_ENV_RENDERER_BUFFER buffer = new KDX_SKYBOX_ENV_RENDERER_BUFFER();
                buffer.World = Matrix.Transpose(Matrix.Identity);
                buffer.View  = Matrix.Transpose(views[i]);
                buffer.Proj  = Matrix.Transpose(Matrix.PerspectiveFovLH(MathUtil.DegreesToRadians(90), 1, 0.01f, 100.0f));
                buffer.MVP   = (buffer.Proj * buffer.View * buffer.World);

                deviceContext.UpdateSubresource(ref buffer, perFaceBuffer);

                deviceContext.DrawIndexed(cubeMesh.Triangles.Count() * 3, 0, 0);

                rtvs[i].Dispose();
            }
        }
Example #3
0
        private void Draw()
        {
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 32, 64));
            d3dDeviceContext.ClearDepthStencilView(depthStencilView, D3D11.DepthStencilClearFlags.Depth | D3D11.DepthStencilClearFlags.Stencil, 1.0f, 0);

            // Camera
            var view = Matrix.LookAtLH(freeCamPos, freeCamPos + freeCamLookDir, new Vector3(0, 1, 0));
            var proj = Matrix.PerspectiveFovLH(45.0f * TORAD, (float)width / height, 0.1f, 100.0f);

            var viewProj = Matrix.Multiply(view, proj);

            var binding = new D3D11.VertexBufferBinding(cubeBuffer, Utilities.SizeOf <Vertex>(), 0);

            d3dDeviceContext.InputAssembler.SetVertexBuffers(0, binding);

            VertexShaderConstants c;

            for (int i = 0; i < renderObjects.Count; i++)
            {
                var o = renderObjects[i];
                c.modelViewProj = o.transform * viewProj;
                c.modelViewProj.Transpose();
                c.color = o.color.ToVector4();

                d3dDeviceContext.UpdateSubresource(ref c, constantBuffer);
                d3dDeviceContext.Draw(cubeVertices.Count(), 0);
            }

            swapChain.Present(1, PresentFlags.None);
        }
Example #4
0
        /// <summary>
        /// Prepares the device for drawing and invoke OnDraw event
        /// </summary>
        /// <exception cref="System.Exception">
        /// </exception>
        public void BeginDraw()
        {
            if (d3dContext == null)
            {
                throw new Exception(MethodBase.GetCurrentMethod().Name + "DeviceContext is null");
            }

            if (d3dRenderTarget != null && viewport != null)
            {
                d3dContext.OutputMerger.SetRenderTargets(d3dDepthStencil, d3dRenderTarget);
                d3dContext.Rasterizer.SetViewport(viewport);
                d3dContext.ClearRenderTargetView(d3dRenderTarget, BackgroundColor);
                d3dContext.ClearDepthStencilView(d3dDepthStencil,
                                                 D3D11.DepthStencilClearFlags.Depth | D3D11.DepthStencilClearFlags.Stencil, 1, 0);

                if (OnDraw != null)
                {
                    OnDraw.Invoke(this, EventArgs.Empty);
                }
            }
            else
            {
                throw new Exception(MethodBase.GetCurrentMethod().Name + " RenderTarget or Viewport is null");
            }
        }
Example #5
0
        /// <summary>
        /// Draw the game.
        /// </summary>
        private void Draw()
        {
            // Clear the screen
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 103, 178));

            // Swap front and back buffer
            swapChain.Present(1, PresentFlags.None);
        }
        public void Clear(Texture renderTarget, Color4 color)
        {
            if (renderTarget == null)
            {
                throw new ArgumentNullException("RenderTarget");
            }

            NativeDeviceContext.ClearRenderTargetView(renderTarget.NativeRenderTargetView, color);
        }
Example #7
0
        public virtual void RenderCallback()
        {
            DeviceContext.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);
            DeviceContext.ClearRenderTargetView(RenderTargetView, Color.Black);

            deltaTime = FrameTimer.ElapsedMilliseconds;
            Draw(deltaTime - tempTime);
            tempTime = deltaTime;
        }
Example #8
0
        public void Clear(Color color)
        {
            if (!Initialized)
            {
                return;
            }

            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, color);
        }
Example #9
0
        private void Draw()
        {
            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new Color(32, 103, 178));

            d3dDeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(triangleVertexBuffer, Utilities.SizeOf <Vector3>(), 0));
            d3dDeviceContext.Draw(vertices.Count(), 0);

            swapChain.Present(1, PresentFlags.None);
        }
Example #10
0
        public Bitmap CaptureAndProcess(ModernCaptureItemDescription itemDescription)
        {
            // Assuming old texture is already disposed
            description = itemDescription;

            // Initialize DirectX context (for the canvas)
            textureSDRImage = new D3D11.Texture2D(d3dDevice, new D3D11.Texture2DDescription
            {
                Width             = description.CanvasRect.Width,
                Height            = description.CanvasRect.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = DXGI.Format.B8G8R8A8_UNorm_SRgb,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags         = D3D11.BindFlags.RenderTarget,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
            });
            rtvSdrTexture = new D3D11.RenderTargetView(d3dDevice, textureSDRImage);

            d3dContext.Rasterizer.SetViewport(new Viewport(0, 0, description.CanvasRect.Width, description.CanvasRect.Height));
            d3dContext.OutputMerger.SetRenderTargets(rtvSdrTexture);
            d3dContext.ClearRenderTargetView(rtvSdrTexture, new SharpDX.Mathematics.Interop.RawColor4 {
                A = 0.0f, B = 0.0f, G = 0.0f, R = 0.0f
            });

            foreach (var item in description.Regions)
            {
                using (var session = new ModernCaptureMonitorSession(wrtD3D11Device, item))
                {
                    Direct3D11CaptureFrame f;
                    currentSession = session;
                    session.Session.StartCapture();
                    while ((f = session.FramePool.TryGetNextFrame()) == null)
                    {
                        Thread.Sleep(1);
                    }
                    ProcessFrame(f);
                    f.Dispose();
                }
            }

            // Process final 8-bit bitmap
            var gdiPlusBitmap = new Bitmap(DumpAndSaveImage());

            rtvSdrTexture.Dispose();
            textureSDRImage.Dispose();
            description = null;

#if DEBUG
            System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
#endif
            return(gdiPlusBitmap);
        }
Example #11
0
    void Draw()
    {
        m_d3d11DeviceContext.OutputMerger.SetRenderTargets(m_renderTargetView);
        SharpDX.Mathematics.Interop.RawColor4 color = new SharpDX.Mathematics.Interop.RawColor4(32 / (float)255, 103 / (float)255, 178 / (float)255, 1);
        m_d3d11DeviceContext.ClearRenderTargetView(m_renderTargetView, color);

        m_d3d11DeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(m_triangleVertexBuffer, SharpDX.Utilities.SizeOf <VertexPositionColor>(), 0));
        m_d3d11DeviceContext.Draw(m_vertices.Count(), 0);

        m_swapChain.Present(1, DXGI.PresentFlags.None);
    }
Example #12
0
        /// <summary>
        /// Draw the game.
        /// </summary>
        private void Draw()
        {
            // Set back buffer as current render target view
            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);

            // Clear the screen
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 103, 178));

            // Swap front and back buffer
            swapChain.Present(1, PresentFlags.None);
        }
 private void Draw()
 {
     if (isPaused)
     {
         return;
     }
     _dx11DeviceContext.ClearRenderTargetView(_renderView, new SharpDX.Color(0, 0, 0));
     _dx11DeviceContext.ClearDepthStencilView(_depthView, DX11.DepthStencilClearFlags.Depth | DX11.DepthStencilClearFlags.Stencil, 1.0f, 0);
     OnDraw?.Invoke(1);
     _swapChain.Present(0, PresentFlags.None);
 }
Example #14
0
        void OnRender(IntPtr resourcePtr, bool isNewSurface)
        {
            if (isNewSurface)
            {
                // a new surface has been created (e.g. after a resize)
                InitializeSharedBackBuffer(resourcePtr);
            }

            deviceContext.ClearRenderTargetView(renderTargetView, new RawColor4(0, 0, 0, 1));
            deviceContext.Draw(3, 0);
            deviceContext.Flush();
        }
Example #15
0
        public void PresentFrame(MediaFrame frame = null)
        {
            // Design Mode Only?
            if (device == null)
            {
                return;
            }

            // Should work better in case of frame delay (to avoid more delay on screamer)
            if (Monitor.TryEnter(device, 4))
            {
                try
                {
                    if (frame != null)
                    {
                        // NV12 | P010
                        if (frame.textureHW != null)
                        {
                            PresentNV12P010(frame);
                        }

                        // YUV420P
                        else if (frame.textureY != null)
                        {
                            PresentYUV(frame);
                        }

                        // RGB
                        else if (frame.textureRGB != null)
                        {
                            PresentRGB(frame);
                        }
                    }

                    context.OutputMerger.SetRenderTargets(rtv);
                    context.ClearRenderTargetView(rtv, clearColor);
                    context.Draw(6, 0);

                    rtv2d.BeginDraw();
                    try
                    {
                        PresentOSD();
                    } finally {
                        rtv2d.EndDraw();
                    }
                    swapChain.Present(vsync, PresentFlags.None);
                } finally { Monitor.Exit(device); }
            }
            else
            {
                Console.WriteLine("[RENDERER] Drop Frame - Lock timeout " + (frame != null ? Utils.TicksToTime(frame.timestamp) : "")); player.ClearVideoFrame(frame);
            }
        }
Example #16
0
        /// <summary>
        /// Draw the game.
        /// </summary>
        private void Draw()
        {
            // Clear the screen
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 103, 178));

            // Set vertex buffer
            d3dDeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(triangleVertexBuffer, Utilities.SizeOf <Vector3>(), 0));

            // Draw the triangle
            d3dDeviceContext.Draw(vertices.Count(), 0);

            // Swap front and back buffer
            swapChain.Present(1, PresentFlags.None);
        }
Example #17
0
        private void Draw()
        {
            _d3DDeviceContext.OutputMerger.SetRenderTargets(_renderTargetView);
            _d3DDeviceContext.ClearRenderTargetView(_renderTargetView, ColorToRaw4(Color.Coral));

            _swapChain.Present(1, PresentFlags.None);

            RawColor4 ColorToRaw4(Color color)
            {
                const float n = 255f;

                return(new RawColor4(color.R / n, color.G / n, color.B / n, color.A / n));
            }
        }
Example #18
0
//____________________________________________________________________________________________________________________________________________________________________________________________
        private void Draw()
        {
            InitBuffers();                                                                                                                                       //MEMORY LEAK -- FIXED???
            //d3dDeviceContext.UpdateSubresource(,);
            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);                                                                                    // Set back buffer as current render target view
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new RawColor4(0, 0, 0, 2));                                                                 // Clear the screen
            d3dDeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(screenVertexBuffer, Utilities.SizeOf <VertexPositionColor>(), 0)); // Set vertex buffer
            //SYS_STATE();
            for (int i = 0; i < 64 * 32; i++)
            {
                d3dDeviceContext.Draw(4, i * 4);
            }
            swapChain.Present(0, PresentFlags.None);// Swap front and back buffer
            screenVertexBuffer.Dispose();
        }
Example #19
0
        /// <summary>
        /// This code first sets the active render target view to the one we just created.
        /// Then it clears the render target view (currently our back buffer)
        /// and then swaps the back with the front buffer, making the back buffer visible.
        ///  By specifying 1 as the first parameter to Present(…) we wait for vertical sync of the monitor before we present.
        ///  This will limit the FPS to the update frequency of the monitor.
        /// </summary>
        private void Draw()
        {
            _d3DDeviceContext.OutputMerger.SetRenderTargets(_renderTargetView);
            _d3DDeviceContext.ClearRenderTargetView(_renderTargetView, new RawColor4(0.0f, 0.0f, 0.0f, 0.0f));

            //The first method tells the device context to use the vertex buffer holding the triangle vertex data,
            //with the second parameter specifying the size (in bytes) for the data of each vertex.
            //To get this size we use a nice helper method available in SharpDX.
            _d3DDeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(_triangleVertexBuffer, Utilities.SizeOf <VertexPositionColor>(), 0));

            //The Draw() method on the device context draws vertices.Count() many vertices from our vertex buffer.
            //The second parameter specifies the offset in our vertex buffer,
            //by settings this to 1 for example, the first vertex would be skipped.
            _d3DDeviceContext.Draw(_vertices.Count(), 0);

            _swapChain.Present(1, PresentFlags.None);
        }
Example #20
0
        private void Draw()
        {
            deviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            deviceContext.ClearRenderTargetView(renderTargetView, ColorToRaw4(Color.Coral));

            deviceContext.InputAssembler.SetVertexBuffers(0,
                                                          new D3D11.VertexBufferBinding(triangleVertexBuffer, Utilities.SizeOf <Vector3>(), 0));
            deviceContext.Draw(vertices.Length, 0);

            swapChain.Present(1, PresentFlags.None);

            RawColor4 ColorToRaw4(Color color)
            {
                const float n = 255f;

                return(new RawColor4(color.R / n, color.G / n, color.B / n, color.A / n));
            }
        }
Example #21
0
        private void Draw()
        {
            // Clear the screen
            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(127, 178, 229));
            d3dDeviceContext.ClearDepthStencilView(depthStencilView, D3D11.DepthStencilClearFlags.Depth, 0, 0);

            // Draw the scene
            Scene.Draw(orthoProjMatrix);

            // Draw the gui
            if (gui != null)
            {
                gui.Draw(orthoProjMatrix);
            }

            // Swap the front and back buffers
            swapChain.Present(1, PresentFlags.None);
        }
Example #22
0
        internal void BeginRender(Color4 clearingColor)
        {
            if (sw == null)
            {
                sw          = new Stopwatch();
                refreshRate = Dwm.DisplayRefreshRate * 2;
                sw.Start();
            }

            if (resized)
            {
                resized = false;
                ResizeSurface();
            }

            deviceContext.OutputMerger.SetDepthStencilState(defaultDepthStencilState);
            deviceContext.ClearDepthStencilView(depthStencilView, D3D11.DepthStencilClearFlags.Depth | D3D11.DepthStencilClearFlags.Stencil, 1, 0);
            deviceContext.ClearRenderTargetView(surfaceTarget, new SharpDX.Color4(clearingColor.R, clearingColor.G, clearingColor.B, 1));
        }
Example #23
0
        public void Render()
        {
            float time = stopWatch.ElapsedMilliseconds / 1000.0f;

            Viewport viewport = new Viewport(0, 0, width, height);

            int vertexSize  = Utilities.SizeOf <Vector3>();
            int vertexCount = trianglePositionVertexBuffer.Description.SizeInBytes / vertexSize;

            deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(trianglePositionVertexBuffer, vertexSize, 0));
            deviceContext.InputAssembler.InputLayout       = inputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;

            deviceContext.VertexShader.Set(mainVertexShader);
            deviceContext.PixelShader.Set(mainPixelShader);

            deviceContext.Rasterizer.SetViewport(viewport);
            deviceContext.Rasterizer.State = rasterizerState;

            deviceContext.OutputMerger.SetDepthStencilState(depthStencilState, 1);
            deviceContext.OutputMerger.SetRenderTargets(depthDSV, sceneRTV);

            deviceContext.ClearDepthStencilView(depthDSV, D3D11.DepthStencilClearFlags.Depth, 1.0f, 0);
            deviceContext.ClearRenderTargetView(sceneRTV, new Color(255, 135, 60));

            for (int i = 0; i < CubeCount; i++)
            {
                for (int j = 0; j < CubeCount; j++)
                {
                    UpdateConstantBuffer(GetConstantBufferForCube(i, j, time));

                    int indexCount = triangleIndexBuffer.Description.SizeInBytes / Utilities.SizeOf <int>();
                    deviceContext.InputAssembler.SetIndexBuffer(triangleIndexBuffer, DXGI.Format.R32_UInt, 0);
                    deviceContext.DrawIndexed(indexCount, 0, 0);
                }
            }

            deviceContext.OutputMerger.SetRenderTargets(null, (D3D11.RenderTargetView)null);    // Tip: always set to null after rendering. If bound as rendertarget it cannot be set as shader resource view (as texture)

            postEffect.Run(sceneSRV, depthSRV, backbufferRTV, width, height, time);
        }
Example #24
0
 public void ClearRenderTargetView(RenderTargetView view, RawColor4 color)
 {
     context.ClearRenderTargetView(view, color);
 }
Example #25
0
 /// <summary>
 /// clears the window with the given color
 /// </summary>
 /// <param name="c"></param>
 public void Clear(Color4 c)
 {
     deviceContext.ClearRenderTargetView(view, c);
     TriangleList.Clear();
 }
Example #26
0
        public void PresentFrame(MediaFrame frame = null)
        {
            if (device == null)
            {
                return;
            }

            // Drop Frames | Priority on video frames
            bool gotIn = frame == null?Monitor.TryEnter(device, 1) : Monitor.TryEnter(device, 5);

            if (gotIn)
            {
                try
                {
                    if (frame != null)
                    {
                        if (decoder.vDecoder.hwAccelSuccess)
                        {
                            curSRVs    = new ShaderResourceView[2];
                            curSRVs[0] = new ShaderResourceView(device, frame.textures[0], srvDescR);
                            curSRVs[1] = new ShaderResourceView(device, frame.textures[0], srvDescRG);
                        }
                        else if (decoder.vDecoder.info.PixelFormatType == PixelFormatType.Software_Handled)
                        {
                            curSRVs    = new ShaderResourceView[3];
                            curSRVs[0] = new ShaderResourceView(device, frame.textures[0]);
                            curSRVs[1] = new ShaderResourceView(device, frame.textures[1]);
                            curSRVs[2] = new ShaderResourceView(device, frame.textures[2]);
                        }
                        else
                        {
                            curSRVs    = new ShaderResourceView[1];
                            curSRVs[0] = new ShaderResourceView(device, frame.textures[0]);
                        }

                        context.PixelShader.Set(curPixelShader);
                        context.PixelShader.SetShaderResources(0, curSRVs);
                    }

                    context.OutputMerger.SetRenderTargets(rtv);
                    context.ClearRenderTargetView(rtv, cfg.video._ClearColor);
                    context.Draw(6, 0);

                    swapChain.Present(cfg.video.VSync, PresentFlags.None);

                    if (frame != null)
                    {
                        if (frame.textures != null)
                        {
                            for (int i = 0; i < frame.textures.Length; i++)
                            {
                                Utilities.Dispose(ref frame.textures[i]);
                            }
                        }
                        if (curSRVs != null)
                        {
                            for (int i = 0; i < curSRVs.Length; i++)
                            {
                                Utilities.Dispose(ref curSRVs[i]);
                            }
                            curSRVs = null;
                        }
                    }
                } finally { Monitor.Exit(device); }
            }
            else
            {
                Log("Dropped Frame - Lock timeout " + (frame != null ? Utils.TicksToTime(frame.timestamp) : "")); Utils.DisposeVideoFrame(frame);
            }
        }
Example #27
0
        public void Draw()
        {
            lock (_drawLock)
            {
                if (_ui == null || !_ui.ready)
                {
                    return;
                }

                if (_ui.gameStarted)
                {
                    // Update Device Tracking
                    compositor.WaitGetPoses(currentPoses, nextPoses);

                    if (currentPoses[headset].bPoseIsValid)
                    {
                        Convert(ref currentPoses[headset].mDeviceToAbsoluteTracking, ref head);
                    }

                    // Render Left Eye
                    context.Rasterizer.SetViewport(0, 0, headsetSize.Width, headsetSize.Height);
                    context.OutputMerger.SetTargets(eyeDepthView, leftEyeTextureView);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.ClearRenderTargetView(leftEyeTextureView, backgroundColor);
                    context.ClearDepthStencilView(eyeDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                    Shaders.Normal.Apply(context);

                    context.Rasterizer.State = rasterizerState;

                    context.OutputMerger.SetBlendState(blendState);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.PixelShader.SetSampler(0, samplerState);

                    var ratio = (float)headsetSize.Width / (float)headsetSize.Height;

                    var projection = leftEyeProjection;
                    var view       = Matrix.Invert(leftEyeView * head);
                    var world      = Matrix.Translation(0, 0, -100.0f);

                    var worldViewProjection = world * view * projection;

                    //context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                    context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                    context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                    //Shapes.Cube.Begin(context);
                    //Shapes.Cube.Draw(context);

                    //Shapes.Sphere.Begin(context);
                    //Shapes.Sphere.Draw(context);

                    DrawPixels(worldViewProjection);

                    // Draw Controllers
                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                    Shaders.NormalTexture.Apply(context);

                    context.PixelShader.SetSampler(0, samplerState);

                    foreach (var controller in controllers)
                    {
                        context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                        context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                        context.PixelShader.SetShaderResource(0, controllerTextureViews[controller]);

                        Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                        shaderParameters.WorldViewProjection = world * view * projection;
                        shaderParameters.Diffuse             = new Vector4(1, 1, 1, 1);

                        context.UpdateSubresource(ref shaderParameters, shaderParameterBuffer);

                        context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                        context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                        context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                    }

                    var texture = new Texture_t
                    {
                        eType       = ETextureType.DirectX,
                        eColorSpace = EColorSpace.Gamma,
                        handle      = leftEyeTextureView.Resource.NativePointer
                    };

                    var bounds = new VRTextureBounds_t
                    {
                        uMin = 0.0f,
                        uMax = 1.0f,
                        vMin = 0.0f,
                        vMax = 1.0f,
                    };

                    var submitError = compositor.Submit(EVREye.Eye_Left, ref texture, ref bounds, EVRSubmitFlags.Submit_Default);

                    if (submitError != EVRCompositorError.None)
                    {
                        System.Diagnostics.Debug.WriteLine(submitError);
                    }

                    // Render Right Eye
                    context.Rasterizer.SetViewport(0, 0, headsetSize.Width, headsetSize.Height);
                    context.OutputMerger.SetTargets(eyeDepthView, rightEyeTextureView);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.ClearRenderTargetView(rightEyeTextureView, backgroundColor);
                    context.ClearDepthStencilView(eyeDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                    Shaders.Normal.Apply(context);

                    context.Rasterizer.State = rasterizerState;

                    context.OutputMerger.SetBlendState(blendState);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.PixelShader.SetSampler(0, samplerState);

                    projection = rightEyeProjection;
                    view       = Matrix.Invert(rightEyeView * head);
                    world      = Matrix.Translation(0, 0, -100.0f);

                    worldViewProjection = world * view * projection;

                    //context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                    context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                    context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                    //Shapes.Cube.Begin(context);
                    //Shapes.Cube.Draw(context);

                    //Shapes.Sphere.Begin(context);
                    //Shapes.Sphere.Draw(context);

                    DrawPixels(worldViewProjection);

                    // Draw Controllers
                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                    Shaders.NormalTexture.Apply(context);

                    context.PixelShader.SetSampler(0, samplerState);

                    foreach (var controller in controllers)
                    {
                        context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                        context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                        context.PixelShader.SetShaderResource(0, controllerTextureViews[controller]);

                        Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                        shaderParameters.WorldViewProjection = world * view * projection;
                        shaderParameters.Diffuse             = new Vector4(1, 1, 1, 1);

                        context.UpdateSubresource(ref shaderParameters, shaderParameterBuffer);

                        context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                        context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                        context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                    }

                    texture.handle = rightEyeTextureView.Resource.NativePointer;

                    submitError = compositor.Submit(EVREye.Eye_Right, ref texture, ref bounds, EVRSubmitFlags.Submit_Default);

                    if (submitError != EVRCompositorError.None)
                    {
                        System.Diagnostics.Debug.WriteLine(submitError);
                    }

                    // Render Window
                    context.Rasterizer.SetViewport(0, 0, windowSize.Width, windowSize.Height);

                    context.OutputMerger.SetTargets(depthStencilView, backBufferView);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.ClearRenderTargetView(backBufferView, backgroundColor);
                    context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);

                    Shaders.Normal.Apply(context);

                    context.Rasterizer.State = rasterizerState;

                    context.OutputMerger.SetBlendState(blendState);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.PixelShader.SetSampler(0, samplerState);

                    ratio = (float)ClientSize.Width / (float)ClientSize.Height;

                    projection = Matrix.PerspectiveFovRH(3.14F / 3.0F, ratio, 0.01f, 1000);
                    view       = Matrix.Invert(head);
                    world      = Matrix.Translation(0, 0, -100.0f);

                    worldViewProjection = world * view * projection;

                    //context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                    context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                    context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                    //Shapes.Cube.Begin(context);
                    //Shapes.Cube.Draw(context);

                    //Shapes.Sphere.Begin(context);
                    //Shapes.Sphere.Draw(context);

                    DrawPixels(worldViewProjection);

                    // Draw Controllers
                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                    Shaders.NormalTexture.Apply(context);

                    context.PixelShader.SetSampler(0, samplerState);

                    foreach (var controller in controllers)
                    {
                        context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                        context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                        Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                        shaderParameters.WorldViewProjection = world * view * projection;
                        shaderParameters.Diffuse             = new Vector4(1, 1, 1, 1);

                        context.UpdateSubresource(ref shaderParameters, shaderParameterBuffer);

                        context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                        context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                        context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                    }

                    // Show Backbuffer
                    swapChain.Present(0, PresentFlags.None);
                }
            }
        }
Example #28
0
 private void Draw()
 {
     d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
     d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(0, 0, 0));
     swapChain.Present(1, PresentFlags.None);
 }
Example #29
0
 internal void ClearRtv(IRtvBindable rtv, RawColor4 colorRGBA)
 {
     m_deviceContext.ClearRenderTargetView(rtv.Rtv, colorRGBA);
     CheckErrors();
 }
Example #30
0
        /// <summary>
        /// 三大块:初始化设备、设置缓冲和管线等、渲染循环
        /// </summary>
        private void DoCommonThings()
        {
            _renderForm              = new RenderForm();
            _renderForm.ClientSize   = new System.Drawing.Size(800, 600);
            _renderForm.KeyDown     += _renderForm_KeyDown;
            _renderForm.Text         = "愉快的学习SharpDX";
            _renderForm.Icon         = null;
            _renderForm.ResizeBegin += (object sender, EventArgs e) => { _resized = true; };
            _renderForm.MouseDown   += _renderForm_MouseDown;
            _renderForm.MouseUp     += _renderForm_MouseUp;
            _renderForm.MouseMove   += _renderForm_MouseMove;
            ModeDescription      backBufferDesc = new ModeDescription(_renderForm.ClientSize.Width, _renderForm.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            SwapChainDescription swapChainDesc  = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = _renderForm.Handle,
                IsWindowed        = true,
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard,
            };

            D3D11.Device.CreateWithSwapChain(
                SharpDX.Direct3D.DriverType.Hardware,
                D3D11.DeviceCreationFlags.Debug,
                swapChainDesc, out _d3DDevice, out _swapChain);
            _d3DDeviceContext = _d3DDevice.ImmediateContext;
            using (var effectByteCode = ShaderBytecode.CompileFromFile("../../MyShader.fx", "fx_5_0", ShaderFlags.Debug | ShaderFlags.SkipOptimization)) {
                var effect    = new Effect(_d3DDevice, effectByteCode);
                var technique = effect.GetTechniqueByName("LightTech");

                //光照
                mfxDirLight   = effect.GetVariableByName("gDirLight");
                mfxPointLight = effect.GetVariableByName("gPointLight");
                mfxSpotLight  = effect.GetVariableByName("gSpotLight");

                mfxEyePosW = effect.GetVariableByName("gEyePosW");

                //材质
                mfxMaterial = effect.GetVariableByName("gMaterial");

                //纹理
                mfxShaderRSVar  = effect.GetVariableByName("gTexture").AsShaderResource();
                mfxTexTransform = effect.GetVariableByName("gTexTransform").AsMatrix();

                //pass
                mfxPassW = technique.GetPassByName("P0");
                mfxPassS = technique.GetPassByName("P1");
                mfxPass  = mfxPassS;

                mfxWorld         = effect.GetVariableByName("gWorld").AsMatrix();
                mfxWorldTranInv  = effect.GetVariableByName("gWorldInvTranspose").AsMatrix();
                mfxWorldViewProj = effect.GetVariableByName("gWorldViewProj").AsMatrix();


                var passSignature = mfxPassW.Description.Signature;
                _inputShaderSignature = ShaderSignature.GetInputSignature(passSignature);
            }
            _inputLayout = new D3D11.InputLayout(_d3DDevice, _inputShaderSignature, _inputElementsForMesh);
            var VertexBuffer = D3D11.Buffer.Create <MyVertex>(_d3DDevice, BindFlags.VertexBuffer, mMeshData.Vertices.ToArray());
            var IndexBuffer  = D3D11.Buffer.Create <int>(_d3DDevice, BindFlags.IndexBuffer, mMeshData.Indices.ToArray());

            ShaderRSV = Tools.CreateShaderResourceViewFromFile(_d3DDevice, System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "../../model/ydmy.jpg"));

            _d3DDeviceContext.InputAssembler.InputLayout       = _inputLayout;
            _d3DDeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            _d3DDeviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VertexBuffer, Utilities.SizeOf <MyVertex>(), 0));
            _d3DDeviceContext.InputAssembler.SetIndexBuffer(IndexBuffer, Format.R32_UInt, 0);
            proj  = Matrix.Identity;
            world = new Matrix[228];
            for (int i = 0; i < 228; i++)
            {
                world[i] = Matrix.Identity;
            }
            //world[0] = Matrix.Identity;
            _resized = true;
            Texture2D        backBuffer  = null;
            RenderTargetView renderView  = null;
            Texture2D        depthBuffer = null;
            DepthStencilView depthView   = null;
            long             lastTime    = 0;
            var clock = new System.Diagnostics.Stopwatch();

            clock.Start();
            int fpsCounter = 0;

            byte[] d;
            RenderLoop.Run(_renderForm, () => {
                view.Row1 = new Vector4(camRight, 0);
                view.Row2 = new Vector4(camUp, 0);
                view.Row3 = new Vector4(camLook, 0);
                view.Row4 = new Vector4(camPos, 1);
                view      = Matrix.Invert(view);

                if (_resized)
                {
                    Utilities.Dispose(ref backBuffer);
                    Utilities.Dispose(ref renderView);
                    Utilities.Dispose(ref depthBuffer);
                    Utilities.Dispose(ref depthView);
                    _swapChain.ResizeBuffers(swapChainDesc.BufferCount, _renderForm.ClientSize.Width, _renderForm.ClientSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
                    backBuffer  = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0);
                    renderView  = new RenderTargetView(_d3DDevice, backBuffer);
                    depthBuffer = new Texture2D(_d3DDevice, new Texture2DDescription()
                    {
                        Format            = Format.D32_Float_S8X24_UInt,
                        ArraySize         = 1,
                        MipLevels         = 1,
                        Width             = _renderForm.ClientSize.Width,
                        Height            = _renderForm.ClientSize.Height,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = ResourceUsage.Default,
                        BindFlags         = BindFlags.DepthStencil,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        OptionFlags       = ResourceOptionFlags.None
                    });
                    depthView = new DepthStencilView(_d3DDevice, depthBuffer);
                    _d3DDeviceContext.Rasterizer.SetViewport(new Viewport(0, 0, _renderForm.ClientSize.Width, _renderForm.ClientSize.Height, 0.0f, 1.0f));
                    _d3DDeviceContext.OutputMerger.SetTargets(depthView, renderView);
                    proj     = Matrix.PerspectiveFovLH((float)Math.PI / 4f, _renderForm.ClientSize.Width / (float)_renderForm.ClientSize.Height, 0.1f, 1000f);
                    _resized = false;
                }
                _d3DDeviceContext.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                _d3DDeviceContext.ClearRenderTargetView(renderView, SharpDX.Color.Black);
                var viewProj = Matrix.Multiply(view, proj);

                //设置平行光
                d = Tools.StructureToBytes(mDirLight);
                Array.Copy(d, 0, _dirLightArray, 0, Marshal.SizeOf(typeof(DirectionalLight)));
                using (var dataStream = DataStream.Create(_dirLightArray, false, false)) {
                    mfxDirLight.SetRawValue(dataStream, _dirLightArray.Length);
                }

                //纹理贴图:画正方体
                //world[0] = Matrix.RotationAxis(Vector3.UnitY, clock.ElapsedMilliseconds / 1000f);
                for (int i = 0; i < mSubMeshData.Length - 1; i++)
                {
                    world[i]      = Matrix.RotationAxis(Vector3.UnitY, clock.ElapsedMilliseconds / 1000f);
                    worldViewProj = world[i] * viewProj;
                    //像素着色器计算需要的变量
                    mfxWorld.SetMatrix(world[i]);
                    mfxWorldTranInv.SetMatrix(Tools.InverseTranspose(world[i]));
                    mfxWorldViewProj.SetMatrix(worldViewProj);
                    //设置材质
                    d = Tools.StructureToBytes(mMatArray[0]);
                    Array.Copy(d, 0, _matArray, 0, Marshal.SizeOf(typeof(Material))); // 结构体大小
                    using (var dataStream = DataStream.Create(_matArray, false, false)) {
                        mfxMaterial.SetRawValue(dataStream, _matArray.Length);
                    }
                    //设置纹理
                    mfxShaderRSVar.SetResource(ShaderRSV);
                    mfxTexTransform.SetMatrix(Matrix.Identity);

                    mfxPass.Apply(_d3DDeviceContext);
                    _d3DDeviceContext.DrawIndexed(mSubMeshData[i].Indices.Length, indOff[i], vexOff[i]);
                }

                //平面
                worldViewProj = Matrix.Identity * viewProj;
                //像素着色器计算需要的变量
                mfxWorld.SetMatrix(Matrix.Identity);
                mfxWorldTranInv.SetMatrix(Tools.InverseTranspose(Matrix.Identity));
                mfxWorldViewProj.SetMatrix(worldViewProj);
                //设置材质
                d = Tools.StructureToBytes(mMatArray[0]);
                Array.Copy(d, 0, _matArray, 0, Marshal.SizeOf(typeof(Material))); // 结构体大小
                using (var dataStream = DataStream.Create(_matArray, false, false)) {
                    mfxMaterial.SetRawValue(dataStream, _matArray.Length);
                }
                //设置纹理
                mfxShaderRSVar.SetResource(ShaderRSV);
                mfxTexTransform.SetMatrix(Matrix.Identity);
                mfxPass.Apply(_d3DDeviceContext);
                _d3DDeviceContext.DrawIndexed(mSubMeshData[228].Indices.Length, indOff[228], vexOff[228]);

                _swapChain.Present(0, PresentFlags.None);
                fpsCounter++;
                if (clock.ElapsedMilliseconds - lastTime >= 1000)
                {
                    _renderForm.Text = "FPS:" + fpsCounter.ToString();
                    fpsCounter       = 0;
                    lastTime         = clock.ElapsedMilliseconds;
                }
            });
        }