Renderscript,forEach_root和从OpenCL移植

时间:2013-05-11 19:35:20

标签: renderscript

1)如何在forEach_root()中访问除当前元素之外的其他元素?

在OpenCL中,我们有指向第一个元素的指针,然后可以使用get_global_id(0)来获取当前索引。但我们仍然可以访问所有其他元素。在Renderscript中,我们只有指向当前元素的指针吗?

2)如何在forEach_root()中循环分配?

我有一个在java中使用嵌套(双)循环的代码。 Renderscript自动化外循环,但我找不到任何有关实现内循环的信息。以下是我的最大努力:

void root(const float3 *v_in, float3 *v_out) {
  rs_allocation alloc = rsGetAllocation(v_in);
  uint32_t cnt = rsAllocationGetDimX(alloc);
  *v_out = 0;
  for(int i=0; i<cnt; i++)  
    *v_out += v_in[i];
}

但是从forEach_root()调用时,rsGetAllocation()失败了。

05-11 21:31:29.639: E/RenderScript(17032): ScriptC::ptrToAllocation, failed to find 0x5beb1a40

以防我添加在Windows下运行良好的 OpenCL 代码。我正在尝试将其移植到Renderscript

typedef float4 wType;

__kernel void gravity_kernel(__global wType *src,__global wType *dst)
{
  int id = get_global_id(0);
  int count = get_global_size(0);
  double4 tmp = 0;
  for(int i=0;i<count;i++) {
    float4 diff = src[i] - src[id];
    float sq_dist = dot(diff, diff);
    float4 norm = normalize(diff);
    if (sq_dist<0.5/60)
      tmp += convert_double4(norm*sq_dist);
    else
      tmp += convert_double4(norm/sq_dist);
  }
  dst[id] = convert_float4(tmp);
}

1 个答案:

答案 0 :(得分:2)

您可以提供除根功能之外的数据。在当前的Android版本(4.2)中,您可以执行以下操作(这是图像处理方案中的示例):

Renderscript代码段

#pragma version(1)
#pragma rs java_package_name(com.example.renderscripttests)

//Define global variables in your renderscript:
rs_allocation pixels;
int width;
int height;

// And access these in your root function via rsGetElementAt(pixels, px, py)
void root(uchar4 *v_out, uint32_t x, uint32_t y)
{
    for(int px = 0; px < width; ++px)
        for(int py = 0; py < height; ++py)
        {
            // unpack a color to a float4
            float4 f4 = rsUnpackColor8888(*(uchar*)rsGetElementAt(pixels, px, py));
            ...

Java文件摘要

// In your java file, create a renderscript:
RenderScript renderscript = RenderScript.create(this);

ScriptC_myscript script = new ScriptC_myscript(renderscript);

// Create Allocations for in- and output (As input the bitmap 'bitmapIn' should be used):
Allocation pixelsIn = Allocation.createFromBitmap(renderscript, bitmapIn,
         Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
Allocation pixelsOut = Allocation.createTyped(renderscript, pixelsIn.getType());

// Set width, height and pixels in the script:
script.set_width(640);
script.set_height(480);
script.set_pixels(pixelsIn);

// Call the for each loop:
script.forEach_root(pixelsOut);

// Copy Allocation to the bitmap 'bitmapOut':
pixelsOut.copyTo(bitmapOut);

你可以看到,在调用forEach_root函数来计算'pixelsOut'的值时,输入'pixelsIn'是先前在renderscript中设置和使用的。此前还设置了宽度和高度。