首页 > 解决方案 > 用于馈送 SCNTechnique 的 sampler2D 输入的低成本图像到 NSData 转换

问题描述

有时,将宝贵数据从 CPU 传递到 GPU 的唯一方法是将其隐藏在纹理中。

我试图欺骗 SCNTechnique 并简单地传递[NSData dataWithBytes:length:]CGDataProviderRef包含我精心准备的原始像素数据字节,但 SceneKit 足够聪明,可以检测到我的险恶企图。

但我没有放弃,发现了一个漏洞:

  [_sceneView.technique setValue: UIImagePNGRepresentation(encodeInSinglePixelUIImage(pos.x, pos.y)) forKey:@"blob_pos_"];

在移动设备上以 60 fps 编码和解码单像素 PNG 是您负担得起的,在 iPhone X 上只需 2 毫秒,让您的手掌保持温暖一点。但是,直到 11 月我才需要任何发热功能,所以我想知道这种方法是否有一个很酷的替代方法。

标签: uiimagescenekitnsdatascntechnique

解决方案


我发现最有效的方法是构建浮点 RGB TIFF。它仍然不是超级快,在 iPhone X 上消耗 0.7ms,但比 PNG 方法快很多。

具有浮点纹理还具有直接浮点传输的好处,即无需在 CPU 上对多个 uint8 RGBA 值进行编码,并在 GPU 上重建浮点数。

就是这样:

NSData * tiffencode(float x, float y)
{
    const uint8_t tags = 9;
    const uint8_t headerlen = 8+2+tags*12+4;
    const uint8_t width = 1;
    const uint8_t height = 1;
    const uint8_t datalen = width*height*3*4;
    static uint8_t tiff[headerlen+datalen] = {
        'I', 'I', 0x2a, 0, //little endian/'I'ntel
        8, 0, 0, 0, //index of metadata
        tags, 0,
        0x00, 1,  4, 0,  1, 0, 0, 0,  width, 0, 0, 0,   //width
        0x01, 1,  4, 0,  1, 0, 0, 0,  height, 0, 0, 0,  //height
        0x02, 1,  3, 0,  1, 0, 0, 0,  32, 0, 0, 0,      //bits per sample(s)
        0x06, 1,  3, 0,  1, 0, 0, 0,  2, 0, 0, 0,       //photometric interpretation: RGB
        0x11, 1,  4, 0,  1, 0, 0, 0,  headerlen, 0, 0, 0,//strip offset
        0x15, 1,  3, 0,  1, 0, 0, 0,  3, 0, 0, 0,       //samples per pixel: 3
        0x16, 1,  4, 0,  1, 0, 0, 0,  height, 0, 0, 0,  //rows per strip: height
        0x17, 1,  4, 0,  1, 0, 0, 0,  datalen, 0, 0, 0, //strip byte length
        0x53, 1,  3, 0,  1, 0, 0, 0,  3, 0, 0, 0,       //sampleformat: float
        0, 0, 0, 0, //end of metadata

        //RGBRGB.. pixeldata here
    };

    float *rawData = tiff+headerlen;
    rawData[0] = x;
    rawData[1] = y;

    NSData *data = [NSData dataWithBytes:&tiff length:sizeof(tiff)];
    return data;
}

我使用的有用的 TIFF 链接:

http://www.fileformat.info/format/tiff/corion.htm

http://paulbourke.net/dataformats/tiff/

https://www.fileformat.info/format/tiff/egff.htm

https://www.awaresystems.be/imaging/tiff/tifftags/sampleformat.html


推荐阅读