RenderScript.java revision c2908e60c9b021fb4bb69acff8d49981dd4dade8
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.graphics.Bitmap;
22import android.graphics.BitmapFactory;
23import android.util.Config;
24import android.util.Log;
25import android.view.Surface;
26
27
28/**
29 * @hide
30 *
31 **/
32public class RenderScript {
33    static final String LOG_TAG = "RenderScript_jni";
34    protected static final boolean DEBUG  = false;
35    @SuppressWarnings({"UnusedDeclaration", "deprecation"})
36    protected static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
37
38
39
40     /*
41     * We use a class initializer to allow the native code to cache some
42     * field offsets.
43     */
44    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
45    protected static boolean sInitialized;
46    native protected static void _nInit();
47
48
49    static {
50        sInitialized = false;
51        try {
52            System.loadLibrary("rs_jni");
53            _nInit();
54            sInitialized = true;
55        } catch (UnsatisfiedLinkError e) {
56            Log.d(LOG_TAG, "RenderScript JNI library not found!");
57        }
58    }
59
60    native void nInitElements(int a8, int rgba4444, int rgba8888, int rgb565);
61
62    native int  nDeviceCreate();
63    native void nDeviceDestroy(int dev);
64    native void nDeviceSetConfig(int dev, int param, int value);
65    native int  nContextCreateGL(int dev, int ver, boolean useDepth);
66    native int  nContextCreate(int dev, int ver);
67    native void nContextDestroy(int con);
68    native void nContextSetSurface(int w, int h, Surface sur);
69    native void nContextSetPriority(int p);
70    native void nContextDump(int bits);
71
72    native void nContextBindRootScript(int script);
73    native void nContextBindSampler(int sampler, int slot);
74    native void nContextBindProgramFragmentStore(int pfs);
75    native void nContextBindProgramFragment(int pf);
76    native void nContextBindProgramVertex(int pf);
77    native void nContextBindProgramRaster(int pr);
78    native void nContextPause();
79    native void nContextResume();
80    native int nContextGetMessage(int[] data, boolean wait);
81    native void nContextInitToClient();
82    native void nContextDeinitToClient();
83
84    native void nAssignName(int obj, byte[] name);
85    native void nObjDestroy(int id);
86    native void nObjDestroyOOB(int id);
87    native int  nFileOpen(byte[] name);
88
89
90    native int  nElementCreate(int type, int kind, boolean norm, int vecSize);
91    native int  nElementCreate2(int[] elements, String[] names);
92
93    native void nTypeBegin(int elementID);
94    native void nTypeAdd(int dim, int val);
95    native int  nTypeCreate();
96    native void nTypeFinalDestroy(Type t);
97    native void nTypeSetupFields(Type t, int[] types, int[] bits, Field[] IDs);
98
99    native int  nAllocationCreateTyped(int type);
100    native int  nAllocationCreateFromBitmap(int dstFmt, boolean genMips, Bitmap bmp);
101    native int  nAllocationCreateFromBitmapBoxed(int dstFmt, boolean genMips, Bitmap bmp);
102    native int  nAllocationCreateFromAssetStream(int dstFmt, boolean genMips, int assetStream);
103
104    native void nAllocationUploadToTexture(int alloc, boolean genMips, int baseMioLevel);
105    native void nAllocationUploadToBufferObject(int alloc);
106
107    native void nAllocationSubData1D(int id, int off, int count, int[] d, int sizeBytes);
108    native void nAllocationSubData1D(int id, int off, int count, short[] d, int sizeBytes);
109    native void nAllocationSubData1D(int id, int off, int count, byte[] d, int sizeBytes);
110    native void nAllocationSubData1D(int id, int off, int count, float[] d, int sizeBytes);
111
112    native void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, int[] d, int sizeBytes);
113    native void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, float[] d, int sizeBytes);
114    native void nAllocationRead(int id, int[] d);
115    native void nAllocationRead(int id, float[] d);
116    native void nAllocationSubDataFromObject(int id, Type t, int offset, Object o);
117    native void nAllocationSubReadFromObject(int id, Type t, int offset, Object o);
118
119    native void nAdapter1DBindAllocation(int ad, int alloc);
120    native void nAdapter1DSetConstraint(int ad, int dim, int value);
121    native void nAdapter1DData(int ad, int[] d);
122    native void nAdapter1DData(int ad, float[] d);
123    native void nAdapter1DSubData(int ad, int off, int count, int[] d);
124    native void nAdapter1DSubData(int ad, int off, int count, float[] d);
125    native int  nAdapter1DCreate();
126
127    native void nAdapter2DBindAllocation(int ad, int alloc);
128    native void nAdapter2DSetConstraint(int ad, int dim, int value);
129    native void nAdapter2DData(int ad, int[] d);
130    native void nAdapter2DData(int ad, float[] d);
131    native void nAdapter2DSubData(int ad, int xoff, int yoff, int w, int h, int[] d);
132    native void nAdapter2DSubData(int ad, int xoff, int yoff, int w, int h, float[] d);
133    native int  nAdapter2DCreate();
134
135    native void nScriptBindAllocation(int script, int alloc, int slot);
136    native void nScriptSetClearColor(int script, float r, float g, float b, float a);
137    native void nScriptSetClearDepth(int script, float depth);
138    native void nScriptSetClearStencil(int script, int stencil);
139    native void nScriptSetTimeZone(int script, byte[] timeZone);
140    native void nScriptSetType(int type, boolean writable, String name, int slot);
141    native void nScriptSetRoot(boolean isRoot);
142    native void nScriptSetInvokable(String name, int slot);
143    native void nScriptInvoke(int id, int slot);
144
145    native void nScriptCBegin();
146    native void nScriptCSetScript(byte[] script, int offset, int length);
147    native int  nScriptCCreate();
148    native void nScriptCAddDefineI32(String name, int value);
149    native void nScriptCAddDefineF(String name, float value);
150
151    native void nSamplerBegin();
152    native void nSamplerSet(int param, int value);
153    native int  nSamplerCreate();
154
155    native void nProgramFragmentStoreBegin(int in, int out);
156    native void nProgramFragmentStoreDepthFunc(int func);
157    native void nProgramFragmentStoreDepthMask(boolean enable);
158    native void nProgramFragmentStoreColorMask(boolean r, boolean g, boolean b, boolean a);
159    native void nProgramFragmentStoreBlendFunc(int src, int dst);
160    native void nProgramFragmentStoreDither(boolean enable);
161    native int  nProgramFragmentStoreCreate();
162
163    native int  nProgramRasterCreate(int in, int out, boolean pointSmooth, boolean lineSmooth, boolean pointSprite);
164    native void nProgramRasterSetLineWidth(int pr, float v);
165    native void nProgramRasterSetPointSize(int pr, float v);
166
167    native void nProgramBindConstants(int pv, int slot, int mID);
168    native void nProgramBindTexture(int vpf, int slot, int a);
169    native void nProgramBindSampler(int vpf, int slot, int s);
170
171    native int  nProgramFragmentCreate(int[] params);
172    native int  nProgramFragmentCreate2(String shader, int[] params);
173
174    native int  nProgramVertexCreate(boolean texMat);
175    native int  nProgramVertexCreate2(String shader, int[] params);
176
177    native void nLightBegin();
178    native void nLightSetIsMono(boolean isMono);
179    native void nLightSetIsLocal(boolean isLocal);
180    native int  nLightCreate();
181    native void nLightSetColor(int l, float r, float g, float b);
182    native void nLightSetPosition(int l, float x, float y, float z);
183
184    native int  nSimpleMeshCreate(int batchID, int idxID, int[] vtxID, int prim);
185    native void nSimpleMeshBindVertex(int id, int alloc, int slot);
186    native void nSimpleMeshBindIndex(int id, int alloc);
187
188    native void nAnimationBegin(int attribCount, int keyframeCount);
189    native void nAnimationAdd(float time, float[] attribs);
190    native int  nAnimationCreate();
191
192    protected int     mDev;
193    protected int     mContext;
194    @SuppressWarnings({"FieldCanBeLocal"})
195    protected MessageThread mMessageThread;
196
197    Element mElement_USER_U8;
198    Element mElement_USER_I8;
199    Element mElement_USER_U16;
200    Element mElement_USER_I16;
201    Element mElement_USER_U32;
202    Element mElement_USER_I32;
203    Element mElement_USER_F32;
204
205    Element mElement_A_8;
206    Element mElement_RGB_565;
207    Element mElement_RGB_888;
208    Element mElement_RGBA_5551;
209    Element mElement_RGBA_4444;
210    Element mElement_RGBA_8888;
211
212    Element mElement_INDEX_16;
213    Element mElement_POSITION_2;
214    Element mElement_POSITION_3;
215    Element mElement_TEXTURE_2;
216    Element mElement_NORMAL_3;
217    Element mElement_COLOR_U8_4;
218    Element mElement_COLOR_F32_4;
219
220    ///////////////////////////////////////////////////////////////////////////////////
221    //
222
223    public static class RSMessage implements Runnable {
224        protected int[] mData;
225        protected int mID;
226        public void run() {
227        }
228    }
229    public RSMessage mMessageCallback = null;
230
231    public enum Priority {
232        LOW (5),     //ANDROID_PRIORITY_BACKGROUND + 5
233        NORMAL (-4);  //ANDROID_PRIORITY_DISPLAY
234
235        int mID;
236        Priority(int id) {
237            mID = id;
238        }
239    }
240
241    void validate() {
242        if (mContext == 0) {
243            throw new IllegalStateException("Calling RS with no Context active.");
244        }
245    }
246
247    public void contextSetPriority(Priority p) {
248        validate();
249        nContextSetPriority(p.mID);
250    }
251
252    protected static class MessageThread extends Thread {
253        RenderScript mRS;
254        boolean mRun = true;
255
256        MessageThread(RenderScript rs) {
257            super("RSMessageThread");
258            mRS = rs;
259
260        }
261
262        public void run() {
263            // This function is a temporary solution.  The final solution will
264            // used typed allocations where the message id is the type indicator.
265            int[] rbuf = new int[16];
266            mRS.nContextInitToClient();
267            while(mRun) {
268                int msg = mRS.nContextGetMessage(rbuf, true);
269                if (msg == 0) {
270                    // Should only happen during teardown.
271                    // But we want to avoid starving other threads during
272                    // teardown by yielding until the next line in the destructor
273                    // can execute to set mRun = false
274                    try {
275                        sleep(1, 0);
276                    } catch(InterruptedException e) {
277                    }
278                }
279                if(mRS.mMessageCallback != null) {
280                    mRS.mMessageCallback.mData = rbuf;
281                    mRS.mMessageCallback.mID = msg;
282                    mRS.mMessageCallback.run();
283                }
284                //Log.d(LOG_TAG, "MessageThread msg " + msg + " v1 " + rbuf[0] + " v2 " + rbuf[1] + " v3 " +rbuf[2]);
285            }
286            Log.d(LOG_TAG, "MessageThread exiting.");
287        }
288    }
289
290    protected RenderScript() {
291    }
292
293    public static RenderScript create() {
294        RenderScript rs = new RenderScript();
295
296        rs.mDev = rs.nDeviceCreate();
297        rs.mContext = rs.nContextCreate(rs.mDev, 0);
298        rs.mMessageThread = new MessageThread(rs);
299        rs.mMessageThread.start();
300        Element.initPredefined(rs);
301        return rs;
302    }
303
304    public void contextDump(int bits) {
305        validate();
306        nContextDump(bits);
307    }
308
309    public void destroy() {
310        validate();
311        nContextDeinitToClient();
312        mMessageThread.mRun = false;
313
314        nContextDestroy(mContext);
315        mContext = 0;
316
317        nDeviceDestroy(mDev);
318        mDev = 0;
319    }
320
321    boolean isAlive() {
322        return mContext != 0;
323    }
324
325    ///////////////////////////////////////////////////////////////////////////////////
326    // Root state
327
328    protected int safeID(BaseObj o) {
329        if(o != null) {
330            return o.mID;
331        }
332        return 0;
333    }
334}
335
336
337