Improve plasma sample code

Change-Id: I57f34786eafb0720f89c11bd69abf4354415d249
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..9300daa
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+samples/*/libs
+samples/*/obj
+samples/*/res/raw
+toolchains/*/prebuilt
diff --git a/build/core/definitions.mk b/build/core/definitions.mk
index 204fc29..e84415c 100644
--- a/build/core/definitions.mk
+++ b/build/core/definitions.mk
@@ -1143,7 +1143,7 @@
 _CC   := $$($$(my)CXX)
 _TEXT := "Compile++ $$(call get-src-file-text,$1)"
 
-$$(eval $$(call ev-build-source-file))
+$$(eval $$(call ev-build-file)) # FIXME 
 endef
 
 # -----------------------------------------------------------------------------
diff --git a/samples/bitmap-plasma-llvm/default.properties b/samples/bitmap-plasma-llvm/default.properties
index 9a2c9f6..0cdab95 100644
--- a/samples/bitmap-plasma-llvm/default.properties
+++ b/samples/bitmap-plasma-llvm/default.properties
@@ -8,4 +8,4 @@
 # project structure.
 
 # Project target.
-target=android-9
+target=android-12
diff --git a/samples/bitmap-plasma-llvm/jni/Android.mk b/samples/bitmap-plasma-llvm/jni/Android.mk
index 8e3cd13..c3fe5f1 100644
--- a/samples/bitmap-plasma-llvm/jni/Android.mk
+++ b/samples/bitmap-plasma-llvm/jni/Android.mk
@@ -6,7 +6,7 @@
 LOCAL_LDFLAGS := -L/usr/local/google/work/m/out/target/product/crespo4g/system/lib/
 
 LOCAL_MODULE    := plasma
-LOCAL_SRC_FILES := plasmaLLVM.c
+LOCAL_SRC_FILES := plasmaLLVM.cpp
 LOCAL_LDLIBS    := -lm -llog -ljnigraphics -lbcc
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/samples/bitmap-plasma-llvm/jni/plasmaLLVM.c b/samples/bitmap-plasma-llvm/jni/plasmaLLVM.cpp
similarity index 84%
rename from samples/bitmap-plasma-llvm/jni/plasmaLLVM.c
rename to samples/bitmap-plasma-llvm/jni/plasmaLLVM.cpp
index 64edc3e..1343dcb 100644
--- a/samples/bitmap-plasma-llvm/jni/plasmaLLVM.c
+++ b/samples/bitmap-plasma-llvm/jni/plasmaLLVM.cpp
@@ -363,12 +363,9 @@
     s->lastTime = now;
 }
 
-void* rsdLookupRuntimeStub(void* pContext, char const* name) {
-    LOGE("ScriptC sym lookup failed for %s", name);
-    return NULL;
-}
-
-JNIEXPORT void JNICALL Java_com_example_plasma_llvm_PlasmaView_renderPlasma(JNIEnv * env, jobject  obj, jobject bitmap,  jlong  time_ms)
+extern "C" JNIEXPORT jint JNICALL Java_com_example_plasma_llvm_PlasmaView_nativeRenderPlasma
+    (JNIEnv * env, jobject  obj,
+     jobject bitmap,  jlong  time_ms, jbyteArray scriptRef, jint length, jboolean use_llvm)
 {
     AndroidBitmapInfo  info;
     void*              pixels;
@@ -377,6 +374,11 @@
     static int         init;
     static double      time_sum = 0;
     static int         count = 0;
+    static bool        last_mode = false;
+
+    if (last_mode != use_llvm)
+      count = 0, time_sum = 0;
+    last_mode = use_llvm;
 
     if (!init) {
         init_tables();
@@ -386,12 +388,12 @@
 
     if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {
         LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
-        return;
+        return -1;
     }
 
     if (info.format != ANDROID_BITMAP_FORMAT_RGB_565) {
         LOGE("Bitmap format is not RGB_565 !");
-        return;
+        return -1;
     }
 
     if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {
@@ -399,65 +401,55 @@
     }
 
 
-    //stats_startFrame(&stats);
+    if (use_llvm) {
+      double start_jit = now_ms();
+      
+      BCCScriptRef script_ref = bccCreateScript();
 
+      jbyte* script_ptr = (jbyte *)env->GetPrimitiveArrayCritical(scriptRef, (jboolean *)0);
 
-    /* Now fill the values with a nice little plasma */
-    //LOGI("Entering libplasma.so from JNI");
+      LOGE("BCC Script Len: %d", length);
+      if(bccReadBC(script_ref, "libplasma.bc", (const char*)script_ptr, length, 0)) {
+        LOGE("Error! Cannot bccReadBc");
+        return -1;
+      }
+      if (script_ptr) {
+        env->ReleasePrimitiveArrayCritical(scriptRef, script_ptr, 0);
+      }
 
-    double start_jit = now_ms();
+      if (bccLinkFile(script_ref, "/system/lib/libclcore.bc", 0)) {
+        LOGE("Error! Cannot bccLinkBC");
+        return -1;
+      }
 
-#define JIT 1
-
-#if JIT
-    BCCScriptRef script_ref = bccCreateScript();
-
-    if (bccRegisterSymbolCallback(script_ref, &rsdLookupRuntimeStub, NULL) != 0) {
-        LOGE("bcc: FAILS to register symbol callback");
-        return;
-    }
-
-    if (bccReadFile(script_ref, "/data/local/tmp/libplasma_portable.bc", 0)) {
-        LOGE("Error! Cannot bccReadFile");
-        return;
-    }
-    //LOGI("bccReadFile done.");
-#if 1
-  if (bccLinkFile(script_ref, "/system/lib/libclcore.bc", 0)) {
-    LOGE("Error! Cannot bccLinkBC");
-    return;
-  }
-  LOGI("bccLinkBC done.");
-#endif
-    if (bccPrepareExecutable(script_ref, "@@/data/data/com.example.plasma.llvm/plasmaLLVM.oBCC", 0)) {
+      if (bccPrepareExecutable(script_ref, "@@/data/data/com.example.plasma.llvm/plasmaLLVM.oBCC", 0)) {
         LOGE("Error! Cannot bccPrepareExecutable");
-        return;
-    }
-    //LOGI("bccPrepareExecutable done.");
+        return -1;
+      }
 
-    double start_run = now_ms();
+      double start_run = now_ms();
 
-    typedef void (*pPlasmaType)(uint32_t, uint32_t, uint32_t, double, uint16_t*, void*, void*);
-    pPlasmaType nativeFunc = (pPlasmaType)bccGetFuncAddr(script_ref, "root");
-    if (nativeFunc == NULL) {
+      typedef void (*pPlasmaType)(uint32_t, uint32_t, uint32_t, double, uint16_t*, void*, void*);
+      pPlasmaType nativeFunc = (pPlasmaType)bccGetFuncAddr(script_ref, "root");
+      if (nativeFunc == NULL) {
         LOGE("Error! Cannot find fill_plasma()");
-        return;
+        return -1;
+      }
+      nativeFunc(info.width, info.height, info.stride, time_ms, palette, pixels, angle_sin_tab);
+      bccDisposeScript(script_ref);
+      double diff = now_ms()-start_run;
+      LOGI("LLVM Time JIT: %.2lf , Run: %.2lf, Avg: %.2lf", start_run-start_jit, diff, time_sum / count);
+      time_sum += diff + start_run - start_jit;
+    } else {
+      double start_run = now_ms();
+      fill_plasma(&info, pixels, time_ms );
+      double diff = now_ms()-start_run;
+      LOGI("GCC Time Run: %.2lf, Avg: %.2lf", diff, time_sum / count);
+      time_sum += diff;
     }
-    nativeFunc(info.width, info.height, info.stride, time_ms, palette, pixels, angle_sin_tab);
-    bccDisposeScript(script_ref);
-    double diff = now_ms()-start_run;
-    LOGI("LLVM Time JIT: %.2lf , Run: %.2lf, Avg: %.2lf", start_run-start_jit, diff, time_sum / count);
-#else
-    double start_run = now_ms();
-    fill_plasma(&info, pixels, time_ms );
-    double diff = now_ms()-start_run;
-    LOGI("GCC Time Run: %.2lf, Avg: %.2lf", diff, time_sum / count);
-#endif
-    time_sum += diff;
     count++;
 
-
     AndroidBitmap_unlockPixels(env, bitmap);
 
-    //stats_endFrame(&stats);
+    return count * 1000.0 / time_sum;
 }
diff --git a/samples/bitmap-plasma-llvm/res/menu/menu.xml b/samples/bitmap-plasma-llvm/res/menu/menu.xml
new file mode 100644
index 0000000..4a0dfe3
--- /dev/null
+++ b/samples/bitmap-plasma-llvm/res/menu/menu.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+  <item android:id="@+id/switch_mode"
+  android:title="@string/switch_mode" />
+</menu>
+
diff --git a/samples/bitmap-plasma-llvm/res/values/strings.xml b/samples/bitmap-plasma-llvm/res/values/strings.xml
index a6c827f..1e05310 100644
--- a/samples/bitmap-plasma-llvm/res/values/strings.xml
+++ b/samples/bitmap-plasma-llvm/res/values/strings.xml
@@ -1,4 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
-    <string name="app_name">PlasmaLLVM</string>
+    <string name="app_name">PlasmaDemo</string>
+    <string name="switch_mode">Switch Mode</string>
 </resources>
diff --git a/samples/bitmap-plasma-llvm/src/com/example/plasma/llvm/Plasma.java b/samples/bitmap-plasma-llvm/src/com/example/plasma/llvm/Plasma.java
index 8d61273..5aabdf4 100644
--- a/samples/bitmap-plasma-llvm/src/com/example/plasma/llvm/Plasma.java
+++ b/samples/bitmap-plasma-llvm/src/com/example/plasma/llvm/Plasma.java
@@ -19,8 +19,20 @@
 import android.os.Bundle;
 import android.content.Context;
 import android.view.View;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.MenuInflater;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
+import android.graphics.Paint;
+
+import java.io.InputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+
+import android.content.res.Resources;
 
 public class Plasma extends Activity
 {
@@ -29,9 +41,31 @@
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
-        setContentView(new PlasmaView(this));
+        view = new PlasmaView(this);
+        setContentView(view);
     }
 
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        MenuInflater inflater = getMenuInflater();
+        inflater.inflate(R.menu.menu, menu);
+        return true;
+    }
+    
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        switch (item.getItemId()) {
+            case R.id.switch_mode:
+                view.switchMode();
+
+                return true;
+            default:
+                return super.onOptionsItemSelected(item);
+        }
+    }
+   
+    private PlasmaView view;
+
     /* load our native library */
     static {
         System.loadLibrary("plasma");
@@ -43,22 +77,61 @@
     private long mStartTime;
 
     /* implementend by libplasma.so */
-    private static native void renderPlasma(Bitmap  bitmap, long time_ms);
+    private static native int nativeRenderPlasma(Bitmap  bitmap, long time_ms, byte[] script, int scriptLength, boolean useLLVM);
+
+    private byte[] pgm;
+    private int pgmLength;
+    
+    private boolean mode = true;
+    private Paint paint = null;
+
+    public void switchMode() {
+        mode = !mode;
+    }
 
     public PlasmaView(Context context) {
         super(context);
 
-        final int W = 480;
-        final int H = 800;
-
-        mBitmap = Bitmap.createBitmap(W, H, Bitmap.Config.RGB_565);
         mStartTime = System.currentTimeMillis();
+        
+        InputStream is = null;
+        is = getResources().openRawResource(R.raw.libplasma_portable);
+        try {
+            try {
+                pgm = new byte[1024];
+                pgmLength = 0;
+                while(true) {
+                    int bytesLeft = pgm.length - pgmLength;
+                    if (bytesLeft == 0) {
+                        byte[] buf2 = new byte[pgm.length * 2];
+                        System.arraycopy(pgm, 0, buf2, 0, pgm.length);
+                        pgm = buf2;
+                        bytesLeft = pgm.length - pgmLength;
+                    }
+                    int bytesRead = is.read(pgm, pgmLength, bytesLeft);
+                    if (bytesRead <= 0) {
+                        break;
+                    }
+                    pgmLength += bytesRead;
+                }
+            } finally {
+                is.close();
+            }
+        } catch(IOException e) {
+            throw new Resources.NotFoundException();
+        }
+        paint = new Paint();
+        paint.setTextSize(40);
     }
 
     @Override protected void onDraw(Canvas canvas) {
-        //canvas.drawColor(0xFFCCCCCC);
-        renderPlasma(mBitmap, System.currentTimeMillis() - mStartTime);
+        if (mBitmap == null || mBitmap.getWidth() != getWidth() || mBitmap.getHeight() != getHeight())
+            mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.RGB_565);
+
+        int frameRate = nativeRenderPlasma(mBitmap, System.currentTimeMillis() - mStartTime, pgm, pgmLength, mode);
         canvas.drawBitmap(mBitmap, 0, 0, null);
+        canvas.drawText((mode ? "LLVM" : "GCC") + " Frame: " + Integer.toString(frameRate), 100, 100, paint);
+        
         // force a redraw, with a different time-based pattern.
         invalidate();
     }