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<p class="note">
189  <strong>Note:</strong> Use of Support Library RenderScript APIs is not currently supported with
190  Android Studio or Gradle-based builds.
191</p>
192
193<p>To use the Support Library RenderScript APIs in Eclipse:</p>
194
195<ol>
196  <li>Make sure you have the required Android SDK version and Build Tools version installed.</li>
197  <li>Open the {@code project.properties} file in the root folder of your application project.</li>
198  <li>Add the following lines to the file:
199<pre>
200renderscript.target=18
201renderscript.support.mode=true
202sdk.buildtools=18.1.0
203</pre>
204  </li>
205  <li>In your application classes that use RenderScript, add an import for the Support Library
206    classes:
207<pre>
208import android.support.v8.renderscript.*;
209</pre>
210  </li>
211</ol>
212
213<p>The {@code project.properties} settings listed above control specific behavior in the Android
214  build process:</p>
215
216<ul>
217  <li>{@code renderscript.target} - Specifies the bytecode version to be generated. We
218    recommend you set this value the highest available API level and set {@code
219    renderscript.support.mode} to {@code true}. Valid values for this setting are any integer value
220    from 11 to the most recently released API level. If your minimum SDK version specified in your
221    application manifest is set to a higher value, this value is ignored and the target value is set
222    to the minimum SDK version.</li>
223  <li>{@code renderscript.support.mode} - Specifies that the generated bytecode should fall
224    back to a compatible version if the device it is running on does not support the target version.
225    </li>
226  <li>{@code sdk.buildtools} - The version of the Android SDK build tools to use. This value
227    should be set to {@code 18.1.0} or higher. If this option is not specified, the highest
228    installed build tools version is used. You should always set this value to ensure the
229    consistency of builds across development machines with different configurations.</li>
230</ul>
231
232
233<h2 id="using-rs-from-java">Using RenderScript from Java Code</h2>
234
235<p>Using RenderScript from Java code relies on the API classes located in the
236{@link android.renderscript} or the {@link android.support.v8.renderscript} package. Most
237applications follow the same basic usage patterns:</p>
238
239<ol>
240
241<li><strong>Initialize a RenderScript context.</strong> The {@link
242android.renderscript.RenderScript} context, created with {@link
243android.renderscript.RenderScript#create}, ensures that RenderScript can be used and provides an
244object to control the lifetime of all subsequent RenderScript objects. You should consider context
245creation to be a potentially long-running operation, since it may create resources on different
246pieces of hardware; it should not be in an application's critical path if at all
247possible. Typically, an application will have only a single RenderScript context at a time.</li>
248
249<li><strong>Create at least one {@link android.renderscript.Allocation} to be passed to a
250script.</strong> An {@link android.renderscript.Allocation} is a RenderScript object that provides
251storage for a fixed amount of data. Kernels in scripts take {@link android.renderscript.Allocation}
252objects as their input and output, and {@link android.renderscript.Allocation} objects can be
253accessed in kernels using <code>rsGetElementAt_<em>type</em>()</code> and
254<code>rsSetElementAt_<em>type</em>()</code> when bound as script globals. {@link
255android.renderscript.Allocation} objects allow arrays to be passed from Java code to RenderScript
256code and vice-versa. {@link android.renderscript.Allocation} objects are typically created using
257{@link android.renderscript.Allocation#createTyped} or {@link
258android.renderscript.Allocation#createFromBitmap}.</li>
259
260<li><strong>Create whatever scripts are necessary.</strong> There are two types of scripts available
261to you when using RenderScript:
262
263<ul>
264
265<li><strong>ScriptC</strong>: These are the user-defined scripts as described in <a
266href="#writing-an-rs-kernel">Writing a RenderScript Kernel</a> above. Every script has a Java class
267reflected by the RenderScript compiler in order to make it easy to access the script from Java code;
268this class will have the name <code>ScriptC_<em>filename</em></code>. For example, if the kernel
269above was located in <code>invert.rs</code> and a RenderScript context was already located in
270<code>mRS</code>, the Java code to instantiate the script would be:
271
272<pre>ScriptC_invert invert = new ScriptC_invert(mRenderScript);</pre></li>
273
274<li><strong>ScriptIntrinsic</strong>: These are built-in RenderScript kernels for common operations,
275such as Gaussian blur, convolution, and image blending. For more information, see the subclasses of
276{@link android.renderscript.ScriptIntrinsic}.</li>
277
278</ul></li>
279
280<li><strong>Populate Allocations with data.</strong> Except for Allocations created with {@link
281android.renderscript#createFromBitmap}, an Allocation will be populated with empty data when it is
282first created. To populate an Allocation, use one of the <code>copy</code> methods in {@link
283android.renderscript.Allocation}.</li>
284
285<li><strong>Set any necessary script globals.</strong> Globals may be set using methods in the same
286<code>ScriptC_<em>filename</em></code> class with methods named
287<code>set_<em>globalname</em></code>. For example, in order to set an <code>int</code> named
288<code>elements</code>, use the Java method <code>set_elements(int)</code>. RenderScript objects can
289also be set in kernels; for example, the <code>rs_allocation</code> variable named
290<code>lookup</code> can be set with the method <code>set_lookup(Allocation)</code>.</li>
291
292<li><strong>Launch the appropriate kernels.</strong> Methods to launch a given kernel will be
293reflected in the same <code>ScriptC_<em>filename</em></code> class with methods named
294<code>forEach_<em>kernelname</em>()</code>. These launches are asynchronous, and launches will be
295serialized in the order in which they are launched. Depending on the arguments to the kernel, the
296method will take either one or two Allocations. By default, a kernel will execute over the entire
297input or output Allocation; to execute over a subset of that Allocation, pass an appropriate {@link
298android.renderscript.Script.LaunchOptions} as the last argument to the <code>forEach</code> method.
299
300<p>Invoked functions can be launched using the <code>invoke_<em>functionname</em></code> methods
301reflected in the same <code>ScriptC_<em>filename</em></code> class.</p></li>
302
303<li><strong>Copy data out of {@link android.renderscript.Allocation} objects.</strong> In order to
304access data from an {@link android.renderscript.Allocation} from Java code, that data must be copied
305back to Java buffers using one of the <code>copy</code> methods in {@link
306android.renderscript.Allocation}. These functions will synchronize with asynchronous kernel and
307function launches as necessary.</li>
308
309<li><strong>Tear down the RenderScript context.</strong> The RenderScript context can be destroyed
310with {@link android.renderscript.RenderScript#destroy} or by allowing the RenderScript context
311object to be garbage collected. This will cause any further use of any object belonging to that
312context to throw an exception.</li> </ol>
313