Search code examples
javaandroidrenderscriptandroid-renderscript

Increment a count variable in RenderScript


I want to count the pixels of a bitmap using the following RenderScript code

RenderScript

Filename: counter.rs

#pragma version(1)
#pragma rs java_package_name(com.mypackage)
#pragma rs_fp_relaxed

uint count; // initialized in Java
void countPixels(uchar4* unused, uint x, uint y) {
  rsAtomicInc(&count);
}

Java

Application context = ...; // The application context
RenderScript rs = RenderScript.create(applicationContext);

Bitmap bitmap = ...; // A random bitmap
Allocation allocation = Allocation.createFromBitmap(rs, bitmap);

ScriptC_Counter script = new ScriptC_Counter(rs);
script.set_count(0);
script.forEach_countPixels(allocation);

allocation.syncAll(Allocation.USAGE_SCRIPT);
long count = script.get_count();

Error

This is the error message I get:

ERROR: Address not found for count

Questions

  • Why doesn't my code work?
  • How can I fix it?

Links


Solution

  • Here is my working solution.

    RenderScript

    Filename: counter.rs

    #pragma version(1)
    #pragma rs java_package_name(com.mypackage)
    #pragma rs_fp_relaxed
    
    int32_t count = 0;
    rs_allocation rsAllocationCount;
    
    void countPixels(uchar4* unused, uint x, uint y) {
      rsAtomicInc(&count);
      rsSetElementAt_int(rsAllocationCount, count, 0);
    }
    

    Java

    Context context = ...;
    RenderScript renderScript = RenderScript.create(context);
    
    Bitmap bitmap = ...; // A random bitmap
    Allocation allocationBitmap = Allocation.createFromBitmap(renderScript, bitmap);
    Allocation allocationCount = Allocation.createTyped(renderScript, Type.createX(renderScript, Element.I32(renderScript), 1));
    
    ScriptC_Counter script = new ScriptC_Counter(renderScript);
    script.set_rsAllocationCount(allocationCount);
    script.forEach_countPixels(allocationBitmap);
    
    int[] count = new int[1];
    allocationBitmap.syncAll(Allocation.USAGE_SCRIPT);
    allocationCount.copyTo(count);
    
    // The count can now be accessed via
    count[0];