ios - 如何使用MTLSamplerState而不是在片段着色器代码中声明采样器?

标签 ios objective-c metal metalkit

我在下面的着色器中定义了采样器(constexpr sampler textureSampler (mag_filter::linear,min_filter::linear);)。

    using namespace metal;

    struct ProjectedVertex {
      'float4 position [[position]];
      'float2 textureCoord;
    };

    fragment float4 fragmentShader(const ProjectedVertex in [[stage_in]],
                                   const texture2d<float> colorTexture [[texture(0)]],
                                   constant float4 &opacity [[buffer(1)]]){

      constexpr sampler textureSampler (mag_filter::linear,min_filter::linear);
      const float4 colorSample = colorTexture.sample(textureSampler, in.textureCoord);
      return colorSample*opacity[0];

    }

现在,我想避免在着色器代码中几乎不定义此采样器。我找到了MTLSamplerState但我不知道如何使用它

最佳答案

要创建采样器,请首先创建 MTLSamplerDescriptor 对象,然后配置描述符的属性。然后在将使用此采样器的 MTLDevice 对象上调用newSamplerStateWithDescriptor:方法。创建采样器后,可以释放描述符或重新配置其属性以创建其他采样器。

// Create default sampler state
MTLSamplerDescriptor *samplerDesc = [MTLSamplerDescriptor new];
samplerDesc.rAddressMode = MTLSamplerAddressModeRepeat;
samplerDesc.sAddressMode = MTLSamplerAddressModeRepeat;
samplerDesc.tAddressMode = MTLSamplerAddressModeRepeat;
samplerDesc.minFilter = MTLSamplerMinMagFilterLinear;
samplerDesc.magFilter = MTLSamplerMinMagFilterLinear;
samplerDesc.mipFilter = MTLSamplerMipFilterNotMipmapped;
id<MTLSamplerState> ss = [device newSamplerStateWithDescriptor:samplerDesc];

为片段函数设置采样器状态:
    id<MTLRenderCommandEncoder> encoder = [commandBuffer renderCommandEncoderWithDescriptor: passDescriptor];
     ...
    [encoder setFragmentSamplerState: ss atIndex:0];

从着色器访问:
fragment float4 albedoMainFragment(ImageColor in [[stage_in]],
                                texture2d<float> diffuseTexture [[texture(0)]],
                                sampler smp [[sampler(0)]]) {

    float4 color = diffuseTexture.sample(smp, in.texCoord);
    return color;
}

关于ios - 如何使用MTLSamplerState而不是在片段着色器代码中声明采样器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59002795/

相关文章:

ios - iphone - 字符串不保持其值(value)

ios - 以编程方式在 swift 中为 tableview 部分索引设置框架

objective-c - 为什么这不起作用? - 将数据写入plist

objective-c - 通用 iOS 应用程序中的 iPad/iPhone 应用程序委托(delegate)有什么意义?

swift - 使用 Metal Framework 将图像保存到磁盘时命令缓冲区的执行被中止/GPU 错误

ios - 邮件和消息未从警报 View 中消失

iOS耳机触控处理

iphone - 无法将 Tapku 库添加到 XCode 4.2 项目中

ios - device.newDefaultLibrary() 返回 nil

ios - Metal 崩溃 - CVMetalTextureCacheCreateTextureFromImage