Ejemplo n.º 1
0
        private void BuildFX()
        {
            SharpDX.D3DCompiler.ShaderBytecode compiledShader = null;
            try
            {
                compiledShader = new SharpDX.D3DCompiler.ShaderBytecode(System.IO.File.ReadAllBytes("fx/lighting.fxo"));
                _fx            = new D3D11.Effect(Device, compiledShader);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                Util.ReleaseCom(ref compiledShader);
            }

            _tech                     = _fx.GetTechniqueByName("LightTech");
            _fxWVP                    = _fx.GetVariableByName("gWorldViewProj").AsMatrix();
            _fxWorld                  = _fx.GetVariableByName("gWorld").AsMatrix();
            _fxWIT                    = _fx.GetVariableByName("gWorldInvTranspose").AsMatrix();
            _fxEyePosW                = _fx.GetVariableByName("gEyePosW").AsVector();
            _fxDirLight               = _fx.GetVariableByName("gDirLight");
            _fxPointLight             = _fx.GetVariableByName("gPointLight");
            _fxSpotLight              = _fx.GetVariableByName("gSpotLight");
            _fxMaterial               = _fx.GetVariableByName("gMaterial");
            _fxDiffuseMap             = _fx.GetVariableByName("gDiffuseMap").AsShaderResource();
            _fxRefractiveMap          = _fx.GetVariableByName("gRefractiveMap").AsShaderResource();
            _fxClipPlane              = _fx.GetVariableByName("gClipPlane").AsVector();
            _fxReflectViewProj        = _fx.GetVariableByName("gReflectViewProj").AsMatrix();
            _fxReflectiveMap          = _fx.GetVariableByName("gReflectiveMap").AsShaderResource();
            _fxgRefractionPositionMap = _fx.GetVariableByName("gRefractionPositionMap").AsShaderResource();
            _fxUseStructBuf           = _fx.GetVariableByName("gUseStructBuf").AsScalar();
            _fxSolutionSR             = _fx.GetVariableByName("gSolution").AsShaderResource();
        }
Ejemplo n.º 2
0
        public DrawingManager(DeviceManager deviceManager)
        {
            _device = deviceManager.Device;
            _context = deviceManager.Context;
            _vertexLayouts = deviceManager.VertexLayouts;

            var effect = deviceManager.Effect;

            _standardSmooth = effect.GetTechniqueByName("Standard|Smooth");
            _standardFlat = effect.GetTechniqueByName("Standard|Flat");
            _standardWireframe = effect.GetTechniqueByName("Standard|Wireframe");
            _prelitSmooth = effect.GetTechniqueByName("Prelit|Smooth");
            _prelitFlat = effect.GetTechniqueByName("Prelit|Flat");
            _prelitWireframe = effect.GetTechniqueByName("Prelit|Wireframe");

            _worldMatrix = effect.GetVariableByName("g_WorldMatrix").AsMatrix();
            _postWorldMatrix = effect.GetVariableByName("g_PostWorldMatrix").AsMatrix();
            _viewMatrix = effect.GetVariableByName("g_ViewMatrix").AsMatrix();
            _projectionMatrix = effect.GetVariableByName("g_ProjectionMatrix").AsMatrix();
            _color = effect.GetVariableByName("g_Color").AsVector();
            _opacity = effect.GetVariableByName("g_Opacity").AsScalar();
            _ambient = effect.GetVariableByName("g_Ambient").AsScalar();
            _diffuse = effect.GetVariableByName("g_Diffuse").AsScalar();
            _texture = effect.GetVariableByName("g_Texture").AsShaderResource();
            _mask = effect.GetVariableByName("g_Mask").AsShaderResource();
            _textureSampler = effect.GetVariableByName("g_TextureSampler").AsSampler();
            _hasTexture = effect.GetVariableByName("g_HasTexture").AsScalar();
            _hasMask = effect.GetVariableByName("g_HasMask").AsScalar();
            _isInstanced = effect.GetVariableByName("g_IsInstanced").AsScalar();
            _isColorTinted = effect.GetVariableByName("g_IsColorTinted").AsScalar();
            _globalLight = effect.GetVariableByName("g_GlobalLight");
            _lightViewProjectionMatrix = effect.GetVariableByName("g_LightViewProjectionMatrix").AsMatrix();

            //Set the states to Unknown initially.
            _currentDrawingState = DrawingState.Unknown;
            _currentTopologyState = PrimitiveTopologyState.Unknown;

            //Set the default of the g_PostWorldMatrix to Identity, so it isn't required to be set.
            _postWorldMatrix.SetMatrix(Matrix.Identity);

            //Setup shadow map technique.
            var shadowEffect = deviceManager.ShadowEffect;
            _shadowMapStandard = shadowEffect.GetTechniqueByName("ShadowMapTechnique|Standard");
            _shadowMapPrelit = shadowEffect.GetTechniqueByName("ShadowMapTechnique|Prelit");

            _isShadowInstanced = shadowEffect.GetVariableByName("g_IsInstanced").AsScalar();
            _shadowWorldMatrix = shadowEffect.GetVariableByName("g_WorldMatrix").AsMatrix();
            _shadowHasMask = shadowEffect.GetVariableByName("g_HasMask").AsScalar();
            _shadowMask = shadowEffect.GetVariableByName("g_Mask").AsShaderResource();
            _shadowLightViewProjectionMatrix = shadowEffect.GetVariableByName("g_LightViewProjectionMatrix").AsMatrix();
        }
Ejemplo n.º 3
0
        private void Init()
        {
            _WorldVar = GetVariableByName("g_World").AsMatrix();
            _WorldInverseTransposeVar = GetVariableByName("g_WorldInverseTranspose").AsMatrix();
            _WorldViewProjectionVar = GetVariableByName("g_WorldViewProjection").AsMatrix();

            _ViewInverseVar = GetVariableByName("m_ViewInverse").AsMatrix();

            _EyePositionVar = GetVariableByName("m_EyePosition").AsVector();
            _DirectionalLight0Var = new EffectDirectionalLightVariable(GetVariableByName("m_Light0"));
            _DirectionalLight1Var = new EffectDirectionalLightVariable(GetVariableByName("m_Light1"));
            _DirectionalLight2Var = new EffectDirectionalLightVariable(GetVariableByName("m_Light2"));

            _DiffuseColorVar = GetVariableByName("m_DiffuseColor").AsVector();
            _EmissiveColorVar = GetVariableByName("m_EmissiveColor").AsVector();
            _AmbientColorVar = GetVariableByName("m_AmbientColor").AsVector();
            _SpecularColorVar = GetVariableByName("m_SpecularColor").AsVector();
            _SpecularPowerVar = GetVariableByName("m_SpecularPower").AsScalar();

            SetDefaults();
        }
Ejemplo n.º 4
0
        public void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                    return;

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                    return;

                Width = Form.ClientSize.Width;
                Height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            Width = 1024;
            Height = 768;
            NearPlane = 1.0f;
            FarPlane = 200.0f;
            FieldOfView = (float)Math.PI / 4;

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 11 device.");
                return;
            }


            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;

            string[] sources = new[] { "shader.fx", "grender.fx" };
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags))
            {
                effect = new Effect(_device, shaderByteCode);
            }
            EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate");
            shadowGenPass = technique.GetPassByName("ShadowMap");
            gBufferGenPass = technique.GetPassByName("GBufferGen");
            debugDrawPass = technique.GetPassByName("DebugDraw");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None
            };
            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");
            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription _rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
            };
            noCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Back;
            backCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _rasterizerStateDesc.CullMode = CullMode.Front;
            frontCullState = new RasterizerState(_device, _rasterizerStateDesc);
            _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState;

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            depthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthWriteMask = DepthWriteMask.Zero;
            outsideLightVolumeDepthState = new DepthStencilState(_device, depthDesc);
            depthDesc.DepthComparison = Comparison.Greater;
            insideLightVolumeDepthState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx
            technique = effect.GetTechniqueByName("DeferredShader");
            gBufferRenderPass = technique.GetPassByName("DeferredShader");
            gBufferPostProcessPass = technique.GetPassByName("Blur");
            gBufferPostProcessPass2 = technique.GetPassByName("PostProcess");
            gBufferOverlayPass = technique.GetPassByName("Overlay");

            lightBufferVar = effect.GetVariableByName("lightBuffer").AsShaderResource();
            normalBufferVar = effect.GetVariableByName("normalBuffer").AsShaderResource();
            diffuseBufferVar = effect.GetVariableByName("diffuseBuffer").AsShaderResource();
            depthMapVar = effect.GetVariableByName("depthMap").AsShaderResource();
            shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource();

            sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector();
            viewportWidthVar = effect.GetVariableByName("ViewportWidth").AsScalar();
            viewportHeightVar = effect.GetVariableByName("ViewportHeight").AsScalar();
            viewParametersVar = effect.GetVariableByName("ViewParameters").AsVector();

            overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix();


            // light.fx
            using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags))
            {
                lightShader = new Effect(_device, shaderByteCode);
            }

            technique = lightShader.GetTechniqueByIndex(0);
            lightAccumulationPass = technique.GetPassByName("Light");

            lightWorldVar = lightShader.GetVariableByName("World").AsMatrix();
            lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector();
            lightColorVar = lightShader.GetVariableByName("Color").AsVector();

            lightProjectionVar = lightShader.GetVariableByName("Projection").AsMatrix();
            lightViewVar = lightShader.GetVariableByName("View").AsMatrix();
            lightViewInverseVar = lightShader.GetVariableByName("ViewInverse").AsMatrix();
            lightViewportWidthVar = lightShader.GetVariableByName("ViewportWidth").AsScalar();
            lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar();
            lightEyePositionVar = lightShader.GetVariableByName("EyePosition").AsVector();
            lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector();

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
            };
            lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements);

            pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices);
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer,
            };

            using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeVertices);
                data.Position = 0;
                pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc);
            }
            pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0);

            BufferDescription indexBufferDesc = new BufferDescription()
            {
                SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.IndexBuffer
            };
            using (var data = new SharpDX.DataStream(indexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(pointLightVolumeIndices);
                data.Position = 0;
                pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc);
            }

            lightDepthBufferVar = lightShader.GetVariableByName("depthBuffer").AsShaderResource();
            lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource();

            lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1)));
            //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1)));
            //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1)));
            //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1)));
            //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1)));


            Info = new InfoText(_device, 256, 256);
            _meshFactory = new MeshFactory(this);

            CreateBuffers();
        }
        void CreateBuffers()
        {
            DisposeBuffers();

            // New RenderTargetView from the backbuffer
            using (var bb = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0))
            {
                renderView = new RenderTargetView(_device, bb);
            }

            Texture2DDescription gBufferDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                Width = _width,
                Height = _height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            gBufferLight = new Texture2D(_device, gBufferDesc);
            gBufferLightView = new RenderTargetView(_device, gBufferLight);

            gBufferNormal = new Texture2D(_device, gBufferDesc);
            gBufferNormalView = new RenderTargetView(_device, gBufferNormal);

            gBufferDiffuse = new Texture2D(_device, gBufferDesc);
            gBufferDiffuseView = new RenderTargetView(_device, gBufferDiffuse);

            gBufferViews = new RenderTargetView[] { gBufferLightView, gBufferNormalView, gBufferDiffuseView };

            ShaderResourceViewDescription gBufferResourceDesc = new ShaderResourceViewDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            };
            lightBufferRes = new ShaderResourceView(_device, gBufferLight, gBufferResourceDesc);
            normalBufferRes = new ShaderResourceView(_device, gBufferNormal, gBufferResourceDesc);
            diffuseBufferRes = new ShaderResourceView(_device, gBufferDiffuse, gBufferResourceDesc);

            Texture2DDescription depthDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R32_Typeless,
                Width = _width,
                Height = _height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            DepthStencilViewDescription depthViewDesc = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D32_Float,
            };

            ShaderResourceViewDescription resourceDesc = new ShaderResourceViewDescription()
            {
                Format = Format.R32_Float,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            };

            depthTexture = new Texture2D(_device, depthDesc);
            depthView = new DepthStencilView(_device, depthTexture, depthViewDesc);
            depthRes = new ShaderResourceView(_device, depthTexture, resourceDesc);

            lightDepthTexture = new Texture2D(_device, depthDesc);
            lightDepthView = new DepthStencilView(_device, lightDepthTexture, depthViewDesc);
            lightDepthRes = new ShaderResourceView(_device, lightDepthTexture, resourceDesc);

            lightBufferVar = effect2.GetVariableByName("lightBuffer").AsShaderResource();
            normalBufferVar = effect2.GetVariableByName("normalBuffer").AsShaderResource();
            diffuseBufferVar = effect2.GetVariableByName("diffuseBuffer").AsShaderResource();
            depthMapVar = effect2.GetVariableByName("depthMap").AsShaderResource();
            lightDepthMapVar = effect2.GetVariableByName("lightDepthMap").AsShaderResource();

            inverseProjectionVar = effect2.GetVariableByName("InverseProjection").AsMatrix();
            inverseViewVar = effect2.GetVariableByName("InverseView").AsMatrix();
            lightInverseViewProjectionVar = effect2.GetVariableByName("LightInverseViewProjection").AsMatrix();
            lightPositionVar = effect2.GetVariableByName("LightPosition").AsVector();
            eyePositionVar = effect2.GetVariableByName("EyePosition").AsVector();
            eyeZAxisVar = effect2.GetVariableByName("EyeZAxis").AsVector();

            tanHalfFOVXVar = effect2.GetVariableByName("TanHalfFOVX").AsScalar();
            tanHalfFOVYVar = effect2.GetVariableByName("TanHalfFOVY").AsScalar();
            projectionAVar = effect2.GetVariableByName("ProjectionA").AsScalar();
            projectionBVar = effect2.GetVariableByName("ProjectionB").AsScalar();

            overlayViewProjectionVar = effect2.GetVariableByName("OverlayViewProjection").AsMatrix();

            _immediateContext.Rasterizer.SetViewport(new ViewportF(0, 0, _width, _height));
        }
Ejemplo n.º 6
0
        public WavesSimulator(IntPtr hInst)
            : base(hInst)
        {
            //Geometry Related Buffers
            _ballIB   = null;
            _ballVB   = null;
            _groundVB = null;
            _groundIB = null;
            _wavesVB  = null;
            _wavesIB  = null;


            _ballIndexCount   = 0;
            _groundIndexCount = 0;

            //WVP Matrices
            _groundWorld = Matrix.Identity;
            _wavesWorld  = Matrix.Translation(0, -2.0f, 0);
            _ballWorld   = Matrix.Translation(-30, 15, 0);
            _view        = Matrix.Identity;
            _proj        = Matrix.Identity;
            _reflectView = Matrix.Identity;

            //Rendering Effects Related
            _fx                       = null;
            _fxWVP                    = null;
            _tech                     = null;
            _fxWorld                  = null;
            _fxWIT                    = null;
            _fxEyePosW                = null;
            _fxDirLight               = null;
            _fxPointLight             = null;
            _fxSpotLight              = null;
            _fxMaterial               = null;
            _fxDiffuseMap             = null;
            _fxRefractiveMap          = null;
            _fxClipPlane              = null;
            _fxReflectiveMap          = null;
            _fxReflectViewProj        = null;
            _fxUseStructBuf           = null;
            _fxgRefractionPositionMap = null;

            //Textures and Views
            refractText             = null;
            refractRenderTargetView = null;
            refractResourceView     = null;

            reflectRenderTargetView = null;
            reflectResourceView     = null;
            reflectText             = null;

            positionMapRenderTargetView = null;
            positionMapResourceView     = null;
            positionMapText             = null;

            _groundMapSRV = null;
            _groundMap    = null;

            //Input Format
            _inputLayout = null;


            //Camera Related
            _theta        = 1.5f * MathF.PI;
            _phi          = 0.1f * MathF.PI;
            _radius       = 200.0f;
            _lastMousePos = new System.Drawing.Point(0, 0);
            _eyePosW      = new Vector3();


            //Shading and Lighting
            _alphaBlend = null;

            _dirLight = new DirectionalLight
            {
                Ambient   = new Color4(0.2f, 0.2f, 0.2f, 1),
                Diffuse   = new Color4(0.5f, 0.5f, 0.5f, 1),
                Specular  = new Color4(0.5f, 0.5f, 0.5f, 1),
                Direction = new Vector3(0.57735f, -0.57735f, 0.57735f)
            };

            _pointLight = new PointLight
            {
                Ambient     = new Color4(0.3f, 0.3f, 0.3f, 1),
                Diffuse     = new Color4(0.7f, 0.7f, 0.7f, 1),
                Specular    = new Color4(0.7f, 0.7f, 0.7f, 1),
                Attenuation = new Vector3(0.1f, 0.1f, 0.1f),
                Range       = 25.0f
            };
            _spotLight = new SpotLight
            {
                Ambient     = new Color4(0, 0, 0, 0),
                Diffuse     = new Color4(1.0f, 1.0f, 1.0f, 1),
                Specular    = Color.White,
                Attenuation = new Vector3(1.0f, 0.0f, 0.0f),
                Spot        = 96.0f,
                Range       = 10000.0f
            };


            _landMaterial = new Material
            {
                Ambient  = new Color4(1f, 1f, 1f, 1.0f),
                Diffuse  = new Color4(1, 1, 1, 1.0f),
                Specular = new Color4(0.2f, 0.2f, 0.2f, 16.0f),
                Reflect  = new Color4(1.0f, 1f, 1f, 1f)
            };
            _wavesMaterial = new Material
            {
                Ambient  = new Color4(1, 1, 1, 0.8f),
                Diffuse  = new Color4(0.137f, 0.42f, 0.556f, 1.0f),
                Specular = new Color4(0.8f, 0.8f, 0.8f, 96.0f),
                Reflect  = new Color4(2f, 1, 1, 1) //R component of Reflect is used for Gama Correction in Effect
            };


            _disposed         = false;
            MainWindowCaption = "Waves Simulator";
        }