[go: nahoru, domu]

RenderScript.java revision c9390c8baf0a41633c176d6d9a2d7e5d0c61c387
1/*
2 * Copyright (C) 2008-2012 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.io.File;
20import java.lang.reflect.Method;
21import java.util.concurrent.locks.ReentrantReadWriteLock;
22
23import android.content.Context;
24import android.content.res.AssetManager;
25import android.graphics.Bitmap;
26import android.graphics.SurfaceTexture;
27import android.util.Log;
28import android.view.Surface;
29import android.os.SystemProperties;
30import android.os.Trace;
31import java.util.ArrayList;
32
33// TODO: Clean up the whitespace that separates methods in this class.
34
35/**
36 * This class provides access to a RenderScript context, which controls RenderScript
37 * initialization, resource management, and teardown. An instance of the RenderScript
38 * class must be created before any other RS objects can be created.
39 *
40 * <div class="special reference">
41 * <h3>Developer Guides</h3>
42 * <p>For more information about creating an application that uses RenderScript, read the
43 * <a href="{@docRoot}guide/topics/renderscript/index.html">RenderScript</a> developer guide.</p>
44 * </div>
45 **/
46public class RenderScript {
47    static final long TRACE_TAG = Trace.TRACE_TAG_RS;
48
49    static final String LOG_TAG = "RenderScript_jni";
50    static final boolean DEBUG  = false;
51    @SuppressWarnings({"UnusedDeclaration", "deprecation"})
52    static final boolean LOG_ENABLED = false;
53
54    static private ArrayList<RenderScript> mProcessContextList = new ArrayList<RenderScript>();
55    private boolean mIsProcessContext = false;
56    private int mContextFlags = 0;
57    private int mContextSdkVersion = 0;
58
59
60    private Context mApplicationContext;
61
62    /*
63     * We use a class initializer to allow the native code to cache some
64     * field offsets.
65     */
66    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) // TODO: now used locally; remove?
67    static boolean sInitialized;
68    native static void _nInit();
69
70    static Object sRuntime;
71    static Method registerNativeAllocation;
72    static Method registerNativeFree;
73
74    /*
75     * Context creation flag that specifies a normal context.
76    */
77    public static final int CREATE_FLAG_NONE = 0x0000;
78
79    /*
80     * Context creation flag which specifies a context optimized for low
81     * latency over peak performance. This is a hint and may have no effect
82     * on some implementations.
83    */
84    public static final int CREATE_FLAG_LOW_LATENCY = 0x0002;
85
86    /*
87     * Context creation flag which specifies a context optimized for long
88     * battery life over peak performance. This is a hint and may have no effect
89     * on some implementations.
90    */
91    public static final int CREATE_FLAG_LOW_POWER = 0x0004;
92
93    /**
94     * @hide
95     * Context creation flag which instructs the implementation to wait for
96     * a debugger to be attached before continuing execution.
97    */
98    public static final int CREATE_FLAG_WAIT_FOR_ATTACH = 0x0008;
99
100    /**
101     * @hide
102     * Context creation flag which specifies that optimization level 0 is
103     * passed to the device compiler upon execution of the RenderScript kernel.
104     * The default optimization level is 3.
105    */
106    public static final int CREATE_FLAG_OPT_LEVEL_0 = 0x0010;
107
108    /*
109     * Detect the bitness of the VM to allow FieldPacker to do the right thing.
110     */
111    static native int rsnSystemGetPointerSize();
112    static int sPointerSize;
113
114    static {
115        sInitialized = false;
116        if (!SystemProperties.getBoolean("config.disable_renderscript", false)) {
117            try {
118                Class<?> vm_runtime = Class.forName("dalvik.system.VMRuntime");
119                Method get_runtime = vm_runtime.getDeclaredMethod("getRuntime");
120                sRuntime = get_runtime.invoke(null);
121                registerNativeAllocation = vm_runtime.getDeclaredMethod("registerNativeAllocation", Integer.TYPE);
122                registerNativeFree = vm_runtime.getDeclaredMethod("registerNativeFree", Integer.TYPE);
123            } catch (Exception e) {
124                Log.e(LOG_TAG, "Error loading GC methods: " + e);
125                throw new RSRuntimeException("Error loading GC methods: " + e);
126            }
127            try {
128                System.loadLibrary("rs_jni");
129                _nInit();
130                sInitialized = true;
131                sPointerSize = rsnSystemGetPointerSize();
132            } catch (UnsatisfiedLinkError e) {
133                Log.e(LOG_TAG, "Error loading RS jni library: " + e);
134                throw new RSRuntimeException("Error loading RS jni library: " + e);
135            }
136        }
137    }
138
139    // Non-threadsafe functions.
140    native long  nDeviceCreate();
141    native void nDeviceDestroy(long dev);
142    native void nDeviceSetConfig(long dev, int param, int value);
143    native int nContextGetUserMessage(long con, int[] data);
144    native String nContextGetErrorMessage(long con);
145    native int  nContextPeekMessage(long con, int[] subID);
146    native void nContextInitToClient(long con);
147    native void nContextDeinitToClient(long con);
148
149    // this should be a monotonically increasing ID
150    // used in conjunction with the API version of a device
151    static final long sMinorVersion = 1;
152
153    /**
154     * @hide
155     *
156     * Only exist to be compatible with old version RenderScript Support lib.
157     * Will eventually be removed.
158     *
159     * @return Always return 1
160     *
161     */
162    public static long getMinorID() {
163        return 1;
164    }
165
166
167    /**
168     * Returns an identifier that can be used to identify a particular
169     * minor version of RS.
170     *
171     * @return The minor RenderScript version number
172     *
173     */
174    public static long getMinorVersion() {
175        return sMinorVersion;
176    }
177
178    /**
179     * ContextType specifies the specific type of context to be created.
180     *
181     */
182    public enum ContextType {
183        /**
184         * NORMAL context, this is the default and what shipping apps should
185         * use.
186         */
187        NORMAL (0),
188
189        /**
190         * DEBUG context, perform extra runtime checks to validate the
191         * kernels and APIs are being used as intended.  Get and SetElementAt
192         * will be bounds checked in this mode.
193         */
194        DEBUG (1),
195
196        /**
197         * PROFILE context, Intended to be used once the first time an
198         * application is run on a new device.  This mode allows the runtime to
199         * do additional testing and performance tuning.
200         */
201        PROFILE (2);
202
203        int mID;
204        ContextType(int id) {
205            mID = id;
206        }
207    }
208
209    ContextType mContextType;
210    ReentrantReadWriteLock mRWLock;
211
212    // Methods below are wrapped to protect the non-threadsafe
213    // lockless fifo.
214    native long  rsnContextCreateGL(long dev, int ver, int sdkVer,
215                 int colorMin, int colorPref,
216                 int alphaMin, int alphaPref,
217                 int depthMin, int depthPref,
218                 int stencilMin, int stencilPref,
219                 int samplesMin, int samplesPref, float samplesQ, int dpi);
220    synchronized long nContextCreateGL(long dev, int ver, int sdkVer,
221                 int colorMin, int colorPref,
222                 int alphaMin, int alphaPref,
223                 int depthMin, int depthPref,
224                 int stencilMin, int stencilPref,
225                 int samplesMin, int samplesPref, float samplesQ, int dpi) {
226        return rsnContextCreateGL(dev, ver, sdkVer, colorMin, colorPref,
227                                  alphaMin, alphaPref, depthMin, depthPref,
228                                  stencilMin, stencilPref,
229                                  samplesMin, samplesPref, samplesQ, dpi);
230    }
231    native long  rsnContextCreate(long dev, int ver, int sdkVer, int contextType);
232    synchronized long nContextCreate(long dev, int ver, int sdkVer, int contextType) {
233        return rsnContextCreate(dev, ver, sdkVer, contextType);
234    }
235    native void rsnContextDestroy(long con);
236    synchronized void nContextDestroy() {
237        validate();
238
239        // take teardown lock
240        // teardown lock can only be taken when no objects are being destroyed
241        ReentrantReadWriteLock.WriteLock wlock = mRWLock.writeLock();
242        wlock.lock();
243
244        long curCon = mContext;
245        // context is considered dead as of this point
246        mContext = 0;
247
248        wlock.unlock();
249        rsnContextDestroy(curCon);
250    }
251    native void rsnContextSetSurface(long con, int w, int h, Surface sur);
252    synchronized void nContextSetSurface(int w, int h, Surface sur) {
253        validate();
254        rsnContextSetSurface(mContext, w, h, sur);
255    }
256    native void rsnContextSetSurfaceTexture(long con, int w, int h, SurfaceTexture sur);
257    synchronized void nContextSetSurfaceTexture(int w, int h, SurfaceTexture sur) {
258        validate();
259        rsnContextSetSurfaceTexture(mContext, w, h, sur);
260    }
261    native void rsnContextSetPriority(long con, int p);
262    synchronized void nContextSetPriority(int p) {
263        validate();
264        rsnContextSetPriority(mContext, p);
265    }
266    native void rsnContextSetCacheDir(long con, String cacheDir);
267    synchronized void nContextSetCacheDir(String cacheDir) {
268        validate();
269        rsnContextSetCacheDir(mContext, cacheDir);
270    }
271    native void rsnContextDump(long con, int bits);
272    synchronized void nContextDump(int bits) {
273        validate();
274        rsnContextDump(mContext, bits);
275    }
276    native void rsnContextFinish(long con);
277    synchronized void nContextFinish() {
278        validate();
279        rsnContextFinish(mContext);
280    }
281
282    native void rsnContextSendMessage(long con, int id, int[] data);
283    synchronized void nContextSendMessage(int id, int[] data) {
284        validate();
285        rsnContextSendMessage(mContext, id, data);
286    }
287
288    native void rsnContextBindRootScript(long con, long script);
289    synchronized void nContextBindRootScript(long script) {
290        validate();
291        rsnContextBindRootScript(mContext, script);
292    }
293    native void rsnContextBindSampler(long con, int sampler, int slot);
294    synchronized void nContextBindSampler(int sampler, int slot) {
295        validate();
296        rsnContextBindSampler(mContext, sampler, slot);
297    }
298    native void rsnContextBindProgramStore(long con, long pfs);
299    synchronized void nContextBindProgramStore(long pfs) {
300        validate();
301        rsnContextBindProgramStore(mContext, pfs);
302    }
303    native void rsnContextBindProgramFragment(long con, long pf);
304    synchronized void nContextBindProgramFragment(long pf) {
305        validate();
306        rsnContextBindProgramFragment(mContext, pf);
307    }
308    native void rsnContextBindProgramVertex(long con, long pv);
309    synchronized void nContextBindProgramVertex(long pv) {
310        validate();
311        rsnContextBindProgramVertex(mContext, pv);
312    }
313    native void rsnContextBindProgramRaster(long con, long pr);
314    synchronized void nContextBindProgramRaster(long pr) {
315        validate();
316        rsnContextBindProgramRaster(mContext, pr);
317    }
318    native void rsnContextPause(long con);
319    synchronized void nContextPause() {
320        validate();
321        rsnContextPause(mContext);
322    }
323    native void rsnContextResume(long con);
324    synchronized void nContextResume() {
325        validate();
326        rsnContextResume(mContext);
327    }
328
329    native long rsnClosureCreate(long con, long kernelID, long returnValue,
330        long[] fieldIDs, long[] values, int[] sizes, long[] depClosures,
331        long[] depFieldIDs);
332    synchronized long nClosureCreate(long kernelID, long returnValue,
333        long[] fieldIDs, long[] values, int[] sizes, long[] depClosures,
334        long[] depFieldIDs) {
335      validate();
336      long c = rsnClosureCreate(mContext, kernelID, returnValue, fieldIDs, values,
337          sizes, depClosures, depFieldIDs);
338      if (c == 0) {
339          throw new RSRuntimeException("Failed creating closure.");
340      }
341      return c;
342    }
343
344    native long rsnInvokeClosureCreate(long con, long invokeID, byte[] params,
345        long[] fieldIDs, long[] values, int[] sizes);
346    synchronized long nInvokeClosureCreate(long invokeID, byte[] params,
347        long[] fieldIDs, long[] values, int[] sizes) {
348      validate();
349      long c = rsnInvokeClosureCreate(mContext, invokeID, params, fieldIDs,
350          values, sizes);
351      if (c == 0) {
352          throw new RSRuntimeException("Failed creating closure.");
353      }
354      return c;
355    }
356
357    native void rsnClosureSetArg(long con, long closureID, int index,
358      long value, int size);
359    synchronized void nClosureSetArg(long closureID, int index, long value,
360        int size) {
361      validate();
362      rsnClosureSetArg(mContext, closureID, index, value, size);
363    }
364
365    native void rsnClosureSetGlobal(long con, long closureID, long fieldID,
366        long value, int size);
367    // Does this have to be synchronized?
368    synchronized void nClosureSetGlobal(long closureID, long fieldID,
369        long value, int size) {
370      validate(); // TODO: is this necessary?
371      rsnClosureSetGlobal(mContext, closureID, fieldID, value, size);
372    }
373
374    native long rsnScriptGroup2Create(long con, String name, String cachePath,
375                                      long[] closures);
376    synchronized long nScriptGroup2Create(String name, String cachePath,
377                                          long[] closures) {
378      validate();
379      long g = rsnScriptGroup2Create(mContext, name, cachePath, closures);
380      if (g == 0) {
381          throw new RSRuntimeException("Failed creating script group.");
382      }
383      return g;
384    }
385
386    native void rsnScriptGroup2Execute(long con, long groupID);
387    synchronized void nScriptGroup2Execute(long groupID) {
388      validate();
389      rsnScriptGroup2Execute(mContext, groupID);
390    }
391
392    native void rsnAssignName(long con, long obj, byte[] name);
393    synchronized void nAssignName(long obj, byte[] name) {
394        validate();
395        rsnAssignName(mContext, obj, name);
396    }
397    native String rsnGetName(long con, long obj);
398    synchronized String nGetName(long obj) {
399        validate();
400        return rsnGetName(mContext, obj);
401    }
402
403    // nObjDestroy is explicitly _not_ synchronous to prevent crashes in finalizers
404    native void rsnObjDestroy(long con, long id);
405    void nObjDestroy(long id) {
406        // There is a race condition here.  The calling code may be run
407        // by the gc while teardown is occuring.  This protects againts
408        // deleting dead objects.
409        if (mContext != 0) {
410            rsnObjDestroy(mContext, id);
411        }
412    }
413
414    native long rsnElementCreate(long con, long type, int kind, boolean norm, int vecSize);
415    synchronized long nElementCreate(long type, int kind, boolean norm, int vecSize) {
416        validate();
417        return rsnElementCreate(mContext, type, kind, norm, vecSize);
418    }
419    native long rsnElementCreate2(long con, long[] elements, String[] names, int[] arraySizes);
420    synchronized long nElementCreate2(long[] elements, String[] names, int[] arraySizes) {
421        validate();
422        return rsnElementCreate2(mContext, elements, names, arraySizes);
423    }
424    native void rsnElementGetNativeData(long con, long id, int[] elementData);
425    synchronized void nElementGetNativeData(long id, int[] elementData) {
426        validate();
427        rsnElementGetNativeData(mContext, id, elementData);
428    }
429    native void rsnElementGetSubElements(long con, long id,
430                                         long[] IDs, String[] names, int[] arraySizes);
431    synchronized void nElementGetSubElements(long id, long[] IDs, String[] names, int[] arraySizes) {
432        validate();
433        rsnElementGetSubElements(mContext, id, IDs, names, arraySizes);
434    }
435
436    native long rsnTypeCreate(long con, long eid, int x, int y, int z, boolean mips, boolean faces, int yuv);
437    synchronized long nTypeCreate(long eid, int x, int y, int z, boolean mips, boolean faces, int yuv) {
438        validate();
439        return rsnTypeCreate(mContext, eid, x, y, z, mips, faces, yuv);
440    }
441    native void rsnTypeGetNativeData(long con, long id, long[] typeData);
442    synchronized void nTypeGetNativeData(long id, long[] typeData) {
443        validate();
444        rsnTypeGetNativeData(mContext, id, typeData);
445    }
446
447    native long rsnAllocationCreateTyped(long con, long type, int mip, int usage, long pointer);
448    synchronized long nAllocationCreateTyped(long type, int mip, int usage, long pointer) {
449        validate();
450        return rsnAllocationCreateTyped(mContext, type, mip, usage, pointer);
451    }
452    native long rsnAllocationCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage);
453    synchronized long nAllocationCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
454        validate();
455        return rsnAllocationCreateFromBitmap(mContext, type, mip, bmp, usage);
456    }
457
458    native long rsnAllocationCreateBitmapBackedAllocation(long con, long type, int mip, Bitmap bmp, int usage);
459    synchronized long nAllocationCreateBitmapBackedAllocation(long type, int mip, Bitmap bmp, int usage) {
460        validate();
461        return rsnAllocationCreateBitmapBackedAllocation(mContext, type, mip, bmp, usage);
462    }
463
464    native long rsnAllocationCubeCreateFromBitmap(long con, long type, int mip, Bitmap bmp, int usage);
465    synchronized long nAllocationCubeCreateFromBitmap(long type, int mip, Bitmap bmp, int usage) {
466        validate();
467        return rsnAllocationCubeCreateFromBitmap(mContext, type, mip, bmp, usage);
468    }
469    native long  rsnAllocationCreateBitmapRef(long con, long type, Bitmap bmp);
470    synchronized long nAllocationCreateBitmapRef(long type, Bitmap bmp) {
471        validate();
472        return rsnAllocationCreateBitmapRef(mContext, type, bmp);
473    }
474    native long  rsnAllocationCreateFromAssetStream(long con, int mips, int assetStream, int usage);
475    synchronized long nAllocationCreateFromAssetStream(int mips, int assetStream, int usage) {
476        validate();
477        return rsnAllocationCreateFromAssetStream(mContext, mips, assetStream, usage);
478    }
479
480    native void  rsnAllocationCopyToBitmap(long con, long alloc, Bitmap bmp);
481    synchronized void nAllocationCopyToBitmap(long alloc, Bitmap bmp) {
482        validate();
483        rsnAllocationCopyToBitmap(mContext, alloc, bmp);
484    }
485
486
487    native void rsnAllocationSyncAll(long con, long alloc, int src);
488    synchronized void nAllocationSyncAll(long alloc, int src) {
489        validate();
490        rsnAllocationSyncAll(mContext, alloc, src);
491    }
492    native Surface rsnAllocationGetSurface(long con, long alloc);
493    synchronized Surface nAllocationGetSurface(long alloc) {
494        validate();
495        return rsnAllocationGetSurface(mContext, alloc);
496    }
497    native void rsnAllocationSetSurface(long con, long alloc, Surface sur);
498    synchronized void nAllocationSetSurface(long alloc, Surface sur) {
499        validate();
500        rsnAllocationSetSurface(mContext, alloc, sur);
501    }
502    native void rsnAllocationIoSend(long con, long alloc);
503    synchronized void nAllocationIoSend(long alloc) {
504        validate();
505        rsnAllocationIoSend(mContext, alloc);
506    }
507    native void rsnAllocationIoReceive(long con, long alloc);
508    synchronized void nAllocationIoReceive(long alloc) {
509        validate();
510        rsnAllocationIoReceive(mContext, alloc);
511    }
512
513
514    native void rsnAllocationGenerateMipmaps(long con, long alloc);
515    synchronized void nAllocationGenerateMipmaps(long alloc) {
516        validate();
517        rsnAllocationGenerateMipmaps(mContext, alloc);
518    }
519    native void  rsnAllocationCopyFromBitmap(long con, long alloc, Bitmap bmp);
520    synchronized void nAllocationCopyFromBitmap(long alloc, Bitmap bmp) {
521        validate();
522        rsnAllocationCopyFromBitmap(mContext, alloc, bmp);
523    }
524
525
526    native void rsnAllocationData1D(long con, long id, int off, int mip, int count, Object d, int sizeBytes, int dt,
527                                    int mSize, boolean usePadding);
528    synchronized void nAllocationData1D(long id, int off, int mip, int count, Object d, int sizeBytes, Element.DataType dt,
529                                        int mSize, boolean usePadding) {
530        validate();
531        rsnAllocationData1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID, mSize, usePadding);
532    }
533
534    native void rsnAllocationElementData(long con,long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes);
535    synchronized void nAllocationElementData(long id, int xoff, int yoff, int zoff, int mip, int compIdx, byte[] d, int sizeBytes) {
536        validate();
537        rsnAllocationElementData(mContext, id, xoff, yoff, zoff, mip, compIdx, d, sizeBytes);
538    }
539
540    native void rsnAllocationData2D(long con,
541                                    long dstAlloc, int dstXoff, int dstYoff,
542                                    int dstMip, int dstFace,
543                                    int width, int height,
544                                    long srcAlloc, int srcXoff, int srcYoff,
545                                    int srcMip, int srcFace);
546    synchronized void nAllocationData2D(long dstAlloc, int dstXoff, int dstYoff,
547                                        int dstMip, int dstFace,
548                                        int width, int height,
549                                        long srcAlloc, int srcXoff, int srcYoff,
550                                        int srcMip, int srcFace) {
551        validate();
552        rsnAllocationData2D(mContext,
553                            dstAlloc, dstXoff, dstYoff,
554                            dstMip, dstFace,
555                            width, height,
556                            srcAlloc, srcXoff, srcYoff,
557                            srcMip, srcFace);
558    }
559
560    native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face,
561                                    int w, int h, Object d, int sizeBytes, int dt,
562                                    int mSize, boolean usePadding);
563    synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face,
564                                        int w, int h, Object d, int sizeBytes, Element.DataType dt,
565                                        int mSize, boolean usePadding) {
566        validate();
567        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID, mSize, usePadding);
568    }
569
570    native void rsnAllocationData2D(long con, long id, int xoff, int yoff, int mip, int face, Bitmap b);
571    synchronized void nAllocationData2D(long id, int xoff, int yoff, int mip, int face, Bitmap b) {
572        validate();
573        rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b);
574    }
575
576    native void rsnAllocationData3D(long con,
577                                    long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
578                                    int dstMip,
579                                    int width, int height, int depth,
580                                    long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
581                                    int srcMip);
582    synchronized void nAllocationData3D(long dstAlloc, int dstXoff, int dstYoff, int dstZoff,
583                                        int dstMip,
584                                        int width, int height, int depth,
585                                        long srcAlloc, int srcXoff, int srcYoff, int srcZoff,
586                                        int srcMip) {
587        validate();
588        rsnAllocationData3D(mContext,
589                            dstAlloc, dstXoff, dstYoff, dstZoff,
590                            dstMip, width, height, depth,
591                            srcAlloc, srcXoff, srcYoff, srcZoff, srcMip);
592    }
593
594    native void rsnAllocationData3D(long con, long id, int xoff, int yoff, int zoff, int mip,
595                                    int w, int h, int depth, Object d, int sizeBytes, int dt,
596                                    int mSize, boolean usePadding);
597    synchronized void nAllocationData3D(long id, int xoff, int yoff, int zoff, int mip,
598                                        int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt,
599                                        int mSize, boolean usePadding) {
600        validate();
601        rsnAllocationData3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes,
602                            dt.mID, mSize, usePadding);
603    }
604
605    native void rsnAllocationRead(long con, long id, Object d, int dt, int mSize, boolean usePadding);
606    synchronized void nAllocationRead(long id, Object d, Element.DataType dt, int mSize, boolean usePadding) {
607        validate();
608        rsnAllocationRead(mContext, id, d, dt.mID, mSize, usePadding);
609    }
610
611    native void rsnAllocationRead1D(long con, long id, int off, int mip, int count, Object d,
612                                    int sizeBytes, int dt, int mSize, boolean usePadding);
613    synchronized void nAllocationRead1D(long id, int off, int mip, int count, Object d,
614                                        int sizeBytes, Element.DataType dt, int mSize, boolean usePadding) {
615        validate();
616        rsnAllocationRead1D(mContext, id, off, mip, count, d, sizeBytes, dt.mID, mSize, usePadding);
617    }
618
619    native void rsnAllocationElementRead(long con,long id, int xoff, int yoff, int zoff,
620                                         int mip, int compIdx, byte[] d, int sizeBytes);
621    synchronized void nAllocationElementRead(long id, int xoff, int yoff, int zoff,
622                                             int mip, int compIdx, byte[] d, int sizeBytes) {
623        validate();
624        rsnAllocationElementRead(mContext, id, xoff, yoff, zoff, mip, compIdx, d, sizeBytes);
625    }
626
627    native void rsnAllocationRead2D(long con, long id, int xoff, int yoff, int mip, int face,
628                                    int w, int h, Object d, int sizeBytes, int dt,
629                                    int mSize, boolean usePadding);
630    synchronized void nAllocationRead2D(long id, int xoff, int yoff, int mip, int face,
631                                        int w, int h, Object d, int sizeBytes, Element.DataType dt,
632                                        int mSize, boolean usePadding) {
633        validate();
634        rsnAllocationRead2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes, dt.mID, mSize, usePadding);
635    }
636
637    native void rsnAllocationRead3D(long con, long id, int xoff, int yoff, int zoff, int mip,
638                                    int w, int h, int depth, Object d, int sizeBytes, int dt,
639                                    int mSize, boolean usePadding);
640    synchronized void nAllocationRead3D(long id, int xoff, int yoff, int zoff, int mip,
641                                        int w, int h, int depth, Object d, int sizeBytes, Element.DataType dt,
642                                        int mSize, boolean usePadding) {
643        validate();
644        rsnAllocationRead3D(mContext, id, xoff, yoff, zoff, mip, w, h, depth, d, sizeBytes, dt.mID, mSize, usePadding);
645    }
646
647    native long  rsnAllocationGetType(long con, long id);
648    synchronized long nAllocationGetType(long id) {
649        validate();
650        return rsnAllocationGetType(mContext, id);
651    }
652
653    native void rsnAllocationResize1D(long con, long id, int dimX);
654    synchronized void nAllocationResize1D(long id, int dimX) {
655        validate();
656        rsnAllocationResize1D(mContext, id, dimX);
657    }
658
659    native long  rsnAllocationAdapterCreate(long con, long allocId, long typeId);
660    synchronized long nAllocationAdapterCreate(long allocId, long typeId) {
661        validate();
662        return rsnAllocationAdapterCreate(mContext, allocId, typeId);
663    }
664
665    native void  rsnAllocationAdapterOffset(long con, long id, int x, int y, int z,
666                                            int mip, int face, int a1, int a2, int a3, int a4);
667    synchronized void nAllocationAdapterOffset(long id, int x, int y, int z,
668                                               int mip, int face, int a1, int a2, int a3, int a4) {
669        validate();
670        rsnAllocationAdapterOffset(mContext, id, x, y, z, mip, face, a1, a2, a3, a4);
671    }
672
673    native long rsnFileA3DCreateFromAssetStream(long con, long assetStream);
674    synchronized long nFileA3DCreateFromAssetStream(long assetStream) {
675        validate();
676        return rsnFileA3DCreateFromAssetStream(mContext, assetStream);
677    }
678    native long rsnFileA3DCreateFromFile(long con, String path);
679    synchronized long nFileA3DCreateFromFile(String path) {
680        validate();
681        return rsnFileA3DCreateFromFile(mContext, path);
682    }
683    native long rsnFileA3DCreateFromAsset(long con, AssetManager mgr, String path);
684    synchronized long nFileA3DCreateFromAsset(AssetManager mgr, String path) {
685        validate();
686        return rsnFileA3DCreateFromAsset(mContext, mgr, path);
687    }
688    native int  rsnFileA3DGetNumIndexEntries(long con, long fileA3D);
689    synchronized int nFileA3DGetNumIndexEntries(long fileA3D) {
690        validate();
691        return rsnFileA3DGetNumIndexEntries(mContext, fileA3D);
692    }
693    native void rsnFileA3DGetIndexEntries(long con, long fileA3D, int numEntries, int[] IDs, String[] names);
694    synchronized void nFileA3DGetIndexEntries(long fileA3D, int numEntries, int[] IDs, String[] names) {
695        validate();
696        rsnFileA3DGetIndexEntries(mContext, fileA3D, numEntries, IDs, names);
697    }
698    native long rsnFileA3DGetEntryByIndex(long con, long fileA3D, int index);
699    synchronized long nFileA3DGetEntryByIndex(long fileA3D, int index) {
700        validate();
701        return rsnFileA3DGetEntryByIndex(mContext, fileA3D, index);
702    }
703
704    native long rsnFontCreateFromFile(long con, String fileName, float size, int dpi);
705    synchronized long nFontCreateFromFile(String fileName, float size, int dpi) {
706        validate();
707        return rsnFontCreateFromFile(mContext, fileName, size, dpi);
708    }
709    native long rsnFontCreateFromAssetStream(long con, String name, float size, int dpi, long assetStream);
710    synchronized long nFontCreateFromAssetStream(String name, float size, int dpi, long assetStream) {
711        validate();
712        return rsnFontCreateFromAssetStream(mContext, name, size, dpi, assetStream);
713    }
714    native long rsnFontCreateFromAsset(long con, AssetManager mgr, String path, float size, int dpi);
715    synchronized long nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
716        validate();
717        return rsnFontCreateFromAsset(mContext, mgr, path, size, dpi);
718    }
719
720
721    native void rsnScriptBindAllocation(long con, long script, long alloc, int slot);
722    synchronized void nScriptBindAllocation(long script, long alloc, int slot) {
723        validate();
724        rsnScriptBindAllocation(mContext, script, alloc, slot);
725    }
726    native void rsnScriptSetTimeZone(long con, long script, byte[] timeZone);
727    synchronized void nScriptSetTimeZone(long script, byte[] timeZone) {
728        validate();
729        rsnScriptSetTimeZone(mContext, script, timeZone);
730    }
731    native void rsnScriptInvoke(long con, long id, int slot);
732    synchronized void nScriptInvoke(long id, int slot) {
733        validate();
734        rsnScriptInvoke(mContext, id, slot);
735    }
736
737    native void rsnScriptForEach(long con, long id, int slot, long[] ains,
738                                 long aout, byte[] params, int[] limits);
739
740    synchronized void nScriptForEach(long id, int slot, long[] ains, long aout,
741                                     byte[] params, int[] limits) {
742        validate();
743        rsnScriptForEach(mContext, id, slot, ains, aout, params, limits);
744    }
745
746    native void rsnScriptReduce(long con, long id, int slot, long ain,
747                                long aout, int[] limits);
748    synchronized void nScriptReduce(long id, int slot, long ain, long aout,
749                                    int[] limits) {
750        validate();
751        rsnScriptReduce(mContext, id, slot, ain, aout, limits);
752    }
753
754    native void rsnScriptInvokeV(long con, long id, int slot, byte[] params);
755    synchronized void nScriptInvokeV(long id, int slot, byte[] params) {
756        validate();
757        rsnScriptInvokeV(mContext, id, slot, params);
758    }
759
760    native void rsnScriptSetVarI(long con, long id, int slot, int val);
761    synchronized void nScriptSetVarI(long id, int slot, int val) {
762        validate();
763        rsnScriptSetVarI(mContext, id, slot, val);
764    }
765    native int rsnScriptGetVarI(long con, long id, int slot);
766    synchronized int nScriptGetVarI(long id, int slot) {
767        validate();
768        return rsnScriptGetVarI(mContext, id, slot);
769    }
770
771    native void rsnScriptSetVarJ(long con, long id, int slot, long val);
772    synchronized void nScriptSetVarJ(long id, int slot, long val) {
773        validate();
774        rsnScriptSetVarJ(mContext, id, slot, val);
775    }
776    native long rsnScriptGetVarJ(long con, long id, int slot);
777    synchronized long nScriptGetVarJ(long id, int slot) {
778        validate();
779        return rsnScriptGetVarJ(mContext, id, slot);
780    }
781
782    native void rsnScriptSetVarF(long con, long id, int slot, float val);
783    synchronized void nScriptSetVarF(long id, int slot, float val) {
784        validate();
785        rsnScriptSetVarF(mContext, id, slot, val);
786    }
787    native float rsnScriptGetVarF(long con, long id, int slot);
788    synchronized float nScriptGetVarF(long id, int slot) {
789        validate();
790        return rsnScriptGetVarF(mContext, id, slot);
791    }
792    native void rsnScriptSetVarD(long con, long id, int slot, double val);
793    synchronized void nScriptSetVarD(long id, int slot, double val) {
794        validate();
795        rsnScriptSetVarD(mContext, id, slot, val);
796    }
797    native double rsnScriptGetVarD(long con, long id, int slot);
798    synchronized double nScriptGetVarD(long id, int slot) {
799        validate();
800        return rsnScriptGetVarD(mContext, id, slot);
801    }
802    native void rsnScriptSetVarV(long con, long id, int slot, byte[] val);
803    synchronized void nScriptSetVarV(long id, int slot, byte[] val) {
804        validate();
805        rsnScriptSetVarV(mContext, id, slot, val);
806    }
807    native void rsnScriptGetVarV(long con, long id, int slot, byte[] val);
808    synchronized void nScriptGetVarV(long id, int slot, byte[] val) {
809        validate();
810        rsnScriptGetVarV(mContext, id, slot, val);
811    }
812    native void rsnScriptSetVarVE(long con, long id, int slot, byte[] val,
813                                  long e, int[] dims);
814    synchronized void nScriptSetVarVE(long id, int slot, byte[] val,
815                                      long e, int[] dims) {
816        validate();
817        rsnScriptSetVarVE(mContext, id, slot, val, e, dims);
818    }
819    native void rsnScriptSetVarObj(long con, long id, int slot, long val);
820    synchronized void nScriptSetVarObj(long id, int slot, long val) {
821        validate();
822        rsnScriptSetVarObj(mContext, id, slot, val);
823    }
824
825    native long rsnScriptCCreate(long con, String resName, String cacheDir,
826                                 byte[] script, int length);
827    synchronized long nScriptCCreate(String resName, String cacheDir, byte[] script, int length) {
828        validate();
829        return rsnScriptCCreate(mContext, resName, cacheDir, script, length);
830    }
831
832    native long rsnScriptIntrinsicCreate(long con, int id, long eid);
833    synchronized long nScriptIntrinsicCreate(int id, long eid) {
834        validate();
835        return rsnScriptIntrinsicCreate(mContext, id, eid);
836    }
837
838    native long  rsnScriptKernelIDCreate(long con, long sid, int slot, int sig);
839    synchronized long nScriptKernelIDCreate(long sid, int slot, int sig) {
840        validate();
841        return rsnScriptKernelIDCreate(mContext, sid, slot, sig);
842    }
843
844    native long  rsnScriptInvokeIDCreate(long con, long sid, int slot);
845    synchronized long nScriptInvokeIDCreate(long sid, int slot) {
846        validate();
847        return rsnScriptInvokeIDCreate(mContext, sid, slot);
848    }
849
850    native long  rsnScriptFieldIDCreate(long con, long sid, int slot);
851    synchronized long nScriptFieldIDCreate(long sid, int slot) {
852        validate();
853        return rsnScriptFieldIDCreate(mContext, sid, slot);
854    }
855
856    native long rsnScriptGroupCreate(long con, long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types);
857    synchronized long nScriptGroupCreate(long[] kernels, long[] src, long[] dstk, long[] dstf, long[] types) {
858        validate();
859        return rsnScriptGroupCreate(mContext, kernels, src, dstk, dstf, types);
860    }
861
862    native void rsnScriptGroupSetInput(long con, long group, long kernel, long alloc);
863    synchronized void nScriptGroupSetInput(long group, long kernel, long alloc) {
864        validate();
865        rsnScriptGroupSetInput(mContext, group, kernel, alloc);
866    }
867
868    native void rsnScriptGroupSetOutput(long con, long group, long kernel, long alloc);
869    synchronized void nScriptGroupSetOutput(long group, long kernel, long alloc) {
870        validate();
871        rsnScriptGroupSetOutput(mContext, group, kernel, alloc);
872    }
873
874    native void rsnScriptGroupExecute(long con, long group);
875    synchronized void nScriptGroupExecute(long group) {
876        validate();
877        rsnScriptGroupExecute(mContext, group);
878    }
879
880    native long  rsnSamplerCreate(long con, int magFilter, int minFilter,
881                                 int wrapS, int wrapT, int wrapR, float aniso);
882    synchronized long nSamplerCreate(int magFilter, int minFilter,
883                                 int wrapS, int wrapT, int wrapR, float aniso) {
884        validate();
885        return rsnSamplerCreate(mContext, magFilter, minFilter, wrapS, wrapT, wrapR, aniso);
886    }
887
888    native long rsnProgramStoreCreate(long con, boolean r, boolean g, boolean b, boolean a,
889                                      boolean depthMask, boolean dither,
890                                      int srcMode, int dstMode, int depthFunc);
891    synchronized long nProgramStoreCreate(boolean r, boolean g, boolean b, boolean a,
892                                         boolean depthMask, boolean dither,
893                                         int srcMode, int dstMode, int depthFunc) {
894        validate();
895        return rsnProgramStoreCreate(mContext, r, g, b, a, depthMask, dither, srcMode,
896                                     dstMode, depthFunc);
897    }
898
899    native long rsnProgramRasterCreate(long con, boolean pointSprite, int cullMode);
900    synchronized long nProgramRasterCreate(boolean pointSprite, int cullMode) {
901        validate();
902        return rsnProgramRasterCreate(mContext, pointSprite, cullMode);
903    }
904
905    native void rsnProgramBindConstants(long con, long pv, int slot, long mID);
906    synchronized void nProgramBindConstants(long pv, int slot, long mID) {
907        validate();
908        rsnProgramBindConstants(mContext, pv, slot, mID);
909    }
910    native void rsnProgramBindTexture(long con, long vpf, int slot, long a);
911    synchronized void nProgramBindTexture(long vpf, int slot, long a) {
912        validate();
913        rsnProgramBindTexture(mContext, vpf, slot, a);
914    }
915    native void rsnProgramBindSampler(long con, long vpf, int slot, long s);
916    synchronized void nProgramBindSampler(long vpf, int slot, long s) {
917        validate();
918        rsnProgramBindSampler(mContext, vpf, slot, s);
919    }
920    native long rsnProgramFragmentCreate(long con, String shader, String[] texNames, long[] params);
921    synchronized long nProgramFragmentCreate(String shader, String[] texNames, long[] params) {
922        validate();
923        return rsnProgramFragmentCreate(mContext, shader, texNames, params);
924    }
925    native long rsnProgramVertexCreate(long con, String shader, String[] texNames, long[] params);
926    synchronized long nProgramVertexCreate(String shader, String[] texNames, long[] params) {
927        validate();
928        return rsnProgramVertexCreate(mContext, shader, texNames, params);
929    }
930
931    native long rsnMeshCreate(long con, long[] vtx, long[] idx, int[] prim);
932    synchronized long nMeshCreate(long[] vtx, long[] idx, int[] prim) {
933        validate();
934        return rsnMeshCreate(mContext, vtx, idx, prim);
935    }
936    native int  rsnMeshGetVertexBufferCount(long con, long id);
937    synchronized int nMeshGetVertexBufferCount(long id) {
938        validate();
939        return rsnMeshGetVertexBufferCount(mContext, id);
940    }
941    native int  rsnMeshGetIndexCount(long con, long id);
942    synchronized int nMeshGetIndexCount(long id) {
943        validate();
944        return rsnMeshGetIndexCount(mContext, id);
945    }
946    native void rsnMeshGetVertices(long con, long id, long[] vtxIds, int vtxIdCount);
947    synchronized void nMeshGetVertices(long id, long[] vtxIds, int vtxIdCount) {
948        validate();
949        rsnMeshGetVertices(mContext, id, vtxIds, vtxIdCount);
950    }
951    native void rsnMeshGetIndices(long con, long id, long[] idxIds, int[] primitives, int vtxIdCount);
952    synchronized void nMeshGetIndices(long id, long[] idxIds, int[] primitives, int vtxIdCount) {
953        validate();
954        rsnMeshGetIndices(mContext, id, idxIds, primitives, vtxIdCount);
955    }
956
957    native void rsnScriptIntrinsicBLAS_Single(long con, long id, int func, int TransA,
958                                              int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
959                                              float alpha, long A, long B, float beta, long C, int incX, int incY,
960                                              int KL, int KU);
961    synchronized void nScriptIntrinsicBLAS_Single(long id, int func, int TransA,
962                                                  int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
963                                                  float alpha, long A, long B, float beta, long C, int incX, int incY,
964                                                  int KL, int KU) {
965        validate();
966        rsnScriptIntrinsicBLAS_Single(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alpha, A, B, beta, C, incX, incY, KL, KU);
967    }
968
969    native void rsnScriptIntrinsicBLAS_Double(long con, long id, int func, int TransA,
970                                              int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
971                                              double alpha, long A, long B, double beta, long C, int incX, int incY,
972                                              int KL, int KU);
973    synchronized void nScriptIntrinsicBLAS_Double(long id, int func, int TransA,
974                                                  int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
975                                                  double alpha, long A, long B, double beta, long C, int incX, int incY,
976                                                  int KL, int KU) {
977        validate();
978        rsnScriptIntrinsicBLAS_Double(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alpha, A, B, beta, C, incX, incY, KL, KU);
979    }
980
981    native void rsnScriptIntrinsicBLAS_Complex(long con, long id, int func, int TransA,
982                                               int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
983                                               float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY,
984                                               int KL, int KU);
985    synchronized void nScriptIntrinsicBLAS_Complex(long id, int func, int TransA,
986                                                   int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
987                                                   float alphaX, float alphaY, long A, long B, float betaX, float betaY, long C, int incX, int incY,
988                                                   int KL, int KU) {
989        validate();
990        rsnScriptIntrinsicBLAS_Complex(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alphaX, alphaY, A, B, betaX, betaY, C, incX, incY, KL, KU);
991    }
992
993    native void rsnScriptIntrinsicBLAS_Z(long con, long id, int func, int TransA,
994                                         int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
995                                         double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY,
996                                         int KL, int KU);
997    synchronized void nScriptIntrinsicBLAS_Z(long id, int func, int TransA,
998                                             int TransB, int Side, int Uplo, int Diag, int M, int N, int K,
999                                             double alphaX, double alphaY, long A, long B, double betaX, double betaY, long C, int incX, int incY,
1000                                             int KL, int KU) {
1001        validate();
1002        rsnScriptIntrinsicBLAS_Z(mContext, id, func, TransA, TransB, Side, Uplo, Diag, M, N, K, alphaX, alphaY, A, B, betaX, betaY, C, incX, incY, KL, KU);
1003    }
1004
1005    native void rsnScriptIntrinsicBLAS_BNNM(long con, long id, int M, int N, int K,
1006                                             long A, int a_offset, long B, int b_offset, long C, int c_offset,
1007                                             int c_mult_int);
1008    synchronized void nScriptIntrinsicBLAS_BNNM(long id, int M, int N, int K,
1009                                             long A, int a_offset, long B, int b_offset, long C, int c_offset,
1010                                             int c_mult_int) {
1011        validate();
1012        rsnScriptIntrinsicBLAS_BNNM(mContext, id, M, N, K, A, a_offset, B, b_offset, C, c_offset, c_mult_int);
1013    }
1014
1015
1016
1017    long     mDev;
1018    long     mContext;
1019    private boolean mDestroyed = false;
1020
1021    @SuppressWarnings({"FieldCanBeLocal"})
1022    MessageThread mMessageThread;
1023
1024    Element mElement_U8;
1025    Element mElement_I8;
1026    Element mElement_U16;
1027    Element mElement_I16;
1028    Element mElement_U32;
1029    Element mElement_I32;
1030    Element mElement_U64;
1031    Element mElement_I64;
1032    Element mElement_F16;
1033    Element mElement_F32;
1034    Element mElement_F64;
1035    Element mElement_BOOLEAN;
1036
1037    Element mElement_ELEMENT;
1038    Element mElement_TYPE;
1039    Element mElement_ALLOCATION;
1040    Element mElement_SAMPLER;
1041    Element mElement_SCRIPT;
1042    Element mElement_MESH;
1043    Element mElement_PROGRAM_FRAGMENT;
1044    Element mElement_PROGRAM_VERTEX;
1045    Element mElement_PROGRAM_RASTER;
1046    Element mElement_PROGRAM_STORE;
1047    Element mElement_FONT;
1048
1049    Element mElement_A_8;
1050    Element mElement_RGB_565;
1051    Element mElement_RGB_888;
1052    Element mElement_RGBA_5551;
1053    Element mElement_RGBA_4444;
1054    Element mElement_RGBA_8888;
1055
1056    Element mElement_HALF_2;
1057    Element mElement_HALF_3;
1058    Element mElement_HALF_4;
1059
1060    Element mElement_FLOAT_2;
1061    Element mElement_FLOAT_3;
1062    Element mElement_FLOAT_4;
1063
1064    Element mElement_DOUBLE_2;
1065    Element mElement_DOUBLE_3;
1066    Element mElement_DOUBLE_4;
1067
1068    Element mElement_UCHAR_2;
1069    Element mElement_UCHAR_3;
1070    Element mElement_UCHAR_4;
1071
1072    Element mElement_CHAR_2;
1073    Element mElement_CHAR_3;
1074    Element mElement_CHAR_4;
1075
1076    Element mElement_USHORT_2;
1077    Element mElement_USHORT_3;
1078    Element mElement_USHORT_4;
1079
1080    Element mElement_SHORT_2;
1081    Element mElement_SHORT_3;
1082    Element mElement_SHORT_4;
1083
1084    Element mElement_UINT_2;
1085    Element mElement_UINT_3;
1086    Element mElement_UINT_4;
1087
1088    Element mElement_INT_2;
1089    Element mElement_INT_3;
1090    Element mElement_INT_4;
1091
1092    Element mElement_ULONG_2;
1093    Element mElement_ULONG_3;
1094    Element mElement_ULONG_4;
1095
1096    Element mElement_LONG_2;
1097    Element mElement_LONG_3;
1098    Element mElement_LONG_4;
1099
1100    Element mElement_YUV;
1101
1102    Element mElement_MATRIX_4X4;
1103    Element mElement_MATRIX_3X3;
1104    Element mElement_MATRIX_2X2;
1105
1106    Sampler mSampler_CLAMP_NEAREST;
1107    Sampler mSampler_CLAMP_LINEAR;
1108    Sampler mSampler_CLAMP_LINEAR_MIP_LINEAR;
1109    Sampler mSampler_WRAP_NEAREST;
1110    Sampler mSampler_WRAP_LINEAR;
1111    Sampler mSampler_WRAP_LINEAR_MIP_LINEAR;
1112    Sampler mSampler_MIRRORED_REPEAT_NEAREST;
1113    Sampler mSampler_MIRRORED_REPEAT_LINEAR;
1114    Sampler mSampler_MIRRORED_REPEAT_LINEAR_MIP_LINEAR;
1115
1116    ProgramStore mProgramStore_BLEND_NONE_DEPTH_TEST;
1117    ProgramStore mProgramStore_BLEND_NONE_DEPTH_NO_DEPTH;
1118    ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_TEST;
1119    ProgramStore mProgramStore_BLEND_ALPHA_DEPTH_NO_DEPTH;
1120
1121    ProgramRaster mProgramRaster_CULL_BACK;
1122    ProgramRaster mProgramRaster_CULL_FRONT;
1123    ProgramRaster mProgramRaster_CULL_NONE;
1124
1125    ///////////////////////////////////////////////////////////////////////////////////
1126    //
1127
1128    /**
1129     * The base class from which an application should derive in order
1130     * to receive RS messages from scripts. When a script calls {@code
1131     * rsSendToClient}, the data fields will be filled, and the run
1132     * method will be called on a separate thread.  This will occur
1133     * some time after {@code rsSendToClient} completes in the script,
1134     * as {@code rsSendToClient} is asynchronous. Message handlers are
1135     * not guaranteed to have completed when {@link
1136     * android.renderscript.RenderScript#finish} returns.
1137     *
1138     */
1139    public static class RSMessageHandler implements Runnable {
1140        protected int[] mData;
1141        protected int mID;
1142        protected int mLength;
1143        public void run() {
1144        }
1145    }
1146    /**
1147     * If an application is expecting messages, it should set this
1148     * field to an instance of {@link RSMessageHandler}.  This
1149     * instance will receive all the user messages sent from {@code
1150     * sendToClient} by scripts from this context.
1151     *
1152     */
1153    RSMessageHandler mMessageCallback = null;
1154
1155    public void setMessageHandler(RSMessageHandler msg) {
1156        mMessageCallback = msg;
1157    }
1158    public RSMessageHandler getMessageHandler() {
1159        return mMessageCallback;
1160    }
1161
1162    /**
1163     * Place a message into the message queue to be sent back to the message
1164     * handler once all previous commands have been executed.
1165     *
1166     * @param id
1167     * @param data
1168     */
1169    public void sendMessage(int id, int[] data) {
1170        nContextSendMessage(id, data);
1171    }
1172
1173    /**
1174     * The runtime error handler base class.  An application should derive from this class
1175     * if it wishes to install an error handler.  When errors occur at runtime,
1176     * the fields in this class will be filled, and the run method will be called.
1177     *
1178     */
1179    public static class RSErrorHandler implements Runnable {
1180        protected String mErrorMessage;
1181        protected int mErrorNum;
1182        public void run() {
1183        }
1184    }
1185
1186    /**
1187     * Application Error handler.  All runtime errors will be dispatched to the
1188     * instance of RSAsyncError set here.  If this field is null a
1189     * {@link RSRuntimeException} will instead be thrown with details about the error.
1190     * This will cause program termaination.
1191     *
1192     */
1193    RSErrorHandler mErrorCallback = null;
1194
1195    public void setErrorHandler(RSErrorHandler msg) {
1196        mErrorCallback = msg;
1197    }
1198    public RSErrorHandler getErrorHandler() {
1199        return mErrorCallback;
1200    }
1201
1202    /**
1203     * RenderScript worker thread priority enumeration.  The default value is
1204     * NORMAL.  Applications wishing to do background processing should set
1205     * their priority to LOW to avoid starving forground processes.
1206     */
1207    public enum Priority {
1208        // These values used to represent official thread priority values
1209        // now they are simply enums to be used by the runtime side
1210        LOW (15),
1211        NORMAL (-8);
1212
1213        int mID;
1214        Priority(int id) {
1215            mID = id;
1216        }
1217    }
1218
1219    void validateObject(BaseObj o) {
1220        if (o != null) {
1221            if (o.mRS != this) {
1222                throw new RSIllegalArgumentException("Attempting to use an object across contexts.");
1223            }
1224        }
1225    }
1226
1227    void validate() {
1228        if (mContext == 0) {
1229            throw new RSInvalidStateException("Calling RS with no Context active.");
1230        }
1231    }
1232
1233
1234    /**
1235     * Change the priority of the worker threads for this context.
1236     *
1237     * @param p New priority to be set.
1238     */
1239    public void setPriority(Priority p) {
1240        validate();
1241        nContextSetPriority(p.mID);
1242    }
1243
1244    static class MessageThread extends Thread {
1245        RenderScript mRS;
1246        boolean mRun = true;
1247        int[] mAuxData = new int[2];
1248
1249        static final int RS_MESSAGE_TO_CLIENT_NONE = 0;
1250        static final int RS_MESSAGE_TO_CLIENT_EXCEPTION = 1;
1251        static final int RS_MESSAGE_TO_CLIENT_RESIZE = 2;
1252        static final int RS_MESSAGE_TO_CLIENT_ERROR = 3;
1253        static final int RS_MESSAGE_TO_CLIENT_USER = 4;
1254        static final int RS_MESSAGE_TO_CLIENT_NEW_BUFFER = 5;
1255
1256        static final int RS_ERROR_FATAL_DEBUG = 0x0800;
1257        static final int RS_ERROR_FATAL_UNKNOWN = 0x1000;
1258
1259        MessageThread(RenderScript rs) {
1260            super("RSMessageThread");
1261            mRS = rs;
1262
1263        }
1264
1265        public void run() {
1266            // This function is a temporary solution.  The final solution will
1267            // used typed allocations where the message id is the type indicator.
1268            int[] rbuf = new int[16];
1269            mRS.nContextInitToClient(mRS.mContext);
1270            while(mRun) {
1271                rbuf[0] = 0;
1272                int msg = mRS.nContextPeekMessage(mRS.mContext, mAuxData);
1273                int size = mAuxData[1];
1274                int subID = mAuxData[0];
1275
1276                if (msg == RS_MESSAGE_TO_CLIENT_USER) {
1277                    if ((size>>2) >= rbuf.length) {
1278                        rbuf = new int[(size + 3) >> 2];
1279                    }
1280                    if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
1281                        RS_MESSAGE_TO_CLIENT_USER) {
1282                        throw new RSDriverException("Error processing message from RenderScript.");
1283                    }
1284
1285                    if(mRS.mMessageCallback != null) {
1286                        mRS.mMessageCallback.mData = rbuf;
1287                        mRS.mMessageCallback.mID = subID;
1288                        mRS.mMessageCallback.mLength = size;
1289                        mRS.mMessageCallback.run();
1290                    } else {
1291                        throw new RSInvalidStateException("Received a message from the script with no message handler installed.");
1292                    }
1293                    continue;
1294                }
1295
1296                if (msg == RS_MESSAGE_TO_CLIENT_ERROR) {
1297                    String e = mRS.nContextGetErrorMessage(mRS.mContext);
1298
1299                    // Throw RSRuntimeException under the following conditions:
1300                    //
1301                    // 1) It is an unknown fatal error.
1302                    // 2) It is a debug fatal error, and we are not in a
1303                    //    debug context.
1304                    // 3) It is a debug fatal error, and we do not have an
1305                    //    error callback.
1306                    if (subID >= RS_ERROR_FATAL_UNKNOWN ||
1307                        (subID >= RS_ERROR_FATAL_DEBUG &&
1308                         (mRS.mContextType != ContextType.DEBUG ||
1309                          mRS.mErrorCallback == null))) {
1310                        throw new RSRuntimeException("Fatal error " + subID + ", details: " + e);
1311                    }
1312
1313                    if(mRS.mErrorCallback != null) {
1314                        mRS.mErrorCallback.mErrorMessage = e;
1315                        mRS.mErrorCallback.mErrorNum = subID;
1316                        mRS.mErrorCallback.run();
1317                    } else {
1318                        android.util.Log.e(LOG_TAG, "non fatal RS error, " + e);
1319                        // Do not throw here. In these cases, we do not have
1320                        // a fatal error.
1321                    }
1322                    continue;
1323                }
1324
1325                if (msg == RS_MESSAGE_TO_CLIENT_NEW_BUFFER) {
1326                    if (mRS.nContextGetUserMessage(mRS.mContext, rbuf) !=
1327                        RS_MESSAGE_TO_CLIENT_NEW_BUFFER) {
1328                        throw new RSDriverException("Error processing message from RenderScript.");
1329                    }
1330                    long bufferID = ((long)rbuf[1] << 32L) + ((long)rbuf[0] & 0xffffffffL);
1331                    Allocation.sendBufferNotification(bufferID);
1332                    continue;
1333                }
1334
1335                // 2: teardown.
1336                // But we want to avoid starving other threads during
1337                // teardown by yielding until the next line in the destructor
1338                // can execute to set mRun = false
1339                try {
1340                    sleep(1, 0);
1341                } catch(InterruptedException e) {
1342                }
1343            }
1344            //Log.d(LOG_TAG, "MessageThread exiting.");
1345        }
1346    }
1347
1348    RenderScript(Context ctx) {
1349        mContextType = ContextType.NORMAL;
1350        if (ctx != null) {
1351            mApplicationContext = ctx.getApplicationContext();
1352        }
1353        mRWLock = new ReentrantReadWriteLock();
1354        try {
1355            registerNativeAllocation.invoke(sRuntime, 4 * 1024 * 1024); // 4MB for GC sake
1356        } catch (Exception e) {
1357            Log.e(RenderScript.LOG_TAG, "Couldn't invoke registerNativeAllocation:" + e);
1358            throw new RSRuntimeException("Couldn't invoke registerNativeAllocation:" + e);
1359        }
1360
1361    }
1362
1363    /**
1364     * Gets the application context associated with the RenderScript context.
1365     *
1366     * @return The application context.
1367     */
1368    public final Context getApplicationContext() {
1369        return mApplicationContext;
1370    }
1371
1372    /**
1373     * Create a RenderScript context.
1374     *
1375     * @param ctx The context.
1376     * @return RenderScript
1377     */
1378    private static RenderScript internalCreate(Context ctx, int sdkVersion, ContextType ct, int flags) {
1379        if (!sInitialized) {
1380            Log.e(LOG_TAG, "RenderScript.create() called when disabled; someone is likely to crash");
1381            return null;
1382        }
1383
1384        if ((flags & ~(CREATE_FLAG_LOW_LATENCY | CREATE_FLAG_LOW_POWER |
1385                       CREATE_FLAG_WAIT_FOR_ATTACH | CREATE_FLAG_OPT_LEVEL_0)) != 0) {
1386            throw new RSIllegalArgumentException("Invalid flags passed.");
1387        }
1388
1389        RenderScript rs = new RenderScript(ctx);
1390
1391        rs.mDev = rs.nDeviceCreate();
1392        rs.mContext = rs.nContextCreate(rs.mDev, flags, sdkVersion, ct.mID);
1393        rs.mContextType = ct;
1394        rs.mContextFlags = flags;
1395        rs.mContextSdkVersion = sdkVersion;
1396        if (rs.mContext == 0) {
1397            throw new RSDriverException("Failed to create RS context.");
1398        }
1399
1400        // set up cache directory for entire context
1401        final String CACHE_PATH = "com.android.renderscript.cache";
1402        File f = new File(RenderScriptCacheDir.mCacheDir, CACHE_PATH);
1403        String mCachePath = f.getAbsolutePath();
1404        f.mkdirs();
1405        rs.nContextSetCacheDir(mCachePath);
1406
1407        rs.mMessageThread = new MessageThread(rs);
1408        rs.mMessageThread.start();
1409        return rs;
1410    }
1411
1412    /**
1413     * calls create(ctx, ContextType.NORMAL, CREATE_FLAG_NONE)
1414     *
1415     * See documentation for @create for details
1416     *
1417     * @param ctx The context.
1418     * @return RenderScript
1419     */
1420    public static RenderScript create(Context ctx) {
1421        return create(ctx, ContextType.NORMAL);
1422    }
1423
1424    /**
1425     * calls create(ctx, ct, CREATE_FLAG_NONE)
1426     *
1427     * See documentation for @create for details
1428     *
1429     * @param ctx The context.
1430     * @param ct The type of context to be created.
1431     * @return RenderScript
1432     */
1433    public static RenderScript create(Context ctx, ContextType ct) {
1434        return create(ctx, ct, CREATE_FLAG_NONE);
1435    }
1436
1437
1438    /**
1439     * Gets or creates a RenderScript context of the specified type.
1440     *
1441     * The returned context will be cached for future reuse within
1442     * the process. When an application is finished using
1443     * RenderScript it should call releaseAllContexts()
1444     *
1445     * A process context is a context designed for easy creation and
1446     * lifecycle management.  Multiple calls to this function will
1447     * return the same object provided they are called with the same
1448     * options.  This allows it to be used any time a RenderScript
1449     * context is needed.
1450     *
1451     * Prior to API 23 this always created a new context.
1452     *
1453     * @param ctx The context.
1454     * @param ct The type of context to be created.
1455     * @param flags The OR of the CREATE_FLAG_* options desired
1456     * @return RenderScript
1457     */
1458    public static RenderScript create(Context ctx, ContextType ct, int flags) {
1459        int v = ctx.getApplicationInfo().targetSdkVersion;
1460        return create(ctx, v, ct, flags);
1461    }
1462
1463    /**
1464     * calls create(ctx, sdkVersion, ContextType.NORMAL, CREATE_FLAG_NONE)
1465     *
1466     * Used by the RenderScriptThunker to maintain backward compatibility.
1467     *
1468     * @hide
1469     * @param ctx The context.
1470     * @param sdkVersion The target SDK Version.
1471     * @return RenderScript
1472     */
1473    public static RenderScript create(Context ctx, int sdkVersion) {
1474        return create(ctx, sdkVersion, ContextType.NORMAL, CREATE_FLAG_NONE);
1475    }
1476
1477     /**
1478     * Gets or creates a RenderScript context of the specified type.
1479     *
1480     * @param ctx The context.
1481     * @param ct The type of context to be created.
1482     * @param sdkVersion The target SDK Version.
1483     * @param flags The OR of the CREATE_FLAG_* options desired
1484     * @return RenderScript
1485     */
1486    private static RenderScript create(Context ctx, int sdkVersion, ContextType ct, int flags) {
1487        if (sdkVersion < 23) {
1488            return internalCreate(ctx, sdkVersion, ct, flags);
1489        }
1490
1491        synchronized (mProcessContextList) {
1492            for (RenderScript prs : mProcessContextList) {
1493                if ((prs.mContextType == ct) &&
1494                    (prs.mContextFlags == flags) &&
1495                    (prs.mContextSdkVersion == sdkVersion)) {
1496
1497                    return prs;
1498                }
1499            }
1500
1501            RenderScript prs = internalCreate(ctx, sdkVersion, ct, flags);
1502            prs.mIsProcessContext = true;
1503            mProcessContextList.add(prs);
1504            return prs;
1505        }
1506    }
1507
1508    /**
1509     * Releases all the process contexts.  This is the same as
1510     * calling .destroy() on each unique context retreived with
1511     * create(...). If no contexts have been created this
1512     * function does nothing.
1513     *
1514     * Typically you call this when your application is losing focus
1515     * and will not be using a context for some time.
1516     *
1517     * This has no effect on a context created with
1518     * createMultiContext()
1519     */
1520    public static void releaseAllContexts() {
1521        ArrayList<RenderScript> oldList;
1522        synchronized (mProcessContextList) {
1523            oldList = mProcessContextList;
1524            mProcessContextList = new ArrayList<RenderScript>();
1525        }
1526
1527        for (RenderScript prs : oldList) {
1528            prs.mIsProcessContext = false;
1529            prs.destroy();
1530        }
1531        oldList.clear();
1532    }
1533
1534
1535
1536    /**
1537     * Create a RenderScript context.
1538     *
1539     * This is an advanced function intended for applications which
1540     * need to create more than one RenderScript context to be used
1541     * at the same time.
1542     *
1543     * If you need a single context please use create()
1544     *
1545     * @param ctx The context.
1546     * @return RenderScript
1547     */
1548    public static RenderScript createMultiContext(Context ctx, ContextType ct, int flags, int API_number) {
1549        return internalCreate(ctx, API_number, ct, flags);
1550    }
1551
1552
1553    /**
1554     * Print the currently available debugging information about the state of
1555     * the RS context to the log.
1556     *
1557     */
1558    public void contextDump() {
1559        validate();
1560        nContextDump(0);
1561    }
1562
1563    /**
1564     * Wait for any pending asynchronous opeations (such as copies to a RS
1565     * allocation or RS script executions) to complete.
1566     *
1567     */
1568    public void finish() {
1569        nContextFinish();
1570    }
1571
1572    private void helpDestroy() {
1573        boolean shouldDestroy = false;
1574        synchronized(this) {
1575            if (!mDestroyed) {
1576                shouldDestroy = true;
1577                mDestroyed = true;
1578            }
1579        }
1580
1581        if (shouldDestroy) {
1582            nContextFinish();
1583
1584            nContextDeinitToClient(mContext);
1585            mMessageThread.mRun = false;
1586
1587            // Wait for mMessageThread to join.  Try in a loop, in case this thread gets interrupted
1588            // during the wait.  If interrupted, set the "interrupted" status of the current thread.
1589            boolean hasJoined = false, interrupted = false;
1590            while (!hasJoined) {
1591                try {
1592                    mMessageThread.join();
1593                    hasJoined = true;
1594                } catch (InterruptedException e) {
1595                    interrupted = true;
1596                }
1597            }
1598            if (interrupted) {
1599                Log.v(LOG_TAG, "Interrupted during wait for MessageThread to join");
1600                Thread.currentThread().interrupt();
1601            }
1602
1603            nContextDestroy();
1604
1605            nDeviceDestroy(mDev);
1606            mDev = 0;
1607        }
1608    }
1609
1610    protected void finalize() throws Throwable {
1611        helpDestroy();
1612        super.finalize();
1613    }
1614
1615
1616    /**
1617     * Destroys this RenderScript context.  Once this function is called,
1618     * using this context or any objects belonging to this context is
1619     * illegal.
1620     *
1621     * API 23+, this function is a NOP if the context was created
1622     * with create().  Please use releaseAllContexts() to clean up
1623     * contexts created with the create function.
1624     *
1625     */
1626    public void destroy() {
1627        if (mIsProcessContext) {
1628            // users cannot destroy a process context
1629            return;
1630        }
1631        validate();
1632        helpDestroy();
1633    }
1634
1635    boolean isAlive() {
1636        return mContext != 0;
1637    }
1638
1639    long safeID(BaseObj o) {
1640        if(o != null) {
1641            return o.getID(this);
1642        }
1643        return 0;
1644    }
1645}
1646