RenderScript.java revision 857d0c7017da763a420e825fffa2f260eb982c97
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.renderscript;
18
19import java.lang.reflect.Field;
20
21import android.content.Context;
22import android.content.pm.ApplicationInfo;
23import android.content.pm.PackageManager;
24import android.content.res.AssetManager;
25import android.graphics.Bitmap;
26import android.graphics.BitmapFactory;
27import android.graphics.SurfaceTexture;
28import android.os.Process;
29import android.util.Log;
30import android.view.Surface;
31
32
33
34/**
35 * RenderScript base master class.  An instance of this class creates native
36 * worker threads for processing commands from this object.  This base class
37 * does not provide any extended capabilities beyond simple data processing.
38 * For extended capabilities use derived classes such as RenderScriptGL.
39 *
40 *
41 *
42 **/
43public class RenderScript {
44    static final String LOG_TAG = "RenderScript_jni";
45    static final boolean DEBUG  = false;
46    @SuppressWarnings({"UnusedDeclaration", "deprecation"})
47    static final boolean LOG_ENABLED = false;
48
49    private Context mApplicationContext;
50
51    /*
52     * We use a class initializer to allow the native code to cache some
53     * field offsets.
54     */
55    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
56    static boolean sInitialized;
57    native static void _nInit();
58
59
60    static {
61        sInitialized = false;
62        try {
63            System.loadLibrary("rs_jni");
64            _nInit();
65            sInitialized = true;
66        } catch (UnsatisfiedLinkError e) {
67            Log.e(LOG_TAG, "Error loading RS jni library: " + e);
68            throw new RSRuntimeException("Error loading RS jni library: " + e);
69        }
70    }
71
72    // Non-threadsafe functions.
73    native int  nDeviceCreate();
74    native void nDeviceDestroy(int dev);
75    native void nDeviceSetConfig(int dev, int param, int value);
76    native int nContextGetUserMessage(int con, int[] data);
77    native String nContextGetErrorMessage(int con);
78    native int  nContextPeekMessage(int con, int[] subID);
79    native void nContextInitToClient(int con);
80    native void nContextDeinitToClient(int con);
81
82
83    // Methods below are wrapped to protect the non-threadsafe
84    // lockless fifo.
85    native int  rsnContextCreateGL(int dev, int ver, int sdkVer,
86                 int colorMin, int colorPref,
87                 int alphaMin, int alphaPref,
88                 int depthMin, int depthPref,
89                 int stencilMin, int stencilPref,
90                 int samplesMin, int samplesPref, float samplesQ, int dpi);
91    synchronized int nContextCreateGL(int dev, int ver, int sdkVer,
92                 int colorMin, int colorPref,
93                 int alphaMin, int alphaPref,
94                 int depthMin, int depthPref,
95                 int stencilMin, int stencilPref,
96                 int samplesMin, int samplesPref, float samplesQ, int dpi) {
97        return rsnContextCreateGL(dev, ver, sdkVer, colorMin, colorPref,
98                                  alphaMin, alphaPref, depthMin, depthPref,
99                                  stencilMin, stencilPref,
100                                  samplesMin, samplesPref, samplesQ, dpi);
101    }
102    native int  rsnContextCreate(int dev, int ver, int sdkVer);
103    synchronized int nContextCreate(int dev, int ver, int sdkVer) {
104        return rsnContextCreate(dev, ver, sdkVer);
105    }
106    native void rsnContextDestroy(int con);
107    synchronized void nContextDestroy() {
108        validate();
109        rsnContextDestroy(mContext);
110    }
111    native void rsnContextSetSurface(int con, int w, int h, Surface sur);
112    synchronized void nContextSetSurface(int w, int h, Surface sur) {
113        validate();
114        rsnContextSetSurface(mContext, w, h, sur);
115    }
116    native void rsnContextSetSurfaceTexture(int con, int w, int h, SurfaceTexture sur);
117    synchronized void nContextSetSurfaceTexture(int w, int h, SurfaceTexture sur) {
118        validate();
119        rsnContextSetSurfaceTexture(mContext, w, h, sur);
120    }
121    native void rsnContextSetPriority(int con, int p);
122    synchronized void nContextSetPriority(int p) {
123        validate();
124        rsnContextSetPriority(mContext, p);
125    }
126    native void rsnContextDump(int con, int bits);
127    synchronized void nContextDump(int bits) {
128        validate();
129        rsnContextDump(mContext, bits);
130    }
131    native void rsnContextFinish(int con);
132    synchronized void nContextFinish() {
133        validate();
134        rsnContextFinish(mContext);
135    }
136
137    native void rsnContextBindRootScript(int con, int script);
138    synchronized void nContextBindRootScript(int script) {
139        validate();
140        rsnContextBindRootScript(mContext, script);
141    }
142    native void rsnContextBindSampler(int con, int sampler, int slot);
143    synchronized void nContextBindSampler(int sampler, int slot) {
144        validate();
145        rsnContextBindSampler(mContext, sampler, slot);
146    }
147    native void rsnContextBindProgramStore(int con, int pfs);
148    synchronized void nContextBindProgramStore(int pfs) {
149        validate();
150        rsnContextBindProgramStore(mContext, pfs);
151    }
152    native void rsnContextBindProgramFragment(int con, int pf);
153    synchronized void nContextBindProgramFragment(int pf) {
154        validate();
155        rsnContextBindProgramFragment(mContext, pf);
156    }
157    native void rsnContextBindProgramVertex(int con, int pv);
158    synchronized void nContextBindProgramVertex(int pv) {
159        validate();
160        rsnContextBindProgramVertex(mContext, pv);
161    }
162    native void rsnContextBindProgramRaster(int con, int pr);
163    synchronized void nContextBindProgramRaster(int pr) {
164        validate();
165        rsnContextBindProgramRaster(mContext, pr);
166    }
167    native void rsnContextPause(int con);
168    synchronized void nContextPause() {
169        validate();
170        rsnContextPause(mContext);
171    }
172    native void rsnContextResume(int con);
173    synchronized void nContextResume() {
174        validate();
175        rsnContextResume(mContext);
176    }
177
178    native void rsnAssignName(int con, int obj, byte[] name);
179    synchronized void nAssignName(int obj, byte[] name) {
180        validate();
181        rsnAssignName(mContext, obj, name);
182    }
183    native String rsnGetName(int con, int obj);
184    synchronized String nGetName(int obj) {
185        validate();
186        return rsnGetName(mContext, obj);
187    }
188    native void rsnObjDestroy(int con, int id);
189    synchronized void nObjDestroy(int id) {
190        // There is a race condition here.  The calling code may be run
191        // by the gc while teardown is occuring.  This protects againts
192        // deleting dead objects.
193        if (mContext != 0) {
194            rsnObjDestroy(mContext, id);
195        }
196    }
197
198    native int  rsnElementCreate(int con, int type, int kind, boolean norm, int vecSize);
199    synchronized int nElementCreate(int type, int kind, boolean norm, int vecSize) {
200        validate();
201        return rsnElementCreate(mContext, type, kind, norm, vecSize);
202    }
203    native int  rsnElementCreate2(int con, int[] elements, String[] names, int[] arraySizes);
204    synchronized int nElementCreate2(int[] elements, String[] names, int[] arraySizes) {
205        validate();
206        return rsnElementCreate2(mContext, elements, names, arraySizes);
207    }
208    native void rsnElementGetNativeData(int con, int id, int[] elementData);
209    synchronized void nElementGetNativeData(int id, int[] elementData) {
210        validate();
211        rsnElementGetNativeData(mContext, id, elementData);
212    }
213    native void rsnElementGetSubElements(int con, int id,
214                                         int[] IDs, String[] names, int[] arraySizes);
215    synchronized void nElementGetSubElements(int id, int[] IDs, String[] names, int[] arraySizes) {
216        validate();
217        rsnElementGetSubElements(mContext, id, IDs, names, arraySizes);
218    }
219
220    native int rsnTypeCreate(int con, int eid, int x, int y, int z, boolean mips, boolean faces);
221    synchronized int nTypeCreate(int eid, int x, int y, int z, boolean mips, boolean faces) {
222        validate();
223        return rsnTypeCreate(mContext, eid, x, y, z, mips, faces);
224    }
225    native void rsnTypeGetNativeData(int con, int id, int[] typeData);
226    synchronized void nTypeGetNativeData(int id, int[] typeData) {
227        validate();
228        rsnTypeGetNativeData(mContext, id, typeData);
229    }
230
231    native int  rsnAllocationCreateTyped(int con, int type, int mip, int usage, int pointer);
232    synchronized int nAllocationCreateTyped(int type, int mip, int usage, int pointer) {
233        validate();
234        return rsnAllocationCreateTyped(mContext, type, mip, usage, pointer);
235    }
236    native int  rsnAllocationCreateFromBitmap(int con, int type, int mip, Bitmap bmp, int usage);
237    synchronized int nAllocationCreateFromBitmap(int type, int mip, Bitmap bmp, int usage) {
238        validate();
239        return rsnAllocationCreateFromBitmap(mContext, type, mip, bmp, usage);
240    }
241    native int  rsnAllocationCubeCreateFromBitmap(int con, int type, int mip, Bitmap bmp, int usage);
242    synchronized int nAllocationCubeCreateFromBitmap(int type, int mip, Bitmap bmp, int usage) {
243        validate();
244        return rsnAllocationCubeCreateFromBitmap(mContext, type, mip, bmp, usage);
245    }
246    native int  rsnAllocationCreateBitmapRef(int con, int type, Bitmap bmp);
247    synchronized int nAllocationCreateBitmapRef(int type, Bitmap bmp) {
248        validate();
249        return rsnAllocationCreateBitmapRef(mContext, type, bmp);
250    }
251    native int  rsnAllocationCreateFromAssetStream(int con, int mips, int assetStream, int usage);
252    synchronized int nAllocationCreateFromAssetStream(int mips, int assetStream, int usage) {
253        validate();
254        return rsnAllocationCreateFromAssetStream(mContext, mips, assetStream, usage);
255    }
256
257    native void  rsnAllocationCopyToBitmap(int con, int alloc, Bitmap bmp);
258    synchronized void nAllocationCopyToBitmap(int alloc, Bitmap bmp) {
259        validate();
260        rsnAllocationCopyToBitmap(mContext, alloc, bmp);
261    }
262
263
264    native void rsnAllocationSyncAll(int con, int alloc, int src);
265    synchronized void nAllocationSyncAll(int alloc, int src) {
266        validate();
267        rsnAllocationSyncAll(mContext, alloc, src);
268    }
269    native void rsnAllocationGenerateMipmaps(int con, int alloc);
270    synchronized void nAllocationGenerateMipmaps(int alloc) {
271        validate();
272        rsnAllocationGenerateMipmaps(mContext, alloc);
273    }
274    native void  rsnAllocationCopyFromBitmap(int con, int alloc, Bitmap bmp);
275    synchronized void nAllocationCopyFromBitmap(int alloc, Bitmap bmp) {
276        validate();
277        rsnAllocationCopyFromBitmap(mContext, alloc, bmp);
278    }
279
280
281    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, int[] d, int sizeBytes);
282    synchronized void nAllocationData1D(int id, int off, int mip, int count, int[] d, int sizeBytes) {
283        validate();
284        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
285    }
286    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, short[] d, int sizeBytes);
287    synchronized void nAllocationData1D(int id, int off, int mip, int count, short[] d, int sizeBytes) {
288        validate();
289        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
290    }
291    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, byte[] d, int sizeBytes);
292    synchronized void nAllocationData1D(int id, int off, int mip, int count, byte[] d, int sizeBytes) {
293        validate();
294        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
295    }
296    native void rsnAllocationData1D(int con, int id, int off, int mip, int count, float[] d, int sizeBytes);
297    synchronized void nAllocationData1D(int id, int off, int mip, int count, float[] d, int sizeBytes) {
298        validate();
299        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes);
300    }
301
302    native void rsnAllocationElementData1D(int con, int id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes);
303    synchronized void nAllocationElementData1D(int id, int xoff, int mip, int compIdx, byte[] d, int sizeBytes) {
304        validate();
305        rsnAllocationElementData1D(mContext, id, xoff, mip, compIdx, d, sizeBytes);
306    }
307
308    native void rsnAllocationData2D(int con,
309                                    int dstAlloc, int dstXoff, int dstYoff,
310                                    int dstMip, int dstFace,
311                                    int width, int height,
312                                    int srcAlloc, int srcXoff, int srcYoff,
313                                    int srcMip, int srcFace);
314    synchronized void nAllocationData2D(int dstAlloc, int dstXoff, int dstYoff,
315                                        int dstMip, int dstFace,
316                                        int width, int height,
317                                        int srcAlloc, int srcXoff, int srcYoff,
318                                        int srcMip, int srcFace) {
319        validate();
320        rsnAllocationData2D(mContext,
321                            dstAlloc, dstXoff, dstYoff,
322                            dstMip, dstFace,
323                            width, height,
324                            srcAlloc, srcXoff, srcYoff,
325                            srcMip, srcFace);
326    }
327
328    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes);
329    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes) {
330        validate();
331        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
332    }
333    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes);
334    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes) {
335        validate();
336        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
337    }
338    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes);
339    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes) {
340        validate();
341        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
342    }
343    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes);
344    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes) {
345        validate();
346        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
347    }
348    native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, Bitmap b);
349    synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, Bitmap b) {
350        validate();
351        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b);
352    }
353
354    native void rsnAllocationRead(int con, int id, byte[] d);
355    synchronized void nAllocationRead(int id, byte[] d) {
356        validate();
357        rsnAllocationRead(mContext, id, d);
358    }
359    native void rsnAllocationRead(int con, int id, short[] d);
360    synchronized void nAllocationRead(int id, short[] d) {
361        validate();
362        rsnAllocationRead(mContext, id, d);
363    }
364    native void rsnAllocationRead(int con, int id, int[] d);
365    synchronized void nAllocationRead(int id, int[] d) {
366        validate();
367        rsnAllocationRead(mContext, id, d);
368    }
369    native void rsnAllocationRead(int con, int id, float[] d);
370    synchronized void nAllocationRead(int id, float[] d) {
371        validate();
372        rsnAllocationRead(mContext, id, d);
373    }
374    native int  rsnAllocationGetType(int con, int id);
375    synchronized int nAllocationGetType(int id) {
376        validate();
377        return rsnAllocationGetType(mContext, id);
378    }
379
380    native void rsnAllocationResize1D(int con, int id, int dimX);
381    synchronized void nAllocationResize1D(int id, int dimX) {
382        validate();
383        rsnAllocationResize1D(mContext, id, dimX);
384    }
385    native void rsnAllocationResize2D(int con, int id, int dimX, int dimY);
386    synchronized void nAllocationResize2D(int id, int dimX, int dimY) {
387        validate();
388        rsnAllocationResize2D(mContext, id, dimX, dimY);
389    }
390
391    native int  rsnFileA3DCreateFromAssetStream(int con, int assetStream);
392    synchronized int nFileA3DCreateFromAssetStream(int assetStream) {
393        validate();
394        return rsnFileA3DCreateFromAssetStream(mContext, assetStream);
395    }
396    native int  rsnFileA3DCreateFromFile(int con, String path);
397    synchronized int nFileA3DCreateFromFile(String path) {
398        validate();
399        return rsnFileA3DCreateFromFile(mContext, path);
400    }
401    native int  rsnFileA3DCreateFromAsset(int con, AssetManager mgr, String path);
402    synchronized int nFileA3DCreateFromAsset(AssetManager mgr, String path) {
403        validate();
404        return rsnFileA3DCreateFromAsset(mContext, mgr, path);
405    }
406    native int  rsnFileA3DGetNumIndexEntries(int con, int fileA3D);
407    synchronized int nFileA3DGetNumIndexEntries(int fileA3D) {
408        validate();
409        return rsnFileA3DGetNumIndexEntries(mContext, fileA3D);
410    }
411    native void rsnFileA3DGetIndexEntries(int con, int fileA3D, int numEntries, int[] IDs, String[] names);
412    synchronized void nFileA3DGetIndexEntries(int fileA3D, int numEntries, int[] IDs, String[] names) {
413        validate();
414        rsnFileA3DGetIndexEntries(mContext, fileA3D, numEntries, IDs, names);
415    }
416    native int  rsnFileA3DGetEntryByIndex(int con, int fileA3D, int index);
417    synchronized int nFileA3DGetEntryByIndex(int fileA3D, int index) {
418        validate();
419        return rsnFileA3DGetEntryByIndex(mContext, fileA3D, index);
420    }
421
422    native int  rsnFontCreateFromFile(int con, String fileName, float size, int dpi);
423    synchronized int nFontCreateFromFile(String fileName, float size, int dpi) {
424        validate();
425        return rsnFontCreateFromFile(mContext, fileName, size, dpi);
426    }
427    native int  rsnFontCreateFromAssetStream(int con, String name, float size, int dpi, int assetStream);
428    synchronized int nFontCreateFromAssetStream(String name, float size, int dpi, int assetStream) {
429        validate();
430        return rsnFontCreateFromAssetStream(mContext, name, size, dpi, assetStream);
431    }
432    native int  rsnFontCreateFromAsset(int con, AssetManager mgr, String path, float size, int dpi);
433    synchronized int nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
434        validate();
435        return rsnFontCreateFromAsset(mContext, mgr, path, size, dpi);
436    }
437
438
439    native void rsnScriptBindAllocation(int con, int script, int alloc, int slot);
440    synchronized void nScriptBindAllocation(int script, int alloc, int slot) {
441        validate();
442        rsnScriptBindAllocation(mContext, script, alloc, slot);
443    }
444    native void rsnScriptSetTimeZone(int con, int script, byte[] timeZone);
445    synchronized void nScriptSetTimeZone(int script, byte[] timeZone) {
446        validate();
447        rsnScriptSetTimeZone(mContext, script, timeZone);
448    }
449    native void rsnScriptInvoke(int con, int id, int slot);
450    synchronized void nScriptInvoke(int id, int slot) {
451        validate();
452        rsnScriptInvoke(mContext, id, slot);
453    }
454    native void rsnScriptForEach(int con, int id, int slot, int ain, int aout, byte[] params);
455    native void rsnScriptForEach(int con, int id, int slot, int ain, int aout);
456    synchronized void nScriptForEach(int id, int slot, int ain, int aout, byte[] params) {
457        validate();
458        if (params == null) {
459            rsnScriptForEach(mContext, id, slot, ain, aout);
460        } else {
461            rsnScriptForEach(mContext, id, slot, ain, aout, params);
462        }
463    }
464    native void rsnScriptInvokeV(int con, int id, int slot, byte[] params);
465    synchronized void nScriptInvokeV(int id, int slot, byte[] params) {
466        validate();
467        rsnScriptInvokeV(mContext, id, slot, params);
468    }
469    native void rsnScriptSetVarI(int con, int id, int slot, int val);
470    synchronized void nScriptSetVarI(int id, int slot, int val) {
471        validate();
472        rsnScriptSetVarI(mContext, id, slot, val);
473    }
474    native void rsnScriptSetVarJ(int con, int id, int slot, long val);
475    synchronized void nScriptSetVarJ(int id, int slot, long val) {
476        validate();
477        rsnScriptSetVarJ(mContext, id, slot, val);
478    }
479    native void rsnScriptSetVarF(int con, int id, int slot, float val);
480    synchronized void nScriptSetVarF(int id, int slot, float val) {
481        validate();
482        rsnScriptSetVarF(mContext, id, slot, val);
483    }
484    native void rsnScriptSetVarD(int con, int id, int slot, double val);
485    synchronized void nScriptSetVarD(int id, int slot, double val) {
486        validate();
487        rsnScriptSetVarD(mContext, id, slot, val);
488    }
489    native void rsnScriptSetVarV(int con, int id, int slot, byte[] val);
490    synchronized void nScriptSetVarV(int id, int slot, byte[] val) {
491        validate();
492        rsnScriptSetVarV(mContext, id, slot, val);
493    }
494    native void rsnScriptSetVarObj(int con, int id, int slot, int val);
495    synchronized void nScriptSetVarObj(int id, int slot, int val) {
496        validate();
497        rsnScriptSetVarObj(mContext, id, slot, val);
498    }
499
500    native int  rsnScriptCCreate(int con, String resName, String cacheDir,
501                                 byte[] script, int length);
502    synchronized int nScriptCCreate(String resName, String cacheDir, byte[] script, int length) {
503        validate();
504        return rsnScriptCCreate(mContext, resName, cacheDir, script, length);
505    }
506
507    native int  rsnSamplerCreate(int con, int magFilter, int minFilter,
508                                 int wrapS, int wrapT, int wrapR, float aniso);
509    synchronized int nSamplerCreate(int magFilter, int minFilter,
510                                 int wrapS, int wrapT, int wrapR, float aniso) {
511        validate();
512        return rsnSamplerCreate(mContext, magFilter, minFilter, wrapS, wrapT, wrapR, aniso);
513    }
514
515    native int  rsnProgramStoreCreate(int con, boolean r, boolean g, boolean b, boolean a,
516                                      boolean depthMask, boolean dither,
517                                      int srcMode, int dstMode, int depthFunc);
518    synchronized int nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a,
519                                         boolean depthMask, boolean dither,
520                                         int srcMode, int dstMode, int depthFunc) {
521        validate();
522        return rsnProgramStoreCreate(mContext, r, g, b, a, depthMask, dither, srcMode,
523                                     dstMode, depthFunc);
524    }
525
526    native int  rsnProgramRasterCreate(int con, boolean pointSprite, int cullMode);
527    synchronized int nProgramRasterCreate(boolean pointSprite, int cullMode) {
528        validate();
529        return rsnProgramRasterCreate(mContext, pointSprite, cullMode);
530    }
531
532    native void rsnProgramBindConstants(int con, int pv, int slot, int mID);
533    synchronized void nProgramBindConstants(int pv, int slot, int mID) {
534        validate();
535        rsnProgramBindConstants(mContext, pv, slot, mID);
536    }
537    native void rsnProgramBindTexture(int con, int vpf, int slot, int a);
538    synchronized void nProgramBindTexture(int vpf, int slot, int a) {
539        validate();
540        rsnProgramBindTexture(mContext, vpf, slot, a);
541    }
542    native void rsnProgramBindSampler(int con, int vpf, int slot, int s);
543    synchronized void nProgramBindSampler(int vpf, int slot, int s) {
544        validate();
545        rsnProgramBindSampler(mContext, vpf, slot, s);
546    }
547    native int  rsnProgramFragmentCreate(int con, String shader, int[] params);
548    synchronized int nProgramFragmentCreate(String shader, int[] params) {
549        validate();
550        return rsnProgramFragmentCreate(mContext, shader, params);
551    }
552    native int  rsnProgramVertexCreate(int con, String shader, int[] params);
553    synchronized int nProgramVertexCreate(String shader, int[] params) {
554        validate();
555        return rsnProgramVertexCreate(mContext, shader, params);
556    }
557
558    native int  rsnMeshCreate(int con, int[] vtx, int[] idx, int[] prim);
559    synchronized int nMeshCreate(int[] vtx, int[] idx, int[] prim) {
560        validate();
561        return rsnMeshCreate(mContext, vtx, idx, prim);
562    }
563    native int  rsnMeshGetVertexBufferCount(int con, int id);
564    synchronized int nMeshGetVertexBufferCount(int id) {
565        validate();
566        return rsnMeshGetVertexBufferCount(mContext, id);
567    }
568    native int  rsnMeshGetIndexCount(int con, int id);
569    synchronized int nMeshGetIndexCount(int id) {
570        validate();
571        return rsnMeshGetIndexCount(mContext, id);
572    }
573    native void rsnMeshGetVertices(int con, int id, int[] vtxIds, int vtxIdCount);
574    synchronized void nMeshGetVertices(int id, int[] vtxIds, int vtxIdCount) {
575        validate();
576        rsnMeshGetVertices(mContext, id, vtxIds, vtxIdCount);
577    }
578    native void rsnMeshGetIndices(int con, int id, int[] idxIds, int[] primitives, int vtxIdCount);
579    synchronized void nMeshGetIndices(int id, int[] idxIds, int[] primitives, int vtxIdCount) {
580        validate();
581        rsnMeshGetIndices(mContext, id, idxIds, primitives, vtxIdCount);
582    }
583
584    native int  rsnPathCreate(int con, int prim, boolean isStatic, int vtx, int loop, float q);
585    synchronized int nPathCreate(int prim, boolean isStatic, int vtx, int loop, float q) {
586        validate();
587        return rsnPathCreate(mContext, prim, isStatic, vtx, loop, q);
588    }
589
590    int     mDev;
591    int     mContext;
592    @SuppressWarnings({"FieldCanBeLocal"})
593    MessageThread mMessageThread;
594
595    Element mElement_U8;
596    Element mElement_I8;
597    Element mElement_U16;
598    Element mElement_I16;
599    Element mElement_U32;
600    Element mElement_I32;
601    Element mElement_U64;
602    Element mElement_I64;
603    Element mElement_F32;
604    Element mElement_F64;
605    Element mElement_BOOLEAN;
606
607    Element mElement_ELEMENT;
608    Element mElement_TYPE;
609    Element mElement_ALLOCATION;
610    Element mElement_SAMPLER;
611    Element mElement_SCRIPT;
612    Element mElement_MESH;
613    Element mElement_PROGRAM_FRAGMENT;
614    Element mElement_PROGRAM_VERTEX;
615    Element mElement_PROGRAM_RASTER;
616    Element mElement_PROGRAM_STORE;
617
618    Element mElement_A_8;
619    Element mElement_RGB_565;
620    Element mElement_RGB_888;
621    Element mElement_RGBA_5551;
622    Element mElement_RGBA_4444;
623    Element mElement_RGBA_8888;
624
625    Element mElement_FLOAT_2;
626    Element mElement_FLOAT_3;
627    Element mElement_FLOAT_4;
628
629    Element mElement_DOUBLE_2;
630    Element mElement_DOUBLE_3;
631    Element mElement_DOUBLE_4;
632
633    Element mElement_UCHAR_2;
634    Element mElement_UCHAR_3;
635    Element mElement_UCHAR_4;
636
637    Element mElement_CHAR_2;
638    Element mElement_CHAR_3;
639    Element mElement_CHAR_4;
640
641    Element mElement_USHORT_2;
642    Element mElement_USHORT_3;
643    Element mElement_USHORT_4;
644
645    Element mElement_SHORT_2;
646    Element mElement_SHORT_3;
647    Element mElement_SHORT_4;
648
649    Element mElement_UINT_2;
650    Element mElement_UINT_3;
651    Element mElement_UINT_4;
652
653    Element mElement_INT_2;
654    Element mElement_INT_3;
655    Element mElement_INT_4;
656
657    Element mElement_ULONG_2;
658    Element mElement_ULONG_3;
659    Element mElement_ULONG_4;
660
661    Element mElement_LONG_2;
662    Element mElement_LONG_3;
663    Element mElement_LONG_4;
664
665    Element mElement_MATRIX_4X4;
666    Element mElement_MATRIX_3X3;
667    Element mElement_MATRIX_2X2;
668
669    Sampler mSampler_CLAMP_NEAREST;
670    Sampler mSampler_CLAMP_LINEAR;
671    Sampler mSampler_CLAMP_LINEAR_MIP_LINEAR;
672    Sampler mSampler_WRAP_NEAREST;
673    Sampler mSampler_WRAP_LINEAR;
674    Sampler mSampler_WRAP_LINEAR_MIP_LINEAR;
675
676    ProgramStore mProgramStore_BLEND_NONE_DEPTH_TEST;
677    ProgramStore mProgramStore_BLEND_NONE_DEPTH_NO_DEPTH;
678    ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_TEST;
679    ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_NO_DEPTH;
680
681    ProgramRaster mProgramRaster_CULL_BACK;
682    ProgramRaster mProgramRaster_CULL_FRONT;
683    ProgramRaster mProgramRaster_CULL_NONE;
684
685    ///////////////////////////////////////////////////////////////////////////////////
686    //
687
688    /**
689     * Base class application should derive from for handling RS messages
690     * coming from their scripts.  When a script calls sendToClient the data
691     * fields will be filled in and then the run method called by a message
692     * handling thread.  This will occur some time after sendToClient completes
693     * in the script.
694     *
695     */
696    public static class RSMessageHandler implements Runnable {
697        protected int[] mData;
698        protected int mID;
699        protected int mLength;
700        public void run() {
701        }
702    }
703    /**
704     * If an application is expecting messages it should set this field to an
705     * instance of RSMessage.  This instance will receive all the user messages
706     * sent from sendToClient by scripts from this context.
707     *
708     */
709    RSMessageHandler mMessageCallback = null;
710
711    public void setMessageHandler(RSMessageHandler msg) {
712        mMessageCallback = msg;
713    }
714    public RSMessageHandler getMessageHandler() {
715        return mMessageCallback;
716    }
717
718    /**
719     * Runtime error base class.  An application should derive from this class
720     * if it wishes to install an error handler.  When errors occur at runtime
721     * the fields in this class will be filled and the run method called.
722     *
723     */
724    public static class RSErrorHandler implements Runnable {
725        protected String mErrorMessage;
726        protected int mErrorNum;
727        public void run() {
728        }
729    }
730
731    /**
732     * Application Error handler.  All runtime errors will be dispatched to the
733     * instance of RSAsyncError set here.  If this field is null a
734     * RSRuntimeException will instead be thrown with details about the error.
735     * This will cause program termaination.
736     *
737     */
738    RSErrorHandler mErrorCallback = null;
739
740    public void setErrorHandler(RSErrorHandler msg) {
741        mErrorCallback = msg;
742    }
743    public RSErrorHandler getErrorHandler() {
744        return mErrorCallback;
745    }
746
747    /**
748     * RenderScript worker threads priority enumeration.  The default value is
749     * NORMAL.  Applications wishing to do background processing such as
750     * wallpapers should set their priority to LOW to avoid starving forground
751     * processes.
752     */
753    public enum Priority {
754        LOW (Process.THREAD_PRIORITY_BACKGROUND + (5 * Process.THREAD_PRIORITY_LESS_FAVORABLE)),
755        NORMAL (Process.THREAD_PRIORITY_DISPLAY);
756
757        int mID;
758        Priority(int id) {
759            mID = id;
760        }
761    }
762
763    void validate() {
764        if (mContext == 0) {
765            throw new RSInvalidStateException("Calling RS with no Context active.");
766        }
767    }
768
769
770    /**
771     * Change the priority of the worker threads for this context.
772     *
773     * @param p New priority to be set.
774     */
775    public void setPriority(Priority p) {
776        validate();
777        nContextSetPriority(p.mID);
778    }
779
780    static class MessageThread extends Thread {
781        RenderScript mRS;
782        boolean mRun = true;
783        int[] mAuxData = new int[2];
784
785        static final int RS_MESSAGE_TO_CLIENT_NONE = 0;
786        static final int RS_MESSAGE_TO_CLIENT_EXCEPTION = 1;
787        static final int RS_MESSAGE_TO_CLIENT_RESIZE = 2;
788        static final int RS_MESSAGE_TO_CLIENT_ERROR = 3;
789        static final int RS_MESSAGE_TO_CLIENT_USER = 4;
790
791        static final int RS_ERROR_FATAL_UNKNOWN = 0x1000;
792
793        MessageThread(RenderScript rs) {
794            super("RSMessageThread");
795            mRS = rs;
796
797        }
798
799        public void run() {
800            // This function is a temporary solution.  The final solution will
801            // used typed allocations where the message id is the type indicator.
802            int[] rbuf = new int[16];
803            mRS.nContextInitToClient(mRS.mContext);
804            while(mRun) {
805                rbuf[0] = 0;
806                int msg = mRS.nContextPeekMessage(mRS.mContext, mAuxData);
807                int size = mAuxData[1];
808                int subID = mAuxData[0];
809
810                if (msg == RS_MESSAGE_TO_CLIENT_USER) {
811                    if ((size>>2) >= rbuf.length) {
812                        rbuf = new int[(size + 3) >> 2];
813                    }
814                    if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
815                        RS_MESSAGE_TO_CLIENT_USER) {
816                        throw new RSDriverException("Error processing message from Renderscript.");
817                    }
818
819                    if(mRS.mMessageCallback != null) {
820                        mRS.mMessageCallback.mData = rbuf;
821                        mRS.mMessageCallback.mID = subID;
822                        mRS.mMessageCallback.mLength = size;
823                        mRS.mMessageCallback.run();
824                    } else {
825                        throw new RSInvalidStateException("Received a message from the script with no message handler installed.");
826                    }
827                    continue;
828                }
829
830                if (msg == RS_MESSAGE_TO_CLIENT_ERROR) {
831                    String e = mRS.nContextGetErrorMessage(mRS.mContext);
832
833                    if (subID >= RS_ERROR_FATAL_UNKNOWN) {
834                        throw new RSRuntimeException("Fatal error " + subID + ", details: " + e);
835                    }
836
837                    if(mRS.mErrorCallback != null) {
838                        mRS.mErrorCallback.mErrorMessage = e;
839                        mRS.mErrorCallback.mErrorNum = subID;
840                        mRS.mErrorCallback.run();
841                    } else {
842                        //throw new RSRuntimeException("Received error num " + subID + ", details: " + e);
843                    }
844                    continue;
845                }
846
847                // 2: teardown.
848                // But we want to avoid starving other threads during
849                // teardown by yielding until the next line in the destructor
850                // can execute to set mRun = false
851                try {
852                    sleep(1, 0);
853                } catch(InterruptedException e) {
854                }
855            }
856            Log.d(LOG_TAG, "MessageThread exiting.");
857        }
858    }
859
860    RenderScript(Context ctx) {
861        mApplicationContext = ctx.getApplicationContext();
862    }
863
864    /**
865     * Gets the application context associated with the RenderScript context.
866     *
867     * @return The application context.
868     */
869    public final Context getApplicationContext() {
870        return mApplicationContext;
871    }
872
873    static int getTargetSdkVersion(Context ctx) {
874        return ctx.getApplicationInfo().targetSdkVersion;
875    }
876
877    /**
878     * Create a basic RenderScript context.
879     *
880     * @param ctx The context.
881     * @return RenderScript
882     */
883    public static RenderScript create(Context ctx) {
884        RenderScript rs = new RenderScript(ctx);
885
886        int sdkVersion = getTargetSdkVersion(ctx);
887
888        rs.mDev = rs.nDeviceCreate();
889        rs.mContext = rs.nContextCreate(rs.mDev, 0, sdkVersion);
890        if (rs.mContext == 0) {
891            throw new RSDriverException("Failed to create RS context.");
892        }
893        rs.mMessageThread = new MessageThread(rs);
894        rs.mMessageThread.start();
895        return rs;
896    }
897
898    /**
899     * Print the currently available debugging information about the state of
900     * the RS context to the log.
901     *
902     */
903    public void contextDump() {
904        validate();
905        nContextDump(0);
906    }
907
908    /**
909     * Wait for any commands in the fifo between the java bindings and native to
910     * be processed.
911     *
912     */
913    public void finish() {
914        nContextFinish();
915    }
916
917    /**
918     * Destroy this renderscript context.  Once this function is called its no
919     * longer legal to use this or any objects created by this context.
920     *
921     */
922    public void destroy() {
923        validate();
924        nContextDeinitToClient(mContext);
925        mMessageThread.mRun = false;
926        try {
927            mMessageThread.join();
928        } catch(InterruptedException e) {
929        }
930
931        nContextDestroy();
932        mContext = 0;
933
934        nDeviceDestroy(mDev);
935        mDev = 0;
936    }
937
938    boolean isAlive() {
939        return mContext != 0;
940    }
941
942    int safeID(BaseObj o) {
943        if(o != null) {
944            return o.getID();
945        }
946        return 0;
947    }
948}
949