Manually set a 1D Texture in Metal

佐手、 提交于 2019-12-04 19:17:52

I don't see any reason for you to pass data using 1D texture. Instead I would go with just passing a buffer. Like this:

var dataBuffer:MTLBuffer? = device.newBufferWithBytes(&manualTextureData, length: sizeOf(manualTextureData), options: MTLResourceOptions.OptionCPUCacheModeDefault)

Then you hook it to your renderCommandEncoder like this:

renderCommandEncoder.setFragmentBuffer(dataBuffer, offset: 0, atIndex: 1)//Note that if you want this buffer to be passed to you vertex shader you should use setVertexBuffer

Then in your shader, you should add parameter like this const device float* bufferPassed [[ buffer(1) ]]

And then use it like this, inside your shader implementation:

float firstFloat = bufferPassed[0];

This will get the job done.

Not really answering your question, but you could just define an array in your metal shader instead of passing the values as a texture.

Something like:

constant float manualData[8] = { 1.0, 0.0, 0.0, 1.0,
                               0.0, 0.0, 1.0, 1.0 };

vertex float4 world_vertex(unsigned int vid[[vertex_id]], ...) {
    int manualIndex = vid % 8;
    float manualValue = manualData[manualIndex];
    // something deep and meaningful here...
    return float4(manualValue);
}
Karsten

If you want a float texture bytesPerRow should be 4 for times the width, because a float has a size of 4 bytes. Metal copies the memory and dont care about the values. That is your task ;-)

Something like:

myTexture.replaceRegion(region, mipmapLevel: 0, withBytes: &manualTextureData, bytesPerRow: manualTextureData.count * sizeof(Float));

Please forgive the terse reply, but you may find it useful to take a look at my experiments with Swift and Metal. I've created a particle system in Swift which is passed to a Metal compute shader as a one dimensional array of Particle structs. By using posix_memalign, I'm able to eliminate the bottleneck caused by passing the array between Metal and Swift.

I've blogged extensively about this: http://flexmonkey.blogspot.co.uk/search/label/Metal

I hope this helps.

Simon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!