hyp*_*not 2 cocoa cocoa-touch swift metal
推荐的使用方法MTKTextureLoader.newTexture不适用于16位图像.
named:版本以静默方式将图像转换为8位像素格式cgImage:版本与终止Image decoding failedUIImage和NSImage都支持加载16位图像,并且有一个方便的.cgimage方法,可以在一个内核中转换为CGImage,从而解决了在两个平台上获得CGImage的问题.
如何编写一个转换CGImage并返回16位Metal纹理的函数?
loadEXRTexture下面的函数加载扩展范围图像并将其像素转换为半精度浮点,将生成的像素数据存储MTLTexture为.rgba16Float格式.它试图通过使用CGImageSource从Quartz默认值改变其行为的选项来保留浮点图像的原始范围(它将"解码"函数应用于将源数据压缩到适合绘制到位图上下文的范围内).它假定图像源创建的图像具有以RGB顺序打包的三个浮点组件.
func convertRGBF32ToRGBAF16(_ src: UnsafePointer<Float>, _ dst: UnsafeMutablePointer<UInt16>, pixelCount: Int) {
for i in 0..<pixelCount {
storeAsF16(src[i * 3 + 0], dst + (i * 4) + 0)
storeAsF16(src[i * 3 + 1], dst + (i * 4) + 1)
storeAsF16(src[i * 3 + 2], dst + (i * 4) + 2)
storeAsF16(1.0, dst + (i * 4) + 3)
}
}
func loadEXRTexture(_ url: URL, device: MTLDevice) -> MTLTexture? {
guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
let options = [ kCGImageSourceShouldCache : true, kCGImageSourceShouldAllowFloat : true ] as CFDictionary
guard let image = CGImageSourceCreateImageAtIndex(imageSource, 0, options) else { return nil }
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba16Float,
width: image.width,
height: image.height,
mipmapped: false)
descriptor.usage = .shaderRead
guard let texture = device.makeTexture(descriptor: descriptor) else { return nil }
if image.bitsPerComponent == 32 && image.bitsPerPixel == 96 {
let srcData: CFData! = image.dataProvider?.data
CFDataGetBytePtr(srcData).withMemoryRebound(to: Float.self, capacity: image.width * image.height * 3) { srcPixels in
let dstPixels = UnsafeMutablePointer<UInt16>.allocate(capacity: 4 * image.width * image.height)
convertRGBF32ToRGBAF16(srcPixels, dstPixels, pixelCount: image.width * image.height)
texture.replace(region: MTLRegionMake2D(0, 0, image.width, image.height),
mipmapLevel: 0,
withBytes: dstPixels,
bytesPerRow: MemoryLayout<UInt16>.size * 4 * image.width)
dstPixels.deallocate()
}
}
return texture
}
Run Code Online (Sandbox Code Playgroud)
你需要在桥接头中包含这个实用程序,因为据我所知,Swift没有__fp16类型或任何等价物:
#include <stdint.h>
static inline void storeAsF16(float value, uint16_t *pointer) { *(__fp16 *)pointer = value; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
565 次 |
| 最近记录: |