Skip to content

Android:Renderscript

렌더스크립트는 고성능 3D 렌더링과 컴퓨팅 연산에 맞춘 새 API입니다. 렌더 스크립트의 목적은 저수준에서 얻은 고성능의 API를 안드로이드 개발자에게 주는 겁니다. 자신의 애플리케이션 성능을 최적화려 기계 수준까지 작업하는게 익숙한 개발자를 대상으로 합니다. 렌더 스크립트는 개발자에게 3종의 기본 도구를 제공합니다. 하드웨어 가속되는 간단한 3D 렌더링 API, CUDA와 유사한 개발자 친화적인 연산 API, C99와 흡사한 언어입니다.

Using the RenderScript Support Library APIs

In order to use the Support Library RenderScript APIs, you must configure your development environment to be able to access them. The following Android SDK tools are required for using these APIs:

  • Android SDK Tools revision 22.2 or higher
  • Android SDK Build-tools revision 18.1.0 or higher
  • You can check and update the installed version of these tools in the Android SDK Manager.

Note: Use of Support Library RenderScript APIs is not currently supported with Android Studio or Gradle-based builds.

RenderScript APIs in Eclipse

To use the Support Library RenderScript APIs in Eclipse:
Make sure you have the required Android SDK version and Build Tools version installed.
Open the project.properties file in the root folder of your application project.
Add the following lines to the file:

  • renderscript.target=18
  • renderscript.support.mode=true
  • sdk.buildtools=18.1.0

In your application classes that use RenderScript, add an import for the Support Library classes:

  • import android.support.v8.renderscript.*;

project.properties settings list

The project.properties settings listed above control specific behavior in the Android build process:

renderscript.target
Specifies the bytecode version to be generated. We recommend you set this value the highest available API level and set renderscript.support.mode to true. Valid values for this setting are any integer value from 11 to the most recently released API level. If your minimum SDK version specified in your application manifest is set to a higher value, this value is ignored and the target value is set to the minimum SDK version.
renderscript.support.mode
Specifies that the generated bytecode should fall back to a compatible version if the device it is running on does not support the target version.
sdk.buildtools
The version of the Android SDK build tools to use. This value should be set to 18.1.0 or higher. If this option is not specified, the highest installed build tools version is used. You should always set this value to ensure the consistency of builds across development machines with different configurations.

APIs & Implement detail

렌더스크립트 지원 라이브러리를 앱에서 사용하고 싶다면 알아야 할게 몇가지 있습니다.

  1. 렌더스크립트 지원 라이브러리는 API 레벨에서와 이후에 지원하는 네이티브 렌더스크립트 API 기능의 대부분을 지원합니다. 주목할 예외는 Allocation.USAGE_IO_INPUTAllocation.USAGE_IO_OUTPUT입니다.
    현재 렌더스크립트 지원 라이브러리에서는 지원하지 못합니다.
  2. 4.3 이후의 렌더스크립트 애플리케이션은 해당 단말기에서 지원하는 프로세서들에서도 돌 수 있는데 비해 안드로이드 4.2와 이전 단말기에서는 렌더스크립트 애플리케이션이 전적으로 CPU에서 돈다는 것입니다.
    (주: 안드로이드 4.3에서도 넥서스 10등의 일부 단말에서 GPU 작동이 지원됩니다.)
    스크립트의 지원 라이브러리 버전들은 모든 가능한 플랫폼을 지원하기 위해 미리 컴파일되어 있기 때문에 런타임에 컴파일되는 안드로이드 4.3에 비해 컴파일러 최적화에 제한이 있고 그에 따른 성능 최적화에 불이익이 있습니다.

RenderScript에서 로그 메시지를 출력하고 싶을 경우 아래와 같은 함수를 사용하면 된다.

void printLog()
{
    rsDebug("[RenderScript] testPreConditionForIntro() call.", 0);
}

Sample code

렌더 스크립트를 입력하기 위한 mono.rs

// mono.rs
#pragma version(1)
#pragma rs java_package_name(com.example.renderscriptsample)

float3 gMonoMult = {0.2125, 0.7154, 0.0721};

void root(const uchar4 *v_in, uchar4 *v_out) {
    float4 f4 = rsUnpackColor8888(*v_in);
    float3 mono = dot(f4.rgb, gMonoMult);
    *v_out = rsPackColorTo8888(mono);
}

Android 화면(Activity)를 구현하기 위한 MainActivity.java

package com.example.renderscriptsample;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

// import android.renderscript.Allocation;
// import android.renderscript.RenderScript;
import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.RenderScript;

import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {
    // RenderScript
    private RenderScript mRS;
    private Allocation mInAllocation;
    private Allocation mOutAllocation;
    private ScriptC_mono mScript;

    private Bitmap loadBitmap(int resource) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        return BitmapFactory.decodeResource(getResources(), resource, options);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // bitmap load
        final Bitmap bm = loadBitmap(R.drawable.data);
        final Bitmap bmOut = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());

        // renderscript init
        mRS = RenderScript.create(this);
        mInAllocation = Allocation.createFromBitmap(mRS, bm, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
        mOutAllocation = Allocation.createFromBitmap(mRS, bm, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
        mScript = new ScriptC_mono(mRS, getResources(), R.raw.mono);

        // renderscript run
        mScript.forEach_root(mInAllocation, mOutAllocation);
        mOutAllocation.copyTo(bmOut);

        // set output bitmap
        final ImageView iv = (ImageView) findViewById(R.id.imageView1);
        iv.setImageBitmap(bmOut);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

RenderScript Animation

위의 예제에서, ValueAnimator를 사용하여 ImageView의 Bitmap을 갱신하는 예제는 아래와 같다.

// set output bitmap
final ImageView iv = (ImageView) findViewById(R.id.activity_main__logo_icon_custom_bg);
iv.setImageBitmap(bmOut);
// ...
ValueAnimator ani = ValueAnimator.ofFloat(0.0f, 360.0f);
ani.setDuration(3000);
ani.setRepeatCount(200);
ani.setInterpolator(new AccelerateDecelerateInterpolator());
ani.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float val = (Float) animation.getAnimatedValue();
        int rgba = Color.HSVToColor(new float[] {val, 1.0f, 1.0f});

        float r = (float)((rgba >> 16) & 0xFF) / 255.0f;
        float g = (float)((rgba >>  8) & 0xFF) / 255.0f;
        float b = (float)( rgba        & 0xFF) / 255.0f;

        mScript.set_g_add(new Float4(r, g, b, 1.0f));
        mScript.forEach_root(mInAllocation, mOutAllocation);
        mOutAllocation.copyTo(bmOut);
        iv.setImageBitmap(bmOut);
    }
});
ani.start();

위의 코드에 사용할 RenderScript는 아래와 같다.
v_in으로 입력된 Bitmap에서 Alpha값이 0이 아닌 모든 색상을 변경한다.

float4 g_add = 0.0f;
/// @brief RenderScript Entry point.
void root(const uchar4 * v_in, uchar4 * v_out)
{
    // rsDebug("[RenderScript] test 1 call.", 0);
    float4 f4 = rsUnpackColor8888(*v_in);
    if (f4.w != 0) {
        f4 = g_add;
        // rsDebug("[RenderScript] test 2 call.", f4);
    }

    *v_out = rsPackColorTo8888(f4);
}

See also

Favorite site

References


  1. Beginning_Android_RenderScript.pdf 

  2. Sample Download: Renderscript-example-Gravity-r2.zip 

  3. RenderScript_android_parallel_programming.pdf 

  4. Designing_Apps_for_XOOM_pt2.pdf 

  5. Blog.iangclifton_-RenderScript1-_Basics_Tutorial.pdf 

  6. Blog.iangclifton_-RenderScript2-_Interaction.pdf 

  7. RenderScript_Step4_(jp)_rsgBindTexture.pdf 

  8. RenderScript_-_Page_flip.pdf 

  9. RenderScript_Support_For_All_Double_Encore.pdf 

  10. Open_Expert_Group_-_RenderScript.pdf 

  11. RenderScript_Real_time_image_processing.pdf 

  12. RSRTImgProc-master-52df27a126e5d3f1d4a32b99ce0a94d05a86cbad.tar.gz 

  13. RenderScriptDemos-master-70307a646cb8f4192d292ff737c22b2dc5aed16c.tar.gz 

  14. Edu4android.com_-_RenderScript.pdf