Beispiel #1
0
        public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
        {
            if (this.pin.PluginIO.IsConnected)
            {
                if (this.pin.IsChanged)
                {
                    if (this.state != null)
                    {
                        this.state.Dispose(); this.state = null;
                    }
                }

                if (this.state == null || this.state.Disposed)
                {
                    this.state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[0]);
                }
                shaderinstance.SetByName(this.Name, this.state);
            }
            else
            {
                if (this.state != null)
                {
                    this.state.Dispose();
                    this.state = null;
                    shaderinstance.SetByName(this.Name, this.state);
                }
            }
        }
Beispiel #2
0
        public SamplerState getSamplerState()
        {
            SamplerState samplerState;

            if (samplerList.Count > 0)
            {
                return(samplerList[0]);
            }
            try
            {
                SamplerDescription description = new SamplerDescription
                {
                    Filter   = SlimDX.Direct3D11.Filter.Anisotropic,
                    AddressU = SlimDX.Direct3D11.TextureAddressMode.Wrap,
                    AddressV = SlimDX.Direct3D11.TextureAddressMode.Wrap,
                    AddressW = TextureAddressMode.Wrap,
                };
                samplerState = SamplerState.FromDescription(device, description);
                samplerList.Add(samplerState);
            }
            catch (Exception e)
            {
                samplerState = null;
            }

            return(samplerState);
        }
Beispiel #3
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="context">レンダーコンテキスト</param>
        /// <param name="width">描画に利用するテクスチャの解像度の幅</param>
        /// <param name="height">描画に利用するテクスチャの解像度の高さ</param>
        public GDISpriteBatch(RenderContext context, int width, int height)
        {
            this.Context = context;
            Resize(width, height);
            SpriteEffect      = CGHelper.CreateEffectFx5("Shader\\sprite.fx", context.DeviceManager.Device);
            renderPass        = SpriteEffect.GetTechniqueByIndex(0).GetPassByIndex(0);
            VertexInputLayout = new InputLayout(context.DeviceManager.Device, SpriteEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, SpriteVertexLayout.InputElements);
            SamplerDescription desc = new SamplerDescription();

            desc.Filter   = Filter.MinMagMipLinear;
            desc.AddressU = TextureAddressMode.Wrap;
            desc.AddressV = TextureAddressMode.Wrap;
            desc.AddressW = TextureAddressMode.Wrap;
            sampler       = SamplerState.FromDescription(context.DeviceManager.Device, desc);
            mapedGraphic  = Graphics.FromImage(mapedBitmap);
            BlendStateDescription blendDesc = new BlendStateDescription();

            blendDesc.AlphaToCoverageEnable  = false;
            blendDesc.IndependentBlendEnable = false;
            for (int i = 0; i < blendDesc.RenderTargets.Length; i++)
            {
                blendDesc.RenderTargets[i].BlendEnable           = true;
                blendDesc.RenderTargets[i].SourceBlend           = BlendOption.SourceAlpha;
                blendDesc.RenderTargets[i].DestinationBlend      = BlendOption.InverseSourceAlpha;
                blendDesc.RenderTargets[i].BlendOperation        = BlendOperation.Add;
                blendDesc.RenderTargets[i].SourceBlendAlpha      = BlendOption.One;
                blendDesc.RenderTargets[i].DestinationBlendAlpha = BlendOption.Zero;
                blendDesc.RenderTargets[i].BlendOperationAlpha   = BlendOperation.Add;
                blendDesc.RenderTargets[i].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            }
            ViewMatrix = Matrix.LookAtLH(new Vector3(0, 0, -1), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
            state      = BlendState.FromDescription(context.DeviceManager.Device, blendDesc);
            NeedRedraw = true;
            Update();
        }
Beispiel #4
0
        public SurfaceMaterial(DX11Game game, ShaderResourceView diffuseTexture)
        {
            this.game = game;


            textures[0] = diffuseTexture;
            textures[1] = null; //normalTexture;
            textures[2] = null; //specularTexture;


            baseShader = BasicShader.LoadAutoreload(game, ShaderFiles.DCSurface, delegate { }, createShaderMacros());
            baseShader.SetTechnique("DCSurface");
            //baseShader.DiffuseTexture = checkerTexture;

            var desc = new SamplerDescription()
            {
                AddressU          = TextureAddressMode.Wrap,
                AddressV          = TextureAddressMode.Wrap,
                AddressW          = TextureAddressMode.Wrap,
                Filter            = Filter.Anisotropic,
                MaximumAnisotropy = 16
            };

            sampler = SamplerState.FromDescription(game.Device, desc);

            inputLayout = CreateInputLayout();
        }
Beispiel #5
0
        public override void Initialize()
        {
            base.Initialize();

            try
            {
                using (ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(
                           "Shaders/GouraudTextured.fx",
                           "VShader",
                           "vs_4_0",
                           ShaderFlags.None,
                           EffectFlags.None,
                           null,
                           new IncludeFX("Shaders")))
                {
                    vertexShader   = new VertexShader(DeviceManager.Instance.device, vertexShaderByteCode);
                    inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
                }

                using (ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(
                           "Shaders/GouraudTextured.fx",
                           "PShader",
                           "ps_4_0",
                           ShaderFlags.None,
                           EffectFlags.None,
                           null,
                           new IncludeFX("Shaders")))
                {
                    pixelShader = new PixelShader(DeviceManager.Instance.device, pixelShaderByteCode);
                }

                layout = new InputLayout(DeviceManager.Instance.device, inputSignature, elements);

                ConstantsBuffer = new SlimDX.Direct3D11.Buffer(
                    DeviceManager.Instance.device,
                    0x140,                    //Marshal.SizeOf(Constants),
                    ResourceUsage.Dynamic,
                    BindFlags.ConstantBuffer,
                    CpuAccessFlags.Write,
                    ResourceOptionFlags.None,
                    0
                    );

                SamplerDescription sDefault = new SamplerDescription();
                sDefault.AddressU           = TextureAddressMode.Wrap;
                sDefault.AddressV           = TextureAddressMode.Wrap;
                sDefault.AddressW           = TextureAddressMode.Wrap;
                sDefault.Filter             = Filter.MinMagMipLinear;
                sDefault.ComparisonFunction = Comparison.Never;
                sDefault.MinimumLod         = 0;
                sDefault.MaximumLod         = float.MaxValue;

                Sampler = SamplerState.FromDescription(DeviceManager.Instance.device, sDefault);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #6
0
        private void RenderTextured(DX11RenderContext context, DX11RenderSettings settings)
        {
            QuadShaderDeviceData qd = quaddata[context];

            qd.quadshader.SelectTechnique("RenderTextured");
            qd.quadgeometry.Bind(qd.quadlayouts[1]);

            for (int i = 0; i < this.spmax; i++)
            {
                bool popstate = false;
                if (this.FInState.IsConnected)
                {
                    context.RenderStateStack.Push(this.FInState[i]);
                    popstate = true;
                }

                if (this.FInSamplerState.IsConnected)
                {
                    SamplerState state = SamplerState.FromDescription(context.Device, this.FInSamplerState[i]);
                    qd.samplervariable.SetSamplerState(0, state);
                }
                else
                {
                    qd.samplervariable.UndoSetSamplerState(0);
                }

                var color = this.FInColor[i];
                color.Alpha *= settings.LayerOpacity;

                qd.quadshader.SetBySemantic("COLOR", color);
                qd.quadshader.SetBySemantic("WORLD", this.FInWorld[i]);
                qd.quadshader.SetBySemantic("TEXTUREMATRIX", this.FInTexTransform[i]);

                if (this.FInTexture[i].Contains(context) && this.FInTexture[i][context] != null)
                {
                    qd.texturevariable.SetResource(this.FInTexture[i][context].SRV);
                }
                else
                {
                    qd.texturevariable.SetResource(null);
                }

                qd.quadshader.ApplyPass(0);
                if (settings.DepthOnly)
                {
                    context.CurrentDeviceContext.PixelShader.Set(null);
                }
                qd.quadgeometry.Draw();

                if (popstate)
                {
                    context.RenderStateStack.Pop();
                }
            }
        }
Beispiel #7
0
 public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
 {
     if (this.pin.IsConnected)
     {
         using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice]))
         {
             shaderinstance.SetByName(this.Name, state);
         }
     }
     else
     {
         shaderinstance.Effect.GetVariableByName(this.Name).AsSampler().UndoSetSamplerState(0);
     }
 }
        void CreateSamplers()
        {
            SamplerDescription desc = new SamplerDescription();

            desc.AddressU          = TextureAddressMode.Mirror;
            desc.AddressV          = TextureAddressMode.Mirror;
            desc.AddressW          = TextureAddressMode.Mirror;
            desc.Filter            = Filter.MinMagMipLinear;
            desc.MaximumAnisotropy = 16;
            desc.MaximumLod        = float.MaxValue;
            SamplerState s = SamplerState.FromDescription(device_, desc);

            samplerStates_.Add("minMagMipLinear", s);
        }
Beispiel #9
0
        private void RenderInstancedTextured(DX11RenderContext context, DX11RenderSettings settings)
        {
            QuadShaderDeviceData qd = quaddata[context];
            bool popstate           = false;

            if (this.FInState.IsConnected)
            {
                context.RenderStateStack.Push(this.FInState[0]);
                popstate = true;
            }

            if (this.FInSamplerState.IsConnected)
            {
                SamplerState state = SamplerState.FromDescription(context.Device, this.FInSamplerState[0]);
                qd.samplervariable.SetSamplerState(0, state);
            }
            else
            {
                qd.samplervariable.UndoSetSamplerState(0);
            }

            qd.quadshader.SelectTechnique("RenderInstancedTextured");
            qd.quadgeometry.Bind(qd.quadlayouts[3]);
            qd.quadshader.SetBySemantic("LAYEROPACITY", settings.LayerOpacity);

            this.BindBuffers(context);

            if (this.FInTexture[0].Contains(context) && this.FInTexture[0][context] != null)
            {
                qd.texturevariable.SetResource(this.FInTexture[0][context].SRV);
            }
            else
            {
                qd.texturevariable.SetResource(null);
            }

            qd.quadshader.ApplyPass(0);
            if (settings.DepthOnly)
            {
                context.CurrentDeviceContext.PixelShader.Set(null);
            }

            context.CurrentDeviceContext.DrawIndexedInstanced(qd.quadgeometry.IndexBuffer.IndicesCount, this.spmax, 0, 0, 0);

            if (popstate)
            {
                context.RenderStateStack.Pop();
            }
        }
        public void Execute()
        {
            if (mRenderTarget == null)
            {
                CreateView(mWidth, mHeight);
            }

            var context = Device.ImmediateContext;
            var view    = mRenderTarget.GetRenderTargetView();

            context.ClearRenderTargetView(view, new Color4(0, 0, 0));
            context.InputAssembler.InputLayout = new InputLayout(Device, ShaderSignature.GetInputSignature(mVertexShaderBytecode), new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0)
            });
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(mVertexBuffer, 20, 0));

            context.VertexShader.Set(mVertexShader);
            context.PixelShader.Set(mPixelShader);

            Constants.Submit();
            Resources.Submit();

            context.PixelShader.SetSampler(SamplerState.FromDescription(Device, new SamplerDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter   = Filter.MinPointMagMipLinear
            }), 0);

            context.OutputMerger.SetTargets(view);
            context.Draw(4, 0);

            mSwapChain.Present(0, PresentFlags.None);

            context.VertexShader.Set(null);
            context.PixelShader.Set(null);

            var sourceDescription = mRenderTarget.GetTexture2D().Description;

            sourceDescription.BindFlags      = 0;
            sourceDescription.CpuAccessFlags = CpuAccessFlags.Read | CpuAccessFlags.Write;
            sourceDescription.Usage          = ResourceUsage.Staging;
        }
Beispiel #11
0
        private void RenderTextured(DX11RenderContext context)
        {
            quadshader.SelectTechnique("RenderTextured");
            quadgeometry.Bind(quadlayouts[1]);

            for (int i = 0; i < this.spmax; i++)
            {
                bool popstate = false;
                if (this.FInState.PluginIO.IsConnected)
                {
                    context.RenderStateStack.Push(this.FInState[i]);
                    popstate = true;
                }

                if (this.FInSamplerState.PluginIO.IsConnected)
                {
                    SamplerState state = SamplerState.FromDescription(context.Device, this.FInSamplerState[i]);
                    samplervariable.SetSamplerState(0, state);
                }
                else
                {
                    samplervariable.UndoSetSamplerState(0);
                }

                quadshader.SetBySemantic("COLOR", this.FInColor[i]);
                quadshader.SetBySemantic("WORLD", this.FInWorld[i]);
                quadshader.SetBySemantic("TEXTUREMATRIX", this.FInTexTransform[i]);

                if (this.FInTexture[i].Contains(context))
                {
                    texturevariable.SetResource(this.FInTexture[i][context].SRV);
                }
                else
                {
                    texturevariable.SetResource(null);
                }

                quadshader.ApplyPass(0);

                quadgeometry.Draw();

                if (popstate)
                {
                    context.RenderStateStack.Pop();
                }
            }
        }
Beispiel #12
0
        public SamplerStates()
        {
            var samplerDesc = new SamplerDescription
            {
                AddressU   = TextureAddressMode.Wrap,
                AddressV   = TextureAddressMode.Wrap,
                AddressW   = TextureAddressMode.Wrap,
                Filter     = Filter.MinMagMipLinear,
                MinimumLod = 0,
                MaximumLod = 0
            };

            LinSampler = SamplerState.FromDescription(RenderFrame.Instance.device, samplerDesc);

            samplerDesc.Filter = Filter.MinMagPointMipLinear;
            PointSampler       = SamplerState.FromDescription(RenderFrame.Instance.device, samplerDesc);
        }
Beispiel #13
0
        public void SwitchWrapMode()
        {
            wrap = !wrap;
            var samplerDesc = new SamplerDescription
            {
                AddressU   = wrap ? TextureAddressMode.Wrap : TextureAddressMode.Clamp,
                AddressV   = wrap ? TextureAddressMode.Wrap : TextureAddressMode.Clamp,
                AddressW   = wrap ? TextureAddressMode.Wrap : TextureAddressMode.Clamp,
                Filter     = Filter.MinMagMipLinear,
                MinimumLod = 0,
                MaximumLod = 0
            };

            LinSampler = SamplerState.FromDescription(RenderFrame.Instance.device, samplerDesc);

            samplerDesc.Filter = Filter.MinMagPointMipLinear;
            PointSampler       = SamplerState.FromDescription(RenderFrame.Instance.device, samplerDesc);
        }
Beispiel #14
0
        /// <summary>
        /// サンプラステート
        /// 現状フィルタはリニア固定
        /// </summary>
        static void InitializeSamplerState()
        {
            var device    = D3D11Device;
            int state_num = (int)RenderState.TextureAddressing.Max;

            samplerState_ = new SamplerState[state_num][];

            TextureAddressMode[] dx_list = new TextureAddressMode[] {
                TextureAddressMode.Clamp,
                TextureAddressMode.Wrap,
                TextureAddressMode.Mirror,
                TextureAddressMode.Border,
            };

            for (int i = 0; i < state_num; i++)
            {
                samplerState_[i] = new SamplerState[state_num];
                for (int j = 0; j < state_num; j++)
                {
                    SamplerDescription samplerDescription = new SamplerDescription()
                    {
                        AddressU = dx_list[i],
                        AddressV = dx_list[j],
                        AddressW = TextureAddressMode.Clamp,
                        Filter   = Filter.MinMagMipLinear,
                        //Filter = Filter.MinMagMipPoint,
                        //Filter = Filter.Anisotropic,		//とりあえず固定でAnisoに
                        MipLodBias        = -1,
                        MinimumLod        = 0,
                        MaximumLod        = 255,
                        MaximumAnisotropy = 4,
                        BorderColor       = new Color4(0, 0, 0, 1),
                    };

                    samplerState_[i][j] = SamplerState.FromDescription(device, samplerDescription);
                }
            }


            // 初期値
            int wrap = (int)RenderState.TextureAddressing.Wrap;

            D3D11ImmediateContext.PixelShader.SetSampler(samplerState_[wrap][wrap], 0);
        }
Beispiel #15
0
        private void RenderInstancedTextured(DX11RenderContext context)
        {
            QuadShaderDeviceData qd = quaddata[context];
            bool popstate           = false;

            if (this.FInState.IsConnected)
            {
                context.RenderStateStack.Push(this.FInState[0]);
                popstate = true;
            }

            if (this.FInSamplerState.PluginIO.IsConnected)
            {
                SamplerState state = SamplerState.FromDescription(context.Device, this.FInSamplerState[0]);
                qd.samplervariable.SetSamplerState(0, state);
            }
            else
            {
                qd.samplervariable.UndoSetSamplerState(0);
            }

            qd.quadshader.SelectTechnique("RenderInstancedTextured");
            qd.quadgeometry.Bind(qd.quadlayouts[3]);

            this.BindBuffers(context);

            if (this.FInTexture[0].Contains(context))
            {
                qd.texturevariable.SetResource(this.FInTexture[0][context].SRV);
            }
            else
            {
                qd.texturevariable.SetResource(null);
            }

            qd.quadshader.ApplyPass(0);

            context.CurrentDeviceContext.DrawIndexedInstanced(qd.quadgeometry.IndexBuffer.IndicesCount, this.spmax, 0, 0, 0);

            if (popstate)
            {
                context.RenderStateStack.Pop();
            }
        }
Beispiel #16
0
        public D2DSpriteBatch(RenderContext context)
        {
            this.context           = context;
            this.DeviceManager     = context.DeviceManager;
            this.SpriteEffect      = CGHelper.CreateEffectFx5FromResource("MMF.Resource.Shader.SpriteShader.fx", this.DeviceManager.Device);
            this.renderPass        = this.SpriteEffect.GetTechniqueByIndex(0).GetPassByIndex(1);
            this.VertexInputLayout = new InputLayout(this.DeviceManager.Device, this.SpriteEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, SpriteVertexLayout.InputElements);
            SamplerDescription desc = new SamplerDescription();

            desc.Filter   = Filter.MinMagMipLinear;
            desc.AddressU = TextureAddressMode.Wrap;
            desc.AddressV = TextureAddressMode.Wrap;
            desc.AddressW = TextureAddressMode.Wrap;
            this.sampler  = SamplerState.FromDescription(this.DeviceManager.Device, desc);
            BlendStateDescription blendDesc = new BlendStateDescription();

            blendDesc.AlphaToCoverageEnable  = false;
            blendDesc.IndependentBlendEnable = false;
            for (int i = 0; i < blendDesc.RenderTargets.Length; i++)
            {
                blendDesc.RenderTargets[i].BlendEnable           = true;
                blendDesc.RenderTargets[i].SourceBlend           = BlendOption.SourceAlpha;
                blendDesc.RenderTargets[i].DestinationBlend      = BlendOption.InverseSourceAlpha;
                blendDesc.RenderTargets[i].BlendOperation        = BlendOperation.Add;
                blendDesc.RenderTargets[i].SourceBlendAlpha      = BlendOption.One;
                blendDesc.RenderTargets[i].DestinationBlendAlpha = BlendOption.Zero;
                blendDesc.RenderTargets[i].BlendOperationAlpha   = BlendOperation.Add;
                blendDesc.RenderTargets[i].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            }
            this.state = BlendState.FromDescription(this.DeviceManager.Device, blendDesc);

            BlendStateDescription bsd = new BlendStateDescription();

            bsd.RenderTargets[0].BlendEnable           = true;
            bsd.RenderTargets[0].SourceBlend           = BlendOption.SourceAlpha;
            bsd.RenderTargets[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            bsd.RenderTargets[0].BlendOperation        = BlendOperation.Add;
            bsd.RenderTargets[0].SourceBlendAlpha      = BlendOption.One;
            bsd.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
            bsd.RenderTargets[0].BlendOperationAlpha   = BlendOperation.Add;
            bsd.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            this.TransParentBlendState = BlendState.FromDescription(this.DeviceManager.Device, bsd);
            Resize();
        }
Beispiel #17
0
        static Result InitDevice()
        {
            //int width = form.ClientSize.Width;
            //int height = form.ClientSize.Height;
            int width  = 2500;
            int height = 1000;

            SlimDX.DXGI.SwapChainDescription swapChainDesc = new SlimDX.DXGI.SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new SlimDX.DXGI.ModeDescription()
                {
                    Width       = width,
                    Height      = height,
                    Format      = SlimDX.DXGI.Format.B8G8R8A8_UNorm,
                    RefreshRate = new Rational(60, 1),
                },
                Usage             = SlimDX.DXGI.Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                SampleDescription = new SlimDX.DXGI.SampleDescription {
                    Count = 1, Quality = 0
                },
                IsWindowed = true,
            };
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, new FeatureLevel[] { FeatureLevel.Level_11_0 }, swapChainDesc, out _Device, out _SwapChain);
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Create a render target view
            Texture2D backBuffer = Resource.FromSwapChain <Texture2D>(_SwapChain, 0);

            _ViewRenderTarget = new RenderTargetView(_Device, backBuffer);
            backBuffer.Dispose();
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }
            _Device.ImmediateContext.OutputMerger.SetTargets(_ViewRenderTarget);

            // Setup the viewport
            Viewport vp = new Viewport
            {
                Width  = width,
                Height = height,
                MinZ   = 0.0f,
                MaxZ   = 1.0f,
                X      = 0,
                Y      = 0,
            };

            _Device.ImmediateContext.Rasterizer.SetViewports(vp);

            // Compile the vertex shader
            ShaderBytecode vertexShaderCode = ShaderBytecode.CompileFromFile("haha.fx", "VS", "vs_4_0", ShaderFlags.EnableStrictness | ShaderFlags.Debug, EffectFlags.None);

            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Create the vertex shader
            _VertexShader = new VertexShader(_Device, vertexShaderCode);
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Define the input layout
            InputElement[] inputElements = new InputElement[2]
            {
                new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("TEXCOORD", 0, SlimDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0),
            };
            _LayOut = new InputLayout(_Device, vertexShaderCode, inputElements);
            vertexShaderCode.Dispose();
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Set the input layout
            _Device.ImmediateContext.InputAssembler.InputLayout = _LayOut;

            // Compile the pixel shader
            ShaderBytecode pixelShaderCode = ShaderBytecode.CompileFromFile("haha.fx", "PS", "ps_4_0", ShaderFlags.EnableStrictness | ShaderFlags.Debug, EffectFlags.None);

            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Create the pixel shader
            _PixelShader = new PixelShader(_Device, pixelShaderCode);
            pixelShaderCode.Dispose();
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Create vertex buffer
            CustomVertex[] vertices = new CustomVertex[]
            {
                new CustomVertex()
                {
                    Pos = new Vector3(-1.0f, 1.0f, 0.0f), Tex = new Vector2(0.0f, 0.0f)
                },                                                                                          // top left
                new CustomVertex()
                {
                    Pos = new Vector3(0.0f, 1.0f, 0.0f), Tex = new Vector2(1.0f, 0.0f)
                },                                                                                           // top right
                new CustomVertex()
                {
                    Pos = new Vector3(-1.0f, 0.0f, 0.0f), Tex = new Vector2(0.0f, 1.0f)
                },                                                                                         // lower left
                new CustomVertex()
                {
                    Pos = new Vector3(0.0f, 0.0f, 0.0f), Tex = new Vector2(1.0f, 1.0f)
                },                                                                                          // lower right

                new CustomVertex()
                {
                    Pos = new Vector3(0.0f, 1.0f, 0.0f), Tex = new Vector2(0.0f, 0.0f)
                },                                                                                          // top left
                new CustomVertex()
                {
                    Pos = new Vector3(1.0f, 1.0f, 0.0f), Tex = new Vector2(1.0f, 0.0f)
                },                                                                                           // top right
                new CustomVertex()
                {
                    Pos = new Vector3(0.0f, 0.0f, 0.0f), Tex = new Vector2(0.0f, 1.0f)
                },                                                                                         // lower left
                new CustomVertex()
                {
                    Pos = new Vector3(1.0f, 0.0f, 0.0f), Tex = new Vector2(1.0f, 1.0f)
                },                                                                                          // lower right

                new CustomVertex()
                {
                    Pos = new Vector3(-1.0f, 0.0f, 0.0f), Tex = new Vector2(0.0f, 0.0f)
                },                                                                                          // top left
                new CustomVertex()
                {
                    Pos = new Vector3(0.0f, 0.0f, 0.0f), Tex = new Vector2(1.0f, 0.0f)
                },                                                                                           // top right
                new CustomVertex()
                {
                    Pos = new Vector3(-1.0f, -1.0f, 0.0f), Tex = new Vector2(0.0f, 1.0f)
                },                                                                                         // lower left
                new CustomVertex()
                {
                    Pos = new Vector3(0.0f, -1.0f, 0.0f), Tex = new Vector2(1.0f, 1.0f)
                },                                                                                          // lower right

                new CustomVertex()
                {
                    Pos = new Vector3(0.0f, 0.0f, 0.0f), Tex = new Vector2(0.0f, 0.0f)
                },                                                                                          // top left
                new CustomVertex()
                {
                    Pos = new Vector3(1.0f, 0.0f, 0.0f), Tex = new Vector2(1.0f, 0.0f)
                },                                                                                           // top right
                new CustomVertex()
                {
                    Pos = new Vector3(0.0f, -1.0f, 0.0f), Tex = new Vector2(0.0f, 1.0f)
                },                                                                                         // lower left
                new CustomVertex()
                {
                    Pos = new Vector3(1.0f, -1.0f, 0.0f), Tex = new Vector2(1.0f, 1.0f)
                },                                                                                          // lower right
            };
            DataStream        vertexData = new DataStream(vertices, true, false);
            int               stride     = System.Runtime.InteropServices.Marshal.SizeOf(vertices[0]);
            BufferDescription bufferDesc = new BufferDescription
            {
                Usage          = ResourceUsage.Default,
                SizeInBytes    = vertices.Length * stride,
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
            };

            _VertexBuffer = new SlimDX.Direct3D11.Buffer(_Device, vertexData, bufferDesc);
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Set vertex buffer
            _Device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_VertexBuffer, stride, 0));

            // Create index buffer
            int[] indices = new int[]
            {
                0, 1, 2,
                1, 3, 2,

                4, 5, 6,
                5, 7, 6,

                8, 9, 10,
                9, 11, 10,

                12, 13, 14,
                13, 15, 14,
            };
            bufferDesc.SizeInBytes = sizeof(int) * indices.Length;
            bufferDesc.BindFlags   = BindFlags.IndexBuffer;
            _IndexBuffer           = new SlimDX.Direct3D11.Buffer(_Device, new DataStream(indices, false, false), bufferDesc);
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Set index buffer
            _Device.ImmediateContext.InputAssembler.SetIndexBuffer(_IndexBuffer, SlimDX.DXGI.Format.R32_UInt, 0);

            // Set primitive topology
            _Device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // Load the Texture
            LoadTexture();
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            // Create the sample state
            SamplerDescription sampDesc = new SamplerDescription
            {
                Filter             = Filter.MinMagMipPoint,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                ComparisonFunction = Comparison.Never,
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue,
            };

            _SamplerLinear = SamplerState.FromDescription(_Device, sampDesc);
            if (Result.Last.IsFailure)
            {
                return(Result.Last);
            }

            return(ResultCode.Success);
        }
Beispiel #18
0
        public void Render(DX11RenderContext context, DX11RenderSettings settings)
        {
            if (this.spmax == 0)
            {
                return;
            }

            if (this.BeginQuery != null)
            {
                this.BeginQuery(context);
            }

            context.CleanShaderStages();
            ShaderDeviceData deviceData = this.shaderData[context];

            context.Primitives.FullScreenTriangle.Bind(null);

            for (int i = 0; i < spmax; i++)
            {
                if (this.FEnabled[i])
                {
                    if (this.FInState.IsConnected)
                    {
                        context.RenderStateStack.Push(this.FInState[i]);
                    }
                    else
                    {
                        this.defaultState.Blend = DX11BlendStates.GetState(this.FInBlendState[i]);
                        context.RenderStateStack.Push(this.defaultState);
                    }

                    if (this.FInSamplerState.IsConnected)
                    {
                        SamplerState state = SamplerState.FromDescription(context.Device, this.FInSamplerState[i]);
                        deviceData.samplerVariable.SetSamplerState(0, state);
                    }
                    else
                    {
                        deviceData.samplerVariable.UndoSetSamplerState(0);
                    }

                    var color = this.FInColor[i];
                    color.Alpha *= settings.LayerOpacity;

                    deviceData.colorVariable.Set(color);
                    deviceData.texTransformVariable.SetMatrix(this.FInTexTransform[i]);

                    if (this.FInTexture.IsConnected)
                    {
                        if (this.FInTexture[i].Contains(context) && this.FInTexture[i][context] != null)
                        {
                            deviceData.inputTextureVariable.SetResource(this.FInTexture[i][context].SRV);
                        }
                        else
                        {
                            deviceData.inputTextureVariable.SetResource(null);
                        }
                    }
                    else
                    {
                        deviceData.inputTextureVariable.SetResource(context.DefaultTextures.WhiteTexture.SRV);
                    }


                    deviceData.pass.Apply(context.CurrentDeviceContext);
                    context.CurrentDeviceContext.Draw(3, 0);

                    context.RenderStateStack.Pop();
                }
            }

            if (this.EndQuery != null)
            {
                this.EndQuery(context);
            }
        }
Beispiel #19
0
        public static void Initialize(Device device)
        {
            m_Initialized = true;

            var samplerDescription = new SamplerDescription()
            {
                AddressU   = TextureAddressMode.Wrap,
                AddressV   = TextureAddressMode.Wrap,
                AddressW   = TextureAddressMode.Wrap,
                Filter     = Filter.MinMagMipPoint,
                MinimumLod = 0,
                MaximumLod = 255,
            };

            m_SamplerStates[(int)SamplerType.PointWrap] = SamplerState.FromDescription(device, samplerDescription);

            samplerDescription = new SamplerDescription()
            {
                AddressU   = TextureAddressMode.Clamp,
                AddressV   = TextureAddressMode.Clamp,
                AddressW   = TextureAddressMode.Clamp,
                Filter     = Filter.MinMagMipPoint,
                MinimumLod = 0,
                MaximumLod = 255,
            };

            m_SamplerStates[(int)SamplerType.PointClamp] = SamplerState.FromDescription(device, samplerDescription);

            samplerDescription = new SamplerDescription()
            {
                AddressU   = TextureAddressMode.Wrap,
                AddressV   = TextureAddressMode.Wrap,
                AddressW   = TextureAddressMode.Wrap,
                Filter     = Filter.MinMagMipLinear,
                MinimumLod = 0,
                MaximumLod = 255,
            };

            m_SamplerStates[(int)SamplerType.LinearWrap] = SamplerState.FromDescription(device, samplerDescription);

            samplerDescription = new SamplerDescription()
            {
                AddressU   = TextureAddressMode.Clamp,
                AddressV   = TextureAddressMode.Clamp,
                AddressW   = TextureAddressMode.Clamp,
                Filter     = Filter.MinMagMipLinear,
                MinimumLod = 0,
                MaximumLod = 255,
            };

            m_SamplerStates[(int)SamplerType.LinearClamp] = SamplerState.FromDescription(device, samplerDescription);

            samplerDescription = new SamplerDescription()
            {
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                Filter             = Filter.ComparisonMinMagMipLinear,
                MinimumLod         = 0,
                MaximumLod         = 255,
                ComparisonFunction = Comparison.LessEqual
            };

            m_SamplerStates[(int)SamplerType.LinearComparisonClamp] = SamplerState.FromDescription(device, samplerDescription);

            samplerDescription = new SamplerDescription()
            {
                AddressU          = TextureAddressMode.Clamp,
                AddressV          = TextureAddressMode.Clamp,
                AddressW          = TextureAddressMode.Clamp,
                Filter            = Filter.Anisotropic,
                MinimumLod        = 0,
                MaximumLod        = 255,
                MaximumAnisotropy = 4,
            };

            m_SamplerStates[(int)SamplerType.AnisotropicClamp] = SamplerState.FromDescription(device, samplerDescription);
        }
Beispiel #20
0
        public void Render(DX11RenderContext context)
        {
            if (this.lasthandle != this.Handle)
            {
                if (this.swapchain != null)
                {
                    if (this.swapchain.Contains(context))
                    {
                        this.swapchain.Dispose(context);
                    }
                }
                this.lasthandle = this.Handle;
            }

            if (!this.swapchain.Contains(context))
            {
                this.swapchain[context] = new DX11SwapChain(context, this.Handle,
                                                            SlimDX.DXGI.Format.R8G8B8A8_UNorm, new SampleDescription(1, 0), 60, 1);
            }

            if (this.resized)
            {
                this.swapchain[context].Resize();
            }

            if (this.FEnabled[0])
            {
                context.CurrentDeviceContext.ClearRenderTargetView(this.swapchain[context].RTV, new SlimDX.Color4(0, 0, 0, 0));
            }

            if (this.FIn.IsConnected && this.spreadMax > 0 && this.FEnabled[0])
            {
                int id = this.FIndex[0];
                if (this.FIn[id].Contains(context) && this.FIn[id][context] != null)
                {
                    context.RenderTargetStack.Push(this.swapchain[context]);
                    var rs = new DX11RenderState();

                    if (FAlpha[0])
                    {
                        rs.Blend = DX11BlendStates.Instance.GetState("Blend");
                        context.CurrentDeviceContext.ClearRenderTargetView(this.swapchain[context].RTV, FInBgColor[0].Color);
                    }
                    context.RenderStateStack.Push(rs);
                    context.CleanShaderStages();

                    context.Primitives.FullTriVS.GetVariableBySemantic("TEXTURE").AsResource().SetResource(this.FIn[id][context].SRV);

                    EffectSamplerVariable samplervariable = context.Primitives.FullTriVS.GetVariableByName("linSamp").AsSampler();
                    SamplerState          state           = null;
                    if (this.FInSamplerState.IsConnected)
                    {
                        state = SamplerState.FromDescription(context.Device, this.FInSamplerState[0]);
                        samplervariable.SetSamplerState(0, state);
                    }
                    else
                    {
                        samplervariable.UndoSetSamplerState(0);
                    }

                    context.Primitives.FullScreenTriangle.Bind(null);
                    context.Primitives.ApplyFullTri();
                    context.Primitives.FullScreenTriangle.Draw();

                    context.RenderStateStack.Pop();
                    context.RenderTargetStack.Pop();
                    context.CleanUpPS();
                    samplervariable.UndoSetSamplerState(0);  //undo as can be used in other places

                    if (state != null)
                    {
                        state.Dispose();
                    }
                }
            }
        }
        public D3DSlimDXCanvas()
        {
            InitializeComponent();

            // hook the application's idle event
            Application.Idle += new EventHandler(OnApplicationIdle);

            GameConsole.Instance.FrameDone += new EventHandler(GameConsole_FrameDone);

            Size maxSize = new Size(bitmapWidth, bitmapHeight);

            foreach (var screen in Screen.AllScreens)
            {
                maxSize.Width  = Math.Max(maxSize.Width, screen.Bounds.Width);
                maxSize.Height = Math.Max(maxSize.Height, screen.Bounds.Height);
            }

            ModeDescription modeDesc = new ModeDescription();

            modeDesc.Width  = maxSize.Width;
            modeDesc.Height = maxSize.Height;
            modeDesc.Format = Format.R8G8B8A8_UNorm;

            var description = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = this.Handle,
                IsWindowed        = true,
                ModeDescription   = modeDesc,
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out device, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                renderTarget = new RenderTargetView(device, resource);

            // Grab the context.
            context = device.ImmediateContext;

            // Set as output merger render target.
            context.OutputMerger.SetTargets(renderTarget);

            // setting a viewport is required if you want to actually see anything
            var viewport = new Viewport(0.0f, 0.0f, maxSize.Width, maxSize.Height);

            context.Rasterizer.SetViewports(viewport);

            ShaderBytecode effectByteCode = ShaderBytecode.CompileFromFile("shader.fx", "Render", "fx_5_0", ShaderFlags.None, EffectFlags.None);

            effect = new Effect(device, effectByteCode);

            // Create sampler
            var samplerDesc = new SamplerDescription();

            samplerDesc.Filter             = Filter.MinMagMipLinear;
            samplerDesc.AddressU           = TextureAddressMode.Wrap;
            samplerDesc.AddressV           = TextureAddressMode.Wrap;
            samplerDesc.AddressW           = TextureAddressMode.Wrap;
            samplerDesc.ComparisonFunction = Comparison.Never;
            samplerDesc.MinimumLod         = 0;
            samplerDesc.MaximumLod         = float.MaxValue;

            SamplerState samplerState = SamplerState.FromDescription(this.device, samplerDesc);

            effect.GetVariableByName("TextureSampler").AsSampler().SetSamplerState(0, samplerState);
            this.context.PixelShader.SetSampler(samplerState, 0);


            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.CompileFromFile("shader.fx", "vs_main", "vs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader   = new VertexShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.CompileFromFile("shader.fx", "ps_main", "ps_4_0", ShaderFlags.None, EffectFlags.None))
            {
                pixelShader = new PixelShader(device, bytecode);
            }

            // create test vertex data, making sure to rewind the stream afterward
            vertices = new DataStream(20 * 4, true, true);
            vertices.Write(new Vector3(-1.0f, -1.0f, 0.5f));             // bottom left
            vertices.Write(new Vector2(0.0f, 1.0f));

            vertices.Write(new Vector3(-1.0f, 1.0f, 0.5f));             // top left
            vertices.Write(new Vector2(0.0f, 0.0f));

            vertices.Write(new Vector3(1.0f, -1.0f, 0.5f));             // bottom right
            vertices.Write(new Vector2(1.0f, 1.0f));

            vertices.Write(new Vector3(1.0f, 1.0f, 0.5f));             // top right
            vertices.Write(new Vector2(1.0f, 0.0f));
            vertices.Position = 0;

            vertexBuffer = new SlimDX.Direct3D11.Buffer(device, vertices, 20 * 4, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // create the vertex layout and buffer
            var elements = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                new InputElement("textcoord", 0, Format.R32G32_Float, 12, 0)
            };

            layout = new InputLayout(device, inputSignature, elements);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 20, 0));

            // set the shaders
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAltEnter);


            texes[0] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame1.jpg");
            texes[1] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame2.jpg");
            texes[2] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame3.jpg");
            texes[3] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame4.jpg");
            texes[4] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame5.jpg");


            initialized = true;
        }
        private const int ThreadGroupSize = 8; // corresponds to shader

        public GPUHermiteCalculator(DX11Game game)
        {
            this.game       = game;
            context         = game.Device.ImmediateContext;
            csX             = loadComputeShader(CompiledShaderCache.Current.RootShaderPath + "DualContouring\\HermiteTerrain.hlsl", "CSGridSigns");
            csIntersections = loadComputeShader(CompiledShaderCache.Current.RootShaderPath + "DualContouring\\HermiteTerrain.hlsl", "CSCalcIntersections");

            var random = new Random(0);

            var noiseSize = 64;
            var data      = new float[noiseSize * noiseSize * noiseSize];

            /*var data = new float[2 * 2 * 2];
             * data[0] = 1;
             * data[1] = -1;
             * data[2] = -1;
             * data[3] = -1;
             * data[4] = -1;
             * data[5] = -1;
             * data[6] = -1;
             * data[7] = -1;*/
            for (int i = 0; i < noiseSize * noiseSize * noiseSize; i++)
            {
                data[i] = (float)(random.NextDouble() * 2 - 1);
            }


            var strm = new DataStream(data, true, false);


            perlin = GPUTexture3D.CreateDefault(game, noiseSize, noiseSize, noiseSize, Format.R32_Float);
            game.Device.ImmediateContext.UpdateSubresource(new DataBox(4 * noiseSize, 4 * noiseSize * noiseSize, strm),
                                                           perlin.Resource, 0, new ResourceRegion(0, 0, 0, noiseSize, noiseSize, noiseSize));

            /*perlin = GPUTexture3D.CreateCPUWritable(game, 64, 64, 64, Format.R8G8B8A8_UNorm);
             * var random = new Random(0);
             * var data = new byte[64 * 64 * 64 * 4];
             * var i = 0;
             * for (int x = 0; x < 64; x++)
             * {
             *  for (int y = 0; y < 64; y++)
             *  {
             *      for (int z = 0; z < 64; z++)
             *      {
             *
             *          //var val = ((x/64f)*2 - 1 + (z/64f)*2 - 1)/2.0f;
             *          //val = val > 0 ? 1 : -1;
             *          //data[i*4] = (byte) ((val/2f + 0.5f)*255f);
             *          data[i * 4] = (byte)random.Next(0, 255);
             *          i++;
             *
             *      }
             *  }
             * }*/
            //perlin.SetTextureRawData(data);
            //perlin.SaveToImageSlices(game, TWDir.Test.CreateSubdirectory("DualContouring.GPU/perlin"));

            trilinearSampler = SamplerState.FromDescription(game.Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter   = Filter.MinMagMipPoint,
            });
        }
Beispiel #23
0
        public void CreateShaders(string code)
        {
            UpdateRenderer = true;
            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.Compile(code, "VShader", "vs_5_0", ShaderFlags.None, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader   = new VertexShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.Compile(code, "PShader", "ps_5_0", ShaderFlags.None, EffectFlags.None))
                pixelShader = new PixelShader(device, bytecode);

            string compilationError = "";

            //ShaderBytecode compiledShader = ShaderBytecode.CompileFromFile("vteffect.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null, out compilationError);

            //fx = new Effect(device, compiledShader);

            // create test vertex data, making sure to rewind the stream afterward
            vertices = new DataStream(20 * 4, true, true);

            vertices.Write(new Vector3(-1f, -1f, 0.5f)); vertices.Write(new Vector2(0f, 1f));
            vertices.Write(new Vector3(-1f, 1f, 0.5f)); vertices.Write(new Vector2(0f, 0f));
            vertices.Write(new Vector3(1f, -1f, 0.5f)); vertices.Write(new Vector2(1f, 1f));
            vertices.Write(new Vector3(1f, 1f, 0.5f)); vertices.Write(new Vector2(1f, 0f));
            vertices.Position = 0;

            // create the vertex layout and buffer
            var elements = new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
            };

            layout       = new InputLayout(device, inputSignature, elements);
            vertexBuffer = new SlimDX.Direct3D11.Buffer(device, vertices, 20 * 4, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);

            List <int> indices = new List <int>();

            indices.Add(0);
            indices.Add(1);
            indices.Add(2);
            indices.Add(2);
            indices.Add(1);
            indices.Add(3);
            var ibd = new BufferDescription(sizeof(int) * indices.Count, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            indexBuffer = new SlimDX.Direct3D11.Buffer(device, new DataStream(indices.ToArray(), false, false), ibd);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 20, 0));
            context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);

            // set the shaders
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);


            SamplerDescription sampleDesc = new SamplerDescription();

            sampleDesc.Filter             = Filter.MinMagMipPoint;
            sampleDesc.AddressU           = TextureAddressMode.Clamp;
            sampleDesc.AddressV           = TextureAddressMode.Clamp;
            sampleDesc.AddressW           = TextureAddressMode.Clamp;
            sampleDesc.MipLodBias         = 0.0f;
            sampleDesc.ComparisonFunction = Comparison.Always;
            sampleDesc.BorderColor        = new Color4(0, 0, 0, 0);
            sampleDesc.MinimumLod         = 0;
            sampleDesc.MaximumLod         = 1;

            sampleState = SamplerState.FromDescription(device, sampleDesc);

            SamplerDescription indSampleDesc = new SamplerDescription();

            sampleDesc.Filter             = Filter.MinMagMipPoint;
            sampleDesc.AddressU           = TextureAddressMode.Wrap;
            sampleDesc.AddressV           = TextureAddressMode.Wrap;
            sampleDesc.AddressW           = TextureAddressMode.Wrap;
            sampleDesc.MipLodBias         = 0.0f;
            sampleDesc.ComparisonFunction = Comparison.Always;
            sampleDesc.BorderColor        = new Color4(0, 0, 0, 0);
            sampleDesc.MinimumLod         = 0;
            sampleDesc.MaximumLod         = 1;

            indSampleState = SamplerState.FromDescription(device, sampleDesc);

            ImageLoadInformation loadInfo = new ImageLoadInformation()
            {
                Width = 2, Height = 2
            };

            loadInfo.BindFlags      = BindFlags.ShaderResource;
            loadInfo.CpuAccessFlags = CpuAccessFlags.None;
            loadInfo.Depth          = 4;
            loadInfo.FilterFlags    = FilterFlags.Point;
            loadInfo.FirstMipLevel  = 0;
            loadInfo.Format         = Format.R8G8B8A8_SInt;
            loadInfo.MipLevels      = 0;
            loadInfo.Usage          = ResourceUsage.Default;
            texture = new Texture2D(device, new Texture2DDescription
            {
                BindFlags         = BindFlags.ShaderResource,
                ArraySize         = 1024,
                Width             = 128,
                Height            = 128,
                Usage             = ResourceUsage.Default,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R8G8B8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None
            });//Texture2D.FromFile(device,"Tourism_Industrial_d.png");
            resourceView = new ShaderResourceView(device, texture);
            device.ImmediateContext.PixelShader.SetShaderResource(resourceView, 0);
            context.PixelShader.SetShaderResource(resourceView, 0);
            context.PixelShader.SetSampler(sampleState, 0);
            context.PixelShader.SetSampler(indSampleState, 1);
            if (currentEntry != null)
            {
                SetTexture(currentEntry);
            }
        }
Beispiel #24
0
        public void OnInitialize(System.Windows.Forms.Form form)
        {
            this.form  = form;
            clientSize = new Size(form.Width, form.Height);

            Device.CreateWithSwapChain(
                DriverType.Hardware,
                DeviceCreationFlags.Debug,
                new SlimDX.DXGI.SwapChainDescription
            {
                BufferCount       = 1,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                SampleDescription = new SlimDX.DXGI.SampleDescription
                {
                    Count   = 1,
                    Quality = 0
                },
                ModeDescription = new SlimDX.DXGI.ModeDescription
                {
                    Width       = form.Width,
                    Height      = form.Height,
                    RefreshRate = new SlimDX.Rational(60, 1),
                    Format      = SlimDX.DXGI.Format.R8G8B8A8_UNorm
                },
                Usage = SlimDX.DXGI.Usage.RenderTargetOutput
            },
                out device,
                out swapChain
                );

            using (Texture2D backBuffer =
                       SlimDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0))
            {
                renderTarget = new RenderTargetView(device, backBuffer);
                device.ImmediateContext.OutputMerger.SetTargets(renderTarget);
            }

            device.ImmediateContext.Rasterizer.SetViewports(
                new Viewport
            {
                Width  = form.Width,
                Height = form.Height,
                MaxZ   = 1
            }
                );

            using (ShaderBytecode shaderBytecode = ShaderBytecode.CompileFromFile(
                       "simple.fx", "fx_5_0",
                       ShaderFlags.None,
                       EffectFlags.None))
            {
                effect = new Effect(device, shaderBytecode);
            }

            vertexLayout = new InputLayout(
                device,
                effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature,
                VertexPointColor.VertexElements
                );

            // VertexBufer
            VertexPointColor[] vertices =
            {
                new VertexPointColor
                {
                    Position = new Vector3(0, 0.5f, 0),
                    Color    = new Vector3(0, 0, 1)
                },
                new VertexPointColor
                {
                    Position = new Vector3(0.5f, 0, 0),
                    Color    = new Vector3(0, 0, 1)
                },
                new VertexPointColor
                {
                    Position = new Vector3(-0.5f, 0, 0),
                    Color    = new Vector3(1, 0, 0)
                },
            };
            DataStream stream = new DataStream(vertices, true, true);

            vertexBuffer = new SlimDX.Direct3D11.Buffer(
                device,
                stream,
                new BufferDescription
            {
                SizeInBytes = (int)stream.Length,
                BindFlags   = BindFlags.VertexBuffer,
                OptionFlags = ResourceOptionFlags.DrawIndirect,
            }
                );
            stream.Dispose();

            // 定数バッファ
            Matrix[] mat = new Matrix[100];
            for (int i = 0; i < 100; i++)
            {
                mat[i] = Matrix.Translation(new Vector3((float)(0.2 * i), 0, (float)(0.2 * i)));
            }
            stream      = new DataStream(mat, true, true);
            inputBuffer = new SlimDX.Direct3D11.Buffer(
                device,
                stream,
                new BufferDescription
            {
                SizeInBytes = (int)stream.Length,
                BindFlags   = BindFlags.ShaderResource,
                OptionFlags = ResourceOptionFlags.DrawIndirect,
                //StructureByteStride = Marshal.SizeOf(typeof(Matrix)),
            }
                );

            // 深度バッファの設定
            Texture2DDescription depthBufferDesc = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil,
                Format            = SlimDX.DXGI.Format.D32_Float,
                Width             = clientSize.Width,
                Height            = clientSize.Height,
                MipLevels         = 1,
                SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0)
            };

            using (Texture2D depthBuffer = new Texture2D(device, depthBufferDesc))
            {
                depthStencil = new DepthStencilView(device, depthBuffer);
            }
            device.ImmediateContext.OutputMerger.SetTargets(depthStencil, renderTarget);

            EffectPass pass = effect.GetTechniqueByIndex(2).GetPassByIndex(0);

            foreach (IRenderObject itr in renderObjectArray)
            {
                itr.OnInitialize(device, pass);
            }

            // Textureの読み込み
            try
            {
                int testMode = 2;
                switch (testMode)
                {
                case 1:

                    Texture2D[] textureArray = new Texture2D[]
                    {
                        Texture2D.FromFile(device, "cobblestone_mossy.png"),
                        Texture2D.FromFile(device, "brick.png"),
                    };
                    stream = new DataStream(textureArray, true, true);

                    srv = new ShaderResourceView(device, textureArray[0]);

                    effect.GetVariableByName("g_DecalMap").AsResource().SetResource(srv);
                    break;

                case 2:

                    srv
                        = ShaderResourceView.FromFile(device, "cobblestone_mossy.png");
                    effect.GetVariableByName("g_DecalMap").AsResource().SetResource(srv);
                    //device.ImmediateContext.PixelShader.SetShaderResource(shaderResourceView, 19);

                    break;
                }

                SamplerDescription description = new SamplerDescription
                {
                    Filter   = SlimDX.Direct3D11.Filter.Anisotropic,
                    AddressU = SlimDX.Direct3D11.TextureAddressMode.Wrap,
                    AddressV = SlimDX.Direct3D11.TextureAddressMode.Wrap,
                    AddressW = TextureAddressMode.Wrap,
                };
                samplerState = SamplerState.FromDescription(device, description);
            }
            catch (Exception e)
            {
                return;
            }
            return;
        }
Beispiel #25
0
        private void DoRenderLoop(object pmMain = null)
        {
            RasterizerStateDescription rsd = new RasterizerStateDescription();

            rsd.CullMode = CullMode.None;
            rsd.FillMode = FillMode.Solid;
            mainD11.ImmediateContext.Rasterizer.State = RasterizerState.FromDescription(mainD11, rsd);
            SamplerDescription sd = new SamplerDescription();

            sd.Filter      = Filter.MinLinearMagPointMipLinear;
            sd.AddressU    = TextureAddressMode.Wrap;
            sd.AddressV    = TextureAddressMode.Wrap;
            sd.AddressW    = TextureAddressMode.Wrap;
            sd.BorderColor = new Color4(Color.White);
            SamplerState ssMain     = SamplerState.FromDescription(mainD11, sd);
            Texture2D    backBuffer = Texture2D.FromSwapChain <Texture2D>(mainSC, 0);
            var          renderView = new RenderTargetView(mainD11, backBuffer);

            BlendStateDescription bsd = new BlendStateDescription();

            bsd.RenderTargets[0]                             = new RenderTargetBlendDescription();
            bsd.RenderTargets[0].BlendEnable                 = true;
            bsd.RenderTargets[0].RenderTargetWriteMask       = ColorWriteMaskFlags.All;
            bsd.RenderTargets[0].BlendOperation              = BlendOperation.Add;
            bsd.RenderTargets[0].SourceBlend                 = BlendOption.SourceColor;
            bsd.RenderTargets[0].DestinationBlend            = BlendOption.DestinationAlpha;
            bsd.RenderTargets[0].SourceBlendAlpha            = BlendOption.One;
            bsd.RenderTargets[0].BlendOperationAlpha         = BlendOperation.Add;
            bsd.RenderTargets[0].DestinationBlendAlpha       = BlendOption.One;
            mainD11.ImmediateContext.OutputMerger.BlendState = BlendState.FromDescription(mainD11, bsd);

            Dictionary <int, MmapUnit> mmapIndexDictionaryFloor   = null;
            Dictionary <int, MmapUnit> mmapIndexDictionarySurface = null;
            ShaderResourceView         resourceViewFloor          = GenerateMmapSRV(mainD11, 0, 512, out mmapIndexDictionaryFloor);
            ShaderResourceView         resourceViewSurface        = GenerateMmapSRV(mainD11, 512, 1024, out mmapIndexDictionarySurface);
            MapRange mmapRangeFloor   = GenerateMmapRange(mainD11, 1, 0, 80, 0, 210, mmapIndexDictionaryFloor, screenPixelRateX, screenPixelRateY);
            MapRange mmapRangeSurface = GenerateMmapRange(mainD11, 2, 0, 80, 0, 210, mmapIndexDictionarySurface, screenPixelRateX, screenPixelRateY);

            var          colorBytecodeV = ShaderBytecode.CompileFromFile("Color.hlsl", "VS", "vs_5_0", ShaderFlags.None, EffectFlags.None);
            VertexShader vsColor        = new VertexShader(mainD11, colorBytecodeV);
            var          colorBytecodeP = ShaderBytecode.CompileFromFile("Color.hlsl", "PS", "ps_5_0", ShaderFlags.None, EffectFlags.None);
            PixelShader  psColor        = new PixelShader(mainD11, colorBytecodeP);
            var          signatureColor = ShaderSignature.GetInputSignature(colorBytecodeV);
            var          layoutColor    = new InputLayout(mainD11, signatureColor, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            var          textureBytecodeV = ShaderBytecode.CompileFromFile("Texture.hlsl", "VS", "vs_5_0", ShaderFlags.None, EffectFlags.None);
            VertexShader vsTexture        = new VertexShader(mainD11, textureBytecodeV);
            var          textureBytecodeP = ShaderBytecode.CompileFromFile("Texture.hlsl", "PS", "ps_5_0", ShaderFlags.None, EffectFlags.None);
            PixelShader  psTexture        = new PixelShader(mainD11, textureBytecodeP);
            var          signatureTexture = ShaderSignature.GetInputSignature(textureBytecodeV);
            var          layoutTexture    = new InputLayout(mainD11, signatureTexture, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            mainD11.ImmediateContext.OutputMerger.SetTargets(renderView);
            mainD11.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, this.Width, this.Height, 0.0f, 1.0f));
            mainD11.ImmediateContext.PixelShader.SetSampler(ssMain, 0);
            mainD11.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            mainD11.ImmediateContext.InputAssembler.InputLayout       = layoutTexture;
            mainD11.ImmediateContext.VertexShader.Set(vsTexture);
            mainD11.ImmediateContext.PixelShader.Set(psTexture);

            Matrix   projection       = Matrix.OrthoLH(2f, 2f, 0, 2f);
            Matrix   view             = Matrix.LookAtLH(new Vector3(0, 0, -1f), Vector3.Zero, Vector3.UnitY);
            Matrix   world            = Matrix.Translation(Vector3.Zero);
            Matrix   WVP              = world * view * projection;
            Buffer11 constantBufferCB = new Buffer11(mainD11, new BufferDescription
            {
                Usage               = ResourceUsage.Default,
                SizeInBytes         = Marshal.SizeOf(WVP),
                BindFlags           = BindFlags.ConstantBuffer,
                CpuAccessFlags      = CpuAccessFlags.None,
                OptionFlags         = ResourceOptionFlags.None,
                StructureByteStride = 0,
            });

            mainD11.ImmediateContext.VertexShader.SetConstantBuffer(constantBufferCB, 0);

            while (running)
            {
                mainD11.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                world = Matrix.Translation(new Vector3(moveX, moveY, 0));

                WVP = world * view * projection;
                DataStream dsCamera = new DataStream(Marshal.SizeOf(WVP), true, true);
                dsCamera.Write(WVP);
                dsCamera.Position = 0;
                mainD11.ImmediateContext.UpdateSubresource(new DataBox(0, 0, dsCamera), constantBufferCB, 0);

                mainD11.ImmediateContext.PixelShader.SetShaderResource(resourceViewFloor, 0);
                mainD11.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(mmapRangeFloor.mapVertexBuffer, 32, 0));
                mainD11.ImmediateContext.Draw(mmapRangeFloor.vector4Count, 0);

                mainD11.ImmediateContext.PixelShader.SetShaderResource(resourceViewSurface, 0);
                if (mmapRangeSurface != null)
                {
                    mainD11.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(mmapRangeSurface.mapVertexBuffer, 32, 0));
                    mainD11.ImmediateContext.Draw(mmapRangeSurface.vector4Count, 0);
                }

                mainSC.Present(0, PresentFlags.None);
                Thread.Sleep(10);
            }

            colorBytecodeP.Dispose();
            colorBytecodeV.Dispose();
            textureBytecodeP.Dispose();
            textureBytecodeV.Dispose();
            mmapRangeFloor.mapVertexBuffer.Dispose();
            if (mmapRangeSurface != null)
            {
                mmapRangeSurface.mapVertexBuffer.Dispose();
            }
            layoutColor.Dispose();
            layoutTexture.Dispose();
            constantBufferCB.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            mainD11.Dispose();
            mainSC.Dispose();
        }