1page.title=RenderScript
2parent.title=Computation
3parent.link=index.html
4
5@jd:body
6
7<div id="qv-wrapper">
8  <div id="qv">
9    <h2>In this document</h2>
10
11    <ol>
12      <li><a href="#writing-an-rs-kernel">Writing a RenderScript Kernel</a></li>
13      <li><a href="#access-rs-apis">Accessing RenderScript APIs</a>
14        <ol>
15          <li><a href="#ide-setup">Setting Up Your Development Environment</a></li>
16        </ol>
17      </li>
18      <li><a href="#using-rs-from-java">Using RenderScript from Java Code</a></li>
19    </ol>
20
21    <h2>Related Samples</h2>
22
23    <ol>
24      <li><a href="{@docRoot}resources/samples/RenderScript/HelloCompute/index.html">Hello
25      Compute</a></li>
26    </ol>
27  </div>
28</div>
29
30<p>RenderScript is a framework for running computationally intensive tasks at high performance on
31Android. RenderScript is primarily oriented for use with data-parallel computation, although serial
32computationally intensive workloads can benefit as well. The RenderScript runtime will parallelize
33work across all processors available on a device, such as multi-core CPUs, GPUs, or DSPs, allowing
34you to focus on expressing algorithms rather than scheduling work or load balancing. RenderScript is
35especially useful for applications performing image processing, computational photography, or
36computer vision.</p>
37
38<p>To begin with RenderScript, there are two main concepts you should understand:</p>
39<ul>
40
41<li>High-performance compute kernels are written in a C99-derived language.</li>
42
43<li>A Java API is used for managing the lifetime of RenderScript resources and controlling kernel
44execution.</li>
45</ul>
46
47<h2 id="writing-an-rs-kernel">Writing a RenderScript Kernel</h2>
48
49<p>A RenderScript kernel typically resides in a <code>.rs</code> file in the
50<code>&lt;project_root&gt;/src/</code> directory; each <code>.rs</code> file is called a
51script. Every script contains its own set of kernels, functions, and variables. A script can
52contain:</p>
53
54<ul>
55<li>A pragma declaration (<code>#pragma version(1)</code>) that declares the version of the
56RenderScript kernel language used in this script. Currently, 1 is the only valid value.</li>
57
58<li>A pragma declaration (<code>#pragma rs java_package_name(com.example.app)</code>) that
59declares the package name of the Java classes reflected from this script.
60Note that your .rs file must be part of your application package, and not in a
61library project.</li>
62
63<li>Some number of invokable functions. An invokable function is a single-threaded RenderScript
64function that you can call from your Java code with arbitrary arguments. These are often useful for
65initial setup or serial computations within a larger processing pipeline.</li>
66
67<li>Some number of script globals. A script global is equivalent to a global variable in C. You can
68access script globals from Java code, and these are often used for parameter passing to RenderScript
69kernels.</li>
70
71<li>Some number of compute kernels. A kernel is a parallel function that executes across every
72{@link android.renderscript.Element} within an {@link android.renderscript.Allocation}.
73
74<p>A simple kernel may look like the following:</p>
75
76<pre>uchar4 __attribute__((kernel)) invert(uchar4 in, uint32_t x, uint32_t y) {
77  uchar4 out = in;
78  out.r = 255 - in.r;
79  out.g = 255 - in.g;
80  out.b = 255 - in.b;
81  return out;
82}</pre>
83
84<p>In most respects, this is identical to a standard C function. The first notable feature is the
85<code>__attribute__((kernel))</code> applied to the function prototype. This denotes that the
86function is a RenderScript kernel instead of an invokable function. The next feature is the
87<code>in</code> argument and its type. In a RenderScript kernel, this is a special argument that is
88automatically filled in based on the input {@link android.renderscript.Allocation} passed to the
89kernel launch. By default, the kernel is run across an entire {@link
90android.renderscript.Allocation}, with one execution of the kernel body per {@link
91android.renderscript.Element} in the {@link android.renderscript.Allocation}. The third notable
92feature is the return type of the kernel. The value returned from the kernel is automatically
93written to the appropriate location in the output {@link android.renderscript.Allocation}. The
94RenderScript runtime checks to ensure that the {@link android.renderscript.Element} types of the
95input and output Allocations match the kernel's prototype; if they do not match, an exception is
96thrown.</p>
97
98<p>A kernel may have an input {@link android.renderscript.Allocation}, an output {@link
99android.renderscript.Allocation}, or both. A kernel may not have more than one input or one output
100{@link android.renderscript.Allocation}. If more than one input or output is required, those objects
101should be bound to <code>rs_allocation</code> script globals and accessed from a kernel or invokable
102function via <code>rsGetElementAt_<em>type</em>()</code> or
103<code>rsSetElementAt_<em>type</em>()</code>.</p>
104
105<p>A kernel may access the coordinates of the current execution using the <code>x</code>,
106<code>y</code>, and <code>z</code> arguments. These arguments are optional, but the type of the
107coordinate arguments must be <code>uint32_t</code>.</p></li>
108
109<li>An optional <code>init()</code> function. An <code>init()</code> function is a special type of
110invokable function that is run when the script is first instantiated. This allows for some
111computation to occur automatically at script creation.</li>
112
113<li>Some number of static script globals and functions. A static script global is equivalent to a
114script global except that it cannot be set from Java code. A static function is a standard C
115function that can be called from any kernel or invokable function in the script but is not exposed
116to the Java API. If a script global or function does not need to be called from Java code, it is
117highly recommended that those be declared <code>static</code>.</li> </ul>
118
119<h4>Setting floating point precision</h4>
120
121<p>You can control the required level of floating point precision in a script. This is useful if
122full IEEE 754-2008 standard (used by default) is not required. The following pragmas can set a
123different level of floating point precision:</p>
124
125<ul>
126
127<li><code>#pragma rs_fp_full</code> (default if nothing is specified): For apps that require
128  floating point precision as outlined by the IEEE 754-2008 standard.
129
130</li>
131
132  <li><code>#pragma rs_fp_relaxed</code> - For apps that don’t require strict IEEE 754-2008
133    compliance and can tolerate less precision. This mode enables flush-to-zero for denorms and
134    round-towards-zero.
135
136</li>
137
138  <li><code>#pragma rs_fp_imprecise</code> - For apps that don’t have stringent precision
139    requirements. This mode enables everything in <code>rs_fp_relaxed</code> along with the
140    following:
141
142<ul>
143
144  <li>Operations resulting in -0.0 can return +0.0 instead.</li>
145  <li>Operations on INF and NAN are undefined.</li>
146</ul>
147</li>
148</ul>
149
150<p>Most applications can use <code>rs_fp_relaxed</code> without any side effects. This may be very
151beneficial on some architectures due to additional optimizations only available with relaxed
152precision (such as SIMD CPU instructions).</p>
153
154
155<h2 id="access-rs-apis">Accessing RenderScript APIs</h2>
156
157<p>When developing an Android application that uses RenderScript, you can access its API in
158  one of two ways:</p>
159
160<ul>
161  <li><strong>{@link android.renderscript}</strong> - The APIs in this class package are
162    available on devices running Android 3.0 (API level 11) and higher. </li>
163  <li><strong>{@link android.support.v8.renderscript}</strong> - The APIs in this package are
164    available through a <a href="{@docRoot}tools/support-library/features.html#v8">Support
165    Library</a>, which allows you to use them on devices running Android 2.2 (API level 8) and
166    higher.</li>
167</ul>
168
169<p>We strongly recommend using the Support Library APIs for accessing RenderScript because they
170  provide a wider range of device compatibility. Developers targeting specific versions of
171  Android can use {@link android.renderscript} if necessary.</p>
172
173
174<h3 id="ide-setup">Using the RenderScript Support Library APIs</h3>
175
176<p>In order to use the Support Library RenderScript APIs, you must configure your development
177  environment to be able to access them. The following Android SDK tools are required for using
178  these APIs:</p>
179
180<ul>
181  <li>Android SDK Tools revision 22.2 or higher</li>
182  <li>Android SDK Build-tools revision 18.1.0 or higher</li>
183</ul>
184
185<p>You can check and update the installed version of these tools in the
186  <a href="{@docRoot}tools/help/sdk-manager.html">Android SDK Manager</a>.</p>
187
188
189<p>To use the Support Library RenderScript APIs:</p>
190
191<ol>
192  <li>Make sure you have the required Android SDK version and Build Tools version installed.</li>
193  <li> Update the settings for the Android build process to include the RenderScript settings:
194
195    <p><strong>For Android Studio or Gradle-based builds</strong></p>
196    <ul>
197      <li>Open the {@code build.gradle} file in the app folder of your application module. </li>
198      <li>Add the following RenderScript settings to the file:
199
200<pre>
201android {
202    compileSdkVersion 19
203    buildToolsVersion "19.0.3"
204
205    defaultConfig {
206        minSdkVersion 8
207        targetSdkVersion 16
208<strong>
209        renderscriptTargetApi 18
210        renderscriptSupportModeEnabled true
211</strong>
212    }
213}
214</pre>
215
216
217    <p>The settings listed above control specific behavior in the Android build process:</p>
218
219    <ul>
220      <li>{@code renderscriptTargetApi} - Specifies the bytecode version to be generated. We
221      recommend you set this value to the highest available API level and set
222      {@code renderscriptSupportModeEnabled}
223      to {@code true}. Valid values for this setting are any integer value
224      from 11 to the most recently released API level. If your minimum SDK version specified in your
225      application manifest is set to a different value, that value is ignored and the target value
226      in the build file is used to set the minimum SDK version.</li>
227      <li>{@code renderscriptSupportModeEnabled} - Specifies that the generated bytecode should fall
228      back to a compatible version if the device it is running on does not support the target
229      version.
230      </li>
231      <li>{@code buildToolsVersion} - The version of the Android SDK build tools to use. This value
232      should be set to {@code 18.1.0} or higher. If this option is not specified, the highest
233      installed build tools version is used. You should always set this value to ensure the
234      consistency of builds across development machines with different configurations.</li>
235    </ul>
236
237    </li>
238
239    <p><strong>For Eclipse</strong></p>
240    <ul>
241      <li>Open the {@code project.properties} file in the root folder of your application project.</li>
242      <li>Add the following lines to the file:
243
244<pre>
245renderscript.target=18
246renderscript.support.mode=true
247sdk.buildtools=18.1.0
248</pre>
249
250      <p>The settings listed above control specific behavior in the Android build process:</p>
251
252      <ul>
253        <li>{@code renderscript.target} - Specifies the bytecode version to be generated. We
254        recommend you set this value to the highest available API level and set
255        {@code renderscript.support.mode} to {@code true}. Valid values for this setting are any
256        integer value from 11 to the most recently released API level. If your minimum SDK version
257        specified in your application manifest is set to a higher value, this value is ignored and
258        the target value is set to the minimum SDK version.</li>
259        <li>{@code renderscript.support.mode} - Specifies that the generated bytecode should fall
260        back to a compatible version if the device it is running on does not support the target version.
261        </li>
262        <li>{@code sdk.buildtools} - The version of the Android SDK build tools to use. This value
263        should be set to {@code 18.1.0} or higher. If this option is not specified, the highest
264        installed build tools version is used. You should always set this value to ensure the
265        consistency of builds across development machines with different configurations.</li>
266      </ul>
267     </li>
268
269    </ul>
270
271  </ul>
272
273  <li>In your application classes that use RenderScript, add an import for the Support Library
274    classes:
275
276<pre>
277import android.support.v8.renderscript.*;
278</pre>
279
280  </li>
281
282 </0l>
283
284<h2 id="using-rs-from-java">Using RenderScript from Java Code</h2>
285
286<p>Using RenderScript from Java code relies on the API classes located in the
287{@link android.renderscript} or the {@link android.support.v8.renderscript} package. Most
288applications follow the same basic usage patterns:</p>
289
290<ol>
291
292<li><strong>Initialize a RenderScript context.</strong> The {@link
293android.renderscript.RenderScript} context, created with {@link
294android.renderscript.RenderScript#create}, ensures that RenderScript can be used and provides an
295object to control the lifetime of all subsequent RenderScript objects. You should consider context
296creation to be a potentially long-running operation, since it may create resources on different
297pieces of hardware; it should not be in an application's critical path if at all
298possible. Typically, an application will have only a single RenderScript context at a time.</li>
299
300<li><strong>Create at least one {@link android.renderscript.Allocation} to be passed to a
301script.</strong> An {@link android.renderscript.Allocation} is a RenderScript object that provides
302storage for a fixed amount of data. Kernels in scripts take {@link android.renderscript.Allocation}
303objects as their input and output, and {@link android.renderscript.Allocation} objects can be
304accessed in kernels using <code>rsGetElementAt_<em>type</em>()</code> and
305<code>rsSetElementAt_<em>type</em>()</code> when bound as script globals. {@link
306android.renderscript.Allocation} objects allow arrays to be passed from Java code to RenderScript
307code and vice-versa. {@link android.renderscript.Allocation} objects are typically created using
308{@link android.renderscript.Allocation#createTyped} or {@link
309android.renderscript.Allocation#createFromBitmap}.</li>
310
311<li><strong>Create whatever scripts are necessary.</strong> There are two types of scripts available
312to you when using RenderScript:
313
314<ul>
315
316<li><strong>ScriptC</strong>: These are the user-defined scripts as described in <a
317href="#writing-an-rs-kernel">Writing a RenderScript Kernel</a> above. Every script has a Java class
318reflected by the RenderScript compiler in order to make it easy to access the script from Java code;
319this class will have the name <code>ScriptC_<em>filename</em></code>. For example, if the kernel
320above was located in <code>invert.rs</code> and a RenderScript context was already located in
321<code>mRS</code>, the Java code to instantiate the script would be:
322
323<pre>ScriptC_invert invert = new ScriptC_invert(mRenderScript);</pre></li>
324
325<li><strong>ScriptIntrinsic</strong>: These are built-in RenderScript kernels for common operations,
326such as Gaussian blur, convolution, and image blending. For more information, see the subclasses of
327{@link android.renderscript.ScriptIntrinsic}.</li>
328
329</ul></li>
330
331<li><strong>Populate Allocations with data.</strong> Except for Allocations created with {@link
332android.renderscript#createFromBitmap}, an Allocation will be populated with empty data when it is
333first created. To populate an Allocation, use one of the <code>copy</code> methods in {@link
334android.renderscript.Allocation}.</li>
335
336<li><strong>Set any necessary script globals.</strong> Globals may be set using methods in the same
337<code>ScriptC_<em>filename</em></code> class with methods named
338<code>set_<em>globalname</em></code>. For example, in order to set an <code>int</code> named
339<code>elements</code>, use the Java method <code>set_elements(int)</code>. RenderScript objects can
340also be set in kernels; for example, the <code>rs_allocation</code> variable named
341<code>lookup</code> can be set with the method <code>set_lookup(Allocation)</code>.</li>
342
343<li><strong>Launch the appropriate kernels.</strong> Methods to launch a given kernel will be
344reflected in the same <code>ScriptC_<em>filename</em></code> class with methods named
345<code>forEach_<em>kernelname</em>()</code>. These launches are asynchronous, and launches will be
346serialized in the order in which they are launched. Depending on the arguments to the kernel, the
347method will take either one or two Allocations. By default, a kernel will execute over the entire
348input or output Allocation; to execute over a subset of that Allocation, pass an appropriate {@link
349android.renderscript.Script.LaunchOptions} as the last argument to the <code>forEach</code> method.
350
351<p>Invoked functions can be launched using the <code>invoke_<em>functionname</em></code> methods
352reflected in the same <code>ScriptC_<em>filename</em></code> class.</p></li>
353
354<li><strong>Copy data out of {@link android.renderscript.Allocation} objects.</strong> In order to
355access data from an {@link android.renderscript.Allocation} from Java code, that data must be copied
356back to Java buffers using one of the <code>copy</code> methods in {@link
357android.renderscript.Allocation}. These functions will synchronize with asynchronous kernel and
358function launches as necessary.</li>
359
360<li><strong>Tear down the RenderScript context.</strong> The RenderScript context can be destroyed
361with {@link android.renderscript.RenderScript#destroy} or by allowing the RenderScript context
362object to be garbage collected. This will cause any further use of any object belonging to that
363context to throw an exception.</li> </ol>
364