// called by AppThreadFunction
            public void ovrApp_BackButtonAction()
            {
                // 1484

                if (this.BackButtonState == ovrBackButtonState.BACK_BUTTON_STATE_PENDING_DOUBLE_TAP)
                {
                    //ALOGV("back button double tap");
                    this.BackButtonState = ovrBackButtonState.BACK_BUTTON_STATE_SKIP_UP;
                }
                else if (this.BackButtonState == ovrBackButtonState.BACK_BUTTON_STATE_PENDING_SHORT_PRESS && !this.BackButtonDown)
                {
                    if ((VrApi.vrapi_GetTimeInSeconds() - this.BackButtonDownStartTime) > VrApi_Android.BACK_BUTTON_DOUBLE_TAP_TIME_IN_SECONDS)
                    {
                        ConsoleExtensions.trace("back button short press");
                        //ALOGV("        ovr_StartSystemActivity( %s )", PUI_CONFIRM_QUIT);
                        VrApi_Android.ovr_StartSystemActivity(ref Java, VrApi.PUI_CONFIRM_QUIT, default(string));
                        this.BackButtonState = ovrBackButtonState.BACK_BUTTON_STATE_NONE;
                    }
                }
                else if (this.BackButtonState == ovrBackButtonState.BACK_BUTTON_STATE_NONE && this.BackButtonDown)
                {
                    if ((VrApi.vrapi_GetTimeInSeconds() - this.BackButtonDownStartTime) > VrApi_Android.BACK_BUTTON_LONG_PRESS_TIME_IN_SECONDS)
                    {
                        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150704/pui_global_menu
                        ConsoleExtensions.trace("back button long press, ovr_StartSystemActivity PUI_GLOBAL_MENU");
                        //ALOGV("        ovr_StartSystemActivity( %s )", PUI_GLOBAL_MENU);
                        VrApi_Android.ovr_StartSystemActivity(ref Java, VrApi.PUI_GLOBAL_MENU, null);
                        this.BackButtonState = ovrBackButtonState.BACK_BUTTON_STATE_SKIP_UP;
                    }
                }
            }
            // called by AppThreadFunction
            public void ovrApp_HandleVrModeChanges()
            {
                //ConsoleExtensions.tracei("enter ovrApp_HandleVrModeChanges, FrameIndex: ", (int)FrameIndex);

                // 1432
                if (this.NativeWindow != null && this.Egl.MainSurface == egl.EGL_NO_SURFACE)
                {
                    ConsoleExtensions.trace("ovrApp_HandleVrModeChanges, ovrEgl_CreateSurface");
                    this.Egl.ovrEgl_CreateSurface(this.NativeWindow);
                }

                if (this.Resumed != false && this.NativeWindow != null)
                {
                    if (this.Ovr == null)
                    {
                        var parms = VrApi_Helpers.vrapi_DefaultModeParms(ref Java);
                        parms.CpuLevel      = 2;
                        parms.GpuLevel      = 3;
                        parms.MainThreadTid = unistd.gettid();
#if MULTI_THREADED
                        // Also set the renderer thread to SCHED_FIFO.
                        parms.RenderThreadTid = ovrRenderThread_GetTid(&app->RenderThread);
#endif

                        //ALOGV("        eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface(EGL_DRAW));

                        ConsoleExtensions.trace("ovrApp_HandleVrModeChanges, vrapi_EnterVrMode");
                        this.Ovr = VrApi.vrapi_EnterVrMode(ref parms);

                        //ALOGV("        vrapi_EnterVrMode()");
                        //ALOGV("        eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface(EGL_DRAW));
                    }
                }
                else
                {
                    if (this.Ovr != null)
                    {
#if MULTI_THREADED
                        // Make sure the renderer thread is no longer using the ovrMobile.
                        ovrRenderThread_Wait(&app->RenderThread);
#endif
                        //ALOGV("        eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface(EGL_DRAW));

                        ConsoleExtensions.trace("ovrApp_HandleVrModeChanges, vrapi_LeaveVrMode");
                        VrApi.vrapi_LeaveVrMode(this.Ovr);
                        this.Ovr = null;

                        //ALOGV("        vrapi_LeaveVrMode()");
                        //ALOGV("        eglGetCurrentSurface( EGL_DRAW ) = %p", eglGetCurrentSurface(EGL_DRAW));
                    }
                }

                if (this.NativeWindow == null && this.Egl.MainSurface != egl.EGL_NO_SURFACE)
                {
                    ConsoleExtensions.trace("ovrApp_HandleVrModeChanges, ovrEgl_DestroySurface");
                    this.Egl.ovrEgl_DestroySurface();
                }
            }
            // java UI sends over to native, which the uses MQ to send over to bg thread? SharedMemory would be nice?
            // onKeyEvent
            public void ovrApp_HandleKeyEvent(keycodes.AKEYCODE keyCode, input.AInputEventAction action)
            {
                // 1513
                // cannot do this aliasing?
                //var app = this;

                // Handle GearVR back button.
                if (keyCode == keycodes.AKEYCODE.AKEYCODE_BACK)
                {
                    if (action == input.AInputEventAction.AKEY_EVENT_ACTION_DOWN)
                    {
                        if (!this.BackButtonDown)
                        {
                            if ((VrApi.vrapi_GetTimeInSeconds() - this.BackButtonDownStartTime) < VrApi_Android.BACK_BUTTON_DOUBLE_TAP_TIME_IN_SECONDS)
                            {
                                this.BackButtonState = ovrBackButtonState.BACK_BUTTON_STATE_PENDING_DOUBLE_TAP;
                            }
                            this.BackButtonDownStartTime = VrApi.vrapi_GetTimeInSeconds();
                        }
                        this.BackButtonDown = true;
                    }
                    else if (action == input.AInputEventAction.AKEY_EVENT_ACTION_UP)
                    {
                        if (this.BackButtonState == ovrBackButtonState.BACK_BUTTON_STATE_NONE)
                        {
                            if ((VrApi.vrapi_GetTimeInSeconds() - this.BackButtonDownStartTime) < VrApi_Android.BACK_BUTTON_SHORT_PRESS_TIME_IN_SECONDS)
                            {
                                this.BackButtonState = ovrBackButtonState.BACK_BUTTON_STATE_PENDING_SHORT_PRESS;
                            }
                        }
                        else if (this.BackButtonState == ovrBackButtonState.BACK_BUTTON_STATE_SKIP_UP)
                        {
                            this.BackButtonState = ovrBackButtonState.BACK_BUTTON_STATE_NONE;
                        }
                        this.BackButtonDown = false;
                    }
                    //return 1;
                }
                //return 0;
            }
            //I/DEBUG   ( 2941): pid: 31621, tid: 31653, name: Thread-653  >>> OVRWindWheelActivity.Activities <<<
            //I/DEBUG   ( 2941): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x8
            //I/DEBUG   ( 2941):     r0 00000000  r1 00000000  r2 ffffffff  r3 3e86c40e
            //I/DEBUG   ( 2941):     r4 3e86c40e  r5 ff4fffc0  r6 00000000  r7 3f800000
            //I/DEBUG   ( 2941):     r8 e22fe448  r9 3f772ed9  sl e22fe488  fp 00000bb5
            //I/DEBUG   ( 2941):     ip f73a0710  sp e22fe310  lr f7380375  pc f40fab72  cpsr 800f0030
            //I/DEBUG   ( 2941):
            //I/DEBUG   ( 2941): backtrace:
            //I/DEBUG   ( 2941):     #00 pc 00008b72  /data/app/OVRWindWheelActivity.Activities-1/lib/arm/libmain.so (OVRWindWheelNDK___ovrMatrix4f_CreateRotation+99)
            //I/DEBUG   ( 2941):     #01 pc 00008e61  /data/app/OVRWindWheelActivity.Activities-1/lib/arm/libmain.so (OVRWindWheelNDK_VrCubeWorld_ovrRenderer_ovrRenderer_RenderFrame+376)
            //I/DEBUG   ( 2941):     #02 pc 000098eb  /data/app/OVRWindWheelActivity.Activities-1/lib/arm/libmain.so (OVRWindWheelNDK_VrCubeWorld_ovrAppThread_AppThreadFunction+810)


            void AppThreadFunction()
            {
                // 1778
                ConsoleExtensions.trace("enter pthread_create AppThreadFunction, call vrapi_DefaultInitParms");

                var java = default(ovrJava);

                java.Vm = this.JavaVm;
                java.Vm.AttachCurrentThread(java.Vm, out java.Env, null);
                java.ActivityObject = this.ActivityObject;
                // 1785

                var initParms = VrApi_Helpers.vrapi_DefaultInitParms(ref java);

                ConsoleExtensions.trace("AppThreadFunction, call vrapi_Initialize");
                VrApi.vrapi_Initialize(ref initParms);


                ConsoleExtensions.trace("AppThreadFunction, create ovrApp, call ovrEgl_CreateContext");

                this.appState = new ovrApp(ref java)
                {
                    AppThread = this
                };


                // 1794
                this.appState.Egl.ovrEgl_CreateContext(null);


                ConsoleExtensions.trace("AppThreadFunction, call vrapi_GetHmdInfo, then ovrRenderer_Create");
                var hmdInfo = VrApi.vrapi_GetHmdInfo(ref java);

                this.appState.Renderer.ovrRenderer_Create(ref hmdInfo);


                this.headModelParms = VrApi_Helpers.vrapi_DefaultHeadModelParms();


                ConsoleExtensions.trace("AppThreadFunction, enter loop, call ovrMessageQueue_GetNextMessage");
                bool destroyed = false;

                while (!destroyed)
                {
                    //appState.trace60("enter frame, ovrMessageQueue_GetNextMessage");

                    #region ovrMessageQueue_GetNextMessage
                    var ok = true;
                    while (ok)
                    {
                        ovrMessage message;
                        var        waitForMessages = appState.Ovr == null && !destroyed;

                        if (!this.MessageQueue.ovrMessageQueue_GetNextMessage(out message, waitForMessages))
                        {
                            break;
                        }
                        // 1812

                        // no switch for jsc?
                        if (message.Id == MESSAGE.MESSAGE_ON_CREATE)
                        {
                            //ConsoleExtensions.trace("AppThreadFunction, MESSAGE_ON_CREATE");
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_START)
                        {
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_RESUME)
                        {
                            appState.Resumed = true;
                            //ConsoleExtensions.trace("AppThreadFunction, MESSAGE_ON_RESUME");
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_PAUSE)
                        {
                            appState.Resumed = false;
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_STOP)
                        {
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_DESTROY)
                        {
                            appState.NativeWindow = null; destroyed = true;
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_SURFACE_CREATED)
                        {
                            //ConsoleExtensions.trace("AppThreadFunction, MESSAGE_ON_SURFACE_CREATED");
                            var m0 = message[0];
                            appState.NativeWindow = (native_window.ANativeWindow)m0.Pointer;
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_SURFACE_DESTROYED)
                        {
                            appState.NativeWindow = null;
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_KEY_EVENT)
                        {
                            appState.ovrApp_HandleKeyEvent((keycodes.AKEYCODE)(int) message[0], (input.AInputEventAction)(int) message[1]);
                        }
                        else if (message.Id == MESSAGE.MESSAGE_ON_TOUCH_EVENT)
                        {
                            //ConsoleExtensions.tracei("AppThreadFunction, MESSAGE_ON_TOUCH_EVENT");
                            appState.ovrApp_HandleTouchEvent(message[0], message[1], message[2]);
                        }

                        appState.ovrApp_HandleVrModeChanges();
                    }
                    #endregion

                    // ok
                    //appState.trace60("ovrMessageQueue_GetNextMessage done, ovrApp_BackButtonAction");

                    // ok
                    appState.ovrApp_BackButtonAction();

                    //appState.trace60("ovrApp_BackButtonAction done (ok), ovrApp_HandleSystemEvents (leak?)");

                    appState.ovrApp_HandleSystemEvents();

                    //appState.trace60("ovrApp_HandleSystemEvents done");

                    // not ready yet?
                    // set by vrapi_EnterVrMode
                    if (appState.Ovr == null)
                    {
                        appState.trace60("Ovr == null");
                        continue;
                    }


                    #region VRAPI_FRAME_INIT_LOADING_ICON_FLUSH
                    if (!appState.Scene.CreatedScene)
                    {
                        // need to keep the enum typename?

                        var parms = VrApi_Helpers.vrapi_DefaultFrameParms(ref appState.Java, ovrFrameInit.VRAPI_FRAME_INIT_LOADING_ICON_FLUSH, 0);
                        parms.FrameIndex = appState.FrameIndex;
                        ConsoleExtensions.trace("vrapi_SubmitFrame VRAPI_FRAME_INIT_LOADING_ICON_FLUSH");
                        appState.Ovr.vrapi_SubmitFrame(ref parms);

                        //unistd.usleep(1000);

                        appState.Scene.ovrScene_Create();

                        // keep the loader on for a moment...
                        //unistd.usleep(1000);
                    }
                    #endregion


                    if (xmallinfo() > GLES3JNILib.safemodeMemoryLimitMB * 1024 * 1024)
                    {
                        // I/xNativeActivity(24473): \VrCubeWorld.AppThread.cs:71 mallinfo    maximum total allocated space:  1825611032
                        // https://news.ycombinator.com/item?id=9179833

                        // https://www.youtube.com/watch?v=se2KMs5qrqY
                        ConsoleExtensions.tracei64("safe mode before sleep ", appState.FrameIndex);

                        // slow down VR thread...
                        System.Threading.Thread.Sleep(5000);
                        //unistd.usleep(2000 * 1000);

                        //ConsoleExtensions.tracei64("safe mode after sleep ", appState.FrameIndex);

                        //continue;
                    }



                    //appState.tracei60("AppThreadFunction, FrameIndex ", (int)appState.FrameIndex);

                    // 1862


                    appState.FrameIndex++;


                    //appState.trace60("who is eating our memory?");
                    //System.Threading.Thread.Sleep(1000 / 15);
                    //continue;


                    //ConsoleExtensions.tracei("AppThreadFunction, vrapi_GetPredictedDisplayTime");
                    var predictedDisplayTime = appState.Ovr.vrapi_GetPredictedDisplayTime(appState.FrameIndex);
                    //ConsoleExtensions.tracei("AppThreadFunction, vrapi_GetPredictedTracking");

                    this.trackingOld = this.tracking;
                    this.tracking    = appState.Ovr.vrapi_GetPredictedTracking(predictedDisplayTime);

                    // like step in physics?
                    appState.Simulation.ovrSimulation_AdvanceSimulation(predictedDisplayTime);

                    {
                        //var parms = appState.Renderer.ovrRenderer_RenderFrame(ref appState, ref tracking);
                        //var parms = appState.Renderer.ovrRenderer_RenderFrame(this, appState, ref tracking);
                        //var parms = this.appState.Renderer.ovrRenderer_RenderFrame(this, ref tracking);
                        var parms = this.appState.Renderer.ovrRenderer_RenderFrame(this);


                        //if (tracking.Status == trackingOld.Status)
                        //    appState.tracei60(" tracking.Status ", (int)tracking.Status);
                        //else
                        //    ConsoleExtensions.tracei(" tracking.Status ", (int)tracking.Status);

                        //appState.tracei60(" tracking.HeadPose.Pose.Orientation.x ", (int)(1000 * tracking.HeadPose.Pose.Orientation.x));
                        //appState.tracei60(" tracking.HeadPose.Pose.Orientation.y ", (int)(1000 * tracking.HeadPose.Pose.Orientation.y));
                        //appState.tracei60(" tracking.HeadPose.Pose.Orientation.z ", (int)(1000 * tracking.HeadPose.Pose.Orientation.z));
                        //appState.tracei60(" tracking.HeadPose.Pose.Orientation.w ", (int)(1000 * tracking.HeadPose.Pose.Orientation.w));
                        appState.Ovr.vrapi_SubmitFrame(ref parms);
                    }
                    // 1891
                }

                // 1896
                appState.Renderer.ovrRenderer_Destroy();

                // 1898
                appState.Scene.ovrScene_Destroy();
                appState.Egl.ovrEgl_DestroyContext();
                VrApi.vrapi_Shutdown();

                java.Vm.DetachCurrentThread(java.Vm);
            }