Esempio n. 1
0
        internal void ClearDsv(IDepthStencil ds, DepthStencilClearFlags clearFlags,
                               float depth, byte stencil)
        {
            IDepthStencilInternal dsInternal = (IDepthStencilInternal)ds;

            m_deviceContext.ClearDepthStencilView(dsInternal.Dsv, clearFlags, depth, stencil);
            CheckErrors();
        }
Esempio n. 2
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");
            }
        }
Esempio n. 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);
        }
Esempio n. 4
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;
        }
Esempio n. 5
0
 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);
 }
Esempio n. 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);
        }
Esempio n. 7
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));
        }
Esempio n. 8
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);
        }
Esempio n. 9
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);
        }
 public void ClearDepthStencilView(Texture texture, DepthStencilClearFlags flags, int depth = 1, byte stencil = 0)
 {
     NativeDeviceContext.ClearDepthStencilView(texture.NativeDepthStencilView, flags, depth, stencil);
 }
Esempio n. 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;
                }
            });
        }
Esempio n. 12
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);
                }
            }
        }
Esempio n. 13
0
        public void Run()
        {
            if (_userResized)
            {
                Utilities.Dispose(ref _backBuffer);
                Utilities.Dispose(ref _renderView);
                Utilities.Dispose(ref _depthBuffer);
                Utilities.Dispose(ref _depthView);

                _swapChain.ResizeBuffers(_swapChainDescription.BufferCount, _form.ClientSize.Width, _form.ClientSize.Height, Format.Unknown, SwapChainFlags.None);

                _backBuffer = D3D11.Resource.FromSwapChain <D3D11.Texture2D>(_swapChain, 0);

                _renderView = new D3D11.RenderTargetView(_device, _backBuffer);

                _depthBuffer = new D3D11.Texture2D(_device, new D3D11.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             = D3D11.ResourceUsage.Default,
                    BindFlags         = D3D11.BindFlags.DepthStencil,
                    CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                    OptionFlags       = D3D11.ResourceOptionFlags.None
                });

                _depthView = new D3D11.DepthStencilView(_device, _depthBuffer);

                _context.Rasterizer.SetViewport(new Viewport(0, 0, _form.ClientSize.Width, _form.ClientSize.Height, 0.0f, 1.0f));
                _context.Rasterizer.State = new D3D11.RasterizerState(_device, new D3D11.RasterizerStateDescription
                {
                    FillMode = D3D11.FillMode.Solid,
                    CullMode = D3D11.CullMode.Front,
                    IsFrontCounterClockwise = false,
                });
                _context.OutputMerger.SetTargets(_depthView, _renderView);

                const float rads = (60.0f / 360.0f) * (float)Math.PI * 2.0f;

                _proj        = Matrix.PerspectiveFovLH(rads, _form.ClientSize.Width / (float)_form.ClientSize.Height, 0.1f, 1000.0f);
                _userResized = false;
            }

            var time = _clock.ElapsedMilliseconds / 1000.0f;
            var dt   = time - lastTime;

            if (key == Keys.W)
            {
                camera.goForward(dt);
            }

            if (key == Keys.S)
            {
                camera.goBack(dt);
            }
            lastTime = time;
            var point = new System.Drawing.Point(_form.Location.X + (_form.Size.Width / 2), _form.Location.Y + (_form.Size.Height / 2));
            //Cursor.Position = point;


            var modelMatrix = Matrix.RotationX(time) * Matrix.RotationY(time) * Matrix.RotationZ(time) * Matrix.Translation(_primordialObject.Position);


            var worldViewProj = modelMatrix * camera.ViewProjectionMatrix;

            modelMatrix.Transpose();
            worldViewProj.Transpose();
            var modelMatrixArray = modelMatrix.ToArray();
            var MVPMatrix        = worldViewProj.ToArray();

            var modelInverse = modelMatrix;

            modelInverse.Invert();
            //modelInverse.Transpose();


            //_primordialObject.Position = new Vector3((float)Math.Cos(time * 2), (float)Math.Sin(time*2), (float)Math.Sin(time * 2)* (float)Math.Cos(time * 2));
            var renderTime = _clock.ElapsedMilliseconds;

            _context.ClearDepthStencilView(_depthView, D3D11.DepthStencilClearFlags.Depth, 1.0f, 0);
            _context.ClearRenderTargetView(_renderView, SharpDX.Color.Black);

            _context.UpdateSubresource(MVPMatrix, _contantBuffer);
            _context.UpdateSubresource(modelMatrixArray, _contantBuffer2);
            _context.UpdateSubresource(modelInverse.ToArray(), _contantBuffer3);

            var frameTime = _clock.ElapsedMilliseconds;

            _context.Draw(_primordialObject.VertexData.Length, 0);

            _swapChain.Present(0, PresentFlags.None);
            if ((_clock.ElapsedMilliseconds - frameTime) > 15)
            {
                File.AppendAllText(fileTitle + ".txt", (_clock.ElapsedMilliseconds - frameTime).ToString() + "\n");
                count++;
            }
            // if(count > 1)
            //_form.Close();
            if (_clock.Elapsed.TotalSeconds > 105)
            {
                // _form.Close();
            }
        }
        public void WorkThreadFunction()
        {
            // Prepare matrices
            view = Matrix.LookAtLH(new Vector3(0, 0, -40.0f), new Vector3(0, 0, 0), Vector3.UnitY);
            proj = Matrix.Identity;

            Texture2D        backBuffer  = null;
            RenderTargetView renderView  = null;
            Texture2D        depthBuffer = null;
            DepthStencilView depthView   = null;

            float rotation = 0.0f;
            int   T        = 0;

            Master.Invoke(new Action(() =>

                                     RenderLoop.Run(Master, () =>
            {
                // If Form resized
                if (Master.ResizeForm1)
                {
                    Random R = new Random(DateTime.Now.Millisecond);

                    T = R.Next(3);

                    // Dispose all previous allocated resources
                    Utilities.Dispose(ref backBuffer);
                    Utilities.Dispose(ref renderView);
                    Utilities.Dispose(ref depthBuffer);
                    Utilities.Dispose(ref depthView);

                    ScreenWidth  = Master.ClientSize.Width;
                    ScreenHeight = Master.ClientSize.Height;

                    // Resize the backbuffer
                    swapChain.ResizeBuffers(desc.BufferCount, ScreenWidth, ScreenHeight, 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             = ScreenWidth,
                        Height            = ScreenHeight,
                        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, ScreenWidth, ScreenHeight, 0.0f, 1.0f));
                    context.OutputMerger.SetTargets(depthView, renderView);

                    // Setup new projection matrix with correct aspect ratio
                    proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, ScreenWidth / (float)ScreenHeight, 0.1f, 1000.0f);

                    // We are done resizing
                    Master.ResizeForm1 = false;
                }

                SharpDX.Color C;


                if (T == 0)
                {
                    C = SharpDX.Color.Red;
                }
                else if (T == 1)
                {
                    C = SharpDX.Color.Gray;
                }
                else if (T == 2)
                {
                    C = SharpDX.Color.Black;
                }
                else
                {
                    C = SharpDX.Color.SpringGreen;
                }

                // Clear views
                context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                context.ClearRenderTargetView(renderView, C);

                keyboard.Poll();
                var datas = keyboard.GetBufferedData();
                foreach (var state in datas)
                {
                    if (state.IsPressed == true)
                    {
                        if (state.Key == Key.W)
                        {
                            //MessageBox.Show("allo");
                            m_W = true;
                        }
                        if (state.Key == Key.S)
                        {
                            m_S = true;
                        }
                        if (state.Key == Key.Q)
                        {
                            m_Q = true;
                        }
                        if (state.Key == Key.E)
                        {
                            m_E = true;
                        }
                        if (state.Key == Key.A)
                        {
                            m_A = true;
                        }
                        if (state.Key == Key.D)
                        {
                            m_D = true;
                        }
                        if (state.Key == Key.Z)
                        {
                            m_Z = true;
                        }
                        if (state.Key == Key.X)
                        {
                            m_X = true;
                        }
                        if (state.Key == Key.Space)
                        {
                            m_Space = true;
                        }
                        if (state.Key == Key.LeftControl)
                        {
                            Cntrl_Is_Down = true;
                            //Master.Close();
                        }
                    }
                    if (state.IsReleased == true)
                    {
                        if (state.Key == Key.W)
                        {
                            m_W = false;
                        }
                        if (state.Key == Key.S)
                        {
                            m_S = false;
                        }
                        if (state.Key == Key.Q)
                        {
                            m_Q = false;
                        }
                        if (state.Key == Key.E)
                        {
                            m_E = false;
                        }
                        if (state.Key == Key.A)
                        {
                            m_A = false;
                        }
                        if (state.Key == Key.D)
                        {
                            m_D = false;
                        }
                        if (state.Key == Key.Z)
                        {
                            m_Z = false;
                        }
                        if (state.Key == Key.X)
                        {
                            m_X = false;
                        }
                        if (state.Key == Key.Space)
                        {
                            m_Space = false;
                        }
                        if (state.Key == Key.LeftControl)
                        {
                            Cntrl_Is_Down = false;
                            //if (Mouse_Is_In == false) m_LockInput = true;
                        }
                    }
                }

                float facteur = 0.1f;

                if (m_W)
                {
                    Camera_Position += new Vector3(facteur, 0.0f, 0.0f);
                }
                if (m_S)
                {
                    Camera_Position += new Vector3(-facteur, 0.0f, 0.0f);
                }
                if (m_A)
                {
                    Camera_Position += new Vector3(0.0f, facteur, 0.0f);
                }
                if (m_D)
                {
                    Camera_Position += new Vector3(0.0f, -facteur, 0.0f);
                }
                if (m_Q)
                {
                    Camera_Position += new Vector3(0.0f, 0.0f, facteur);
                }
                if (m_E)
                {
                    Camera_Position += new Vector3(0.0f, 0.0f, -facteur);
                }

                mouse.Poll();


                MouseState Mo = mouse.GetCurrentState();


                Cam.Set_Frame(Mo.X, Mo.Y, Camera_Position, Mo.Z, 0, 0);



                rotation += 0.001f;
                O.Render(Cam.Get_View_Matrix(), proj, Matrix.Identity * Matrix.RotationY(rotation) * Matrix.RotationX(2 * rotation), context, new Vector4(0, 0, -100.0f, 0));


                // Present!
                swapChain.Present(1, PresentFlags.None);
                //});
            })));
            depthBuffer.Dispose();
            depthView.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
        }