public ObjectParameterKey <SamplerState> GetSamplerKey(SamplerStateDescription samplerStateDesc, GraphicsDevice graphicsDevice)
        {
            ObjectParameterKey <SamplerState> key;

            if (!declaredSamplerStates.TryGetValue(samplerStateDesc, out key))
            {
                key = MaterialKeys.Sampler.ComposeWith("i" + declaredSamplerStates.Count.ToString(CultureInfo.InvariantCulture));
                declaredSamplerStates.Add(samplerStateDesc, key);
            }

            var samplerState = graphicsDevice != null?SamplerState.New(graphicsDevice, samplerStateDesc) : SamplerState.NewFake(samplerStateDesc);

            Parameters.Set(key, samplerState);
            return(key);
        }
        public ObjectParameterKey <SamplerState> GetSamplerKey(ComputeColorParameterSampler sampler)
        {
            if (sampler == null)
            {
                throw new ArgumentNullException("sampler");
            }

            var samplerStateDesc = new SamplerStateDescription(sampler.Filtering, sampler.AddressModeU)
            {
                AddressV = sampler.AddressModeV,
                AddressW = TextureAddressMode.Wrap
            };

            return(GetSamplerKey(samplerStateDesc, graphicsDevice));
        }
示例#3
0
        internal static SamplerState New(DirectXDevice device, string name, Filter filterMode, TextureAddressMode uvwMode)
        {
            var description = SamplerStateDescription.Default();

            // For 9.1, anisotropy cannot be larger then 2
            if (device.Features.Level == FeatureLevel.Level_9_1)
            {
                description.MaximumAnisotropy = 2;
            }

            description.Filter   = filterMode;
            description.AddressU = uvwMode;
            description.AddressV = uvwMode;
            description.AddressW = uvwMode;
            return(New(device, name, description));
        }
示例#4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StaticSamplerDescription"/> struct.
        /// </summary>
        /// <param name="samplerStateDescription">Sampler state description</param>
        /// <param name="shaderVisibility">The shader visibility.</param>
        /// <param name="shaderRegister">The shader register.</param>
        /// <param name="registerSpace">The register space.</param>
        public StaticSamplerDescription(SamplerStateDescription samplerStateDescription, ShaderVisibility shaderVisibility, int shaderRegister, int registerSpace) : this()
        {
            ShaderVisibility = shaderVisibility;
            ShaderRegister   = shaderRegister;
            RegisterSpace    = registerSpace;
            BorderColor      = StaticBorderColor.TransparentBlack;

            Filter         = samplerStateDescription.Filter;
            AddressU       = samplerStateDescription.AddressU;
            AddressV       = samplerStateDescription.AddressV;
            AddressW       = samplerStateDescription.AddressW;
            MinLOD         = samplerStateDescription.MinimumLod;
            MaxLOD         = samplerStateDescription.MaximumLod;
            MipLODBias     = samplerStateDescription.MipLodBias;
            MaxAnisotropy  = samplerStateDescription.MaximumAnisotropy;
            ComparisonFunc = samplerStateDescription.ComparisonFunction;
        }
        public RadialWobble(Device device, int imageWidth, int imageHeight)
            : base(device, imageWidth, imageHeight, constantBufferSize, "Content/RadialWobble.cso")
        {
            var samplerStateDesc = new SamplerStateDescription()
            {
                Filter   = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Border,
                AddressV = TextureAddressMode.Border,
                AddressW = TextureAddressMode.Border,
                //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f),
                BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f),
            };

            samplerState = new SamplerState(device, samplerStateDesc);

            SetConstants(device.ImmediateContext, 0);
        }
示例#6
0
        internal static void InitOnce()
        {
            SamplerStateDescription description = new SamplerStateDescription();

            description.AddressU   = TextureAddressMode.Clamp;
            description.AddressV   = TextureAddressMode.Clamp;
            description.AddressW   = TextureAddressMode.Clamp;
            description.Filter     = Filter.MinMagMipLinear;
            description.MaximumLod = System.Single.MaxValue;
            m_default = MyPipelineStates.CreateSamplerState(description);

            description.AddressU    = TextureAddressMode.Border;
            description.AddressV    = TextureAddressMode.Border;
            description.AddressW    = TextureAddressMode.Border;
            description.Filter      = Filter.MinMagMipLinear;
            description.MaximumLod  = System.Single.MaxValue;
            description.BorderColor = new Color4(0, 0, 0, 0);
            m_alphamask             = MyPipelineStates.CreateSamplerState(description);

            description.AddressU   = TextureAddressMode.Clamp;
            description.AddressV   = TextureAddressMode.Clamp;
            description.AddressW   = TextureAddressMode.Clamp;
            description.Filter     = Filter.MinMagMipPoint;
            description.MaximumLod = System.Single.MaxValue;
            m_point = MyPipelineStates.CreateSamplerState(description);

            description.Filter     = Filter.MinMagMipLinear;
            description.MaximumLod = System.Single.MaxValue;
            m_linear = MyPipelineStates.CreateSamplerState(description);

            description.AddressU           = TextureAddressMode.Clamp;
            description.AddressV           = TextureAddressMode.Clamp;
            description.AddressW           = TextureAddressMode.Clamp;
            description.Filter             = Filter.ComparisonMinMagMipLinear;
            description.MaximumLod         = System.Single.MaxValue;
            description.ComparisonFunction = Comparison.LessEqual;
            m_shadowmap = MyPipelineStates.CreateSamplerState(description);

            m_texture        = MyPipelineStates.CreateSamplerState(description);
            m_alphamaskArray = MyPipelineStates.CreateSamplerState(description);

            UpdateFiltering();

            Init();
        }
示例#7
0
        private SamplerState(GraphicsDevice device, SamplerStateDescription samplerStateDescription) : base(device)
        {
            Description = samplerStateDescription;

            textureWrapS = samplerStateDescription.AddressU.ToOpenGL();
            textureWrapT = samplerStateDescription.AddressV.ToOpenGL();
            textureWrapR = samplerStateDescription.AddressW.ToOpenGL();
      
            compareFunc = samplerStateDescription.CompareFunction.ToOpenGLDepthFunction();
            borderColor = samplerStateDescription.BorderColor.ToArray();
            // TODO: How to do MipLinear vs MipPoint?
            switch (samplerStateDescription.Filter)
            {
                case TextureFilter.ComparisonMinMagLinearMipPoint:
                case TextureFilter.MinMagLinearMipPoint:
                    minFilter = TextureMinFilter.Linear;
                    magFilter = TextureMagFilter.Linear;
                    break;
                case TextureFilter.Anisotropic:
                case TextureFilter.Linear:
                    minFilter = TextureMinFilter.LinearMipmapLinear;
                    magFilter = TextureMagFilter.Linear;
                    break;
                case TextureFilter.MinPointMagMipLinear:
                case TextureFilter.ComparisonMinPointMagMipLinear:
                    minFilter = TextureMinFilter.NearestMipmapLinear;
                    magFilter = TextureMagFilter.Linear;
                    break;
                case TextureFilter.Point:
                    minFilter = TextureMinFilter.Nearest;
                    magFilter = TextureMagFilter.Nearest;
                    break;
                default:
                    throw new NotImplementedException();
            }

#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
            // On OpenGL ES, we need to choose the appropriate min filter ourself if the texture doesn't contain mipmaps (done at PreDraw)
            minFilterNoMipmap = minFilter;
            if (minFilterNoMipmap == TextureMinFilter.LinearMipmapLinear)
                minFilterNoMipmap = TextureMinFilter.Linear;
            else if (minFilterNoMipmap == TextureMinFilter.NearestMipmapLinear)
                minFilterNoMipmap = TextureMinFilter.Nearest;
#endif
        }
示例#8
0
        private void SetSamplerState(Device device)
        {
            var samplerDescription = new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLodBias         = 0,
                MaximumAnisotropy  = 1,
                ComparisonFunction = Comparison.Always,
                BorderColor        = new Color4(0, 0, 0, 0),
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            };

            SamplerState = new SamplerState(device, samplerDescription);
        }
示例#9
0
        //static ComPtr<ID3D11Texture2D> CreateTexture2D(UINT width, UINT height, UINT mipLevels, UINT arraySize, DXGI_FORMAT format, UINT sampleCount, UINT sampleQuality, D3D11_USAGE usage, UINT bindFlags, UINT cpuAccessFlags, UINT miscFlags, const void* data, const string& name)
        //{
        //    D3D11_TEXTURE2D_DESC td;
        //    td.Width = width;
        //    td.Height = height;
        //    td.MipLevels = mipLevels;
        //    td.ArraySize = arraySize;
        //    td.Format = format;
        //    td.SampleDesc.Count = sampleCount;
        //    td.SampleDesc.Quality = sampleQuality;
        //    td.Usage = usage;
        //    td.BindFlags = bindFlags;
        //    td.CPUAccessFlags = cpuAccessFlags;
        //    td.MiscFlags = miscFlags;
        //    D3D11_SUBRESOURCE_DATA srd;
        //    srd.pSysMem = data;
        //    srd.SysMemPitch = 1;
        //    srd.SysMemSlicePitch = 0;
        //    ComPtr<ID3D11Texture2D> t;
        //    Try(DXManager::GetDevice()->CreateTexture2D(&td, data != nullptr ? &srd : nullptr, &t), name);
        //    DXManager::AddVramUsage(ElementSize(format) * width * height * arraySize);
        //    return t;
        //}


        public static SamplerState CreateSamplerState(Device device, TextureAddressMode addressU, TextureAddressMode addressV, TextureAddressMode addressW, RawColor4 border, Comparison comparisonFunc, Filter filter, int maxAnisotropy, float maxLOD, float minLOD, float mipLODBias)
        {
            SamplerStateDescription smpDesc = new SamplerStateDescription();

            smpDesc.AddressU           = addressU;
            smpDesc.AddressV           = addressV;
            smpDesc.AddressW           = addressW;
            smpDesc.BorderColor        = border;
            smpDesc.ComparisonFunction = comparisonFunc;
            smpDesc.Filter             = filter;
            smpDesc.MaximumAnisotropy  = maxAnisotropy;
            smpDesc.MaximumLod         = maxLOD;
            smpDesc.MinimumLod         = minLOD;
            smpDesc.MipLodBias         = mipLODBias;
            SamplerState smp = new SamplerState(device, smpDesc);

            return(smp);
        }
示例#10
0
        /// <summary>
        /// Set texture sampling
        /// </summary>
        void SetSamplerState()
        {
            Utilities.Dispose(ref samplerState);

            SamplerStateDescription description = SamplerStateDescription.Default();

            /*description.Filter = Filter.Anisotropic;
            *  description.AddressU = TextureAddressMode.Clamp;
            *  description.AddressV = TextureAddressMode.Clamp;
            *  description.AddressW = TextureAddressMode.Clamp;
            *  description.BorderColor = new Color4(0, 0, 0, 1);
            *  description.ComparisonFunction = Comparison.Never;
            *  description.MipLodBias = 0;
            *  description.MinimumLod = -float.MaxValue;
            *  description.MaximumLod = float.MaxValue;*/

            samplerState = new SamplerState(device, description);
        }
        private static void InitilizeSamplerStates()
        {
            SamplerStateDescription description = new SamplerStateDescription();

            description.AddressU   = TextureAddressMode.Clamp;
            description.AddressV   = TextureAddressMode.Clamp;
            description.AddressW   = TextureAddressMode.Clamp;
            description.Filter     = Filter.MinMagMipLinear;
            description.MaximumLod = System.Single.MaxValue;
            m_defaultSamplerState  = MyPipelineStates.CreateSamplerState(description);

            description.AddressU    = TextureAddressMode.Border;
            description.AddressV    = TextureAddressMode.Border;
            description.AddressW    = TextureAddressMode.Border;
            description.Filter      = Filter.MinMagMipLinear;
            description.MaximumLod  = System.Single.MaxValue;
            description.BorderColor = new Color4(0, 0, 0, 0);
            m_alphamaskSamplerState = MyPipelineStates.CreateSamplerState(description);

            description.AddressU   = TextureAddressMode.Clamp;
            description.AddressV   = TextureAddressMode.Clamp;
            description.AddressW   = TextureAddressMode.Clamp;
            description.Filter     = Filter.MinMagMipPoint;
            description.MaximumLod = System.Single.MaxValue;
            m_pointSamplerState    = MyPipelineStates.CreateSamplerState(description);

            description.Filter     = Filter.MinMagMipLinear;
            description.MaximumLod = System.Single.MaxValue;
            m_linearSamplerState   = MyPipelineStates.CreateSamplerState(description);

            description.AddressU           = TextureAddressMode.Clamp;
            description.AddressV           = TextureAddressMode.Clamp;
            description.AddressW           = TextureAddressMode.Clamp;
            description.Filter             = Filter.ComparisonMinMagMipLinear;
            description.MaximumLod         = System.Single.MaxValue;
            description.ComparisonFunction = Comparison.LessEqual;
            m_shadowmapSamplerState        = MyPipelineStates.CreateSamplerState(description);

            m_textureSamplerState        = MyPipelineStates.CreateSamplerState(description);
            m_alphamaskarraySamplerState = MyPipelineStates.CreateSamplerState(description);

            UpdateTextureSampler(m_textureSamplerState, TextureAddressMode.Wrap);
            UpdateTextureSampler(m_alphamaskarraySamplerState, TextureAddressMode.Clamp);
        }
示例#12
0
        protected override void RunPhase1()
        {
            base.RunPhase1();

            utils.MeshManager.Initialize(mDevice);

            SamplerStateDescription desc = new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLodBias         = 0,
                MaximumAnisotropy  = 1,
                ComparisonFunction = Comparison.Always,
                BorderColor        = new Color4(0, 0, 0, 0),
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            };

            mSampler = new SamplerState(mDevice, desc);

            string vsData = System.IO.File.ReadAllText("shaders\\example06.vs");
            string psData = System.IO.File.ReadAllText("shaders\\example06.ps");

            mShader.Load(mDevice, vsData, psData);
            mShader.Compile(mDevice);

            mLayout = new InputLayout(mDevice, mShader.VertexShaderSignature, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 32, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0)
            });

            mDeviceContext.InputAssembler.InputLayout = mLayout;

            mMesh = utils.MeshManager.LoadMesh(@"meshes/teapot.fbx");

            mCamera = new CameraBase(ScreenWidth, ScreenHeight);
            mClock  = new Stopwatch();
            mClock.Start();
        }
示例#13
0
        private unsafe void CreateFontsTexture()
        {
            byte *pixels;
            int   width, height, bytesPerPixel;

            m_imguiIO.Fonts.GetTexDataAsRGBA32(out pixels, out width, out height, out bytesPerPixel);

            Texture2DDescription texDescription = new Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R8G8B8A8_UNorm,
                Usage             = ResourceUsage.Default,
                SampleDescription = new SampleDescription(1, 0),
                OptionFlags       = ResourceOptionFlags.None
            };

            IntPtr   pixelsPointer = new IntPtr(pixels);
            CTexture texture       = new CTexture();

            texture.InitFromData(m_d3Device, m_d3DeviceContext, pixelsPointer, width * bytesPerPixel, in texDescription, false);

            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLodBias         = 0.0f,
                ComparisonFunction = Comparison.Always,
                MinimumLod         = 0,
                MaximumLod         = 0,
            };

            CTextureSampler textureSampler = new CTextureSampler(m_d3Device, m_d3DeviceContext, texture, in samplerDesc);

            m_fontAtlasId = BindTexture(textureSampler);
            m_imguiIO.Fonts.SetTexID(m_fontAtlasId);
            m_imguiIO.Fonts.ClearTexData();
        }
示例#14
0
        private void InitShaders()
        {
            defaultTexture = textureManager.CreateTexture2DFromBitmap(device, textureManager.LoadBitmap(new ImagingFactory2(), "res\\default.png"));
            //Wireframe shaders
            ShaderBytecode vertexShaderByteCodeWired = ShaderBytecode.Compile(Properties.Resources.vertexShaderWired, "main", "vs_4_0", ShaderFlags.Debug);

            vsWired             = new VertexShader(device, vertexShaderByteCodeWired);
            inputSignatureWired = ShaderSignature.GetInputSignature(vertexShaderByteCodeWired);
            inputLayoutWired    = new InputLayout(device, inputSignatureWired, inputElementsWired);
            psWired             = new PixelShader(device, ShaderBytecode.Compile(Properties.Resources.pixelShaderWired, "main", "ps_4_0", ShaderFlags.Debug));

            //Texture shaders
            ShaderBytecode vertexShaderByteCodeTextured = ShaderBytecode.Compile(Properties.Resources.vertexShaderTextured, "main", "vs_4_0", ShaderFlags.Debug);

            vsTextured             = new VertexShader(device, vertexShaderByteCodeTextured);
            inputSignatureTextured = ShaderSignature.GetInputSignature(vertexShaderByteCodeTextured);
            inputLayoutTextured    = new InputLayout(device, inputSignatureTextured, inputElementsTextured);
            psTextured             = new PixelShader(device, ShaderBytecode.Compile(Properties.Resources.pixelShaderTextured, "main", "ps_4_0", ShaderFlags.Debug));

            RasterizerStateDescription renderStateDescWired = RasterizerStateDescription.Default();

            renderStateDescWired.FillMode = FillMode.Wireframe;
            renderStateDescWired.CullMode = CullMode.None;
            rasterStateWired = new RasterizerState(device, renderStateDescWired);
            RasterizerStateDescription renderStateDescTextured = RasterizerStateDescription.Default();

            renderStateDescTextured.IsFrontCounterClockwise = false;
            renderStateDescTextured.FillMode           = FillMode.Solid;
            renderStateDescTextured.CullMode           = CullMode.None;
            renderStateDescTextured.IsDepthClipEnabled = true;
            rasterStateTextured = new RasterizerState(device, renderStateDescTextured);

            samplerStateDescription = new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter   = Filter.MinMagMipLinear
            };
            sampler = new SamplerState(device, samplerStateDescription);

            worldViewProjectionBuffer = new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
        }
示例#15
0
        public Sampler(GxContext context)
        {
            mContext     = context;
            mDescription = new SamplerStateDescription
            {
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                BorderColor        = SharpDX.Color4.Black,
                ComparisonFunction = Comparison.Always,
                Filter             = Filter.MinMagMipLinear,
                MaximumAnisotropy  = 0,
                MaximumLod         = float.MaxValue,
                MinimumLod         = float.MinValue,
                MipLodBias         = 0.0f
            };

            mChanged = true;
        }
示例#16
0
        private static void UpdateTextureSampler(SamplerId samplerState, TextureAddressMode addressMode)
        {
            SamplerStateDescription description = new SamplerStateDescription();

            description.AddressU   = addressMode;
            description.AddressV   = addressMode;
            description.AddressW   = addressMode;
            description.MaximumLod = System.Single.MaxValue;

            if (MyRender11.RenderSettings.AnisotropicFiltering == MyTextureAnisoFiltering.NONE)
            {
                description.Filter = Filter.MinMagMipLinear;
            }
            else
            {
                description.Filter = Filter.Anisotropic;

                switch (MyRender11.RenderSettings.AnisotropicFiltering)
                {
                case MyTextureAnisoFiltering.ANISO_1:
                    description.MaximumAnisotropy = 1;
                    break;

                case MyTextureAnisoFiltering.ANISO_4:
                    description.MaximumAnisotropy = 4;
                    break;

                case MyTextureAnisoFiltering.ANISO_8:
                    description.MaximumAnisotropy = 8;
                    break;

                case MyTextureAnisoFiltering.ANISO_16:
                    description.MaximumAnisotropy = 16;
                    break;

                default:
                    description.MaximumAnisotropy = 1;
                    break;
                }
            }

            MyPipelineStates.ChangeSamplerState(samplerState, description);
        }
示例#17
0
 public static SamplerState New(GraphicsDevice graphicsDevice, SamplerStateDescription samplerStateDescription)
 {
     // Store SamplerState in a cache (D3D seems to have quite bad concurrency when using CreateSampler while rendering)
     SamplerState samplerState;
     lock (graphicsDevice.CachedSamplerStates)
     {
         if (graphicsDevice.CachedSamplerStates.TryGetValue(samplerStateDescription, out samplerState))
         {
             // TODO: Appropriate destroy
             samplerState.AddReferenceInternal();
         }
         else
         {
             samplerState = new SamplerState(graphicsDevice, samplerStateDescription);
             graphicsDevice.CachedSamplerStates.Add(samplerStateDescription, samplerState);
         }
     }
     return samplerState;
 }
示例#18
0
        private static SamplerState CreateSamplerState(bool linear)
        {
            var dev  = ImageFramework.DirectX.Device.Get();
            var desc = new SamplerStateDescription
            {
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                BorderColor        = new RawColor4(),
                ComparisonFunction = Comparison.Never,
                Filter             = linear ? SharpDX.Direct3D11.Filter.MinMagLinearMipPoint : SharpDX.Direct3D11.Filter.MinMagMipPoint,
                MaximumAnisotropy  = 1,
                MaximumLod         = float.MaxValue,
                MinimumLod         = 0,
                MipLodBias         = 0
            };

            return(new SamplerState(dev.Handle, desc));
        }
示例#19
0
        public D3D11Sampler(Device device, ref SamplerDescription description)
        {
            Comparison comparision = description.ComparisonKind == null ? Comparison.Never : D3D11Formats.VdToD3D11DepthComparison(description.ComparisonKind.Value);
            SamplerStateDescription samplerStateDesc = new SamplerStateDescription
            {
                AddressU           = D3D11Formats.VdToD3D11AddressMode(description.AddressModeU),
                AddressV           = D3D11Formats.VdToD3D11AddressMode(description.AddressModeV),
                AddressW           = D3D11Formats.VdToD3D11AddressMode(description.AddressModeW),
                Filter             = D3D11Formats.ToD3D11Filter(description.Filter, description.ComparisonKind.HasValue),
                MinimumLod         = description.MinimumLod,
                MaximumLod         = description.MaximumLod,
                MaximumAnisotropy  = (int)description.MaximumAnisotropy,
                ComparisonFunction = comparision,
                MipLodBias         = description.LodBias,
                BorderColor        = ToRawColor4(description.BorderColor)
            };

            DeviceSampler = new SamplerState(device, samplerStateDesc);
        }
示例#20
0
        internal Sampler(Device device)
        {
            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLodBias         = 0,
                MaximumAnisotropy  = 1,
                ComparisonFunction = Comparison.Always,
                BorderColor        = new Color4(1, 0, 0, 1),
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            };

            sampler = new SamplerState(device, samplerDesc);

            this.device = device;
        }
示例#21
0
        private void LoadTextureShader()
        {
            try
            {
                //Huge difference between texture sets in the resulting depth effect
                //need to find how to do normal/height maps right

                //this is ugly
                textures = new Textures(device, new TextureType[] { TextureType.GenericRockColor, TextureType.GenericRockNormalHeight });

                //textures = new Textures(device, new TextureType[] { TextureType.Stones, TextureType.Stones_NormalMap, TextureType.Stones_HeightMap });
                //textures = new Textures(device, new TextureType[] { TextureType.TestColorMap, TextureType.TestNormalMap, TextureType.TestHeightMap });

                //textures = new Textures(device, new TextureType[] { TextureType.Wall, TextureType.Wall_NS, TextureType.Wall_HS });
                //textures = new Textures(device, new TextureType[] { TextureType.Wall, TextureType.Dirt });
                //textures = new Textures(device, new TextureType[] { TextureType.Wall });

                TextureCollection = textures.Select(item => item).ToArray();

                SamplerStateDescription textureSamplerDescription = new SamplerStateDescription()
                {
                    Filter = Filter.MinMagMipLinear,

                    AddressU = TextureAddressMode.Wrap,
                    AddressV = TextureAddressMode.Wrap,
                    AddressW = TextureAddressMode.Wrap,

                    MipLodBias         = 0,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = Color.Green,
                    MinimumLod         = 0,
                    MaximumLod         = 0
                };

                sampleState = new SamplerState(device, textureSamplerDescription);
            }
            catch (Exception ex)
            {
                throw new Exception("Could not initialize texture shader: " + ex);
            }
        }
示例#22
0
        public ThumbnailModel(QuadShader quad)
        {
            this.quad = quad;
            convert2D = new DirectX.Shader(DirectX.Shader.Type.Pixel, GetSource(ShaderBuilder.Builder2D), "ThumbnailPixelShader2D");
            convert3D = new DirectX.Shader(DirectX.Shader.Type.Pixel, GetSource(ShaderBuilder.Builder3D), "ThumbnailPixelShader3D");
            var samplerDesc = new SamplerStateDescription
            {
                AddressU           = TextureAddressMode.Clamp,
                AddressV           = TextureAddressMode.Clamp,
                AddressW           = TextureAddressMode.Clamp,
                BorderColor        = new RawColor4(),
                ComparisonFunction = Comparison.Never,
                Filter             = SharpDX.Direct3D11.Filter.MinLinearMagMipPoint,
                MaximumAnisotropy  = 1,
                MaximumLod         = float.MaxValue,
                MinimumLod         = 0,
                MipLodBias         = 0
            };

            sampler = new SamplerState(Device.Get().Handle, samplerDesc);
        }
示例#23
0
        public virtual bool Init(Device device, InputElement[] elements, string vsFileName, string psFileName, string vsEntryPoint, string psEntryPoint)
        {
            ShaderBytecode pixelShaderByteCode;
            ShaderBytecode vertexShaderByteCode;

            vsFileName = ToolkitSettings.ShaderPath + vsFileName;
            psFileName = ToolkitSettings.ShaderPath + psFileName;

            pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, psEntryPoint, "ps_4_0", ShaderFlags.None, EffectFlags.None);
            vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, vsEntryPoint, "vs_4_0", ShaderFlags.None, EffectFlags.None);
            PixelShader          = new PixelShader(device, pixelShaderByteCode);
            VertexShader         = new VertexShader(device, vertexShaderByteCode);
            Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), elements);

            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter             = Filter.Anisotropic,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLodBias         = 0,
                MaximumAnisotropy  = 16,
                ComparisonFunction = Comparison.Always,
                BorderColor        = new Color4(0, 0, 0, 0),
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            };

            SamplerState = new SamplerState(device, samplerDesc);

            ConstantCameraBuffer       = ConstantBufferFactory.ConstructBuffer <DCameraBuffer>(device, "CameraBuffer");
            ConstantLightBuffer        = ConstantBufferFactory.ConstructBuffer <LightBuffer>(device, "LightBuffer");
            ConstantMatrixBuffer       = ConstantBufferFactory.ConstructBuffer <MatrixBuffer>(device, "MatrixBuffer");
            ConstantEditorParamsBuffer = ConstantBufferFactory.ConstructBuffer <EditorParameterBuffer>(device, "EditorBuffer");

            pixelShaderByteCode.Dispose();
            vertexShaderByteCode.Dispose();

            return(true);
        }
示例#24
0
        public override bool InitializeGraphics(IRenderManager manager, Device device)
        {
            // Compile our vertex and pixel shaders.
            ShaderBytecode vertexByteCode = ShaderBytecode.FromFile(System.Windows.Forms.Application.StartupPath + "\\FileFormats\\Geometry\\Shaders\\XfLevelMesh.vs");

            this.VertexShader = new VertexShader(device, vertexByteCode);

            ShaderBytecode pixelByteCode = ShaderBytecode.FromFile(System.Windows.Forms.Application.StartupPath + "\\FileFormats\\Geometry\\Shaders\\XfLevelMesh.ps");

            this.PixelShader = new PixelShader(device, pixelByteCode);

            // Setup the sampler states for the vertex shader.
            SamplerStateDescription samplerDesc = new SamplerStateDescription();

            samplerDesc.AddressU          = TextureAddressMode.Wrap;
            samplerDesc.AddressV          = TextureAddressMode.Wrap;
            samplerDesc.AddressW          = TextureAddressMode.Wrap;
            samplerDesc.BorderColor       = new SharpDX.Mathematics.Interop.RawColor4(0.0f, 0.0f, 0.0f, 0.0f);
            samplerDesc.MaximumLod        = 0;
            samplerDesc.Filter            = Filter.Anisotropic;
            samplerDesc.MipLodBias        = 0;
            samplerDesc.MaximumAnisotropy = 3;
            this.PixelSampleStates        = new SamplerState[] { new SamplerState(device, samplerDesc) };

            // Setup our vertex declaration and bind it to the inputs for the vertex shader.
            this.VertexDeclaration = new InputLayout(device, vertexByteCode.Data, new InputElement[]
            {
                // Id: 0x3259609d
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R16G16B16A16_SNorm, 12, 0),
                new InputElement("TANGENT", 0, Format.R16G16B16A16_SNorm, 0, 1),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 20, 0),
                new InputElement("TEXCOORD", 1, Format.R32G32_Float, 8, 1),
                new InputElement("TEXCOORD", 2, Format.R16G16_SNorm, 16, 1),
                new InputElement("TEXCOORD", 3, Format.R32G32_Float, 20, 1),
            });

            // Successfully initialized.
            return(true);
        }
示例#25
0
        public override void Draw(float deltaTime)
        {
            DrawShadowMap();

            //Draw main components
            BindComponents();

            //DeviceContext.VertexShader.Set(VertexShader);
            //DeviceContext.PixelShader.Set(PixelShader);
            //DeviceContext.GeometryShader.Set(null);
            //var normalmapView = new ShaderResourceView(GameDevice, worldPositionMap);
            //DeviceContext.PixelShader.SetShaderResource(1, normalmapView);

            //var eyepos = new Vector4(Camera.EyePosition.X, Camera.EyePosition.Y, Camera.EyePosition.Z, 1f);

            //DeviceContext.UpdateSubresource(ref eyepos, eyeBuf);
            //DeviceContext.PixelShader.SetConstantBuffer(1, eyeBuf);

            //DeviceContext.UpdateSubresource(ref lightBufferStruct, lightBuf);
            //DeviceContext.PixelShader.SetConstantBuffer(2, lightBuf);
            //   DrawComponentsDeffered(deltaTime);

            var samplerStateDescription = new SamplerStateDescription
            {
                AddressU           = TextureAddressMode.Border,
                AddressV           = TextureAddressMode.Border,
                AddressW           = TextureAddressMode.Border,
                Filter             = Filter.ComparisonMinMagMipLinear,
                BorderColor        = Color.Zero,
                ComparisonFunction = Comparison.Less
            };
            var shadowMapSampler = new SamplerState(GameDevice, samplerStateDescription);

            DeviceContext.PixelShader.SetSampler(1, shadowMapSampler);
            DeviceContext.PixelShader.SetShaderResource(1, shadowMapResourseView);

            DrawComponents(deltaTime);
            base.Draw(deltaTime);
        }
示例#26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="device"></param>
        internal D3DSamplerState Apply(GraphicsDevice device)
        {
            if (state == null)
            {
                var ssd = new SamplerStateDescription();

                ssd.ComparisonFunction = Converter.Convert(this.compareFunc);
                ssd.AddressU           = Converter.Convert(this.addressU);
                ssd.AddressV           = Converter.Convert(this.addressV);
                ssd.AddressW           = Converter.Convert(this.addressW);
                ssd.BorderColor        = SharpDXHelper.Convert(this.borderColor);
                ssd.Filter             = Converter.Convert(this.filter);
                ssd.MaximumAnisotropy  = this.maxAnisotropy;
                ssd.MaximumLod         = this.maxMipLevel;
                ssd.MinimumLod         = this.minMipLevel;
                ssd.MipLodBias         = this.mipMapBias;

                state = new D3DSamplerState(device.Device, ssd);
            }

            return(state);
        }
示例#27
0
        internal static void Init()
        {
            m_proxyVs = MyShaders.CreateVs("clouds.hlsl");
            m_cloudPs = MyShaders.CreatePs("clouds.hlsl");
            m_proxyIL = MyShaders.CreateIL(m_proxyVs.BytecodeId, MyVertexLayouts.GetLayout(
                                               new MyVertexInputComponent(MyVertexInputComponentType.POSITION_PACKED, 0),
                                               new MyVertexInputComponent(MyVertexInputComponentType.NORMAL, 1),
                                               new MyVertexInputComponent(MyVertexInputComponentType.TANGENT_SIGN_OF_BITANGENT, 1),
                                               new MyVertexInputComponent(MyVertexInputComponentType.TEXCOORD0_H, 1)));

            m_fogShader = MyShaders.CreateCs("clouds.hlsl", new [] { new ShaderMacro("NUMTHREADS", m_numFogThreads) });

            SamplerStateDescription description = new SamplerStateDescription
            {
                AddressU   = TextureAddressMode.Wrap,
                AddressV   = TextureAddressMode.Wrap,
                AddressW   = TextureAddressMode.Wrap,
                Filter     = Filter.MinMagMipLinear,
                MaximumLod = System.Single.MaxValue
            };

            m_textureSampler = MyPipelineStates.CreateSamplerState(description);
        }
示例#28
0
        private void Update(EvaluationContext context)
        {
            var samplerDesc = new SamplerStateDescription()
            {
                Filter             = Filter.GetValue(context),
                AddressU           = AddressU.GetValue(context),
                AddressV           = AddressV.GetValue(context),
                AddressW           = AddressW.GetValue(context),
                MipLodBias         = MipLoadBias.GetValue(context),
                MaximumAnisotropy  = MaximumAnisotropy.GetValue(context),
                ComparisonFunction = ComparisonFunction.GetValue(context),
                // BorderColor = BorderColor.GetValue(context),
                MinimumLod = MinimumLod.GetValue(context),
                MaximumLod = MaximumLod.GetValue(context)
            };

            try
            {
                var samplerState = new SamplerState(ResourceManager.Instance().Device, samplerDesc); // todo: put into resource manager
                SamplerState.Value?.Dispose();
                SamplerState.Value = samplerState;
            }
            catch (SharpDXException e)
            {
                Log.Error($"{Parent.Symbol.Name}.SamplerStateOp: Invalid sampler state " + e.Message);
                if (SamplerState.Value == null)
                {
                    // there was no previous valid sampler state, so set default sampler state
                    SamplerState.Value = ResourceManager.Instance().DefaultSamplerState;
                    Log.Error("Using the default sampler state instead.");
                }
                else
                {
                    Log.Error("Using the last valid sampler state instead.");
                }
            }
        }
示例#29
0
        public override void Initialize()
        {
            base.Initialize();

            mShader = new ShaderMatrixCBv2();

            // Create a texture sampler state description.
            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLodBias         = 0,
                MaximumAnisotropy  = 1,
                ComparisonFunction = Comparison.Always,
                BorderColor        = new Color4(0, 0, 0, 0), // Black Border.
                MinimumLod         = 0,
                MaximumLod         = float.MaxValue
            };

            // Create the texture sampler state.
            mSampler = new SamplerState(mDevice, samplerDesc);
        }
        internal static SamplerId CreateSamplerState(SamplerStateDescription description)
        {
            var id = new SamplerId { Index = SamplerStates.Allocate() };
            MyArrayHelpers.Reserve(ref SamplerObjects, id.Index + 1);

            SamplerStates.Data[id.Index] = description;

            InitSamplerState(id);
            SamplerIndices.Add(id);

            return id;
        }
示例#31
0
        bool InitializeShader(Device device, string vsFileName, string psFileName)
        {
            try {
                var compileVertexShaderResult = ShaderBytecode.CompileFromFile(vsFileName, "ClipPlaneVertexShader", "vs_5_0", ShaderFlags.EnableStrictness);
                vertexShader = new VertexShader(device, compileVertexShaderResult.Bytecode);

                var compilePixelShaderResult = ShaderBytecode.CompileFromFile(psFileName, "ClipPlanePixelShader", "ps_5_0", ShaderFlags.EnableStrictness);
                pixelShader = new PixelShader(device, compilePixelShaderResult.Bytecode);

                var inputElements = new[] {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0)
                };

                inputLayout = new InputLayout(device, compileVertexShaderResult.Bytecode, inputElements);

                compileVertexShaderResult.Dispose();
                compilePixelShaderResult.Dispose();

                var matrixBufferDescription = new BufferDescription {
                    Usage               = ResourceUsage.Default,
                    SizeInBytes         = Utilities.SizeOf <MatrixBufferType>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.None,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                matrixBuffer = Buffer.Create(device, new[] { new MatrixBufferType() }, matrixBufferDescription);

                var samplerStateDescription = new SamplerStateDescription {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0.0f,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        =
                    {
                        A = 0,
                        R = 0,
                        G = 0,
                        B = 0
                    },
                    MinimumLod = 0,
                    MaximumLod = float.MaxValue
                };

                samplerState = new SamplerState(device, samplerStateDescription);

                var clipPlaneBufferDescription = new BufferDescription {
                    Usage               = ResourceUsage.Default,
                    SizeInBytes         = Utilities.SizeOf <ClipPlaneBufferType>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.None,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                clipPlaneBuffer = Buffer.Create(device, new[] { new ClipPlaneBufferType() }, clipPlaneBufferDescription);
            } catch { return(false); }
            return(true);
        }
        private void BuildModelResources()
        {
            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            var cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBufferData>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart);

            constantBufferData = new ConstantBufferData
            {
                World = Matrix.Identity,
                View = Matrix.Identity,
                Project = Matrix.Identity,
                TexsCount = 1
            };

            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            //build mesh controll buffer

            meshCtrBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = meshCtrBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<MeshCtrBufferData>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbDesc, meshCtrBufferViewHeap.CPUDescriptorHandleForHeapStart);

            meshCtrBufferData = new MeshCtrBufferData
            {
                TexsCount = 1
            };

            meshCtrBufferPointer = meshCtrBuffer.Map(0);
            Utilities.Write(meshCtrBufferPointer, ref meshCtrBufferData);

            //model test
            var modePath = "../../models/MikuDeepSea/";
            Model model = Model.LoadFromFile(modePath + "DeepSeaGirl.x");

            Vertex[] triangleVertices;
            int[] triangleIndexes;
            List<Texture> texs;
            byte[] textureData;
            GCHandle handle;
            IntPtr ptr;
            ResourceDescription textureDesc;
            //int viewStep = 0;
            int viewStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            bufferViews = new List<BufferView>();

            foreach (ModelComponent m in model.Components)
            {
                if (m.TexturePath != null)
                {
                    texs = Texture.LoadFromFile(modePath, m.TexturePath);
                }
                else
                {
                    continue;
                    //texs = Texture.LoadFromFile(modePath, "tex/jacket.png");
                }

                int texsCount = 0;
                foreach (Texture tex in texs)
                {
                    textureData = tex.Data;
                    textureDesc = ResourceDescription.Texture2D(tex.ColorFormat, tex.Width, tex.Height, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
                    // Create the texture.
                    // Describe and create a Texture2D.
                    texture = device.CreateCommittedResource(
                        new HeapProperties(HeapType.Upload),
                        HeapFlags.None,
                        textureDesc,
                        ResourceStates.GenericRead, null);

                    // Copy data to the intermediate upload heap and then schedule a copy
                    // from the upload heap to the Texture2D.

                    handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
                    ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
                    texture.WriteToSubresource(0, null, ptr, tex.Width * tex.PixelWdith, textureData.Length);
                    handle.Free();

                    // Describe and create a SRV for the texture.
                    device.CreateShaderResourceView(
                        texture,
                        new ShaderResourceViewDescription
                        {
                            Shader4ComponentMapping = ((((0) & 0x7) | (((1) & 0x7) << 3) | (((2) & 0x7) << (3 * 2)) | (((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),
                            Format = textureDesc.Format,
                            Dimension = ShaderResourceViewDimension.Texture2D,
                            Texture2D =
                            {
                                MipLevels = 1,
                                MostDetailedMip = 0,
                                PlaneSlice = 0,
                                ResourceMinLODClamp = 0.0f
                            }
                        },
                        shaderRenderViewHeap.CPUDescriptorHandleForHeapStart + viewStep + texsCount * device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView));

                    texsCount++;
                    //break;
                }

                triangleVertices = (new Func<Vertex[]>(() =>
                {
                    var v = new Vertex[m.Vertices.Length];
                    for (int i = 0; i < m.Vertices.Length; i++)
                    {
                        v[i].Position = m.Vertices[i];
                        v[i].TexCoord = m.UV[i];
                        v[i].Normal = m.Normals[i];
                        //v[i].Tangent = m.Tangents[i];
                        //v[i].BiTangent = m.BiTangents[i];
                        v[i].Diffuse = m.Diffuse;
                        v[i].emissive = m.Emissive;
                        v[i].Specular = m.Specular;
                    }
                    return v;
                }))();
                triangleIndexes = m.Indices;

                // build vertex buffer
                vertexBuffer = device.CreateCommittedResource(
                    new HeapProperties(HeapType.Upload),
                    HeapFlags.None,
                    ResourceDescription.Buffer(Utilities.SizeOf(triangleVertices)),
                    ResourceStates.GenericRead);
                Utilities.Write(vertexBuffer.Map(0), triangleVertices, 0, triangleVertices.Length);
                vertexBuffer.Unmap(0);

                // build index buffer
                indexBuffer = device.CreateCommittedResource(
                    new HeapProperties(HeapType.Upload),
                    HeapFlags.None,
                    ResourceDescription.Buffer(Utilities.SizeOf(triangleIndexes)),
                    ResourceStates.GenericRead);
                Utilities.Write(indexBuffer.Map(0), triangleIndexes, 0, triangleIndexes.Length);
                indexBuffer.Unmap(0);

                bufferViews.Add(new BufferView()
                {
                    vertexBufferView = new VertexBufferView()
                    {
                        BufferLocation = vertexBuffer.GPUVirtualAddress,
                        StrideInBytes = Utilities.SizeOf<Vertex>(),
                        SizeInBytes = Utilities.SizeOf(triangleVertices)
                    },
                    indexBufferView = new IndexBufferView()
                    {
                        BufferLocation = indexBuffer.GPUVirtualAddress,
                        SizeInBytes = Utilities.SizeOf(triangleIndexes),
                        Format = Format.R32_UInt
                    },
                    IndexCount = triangleIndexes.Length,
                    ViewStep = viewStep,
                    TexsCount = texsCount
                });

                viewStep += texsCount * device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            }

            SamplerStateDescription samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MaximumAnisotropy = 0,
                MaximumLod = float.MaxValue,
                MinimumLod = -float.MaxValue,
                MipLodBias = 0,
                ComparisonFunction = Comparison.Never
            };

            device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart);
        }
示例#33
0
        private void LoadMesh(CpuDescriptorHandle heapStart)
        {
            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter = Filter.ComparisonMinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                MinimumLod = float.MinValue,
                MaximumLod = float.MaxValue,
                MipLodBias = 0,
                MaximumAnisotropy = 0,
                ComparisonFunction = Comparison.Never

            };
            var heapPosition = heapStart;

            // Load model from obj.
            var importer = new Assimp.AssimpContext();
            var scene = importer.ImportFile(@"../../../Models/lara/lara.obj", PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.FlipUVs | PostProcessSteps.PreTransformVertices);

            Vertex[] vertices = new Vertex[scene.Meshes.Sum(m => m.VertexCount)];
            int[] indices = new int[scene.Meshes.Sum(m => m.FaceCount * 3)];
            faceCounts = new List<int>();

            int vertexOffSet = 0;
            int indexOffSet = 0;
            foreach (var mesh in scene.Meshes)
            {
                var positions = mesh.Vertices;
                var normals = mesh.Normals;
                var texs = mesh.TextureCoordinateChannels[0];
                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    vertices[vertexOffSet + i] = new Vertex()
                    {
                        position = new Vector3(positions[i].X, positions[i].Y, positions[i].Z),
                        normal = new Vector3(normals[i].X, normals[i].Y, normals[i].Z),
                        textureCoordinate = new Vector3(texs[i].X, texs[i].Y, texs[i].Z)
                    };
                }

                var faces = mesh.Faces;
                for (int i = 0; i < mesh.FaceCount; i++)
                {
                    indices[i * 3 + indexOffSet] = (int)faces[i].Indices[0] + vertexOffSet;
                    indices[i * 3 + 1 + indexOffSet] = (int)faces[i].Indices[1] + vertexOffSet;
                    indices[i * 3 + 2 + indexOffSet] = (int)faces[i].Indices[2] + vertexOffSet;
                }

                faceCounts.Add(mesh.FaceCount * 3);
                vertexOffSet += mesh.VertexCount;
                indexOffSet += mesh.FaceCount * 3;

                string textureName = System.IO.Path.GetFileName(scene.Materials[mesh.MaterialIndex].TextureDiffuse.FilePath);
                var texResource = TextureUtilities.CreateTextureFromDDS(device, @"../../../Models/lara/" + textureName);
                textures.Add(texResource);

                int D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING = 5768;
                ShaderResourceViewDescription desc = new ShaderResourceViewDescription
                {
                    Dimension = ShaderResourceViewDimension.Texture2D,
                    Format = texResource.Description.Format,
                    Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
                };
                desc.Texture2D.MipLevels = 1;
                desc.Texture2D.MostDetailedMip = 0;
                desc.Texture2D.ResourceMinLODClamp = 0;

                device.CreateShaderResourceView(texResource, desc, heapStart);
                heapStart += constantBufferDescriptorSize;
            }

            int vertexBufferSize = Utilities.SizeOf(vertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            //Create Index Buffer
            int indexBufferSize = Utilities.SizeOf(indices);
            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, indices, 0, indices.Length);
            indexBuffer.Unmap(0);

            // Initialize the index buffer view.
            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.Format = Format.R32_UInt;
            indexBufferView.SizeInBytes = indexBufferSize;
        }
        public ParameterKey<SamplerState> GetSamplerKey(SamplerStateDescription samplerStateDesc)
        {
            ParameterKey<SamplerState> key;

            if (!declaredSamplerStates.TryGetValue(samplerStateDesc, out key))
            {
                key = MaterialKeys.Sampler.ComposeWith("i" + declaredSamplerStates.Count.ToString(CultureInfo.InvariantCulture));
                declaredSamplerStates.Add(samplerStateDesc, key);
            }

            var samplerState = SamplerState.NewFake(samplerStateDesc);
            Parameters.Set(key, samplerState);
            return key;
        }
示例#35
0
 /// <summary>
 /// Create a new fake sampler state for serialization.
 /// </summary>
 /// <param name="description">The description of the sampler state</param>
 /// <returns>The fake sampler state</returns>
 public static SamplerState NewFake(SamplerStateDescription description)
 {
     return new SamplerState(description);
 }
        private void LoadAssets()
        {
            // Create the root signature description.
            var rootSignatureDesc = new RootSignatureDescription(

                RootSignatureFlags.AllowInputAssemblerInputLayout,
                // Root Parameters
                new[]
                {
                    new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ShaderResourceView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue,
                                BaseShaderRegister = 0
                            },
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ConstantBufferView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue + 1,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.Pixel,
                        new DescriptorRange()
                        {
                            RangeType = DescriptorRangeType.Sampler,
                            DescriptorCount = 1,
                            OffsetInDescriptorsFromTableStart = int.MinValue,
                            BaseShaderRegister = 0
                        }),
                });
                //// Samplers
                //new[]
                //{
                //    new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0)
                //    {
                //        Filter = Filter.MinimumMinMagMipPoint,
                //        AddressUVW = TextureAddressMode.Border,
                //    }
                //});

            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            #if DEBUG
            //var result = SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug);
            var geometryShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            var inputElementDescs = new[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("TEXCOORD",0,Format.R32G32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                GeometryShader = geometryShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();

            // build vertex buffer

            var triangleVertices = new[]
            {
                //TOP
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //BOTTOM
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //LEFT
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                //RIGHT
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)} ,
                //FRONT
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                //BACK
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)}
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // build index buffer

            var triangleIndexes = new uint[]
            {
                0,1,2,
                0,2,3,

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

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

                12,14,13,
                12,15,14,

                16,18,17,
                16,19,18,

                20,21,22,
                20,22,23
            };

            int indexBufferSize = Utilities.SizeOf(triangleIndexes);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, triangleIndexes, 0, triangleIndexes.Length);
            indexBuffer.Unmap(0);

            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.SizeInBytes = indexBufferSize;
            indexBufferView.Format = Format.R32_UInt;

            // Create the texture.
            // Describe and create a Texture2D.
            var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, textureDesc, ResourceStates.GenericRead, null);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = Utilities.ReadStream(new FileStream("../../texture1.dds", FileMode.Open));

            texture.Name = "Texture";

            var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            texture.WriteToSubresource(0, null, ptr, TextureWidth * 4, textureData.Length);
            handle.Free();

            // Describe and create a SRV for the texture.
            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = ((((0) & 0x7) |(((1) & 0x7) << 3) |(((2) & 0x7) << (3 * 2)) |(((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),

                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D =
                {
                    MipLevels = 1,
                    MostDetailedMip = 0,
                    PlaneSlice = 0,
                    ResourceMinLODClamp = 0.0f
                },
            };

            device.CreateShaderResourceView(texture, srvDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart);

            SamplerStateDescription samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MaximumAnisotropy = 0,
                MaximumLod = float.MaxValue,
                MinimumLod = -float.MaxValue,
                MipLodBias = 0,
                ComparisonFunction = Comparison.Never
            };

            device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            // build constant buffer

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            var cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBufferData>() + 255) & ~255
            };
            var srvCbvStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateConstantBufferView(cbDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart + srvCbvStep);

            constantBufferData = new ConstantBufferData
            {
                Project = Matrix.Identity
            };

            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // build depth buffer

            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type = DescriptorHeapType.DepthStencilView,
                Flags = DescriptorHeapFlags.None
            };

            DescriptorHeap descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth = new ResourceDescription()
            {
                Dimension = ResourceDimension.Texture2D,
                DepthOrArraySize = 1,
                MipLevels = 0,
                Flags = ResourceFlags.AllowDepthStencil,
                Width = (int)viewport.Width,
                Height = (int)viewport.Height,
                Format = Format.R32_Typeless,
                Layout = TextureLayout.Unknown,
                SampleDescription = new SampleDescription() { Count = 1 }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;

            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;
            fenceEvent = new AutoResetEvent(false);
        }
示例#37
0
 // For FakeSamplerState.
 private SamplerState(SamplerStateDescription description)
 {
     Description = description;
 }
        public ObjectParameterKey<SamplerState> GetSamplerKey(ComputeColorParameterSampler sampler)
        {
            if (sampler == null) throw new ArgumentNullException("sampler");

            var samplerStateDesc = new SamplerStateDescription(sampler.Filtering, sampler.AddressModeU)
            {
                AddressV = sampler.AddressModeV,
                AddressW = TextureAddressMode.Wrap
            };
            return GetSamplerKey(samplerStateDesc, graphicsDevice);
        }
        private SamplerState(GraphicsDevice device, SamplerStateDescription samplerStateDescription) : base(device)
        {
            Description = samplerStateDescription;

            textureWrapS = samplerStateDescription.AddressU.ToOpenGL();
            textureWrapT = samplerStateDescription.AddressV.ToOpenGL();
            textureWrapR = samplerStateDescription.AddressW.ToOpenGL();

            compareMode = TextureCompareMode.None;

            // ComparisonPoint can act as a mask for Comparison filters (0x80)
            if ((samplerStateDescription.Filter & ComparisonMask) != 0)
                compareMode = TextureCompareMode.CompareRefToTexture;

            compareFunc = samplerStateDescription.CompareFunction.ToOpenGLDepthFunction();
            borderColor = samplerStateDescription.BorderColor.ToArray();
            // TODO: How to do MipLinear vs MipPoint?
            switch (samplerStateDescription.Filter & ~(ComparisonMask | AnisotropicMask)) // Ignore comparison (128) and anisotropic (64) part
            {
                case TextureFilter.MinMagLinearMipPoint:
                    minFilter = TextureMinFilter.LinearMipmapNearest;
                    magFilter = TextureMagFilter.Linear;
                    break;
                case TextureFilter.Linear:
                    minFilter = TextureMinFilter.LinearMipmapLinear;
                    magFilter = TextureMagFilter.Linear;
                    break;
                case TextureFilter.MinPointMagMipLinear:
                    minFilter = TextureMinFilter.NearestMipmapLinear;
                    magFilter = TextureMagFilter.Linear;
                    break;
                case TextureFilter.Point:
                    minFilter = TextureMinFilter.NearestMipmapNearest;
                    magFilter = TextureMagFilter.Nearest;
                    break;
                case TextureFilter.MinPointMagLinearMipPoint:
                    minFilter = TextureMinFilter.NearestMipmapNearest;
                    magFilter = TextureMagFilter.Linear;
                    break;
                case TextureFilter.MinLinearMagMipPoint:
                    minFilter = TextureMinFilter.LinearMipmapNearest;
                    magFilter = TextureMagFilter.Nearest;
                    break;
                case TextureFilter.MinMagPointMipLinear:
                    minFilter = TextureMinFilter.NearestMipmapLinear;
                    magFilter = TextureMagFilter.Nearest;
                    break;
                case TextureFilter.MinLinearMagPointMipLinear:
                    minFilter = TextureMinFilter.LinearMipmapLinear;
                    magFilter = TextureMagFilter.Nearest;
                    break;
                default:
                    throw new NotImplementedException();
            }

            maxAnisotropy = ((samplerStateDescription.Filter & AnisotropicMask) != 0) ? Description.MaxAnisotropy : 1;

#if SILICONSTUDIO_XENKO_GRAPHICS_API_OPENGLES
            // On OpenGL ES, we need to choose the appropriate min filter ourself if the texture doesn't contain mipmaps (done at PreDraw)
            minFilterNoMipmap = minFilter;
            if (minFilterNoMipmap == TextureMinFilter.LinearMipmapLinear)
                minFilterNoMipmap = TextureMinFilter.Linear;
            else if (minFilterNoMipmap == TextureMinFilter.NearestMipmapLinear)
                minFilterNoMipmap = TextureMinFilter.Nearest;
#endif
        }
示例#40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EffectSamplerStateBinding"/> class.
 /// </summary>
 /// <param name="keyName">Name of the key.</param>
 /// <param name="description">The description.</param>
 public EffectSamplerStateBinding(string keyName, SamplerStateDescription description)
 {
     KeyName     = keyName;
     Description = description;
 }
 internal static void ChangeSamplerState(SamplerId id, SamplerStateDescription description)
 {
     SamplerStates.Data[id.Index] = description;
     if(SamplerObjects[id.Index] != null)
     {
         SamplerObjects[id.Index].Dispose();
     }
     SamplerObjects[id.Index] = new SamplerState(MyRender11.Device, description);
 }
        public ObjectParameterKey<SamplerState> GetSamplerKey(SamplerStateDescription samplerStateDesc, GraphicsDevice graphicsDevice)
        {
            ObjectParameterKey<SamplerState> key;

            if (!declaredSamplerStates.TryGetValue(samplerStateDesc, out key))
            {
                key = MaterialKeys.Sampler.ComposeWith("i" + declaredSamplerStates.Count.ToString(CultureInfo.InvariantCulture));
                declaredSamplerStates.Add(samplerStateDesc, key);
            }

            var samplerState = graphicsDevice != null ? SamplerState.New(graphicsDevice, samplerStateDesc) : SamplerState.NewFake(samplerStateDesc);
            Parameters.Set(key, samplerState);
            return key;
        }
示例#43
0
 private SamplerState(GraphicsDevice graphicsDevice, SamplerStateDescription samplerStateDescription)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EffectSamplerStateBinding"/> class.
 /// </summary>
 /// <param name="keyName">Name of the key.</param>
 /// <param name="description">The description.</param>
 public EffectSamplerStateBinding(string keyName, SamplerStateDescription description)
 {
     KeyName = keyName;
     Description = description;
 }
示例#45
0
        private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                // Compile the Vertex Shader & Pixel Shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the Vertex & Pixel Shaders from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout. Kin dof like a Vertex Declaration.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant Matrix buffer that is in the vertex shader.
                BufferDescription matrixBufferDescription = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription);

                // Create a texture sampler state description.
                SamplerStateDescription samplerDesc = new SamplerStateDescription()
                {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        = new Color4(0, 0, 0, 0), // Black Border.
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };

                // Create the texture sampler state.
                SamplerState = new SamplerState(device, samplerDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SamplerState"/> class.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="name">The name.</param>
        /// <param name="samplerStateDescription">The sampler state description.</param>
        private SamplerState(GraphicsDevice device, SamplerStateDescription samplerStateDescription) : base(device)
        {
            Description = samplerStateDescription;

            CreateNativeDeviceChild();
        }