unsafe void DrawVertices(int[] indices, Vertex[] vertices, int bufferIndex)
        {
            if (bufferIndex != currentBufferIndex)
            {
                indexBuffer        = indexBuffers[bufferIndex];
                vertexBuffer       = vertexBuffers[bufferIndex];
                currentBufferIndex = bufferIndex;

                deviceContext.InputAssembler.SetIndexBuffer(indexBuffer, DXGI.Format.R32_UInt, 0);
                deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, sizeof(Vertex), 0));
            }

            DataStream stream;

            deviceContext.MapSubresource(indexBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream);
            stream.Position = 0;
            stream.WriteRange(indices);
            deviceContext.UnmapSubresource(indexBuffer, 0);
            stream.Dispose();

            deviceContext.MapSubresource(vertexBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream);
            stream.Position = 0;
            stream.WriteRange(vertices);
            deviceContext.UnmapSubresource(vertexBuffer, 0);
            stream.Dispose();

            deviceContext.DrawIndexed(indices.Length, 0, 0);
        }
Exemple #2
0
        public override void Draw(SharpDX.Direct3D11.DeviceContext context, int index)
        {
            if (_activatedEffect == null)
            {
                if (_backBufferClouds.OffSreenRenderTarget != null)
                {
                    _backBufferClouds.OffSreenRenderTarget = null;
                }
                return;
            }

            if (index == _postEffectStartingDrawId)
            {
                //Change RenderTarget to this offline texture
                //Clear renderTarger
                _engine.ImmediateContext.ClearRenderTargetView(_renderTargetView, __renderTargetViewDefaultColor);
                _engine.ImmediateContext.OutputMerger.SetTargets(_engine.DepthStencilTarget, _renderTargetView);
                _backBufferClouds.OffSreenRenderTarget = _renderTexture;
                _postEffectStartDrawDone = true;
            }
            else if (index == _postEffectEndingDrawId && _postEffectStartDrawDone)
            {
                //We have finished to draw into the offline texture, link back the screen backbuffer
                _engine.SetRenderTargets(context);
                //Start the Post effect code here
                RenderStatesRepo.ApplyStates(context, DXStates.Rasters.Default, DXStates.Blenders.Disabled, DXStates.DepthStencils.DepthDisabled);
                _vBuffer.SetToDevice(context, 0);
                _iBuffer.SetToDevice(context, 0);

                _activatedEffect.Render(context);

                context.DrawIndexed(6, 0, 0);
                _postEffectStartDrawDone = false;
            }
        }
        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();
            }
        }
Exemple #4
0
 /// <summary>
 /// Draws the specified context.
 /// </summary>
 /// <param name="context">The context.</param>
 public override void Draw(D3D11.DeviceContext context)
 {
     if (Vertices != null && Indices != null)
     {
         context.DrawIndexed(Indices.Length, 0, 0);
     }
 }
Exemple #5
0
        /// <summary>
        /// Renders this GeometryResource.
        /// </summary>
        /// <param name="renderState">Current render state.</param>
        public void Render(RenderState renderState)
        {
            D3D11.DeviceContext deviceContext     = renderState.Device.DeviceImmediateContextD3D11;
            DXGI.Format         indexBufferFormat = renderState.Device.SupportsOnly16BitIndexBuffer ? DXGI.Format.R16_UInt : DXGI.Format.R32_UInt;

            int lastVertexBufferID = -1;
            int lastIndexBufferID  = -1;

            for (int loop = 0; loop < m_loadedStructures.Length; loop++)
            {
                LoadedStructureInfo structureToDraw = m_loadedStructures[loop];

                // Apply VertexBuffer
                if (lastVertexBufferID != structureToDraw.VertexBufferID)
                {
                    lastVertexBufferID = structureToDraw.VertexBufferID;
                    deviceContext.InputAssembler.InputLayout = structureToDraw.InputLayout;
                    deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(structureToDraw.VertexBuffer, structureToDraw.SizePerVertex, 0));
                }

                // Apply IndexBuffer
                if (lastIndexBufferID != structureToDraw.IndexBufferID)
                {
                    deviceContext.InputAssembler.SetIndexBuffer(structureToDraw.IndexBuffer, indexBufferFormat, 0);
                }

                // Apply material
                renderState.ApplyMaterial(structureToDraw.Material);
                D3D11.InputLayout newInputLayout = null;
                if (renderState.ForcedMaterial != null)
                {
                    newInputLayout = renderState.ForcedMaterial.GenerateInputLayout(
                        renderState.Device,
                        StandardVertex.InputElements,
                        MaterialApplyInstancingMode.SingleObject);
                    deviceContext.InputAssembler.InputLayout = newInputLayout;
                }
                try
                {
                    // Draw current rener block
                    deviceContext.DrawIndexed(
                        structureToDraw.IndexCount,
                        structureToDraw.StartIndex,
                        0);
                }
                finally
                {
                    if (newInputLayout != null)
                    {
                        deviceContext.InputAssembler.InputLayout = null;
                        GraphicsHelper.SafeDispose(ref newInputLayout);
                    }
                }
            }
        }
Exemple #6
0
        public void RenderNextAnimationFrame()
        {
            var eye = new Vector3(0.0f, 0.7f, 1.5f);  // Define camera position.
            var at  = new Vector3(0.0f, -0.1f, 0.0f); // Define focus position.
            var up  = new Vector3(0.0f, 1.0f, 0.0f);  // Define up direction.

            if (frameCount >= float.MaxValue)
            {
                frameCount = 0;
            }

            // Set view based on camera position, focal point, and up direction.
            constantBufferData.view = Matrix.Transpose(Matrix.LookAtRH(eye, at, up));

            // Rotate around Y axis by (pi/4) * 16ms per elapsed frame.
            constantBufferData.model = Matrix.Transpose(Matrix.RotationY(frameCount++ *0.016f * MathUtil.PiOverFour));

            // Clear depth/stencil view.
            d3dContext.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);

            // Set render target.
            d3dContext.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);

            // Map update to constant buffer.
            d3dContext.UpdateSubresource(ref constantBufferData, constantBuffer);

            // Set vertex buffer.
            int stride = Utilities.SizeOf <VertexPositionColor>();

            d3dContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, stride, 0));

            // Set index buffer.
            d3dContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0);

            // Set topology to triangle list.
            d3dContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // Set input layout.
            d3dContext.InputAssembler.InputLayout = inputLayout;

            // Set vertex shader.
            d3dContext.VertexShader.Set(vertexShader);

            // Set constant buffer.
            d3dContext.VertexShader.SetConstantBuffer(0, constantBuffer);

            // Set pixel shader.
            d3dContext.PixelShader.Set(pixelShader);

            // Draw cube faces.
            d3dContext.DrawIndexed(indexCount, 0, 0);
        }
Exemple #7
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);
        }
        /// <summary>
        /// Renders this object.
        /// </summary>
        /// <param name="renderState">Render this object.</param>
        private void Render(RenderState renderState)
        {
            renderState.ClearChachedAppliedMaterial();

            D3D11.DeviceContext  deviceContext  = renderState.Device.DeviceImmediateContextD3D11;
            SkyboxLocalResources localResources = m_localResources[renderState.DeviceIndex];

            // Apply constants and shader resources
            deviceContext.VertexShader.Set(localResources.VertexShader.VertexShader);
            deviceContext.PixelShader.Set(localResources.PixelShader.PixelShader);
            deviceContext.PixelShader.SetShaderResource(0, localResources.CubeTexture.TextureView);

            // Bind index and vertex buffer
            deviceContext.InputAssembler.SetIndexBuffer(localResources.IndexBuffer, DXGI.Format.R32_UInt, 0);
            deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(
                                                              localResources.VertexBuffer,
                                                              StandardVertex.Size, 0));

            // Draw the skybox
            deviceContext.DrawIndexed(6 * 6, 0, 0);
        }
Exemple #9
0
        private void Render(Model model)
        {
            D3D11.DeviceContext deviceContext = deviceResources.DeviceContext;

            if (!model.Mesh.HasBuffers)
            {
                // TODO: Should not initialize one buffer per object
                //       Investigate way to "pool" meshes in.
                //       Also, should not be done here.
                model.Mesh.CreateBuffers(deviceResources.Device);
            }

            D3D11.Buffer vertexBuffer = model.Mesh.VertexBuffer;
            D3D11.Buffer indexBuffer  = model.Mesh.IndexBuffer;

            SetShader(model.Material.Shader);
            SetMaterialSRVT(model.Material);

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

            deviceContext.DrawIndexed(model.Mesh.Triangles.Count() * 3, 0, 0);
        }
 public void DrawIndexed(int indexCount, int startVertexLocation = 0, int baseVertexLocation = 0)
 {
     NativeDeviceContext.DrawIndexed(indexCount, startVertexLocation, baseVertexLocation);
 }
Exemple #11
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;
                }
            });
        }
Exemple #12
0
 internal void DrawIndexed(int indexCount, int startIndexLocation, int baseVertexLocation)
 {
     m_deviceContext.DrawIndexed(indexCount, startIndexLocation, baseVertexLocation);
     m_statistics.Draws++;
     CheckErrors();
 }
Exemple #13
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);
                }
            }
        }