RenderScript.java revision 9db3d07b9620b4269ab33f78604a36327e536ce1
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 = "libRS_jni";
34    private static final boolean DEBUG  = false;
35    @SuppressWarnings({"UnusedDeclaration", "deprecation"})
36    private 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    private static boolean sInitialized;
46    native private 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  nContextCreate(int dev, Surface sur, int ver, boolean useDepth);
66    native void nContextDestroy(int con);
67    native void nContextSetSurface(Surface sur);
68
69    native void nContextBindRootScript(int script);
70    native void nContextBindSampler(int sampler, int slot);
71    native void nContextBindProgramFragmentStore(int pfs);
72    native void nContextBindProgramFragment(int pf);
73    native void nContextBindProgramVertex(int pf);
74    native void nContextBindProgramRaster(int pr);
75    native void nContextAddDefineI32(String name, int value);
76    native void nContextAddDefineF(String name, float value);
77    native void nContextPause();
78    native void nContextResume();
79    native int nContextGetMessage(int[] data, boolean wait);
80    native void nContextInitToClient();
81    native void nContextDeinitToClient();
82
83    native void nAssignName(int obj, byte[] name);
84    native void nObjDestroy(int id);
85    native void nObjDestroyOOB(int id);
86    native int  nFileOpen(byte[] name);
87
88    native void nElementBegin();
89    native void nElementAdd(int kind, int type, boolean norm, int bits, String s);
90    native int  nElementCreate();
91
92    native void nTypeBegin(int elementID);
93    native void nTypeAdd(int dim, int val);
94    native int  nTypeCreate();
95    native void nTypeFinalDestroy(Type t);
96    native void nTypeSetupFields(Type t, int[] types, int[] bits, Field[] IDs);
97
98    native int  nAllocationCreateTyped(int type);
99    native int  nAllocationCreateFromBitmap(int dstFmt, boolean genMips, Bitmap bmp);
100    native int  nAllocationCreateFromBitmapBoxed(int dstFmt, boolean genMips, Bitmap bmp);
101    native int  nAllocationCreateFromAssetStream(int dstFmt, boolean genMips, int assetStream);
102
103    native void nAllocationUploadToTexture(int alloc, int baseMioLevel);
104    native void nAllocationUploadToBufferObject(int alloc);
105
106    native void nAllocationSubData1D(int id, int off, int count, int[] d, int sizeBytes);
107    native void nAllocationSubData1D(int id, int off, int count, short[] d, int sizeBytes);
108    native void nAllocationSubData1D(int id, int off, int count, byte[] d, int sizeBytes);
109    native void nAllocationSubData1D(int id, int off, int count, float[] d, int sizeBytes);
110
111    native void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, int[] d, int sizeBytes);
112    native void nAllocationSubData2D(int id, int xoff, int yoff, int w, int h, float[] d, int sizeBytes);
113    native void nAllocationRead(int id, int[] d);
114    native void nAllocationRead(int id, float[] d);
115    native void nAllocationSubDataFromObject(int id, Type t, int offset, Object o);
116    native void nAllocationSubReadFromObject(int id, Type t, int offset, Object o);
117
118    native void nAdapter1DBindAllocation(int ad, int alloc);
119    native void nAdapter1DSetConstraint(int ad, int dim, int value);
120    native void nAdapter1DData(int ad, int[] d);
121    native void nAdapter1DData(int ad, float[] d);
122    native void nAdapter1DSubData(int ad, int off, int count, int[] d);
123    native void nAdapter1DSubData(int ad, int off, int count, float[] d);
124    native int  nAdapter1DCreate();
125
126    native void nAdapter2DBindAllocation(int ad, int alloc);
127    native void nAdapter2DSetConstraint(int ad, int dim, int value);
128    native void nAdapter2DData(int ad, int[] d);
129    native void nAdapter2DData(int ad, float[] d);
130    native void nAdapter2DSubData(int ad, int xoff, int yoff, int w, int h, int[] d);
131    native void nAdapter2DSubData(int ad, int xoff, int yoff, int w, int h, float[] d);
132    native int  nAdapter2DCreate();
133
134    native void nScriptBindAllocation(int script, int alloc, int slot);
135    native void nScriptSetClearColor(int script, float r, float g, float b, float a);
136    native void nScriptSetClearDepth(int script, float depth);
137    native void nScriptSetClearStencil(int script, int stencil);
138    native void nScriptSetTimeZone(int script, byte[] timeZone);
139    native void nScriptSetType(int type, boolean writable, String name, int slot);
140    native void nScriptSetRoot(boolean isRoot);
141    native void nScriptSetInvokable(String name, int slot);
142    native void nScriptInvoke(int id, int slot);
143
144    native void nScriptCBegin();
145    native void nScriptCSetScript(byte[] script, int offset, int length);
146    native int  nScriptCCreate();
147    native void nScriptCAddDefineI32(String name, int value);
148    native void nScriptCAddDefineF(String name, float value);
149
150    native void nSamplerBegin();
151    native void nSamplerSet(int param, int value);
152    native int  nSamplerCreate();
153
154    native void nProgramFragmentStoreBegin(int in, int out);
155    native void nProgramFragmentStoreDepthFunc(int func);
156    native void nProgramFragmentStoreDepthMask(boolean enable);
157    native void nProgramFragmentStoreColorMask(boolean r, boolean g, boolean b, boolean a);
158    native void nProgramFragmentStoreBlendFunc(int src, int dst);
159    native void nProgramFragmentStoreDither(boolean enable);
160    native int  nProgramFragmentStoreCreate();
161
162    native int  nProgramRasterCreate(int in, int out, boolean pointSmooth, boolean lineSmooth, boolean pointSprite);
163    native void nProgramRasterSetLineWidth(int pr, float v);
164    native void nProgramRasterSetPointSize(int pr, float v);
165
166    native void nProgramFragmentBegin(int in, int out, boolean pointSpriteEnable);
167    native void nProgramFragmentBindTexture(int vpf, int slot, int a);
168    native void nProgramFragmentBindSampler(int vpf, int slot, int s);
169    native void nProgramFragmentSetSlot(int slot, boolean enable, int env, int vt);
170    native int  nProgramFragmentCreate();
171
172    native void nProgramVertexBindAllocation(int pv, int mID);
173    native void nProgramVertexBegin(int inID, int outID);
174    native void nProgramVertexSetTextureMatrixEnable(boolean enable);
175    native void nProgramVertexAddLight(int id);
176    native int  nProgramVertexCreate();
177
178    native void nLightBegin();
179    native void nLightSetIsMono(boolean isMono);
180    native void nLightSetIsLocal(boolean isLocal);
181    native int  nLightCreate();
182    native void nLightSetColor(int l, float r, float g, float b);
183    native void nLightSetPosition(int l, float x, float y, float z);
184
185    native int  nSimpleMeshCreate(int batchID, int idxID, int[] vtxID, int prim);
186    native void nSimpleMeshBindVertex(int id, int alloc, int slot);
187    native void nSimpleMeshBindIndex(int id, int alloc);
188
189    native void nAnimationBegin(int attribCount, int keyframeCount);
190    native void nAnimationAdd(float time, float[] attribs);
191    native int  nAnimationCreate();
192
193    private int     mDev;
194    private int     mContext;
195    @SuppressWarnings({"FieldCanBeLocal"})
196    private Surface mSurface;
197    private MessageThread mMessageThread;
198
199
200    Element mElement_USER_U8;
201    Element mElement_USER_I8;
202    Element mElement_USER_U16;
203    Element mElement_USER_I16;
204    Element mElement_USER_U32;
205    Element mElement_USER_I32;
206    Element mElement_USER_FLOAT;
207
208    Element mElement_A_8;
209    Element mElement_RGB_565;
210    Element mElement_RGB_888;
211    Element mElement_RGBA_5551;
212    Element mElement_RGBA_4444;
213    Element mElement_RGBA_8888;
214
215    Element mElement_INDEX_16;
216    Element mElement_XY_F32;
217    Element mElement_XYZ_F32;
218
219    ///////////////////////////////////////////////////////////////////////////////////
220    //
221
222    public static class RSMessage implements Runnable {
223        protected int[] mData;
224        protected int mID;
225        public void run() {
226        }
227    }
228    public RSMessage mMessageCallback = null;
229
230    private static class MessageThread extends Thread {
231        RenderScript mRS;
232        boolean mRun = true;
233
234        MessageThread(RenderScript rs) {
235            super("RSMessageThread");
236            mRS = rs;
237
238        }
239
240        public void run() {
241            // This function is a temporary solution.  The final solution will
242            // used typed allocations where the message id is the type indicator.
243            int[] rbuf = new int[16];
244            mRS.nContextInitToClient();
245            while(mRun) {
246                int msg = mRS.nContextGetMessage(rbuf, true);
247                if (msg == 0) {
248                    // Should only happen during teardown.
249                    // But we want to avoid starving other threads during
250                    // teardown by yielding until the next line in the destructor
251                    // can execute to set mRun = false
252                    try {
253                        sleep(1, 0);
254                    } catch(InterruptedException e) {
255                    }
256                }
257                if(mRS.mMessageCallback != null) {
258                    mRS.mMessageCallback.mData = rbuf;
259                    mRS.mMessageCallback.mID = msg;
260                    mRS.mMessageCallback.run();
261                }
262                //Log.d("rs", "MessageThread msg " + msg + " v1 " + rbuf[0] + " v2 " + rbuf[1] + " v3 " +rbuf[2]);
263            }
264            Log.d("rs", "MessageThread exiting.");
265        }
266    }
267
268    public RenderScript(Surface sur, boolean useDepth, boolean forceSW) {
269        mSurface = sur;
270        mDev = nDeviceCreate();
271        if(forceSW) {
272            nDeviceSetConfig(mDev, 0, 1);
273        }
274        mContext = nContextCreate(mDev, mSurface, 0, useDepth);
275        Element.initPredefined(this);
276        mMessageThread = new MessageThread(this);
277        mMessageThread.start();
278    }
279
280    public void contextSetSurface(Surface sur) {
281        mSurface = sur;
282        nContextSetSurface(mSurface);
283    }
284
285    public void destroy() {
286        nContextDeinitToClient();
287        mMessageThread.mRun = false;
288
289        nContextDestroy(mContext);
290        mContext = 0;
291
292        nDeviceDestroy(mDev);
293        mDev = 0;
294    }
295
296    boolean isAlive() {
297        return mContext != 0;
298    }
299
300    void pause() {
301        nContextPause();
302    }
303
304    void resume() {
305        nContextResume();
306    }
307
308    //////////////////////////////////////////////////////////////////////////////////
309    // File
310
311    public class File extends BaseObj {
312        File(int id) {
313            super(RenderScript.this);
314            mID = id;
315        }
316    }
317
318    public File fileOpen(String s) throws IllegalStateException, IllegalArgumentException
319    {
320        if(s.length() < 1) {
321            throw new IllegalArgumentException("fileOpen does not accept a zero length string.");
322        }
323
324        try {
325            byte[] bytes = s.getBytes("UTF-8");
326            int id = nFileOpen(bytes);
327            return new File(id);
328        } catch (java.io.UnsupportedEncodingException e) {
329            throw new RuntimeException(e);
330        }
331    }
332
333
334    ///////////////////////////////////////////////////////////////////////////////////
335    // Root state
336
337    private int safeID(BaseObj o) {
338        if(o != null) {
339            return o.mID;
340        }
341        return 0;
342    }
343
344    public void contextBindRootScript(Script s) {
345        nContextBindRootScript(safeID(s));
346    }
347
348    public void contextBindProgramFragmentStore(ProgramStore p) {
349        nContextBindProgramFragmentStore(safeID(p));
350    }
351
352    public void contextBindProgramFragment(ProgramFragment p) {
353        nContextBindProgramFragment(safeID(p));
354    }
355
356    public void contextBindProgramRaster(ProgramRaster p) {
357        nContextBindProgramRaster(safeID(p));
358    }
359
360    public void contextBindProgramVertex(ProgramVertex p) {
361        nContextBindProgramVertex(safeID(p));
362    }
363
364}
365
366
367