个人资料

跳过导航链接首页 > 博客列表 > 博客正文

MonoGame在shader中使用两张或多张texture的注意事项

:

1.使用标准写法

texture Texture;
sampler2D TextureSampler = sampler_state
{
    Texture = <Texture>;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
    MipFilter = LINEAR;
    AddressU = WRAP;
    AddressV = WRAP;
};

texture MyNoiseTexture;
sampler2D NoiseSampler = sampler_state
{
    Texture = <MyNoiseTexture>;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
    MipFilter = LINEAR;
    AddressU = WRAP;
    AddressV = WRAP;
};
在C#侧,通过参数赋值
drawEffect.Parameters["Texture"].SetValue(tile_texture);
drawEffect.Parameters["MyNoiseTexture"].SetValue(noise_texture);
*第一个参数Texture的赋值不是必要的,因为在Draw方法中,会将draw绘制的texture自动绑定第一个Texture

2.要在shader中实际使用,否则将被优化

虽然如1所示,设置了Texture和MyNoiseTexture两个参数,但是如果在代码中没有实际使用和使用这两个参数贴图的数值并不影响最终输出结果,那么没有用到的Texture可能会被优化掉,也就是SetValue会报错.

*在测试过程中可以先使用同一张贴图同时作为主贴图和noise贴图,测试结果可用性再引入Noise贴图,因为代码中的不正确设置可能导致使用多张贴图无效.确保贴图代码使用正确再引入Noise贴图

3.最大兼容性

在shader中,引入兼容性确保可用,如:


#if OPENGL
#define VS_SHADERMODEL vs_3_0
#define PS_SHADERMODEL ps_3_0
#else
#define VS_SHADERMODEL vs_4_0
#define PS_SHADERMODEL ps_4_0
#endif
//

......

//

technique SpriteBatch
{
    //pass P0
    //{
    //    VertexShader = compile vs_4_0 VS();
    //    PixelShader = compile ps_4_0 PS();
    //}

    pass P0
    {
        VertexShader = compile VS_SHADERMODEL VS();
        PixelShader = compile PS_SHADERMODEL PS();
    }
}
*不确定是否有用,但可作为排查错误选项之一



songshizhao
最初发表2025/10/20 19:50:50 最近更新2025/10/20 19:53:30 52
为此篇作品打分
10