summaryrefslogtreecommitdiff
path: root/platform/android/java/lib/src/org
diff options
context:
space:
mode:
authorfhuya <fhuya@google.com>2019-09-02 17:31:51 -0700
committerfhuya <fhuya@google.com>2019-09-04 16:20:22 -0700
commit7fabfd402f235ebcf64cfde3b399b8b62b969243 (patch)
tree99bb4eacc7828bedae43316f7415091de9782922 /platform/android/java/lib/src/org
parentba854bbc7bb0eae230299de4da8dfcb7caf74b69 (diff)
Split the Android platform java logic into an Android library module (`lib`) and an application module (`app`).
The application module `app` serves double duties of providing the prebuilt Godot binaries ('android_debug.apk', 'android_release.apk') and the Godot custom build template ('android_source.zip').
Diffstat (limited to 'platform/android/java/lib/src/org')
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/Dictionary.java81
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/Godot.java1111
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java59
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotDownloaderService.java84
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotIO.java631
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotInstrumentation.java50
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotLib.java214
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotPaymentV3.java230
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java61
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/GodotView.java170
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java171
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java360
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java150
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/InputManagerCompat.java135
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/InputManagerV16.java102
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/input/Joystick.java44
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/payments/ConsumeTask.java116
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/payments/HandlePurchaseTask.java93
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsCache.java72
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsManager.java419
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/payments/PurchaseTask.java118
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java141
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/payments/ValidateTask.java142
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/utils/Crypt.java69
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java69
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/utils/GLUtils.java157
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/utils/HttpRequester.java227
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/utils/RequestParams.java85
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/xr/XRMode.java51
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrConfigChooser.java112
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrContextFactory.java58
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrWindowSurfaceFactory.java60
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularConfigChooser.java151
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java81
-rw-r--r--platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularFallbackConfigChooser.java61
35 files changed, 5935 insertions, 0 deletions
diff --git a/platform/android/java/lib/src/org/godotengine/godot/Dictionary.java b/platform/android/java/lib/src/org/godotengine/godot/Dictionary.java
new file mode 100644
index 0000000000..588d9ae646
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/Dictionary.java
@@ -0,0 +1,81 @@
+/*************************************************************************/
+/* Dictionary.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+
+import java.util.HashMap;
+import java.util.Set;
+
+public class Dictionary extends HashMap<String, Object> {
+
+ protected String[] keys_cache;
+
+ public String[] get_keys() {
+
+ String[] ret = new String[size()];
+ int i = 0;
+ Set<String> keys = keySet();
+ for (String key : keys) {
+
+ ret[i] = key;
+ i++;
+ };
+
+ return ret;
+ };
+
+ public Object[] get_values() {
+
+ Object[] ret = new Object[size()];
+ int i = 0;
+ Set<String> keys = keySet();
+ for (String key : keys) {
+
+ ret[i] = get(key);
+ i++;
+ };
+
+ return ret;
+ };
+
+ public void set_keys(String[] keys) {
+ keys_cache = keys;
+ };
+
+ public void set_values(Object[] vals) {
+
+ int i = 0;
+ for (String key : keys_cache) {
+ put(key, vals[i]);
+ i++;
+ };
+ keys_cache = null;
+ };
+};
diff --git a/platform/android/java/lib/src/org/godotengine/godot/Godot.java b/platform/android/java/lib/src/org/godotengine/godot/Godot.java
new file mode 100644
index 0000000000..7e852b7e08
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/Godot.java
@@ -0,0 +1,1111 @@
+/*************************************************************************/
+/* Godot.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+
+import android.Manifest;
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.ActivityManager;
+import android.app.AlertDialog;
+import android.app.PendingIntent;
+import android.content.ClipData;
+import android.content.ClipboardManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.Editor;
+import android.content.pm.ConfigurationInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Environment;
+import android.os.Messenger;
+import android.os.VibrationEffect;
+import android.os.Vibrator;
+import android.provider.Settings.Secure;
+import android.support.annotation.Keep;
+import android.support.v4.content.ContextCompat;
+import android.view.Display;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+import android.view.Surface;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewGroup.LayoutParams;
+import android.view.ViewTreeObserver;
+import android.view.Window;
+import android.view.WindowManager;
+import android.widget.Button;
+import android.widget.FrameLayout;
+import android.widget.ProgressBar;
+import android.widget.TextView;
+import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
+import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
+import com.google.android.vending.expansion.downloader.DownloaderServiceMarshaller;
+import com.google.android.vending.expansion.downloader.Helpers;
+import com.google.android.vending.expansion.downloader.IDownloaderClient;
+import com.google.android.vending.expansion.downloader.IDownloaderService;
+import com.google.android.vending.expansion.downloader.IStub;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.security.MessageDigest;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import javax.microedition.khronos.opengles.GL10;
+import org.godotengine.godot.input.GodotEditText;
+import org.godotengine.godot.payments.PaymentsManager;
+import org.godotengine.godot.xr.XRMode;
+
+public abstract class Godot extends Activity implements SensorEventListener, IDownloaderClient {
+
+ static final int MAX_SINGLETONS = 64;
+ static final int REQUEST_RECORD_AUDIO_PERMISSION = 1;
+ static final int REQUEST_CAMERA_PERMISSION = 2;
+ static final int REQUEST_VIBRATE_PERMISSION = 3;
+ private IStub mDownloaderClientStub;
+ private TextView mStatusText;
+ private TextView mProgressFraction;
+ private TextView mProgressPercent;
+ private TextView mAverageSpeed;
+ private TextView mTimeRemaining;
+ private ProgressBar mPB;
+ private ClipboardManager mClipboard;
+
+ private View mDashboard;
+ private View mCellMessage;
+
+ private Button mPauseButton;
+ private Button mWiFiSettingsButton;
+
+ private XRMode xrMode = XRMode.REGULAR;
+ private boolean use_32_bits = false;
+ private boolean use_immersive = false;
+ private boolean use_debug_opengl = false;
+ private boolean mStatePaused;
+ private boolean activityResumed;
+ private int mState;
+
+ static private Intent mCurrentIntent;
+
+ @Override
+ public void onNewIntent(Intent intent) {
+ mCurrentIntent = intent;
+ }
+
+ static public Intent getCurrentIntent() {
+ return mCurrentIntent;
+ }
+
+ private void setState(int newState) {
+ if (mState != newState) {
+ mState = newState;
+ mStatusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState));
+ }
+ }
+
+ private void setButtonPausedState(boolean paused) {
+ mStatePaused = paused;
+ int stringResourceID = paused ? R.string.text_button_resume :
+ R.string.text_button_pause;
+ mPauseButton.setText(stringResourceID);
+ }
+
+ static public class SingletonBase {
+
+ protected void registerClass(String p_name, String[] p_methods) {
+
+ GodotLib.singleton(p_name, this);
+
+ Class clazz = getClass();
+ Method[] methods = clazz.getDeclaredMethods();
+ for (Method method : methods) {
+ boolean found = false;
+
+ for (String s : p_methods) {
+ if (s.equals(method.getName())) {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ continue;
+
+ List<String> ptr = new ArrayList<String>();
+
+ Class[] paramTypes = method.getParameterTypes();
+ for (Class c : paramTypes) {
+ ptr.add(c.getName());
+ }
+
+ String[] pt = new String[ptr.size()];
+ ptr.toArray(pt);
+
+ GodotLib.method(p_name, method.getName(), method.getReturnType().getName(), pt);
+ }
+
+ Godot.singletons[Godot.singleton_count++] = this;
+ }
+
+ protected void onMainActivityResult(int requestCode, int resultCode, Intent data) {
+ }
+
+ protected void onMainRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ }
+
+ protected void onMainPause() {}
+ protected void onMainResume() {}
+ protected void onMainDestroy() {}
+ protected boolean onMainBackPressed() { return false; }
+
+ protected void onGLDrawFrame(GL10 gl) {}
+ protected void onGLSurfaceChanged(GL10 gl, int width, int height) {} // singletons will always miss first onGLSurfaceChanged call
+ //protected void onGLSurfaceCreated(GL10 gl, EGLConfig config) {} // singletons won't be ready until first GodotLib.step()
+
+ public void registerMethods() {}
+ }
+
+ /*
+ protected List<SingletonBase> singletons = new ArrayList<SingletonBase>();
+ protected void instanceSingleton(SingletonBase s) {
+
+ s.registerMethods();
+ singletons.add(s);
+ }
+ */
+
+ private String[] command_line;
+ private boolean use_apk_expansion;
+
+ public GodotView mView;
+ private boolean godot_initialized = false;
+
+ private SensorManager mSensorManager;
+ private Sensor mAccelerometer;
+ private Sensor mGravity;
+ private Sensor mMagnetometer;
+ private Sensor mGyroscope;
+
+ public static GodotIO io;
+
+ static SingletonBase[] singletons = new SingletonBase[MAX_SINGLETONS];
+ static int singleton_count = 0;
+
+ public interface ResultCallback {
+ public void callback(int requestCode, int resultCode, Intent data);
+ }
+ public ResultCallback result_callback;
+
+ private PaymentsManager mPaymentsManager = null;
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == PaymentsManager.REQUEST_CODE_FOR_PURCHASE) {
+ mPaymentsManager.processPurchaseResponse(resultCode, data);
+ } else if (result_callback != null) {
+ result_callback.callback(requestCode, resultCode, data);
+ result_callback = null;
+ };
+
+ for (int i = 0; i < singleton_count; i++) {
+
+ singletons[i].onMainActivityResult(requestCode, resultCode, data);
+ }
+ };
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ for (int i = 0; i < singleton_count; i++) {
+ singletons[i].onMainRequestPermissionsResult(requestCode, permissions, grantResults);
+ }
+
+ for (int i = 0; i < permissions.length; i++) {
+ GodotLib.requestPermissionResult(permissions[i], grantResults[i] == PackageManager.PERMISSION_GRANTED);
+ }
+ };
+
+ /**
+ * Used by the native code (java_godot_lib_jni.cpp) to complete initialization of the GLSurfaceView view and renderer.
+ */
+ @Keep
+ private void onVideoInit() {
+ boolean use_gl3 = getGLESVersionCode() >= 0x00030000;
+
+ final FrameLayout layout = new FrameLayout(this);
+ layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
+ setContentView(layout);
+
+ // GodotEditText layout
+ GodotEditText edittext = new GodotEditText(this);
+ edittext.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
+ // ...add to FrameLayout
+ layout.addView(edittext);
+
+ mView = new GodotView(this, xrMode, use_gl3, use_32_bits, use_debug_opengl);
+ layout.addView(mView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
+ edittext.setView(mView);
+ io.setEdit(edittext);
+
+ final Godot godot = this;
+ mView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
+ @Override
+ public void onGlobalLayout() {
+ Point fullSize = new Point();
+ godot.getWindowManager().getDefaultDisplay().getSize(fullSize);
+ Rect gameSize = new Rect();
+ godot.mView.getWindowVisibleDisplayFrame(gameSize);
+
+ final int keyboardHeight = fullSize.y - gameSize.bottom;
+ GodotLib.setVirtualKeyboardHeight(keyboardHeight);
+ }
+ });
+
+ final String[] current_command_line = command_line;
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.setup(current_command_line);
+ setKeepScreenOn("True".equals(GodotLib.getGlobal("display/window/energy_saving/keep_screen_on")));
+ }
+ });
+ }
+
+ public void setKeepScreenOn(final boolean p_enabled) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ if (p_enabled) {
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ } else {
+ getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ }
+ }
+ });
+ }
+
+ /**
+ * Used by the native code (java_godot_wrapper.h) to vibrate the device.
+ * @param durationMs
+ */
+ @SuppressLint("MissingPermission")
+ @Keep
+ private void vibrate(int durationMs) {
+ if (requestPermission("VIBRATE")) {
+ Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
+ if (v != null) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ v.vibrate(VibrationEffect.createOneShot(durationMs, VibrationEffect.DEFAULT_AMPLITUDE));
+ } else {
+ //deprecated in API 26
+ v.vibrate(durationMs);
+ }
+ }
+ }
+ }
+
+ public void restart() {
+ // HACK:
+ //
+ // Currently it's very hard to properly deinitialize Godot on Android to restart the game
+ // from scratch. Therefore, we need to kill the whole app process and relaunch it.
+ //
+ // Restarting only the activity, wouldn't be enough unless it did proper cleanup (including
+ // releasing and reloading native libs or resetting their state somehow and clearing statics).
+ //
+ // Using instrumentation is a way of making the whole app process restart, because Android
+ // will kill any process of the same package which was already running.
+ //
+ Bundle args = new Bundle();
+ args.putParcelable("intent", mCurrentIntent);
+ startInstrumentation(new ComponentName(this, GodotInstrumentation.class), null, args);
+ }
+
+ public void alert(final String message, final String title) {
+ final Activity activity = this;
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ AlertDialog.Builder builder = new AlertDialog.Builder(activity);
+ builder.setMessage(message).setTitle(title);
+ builder.setPositiveButton(
+ "OK",
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ dialog.cancel();
+ }
+ });
+ AlertDialog dialog = builder.create();
+ dialog.show();
+ }
+ });
+ }
+
+ public int getGLESVersionCode() {
+ ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
+ ConfigurationInfo deviceInfo = am.getDeviceConfigurationInfo();
+ return deviceInfo.reqGlEsVersion;
+ }
+
+ private String[] getCommandLine() {
+ InputStream is;
+ try {
+ is = getAssets().open("_cl_");
+ byte[] len = new byte[4];
+ int r = is.read(len);
+ if (r < 4) {
+ return new String[0];
+ }
+ int argc = ((int)(len[3] & 0xFF) << 24) | ((int)(len[2] & 0xFF) << 16) | ((int)(len[1] & 0xFF) << 8) | ((int)(len[0] & 0xFF));
+ String[] cmdline = new String[argc];
+
+ for (int i = 0; i < argc; i++) {
+ r = is.read(len);
+ if (r < 4) {
+
+ return new String[0];
+ }
+ int strlen = ((int)(len[3] & 0xFF) << 24) | ((int)(len[2] & 0xFF) << 16) | ((int)(len[1] & 0xFF) << 8) | ((int)(len[0] & 0xFF));
+ if (strlen > 65535) {
+ return new String[0];
+ }
+ byte[] arg = new byte[strlen];
+ r = is.read(arg);
+ if (r == strlen) {
+ cmdline[i] = new String(arg, "UTF-8");
+ }
+ }
+ return cmdline;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return new String[0];
+ }
+ }
+
+ /**
+ * Used by the native code (java_godot_wrapper.h) to check whether the activity is resumed or paused.
+ */
+ @Keep
+ private boolean isActivityResumed() {
+ return activityResumed;
+ }
+
+ /**
+ * Used by the native code (java_godot_wrapper.h) to access the Android surface.
+ */
+ @Keep
+ private Surface getSurface() {
+ return mView.getHolder().getSurface();
+ }
+
+ /**
+ * Used by the native code (java_godot_wrapper.h) to access the input fallback mapping.
+ * @return The input fallback mapping for the current XR mode.
+ */
+ @Keep
+ private String getInputFallbackMapping() {
+ return xrMode.inputFallbackMapping;
+ }
+
+ String expansion_pack_path;
+
+ private void initializeGodot() {
+
+ if (expansion_pack_path != null) {
+
+ String[] new_cmdline;
+ int cll = 0;
+ if (command_line != null) {
+ new_cmdline = new String[command_line.length + 2];
+ cll = command_line.length;
+ for (int i = 0; i < command_line.length; i++) {
+ new_cmdline[i] = command_line[i];
+ }
+ } else {
+ new_cmdline = new String[2];
+ }
+
+ new_cmdline[cll] = "--main-pack";
+ new_cmdline[cll + 1] = expansion_pack_path;
+ command_line = new_cmdline;
+ }
+
+ io = new GodotIO(this);
+ io.unique_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
+ GodotLib.io = io;
+ mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
+ mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
+ mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
+ mGravity = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
+ mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_GAME);
+ mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
+ mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_GAME);
+ mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
+ mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_GAME);
+
+ GodotLib.initialize(this, getAssets(), use_apk_expansion);
+
+ result_callback = null;
+
+ mPaymentsManager = PaymentsManager.createManager(this).initService();
+
+ godot_initialized = true;
+ }
+
+ @Override
+ public void onServiceConnected(Messenger m) {
+ IDownloaderService remoteService = DownloaderServiceMarshaller.CreateProxy(m);
+ remoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
+ }
+
+ @Override
+ protected void onCreate(Bundle icicle) {
+
+ super.onCreate(icicle);
+ Window window = getWindow();
+ window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
+ mClipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
+
+ //check for apk expansion API
+ if (true) {
+ boolean md5mismatch = false;
+ command_line = getCommandLine();
+ String main_pack_md5 = null;
+ String main_pack_key = null;
+
+ List<String> new_args = new LinkedList<String>();
+
+ for (int i = 0; i < command_line.length; i++) {
+
+ boolean has_extra = i < command_line.length - 1;
+ if (command_line[i].equals(XRMode.REGULAR.cmdLineArg)) {
+ xrMode = XRMode.REGULAR;
+ } else if (command_line[i].equals(XRMode.OVR.cmdLineArg)) {
+ xrMode = XRMode.OVR;
+ } else if (command_line[i].equals("--use_depth_32")) {
+ use_32_bits = true;
+ } else if (command_line[i].equals("--debug_opengl")) {
+ use_debug_opengl = true;
+ } else if (command_line[i].equals("--use_immersive")) {
+ use_immersive = true;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // check if the application runs on an android 4.4+
+ window.getDecorView().setSystemUiVisibility(
+ View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
+ View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
+ View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
+ View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | // hide nav bar
+ View.SYSTEM_UI_FLAG_FULLSCREEN | // hide status bar
+ View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
+
+ UiChangeListener();
+ }
+ } else if (command_line[i].equals("--use_apk_expansion")) {
+ use_apk_expansion = true;
+ } else if (has_extra && command_line[i].equals("--apk_expansion_md5")) {
+ main_pack_md5 = command_line[i + 1];
+ i++;
+ } else if (has_extra && command_line[i].equals("--apk_expansion_key")) {
+ main_pack_key = command_line[i + 1];
+ SharedPreferences prefs = getSharedPreferences("app_data_keys", MODE_PRIVATE);
+ Editor editor = prefs.edit();
+ editor.putString("store_public_key", main_pack_key);
+
+ editor.apply();
+ i++;
+ } else if (command_line[i].trim().length() != 0) {
+ new_args.add(command_line[i]);
+ }
+ }
+
+ if (new_args.isEmpty()) {
+ command_line = null;
+ } else {
+
+ command_line = new_args.toArray(new String[new_args.size()]);
+ }
+ if (use_apk_expansion && main_pack_md5 != null && main_pack_key != null) {
+ //check that environment is ok!
+ if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+ //show popup and die
+ }
+
+ // Build the full path to the app's expansion files
+ try {
+ expansion_pack_path = Helpers.getSaveFilePath(getApplicationContext());
+ expansion_pack_path += "/main." + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + "." + this.getPackageName() + ".obb";
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ File f = new File(expansion_pack_path);
+
+ boolean pack_valid = true;
+
+ if (!f.exists()) {
+
+ pack_valid = false;
+
+ } else if (obbIsCorrupted(expansion_pack_path, main_pack_md5)) {
+ pack_valid = false;
+ try {
+ f.delete();
+ } catch (Exception e) {
+ }
+ }
+
+ if (!pack_valid) {
+
+ Intent notifierIntent = new Intent(this, this.getClass());
+ notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
+ Intent.FLAG_ACTIVITY_CLEAR_TOP);
+
+ PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
+ notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ int startResult;
+ try {
+ startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(
+ getApplicationContext(),
+ pendingIntent,
+ GodotDownloaderService.class);
+
+ if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
+ // This is where you do set up to display the download
+ // progress (next step)
+ mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this,
+ GodotDownloaderService.class);
+
+ setContentView(R.layout.downloading_expansion);
+ mPB = (ProgressBar)findViewById(R.id.progressBar);
+ mStatusText = (TextView)findViewById(R.id.statusText);
+ mProgressFraction = (TextView)findViewById(R.id.progressAsFraction);
+ mProgressPercent = (TextView)findViewById(R.id.progressAsPercentage);
+ mAverageSpeed = (TextView)findViewById(R.id.progressAverageSpeed);
+ mTimeRemaining = (TextView)findViewById(R.id.progressTimeRemaining);
+ mDashboard = findViewById(R.id.downloaderDashboard);
+ mCellMessage = findViewById(R.id.approveCellular);
+ mPauseButton = (Button)findViewById(R.id.pauseButton);
+ mWiFiSettingsButton = (Button)findViewById(R.id.wifiSettingsButton);
+
+ return;
+ }
+ } catch (NameNotFoundException e) {
+ // TODO Auto-generated catch block
+ }
+ }
+ }
+ }
+
+ mCurrentIntent = getIntent();
+
+ initializeGodot();
+ }
+
+ @Override
+ protected void onDestroy() {
+
+ if (mPaymentsManager != null) mPaymentsManager.destroy();
+ for (int i = 0; i < singleton_count; i++) {
+ singletons[i].onMainDestroy();
+ }
+
+ GodotLib.ondestroy(this);
+
+ super.onDestroy();
+
+ // TODO: This is a temp solution. The proper fix will involve tracking down and properly shutting down each
+ // native Godot components that is started in Godot#onVideoInit.
+ forceQuit();
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ activityResumed = false;
+
+ if (!godot_initialized) {
+ if (null != mDownloaderClientStub) {
+ mDownloaderClientStub.disconnect(this);
+ }
+ return;
+ }
+ mView.onPause();
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.focusout();
+ }
+ });
+ mSensorManager.unregisterListener(this);
+
+ for (int i = 0; i < singleton_count; i++) {
+ singletons[i].onMainPause();
+ }
+ }
+
+ public String getClipboard() {
+
+ String copiedText = "";
+
+ if (mClipboard.getPrimaryClip() != null) {
+ ClipData.Item item = mClipboard.getPrimaryClip().getItemAt(0);
+ copiedText = item.getText().toString();
+ }
+
+ return copiedText;
+ }
+
+ public void setClipboard(String p_text) {
+
+ ClipData clip = ClipData.newPlainText("myLabel", p_text);
+ mClipboard.setPrimaryClip(clip);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (!godot_initialized) {
+ if (null != mDownloaderClientStub) {
+ mDownloaderClientStub.connect(this);
+ }
+ return;
+ }
+
+ mView.onResume();
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.focusin();
+ }
+ });
+ mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
+ mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_GAME);
+ mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_GAME);
+ mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_GAME);
+
+ if (use_immersive && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // check if the application runs on an android 4.4+
+ Window window = getWindow();
+ window.getDecorView().setSystemUiVisibility(
+ View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
+ View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
+ View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
+ View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | // hide nav bar
+ View.SYSTEM_UI_FLAG_FULLSCREEN | // hide status bar
+ View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
+ }
+
+ for (int i = 0; i < singleton_count; i++) {
+
+ singletons[i].onMainResume();
+ }
+
+ activityResumed = true;
+ }
+
+ public void UiChangeListener() {
+ final View decorView = getWindow().getDecorView();
+ decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
+ @Override
+ public void onSystemUiVisibilityChange(int visibility) {
+ if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ decorView.setSystemUiVisibility(
+ View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
+ View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
+ View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
+ View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
+ View.SYSTEM_UI_FLAG_FULLSCREEN |
+ View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
+ }
+ }
+ }
+ });
+ }
+
+ @Override
+ public void onSensorChanged(SensorEvent event) {
+ Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
+ int displayRotation = display.getRotation();
+
+ float[] adjustedValues = new float[3];
+ final int axisSwap[][] = {
+ { 1, -1, 0, 1 }, // ROTATION_0
+ { -1, -1, 1, 0 }, // ROTATION_90
+ { -1, 1, 0, 1 }, // ROTATION_180
+ { 1, 1, 1, 0 }
+ }; // ROTATION_270
+
+ final int[] as = axisSwap[displayRotation];
+ adjustedValues[0] = (float)as[0] * event.values[as[2]];
+ adjustedValues[1] = (float)as[1] * event.values[as[3]];
+ adjustedValues[2] = event.values[2];
+
+ final float x = adjustedValues[0];
+ final float y = adjustedValues[1];
+ final float z = adjustedValues[2];
+
+ final int typeOfSensor = event.sensor.getType();
+ if (mView != null) {
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ if (typeOfSensor == Sensor.TYPE_ACCELEROMETER) {
+ GodotLib.accelerometer(-x, y, -z);
+ }
+ if (typeOfSensor == Sensor.TYPE_GRAVITY) {
+ GodotLib.gravity(-x, y, -z);
+ }
+ if (typeOfSensor == Sensor.TYPE_MAGNETIC_FIELD) {
+ GodotLib.magnetometer(-x, y, -z);
+ }
+ if (typeOfSensor == Sensor.TYPE_GYROSCOPE) {
+ GodotLib.gyroscope(x, -y, z);
+ }
+ }
+ });
+ }
+ }
+
+ @Override
+ public final void onAccuracyChanged(Sensor sensor, int accuracy) {
+ // Do something here if sensor accuracy changes.
+ }
+
+ /*
+ @Override public boolean dispatchKeyEvent(KeyEvent event) {
+
+ if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
+
+ System.out.printf("** BACK REQUEST!\n");
+
+ GodotLib.quit();
+ return true;
+ }
+ System.out.printf("** OTHER KEY!\n");
+
+ return false;
+ }
+ */
+
+ @Override
+ public void onBackPressed() {
+ boolean shouldQuit = true;
+
+ for (int i = 0; i < singleton_count; i++) {
+ if (singletons[i].onMainBackPressed()) {
+ shouldQuit = false;
+ }
+ }
+
+ if (shouldQuit && mView != null) {
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.back();
+ }
+ });
+ }
+ }
+
+ private void forceQuit() {
+ System.exit(0);
+ }
+
+ private boolean obbIsCorrupted(String f, String main_pack_md5) {
+
+ try {
+
+ InputStream fis = new FileInputStream(f);
+
+ // Create MD5 Hash
+ byte[] buffer = new byte[16384];
+
+ MessageDigest complete = MessageDigest.getInstance("MD5");
+ int numRead;
+ do {
+ numRead = fis.read(buffer);
+ if (numRead > 0) {
+ complete.update(buffer, 0, numRead);
+ }
+ } while (numRead != -1);
+
+ fis.close();
+ byte[] messageDigest = complete.digest();
+
+ // Create Hex String
+ StringBuffer hexString = new StringBuffer();
+ for (int i = 0; i < messageDigest.length; i++) {
+ String s = Integer.toHexString(0xFF & messageDigest[i]);
+
+ if (s.length() == 1) {
+ s = "0" + s;
+ }
+ hexString.append(s);
+ }
+ String md5str = hexString.toString();
+
+ if (!md5str.equals(main_pack_md5)) {
+ return true;
+ }
+ return false;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return true;
+ }
+ }
+
+ public boolean gotTouchEvent(final MotionEvent event) {
+
+ final int evcount = event.getPointerCount();
+ if (evcount == 0)
+ return true;
+
+ if (mView != null) {
+ final int[] arr = new int[event.getPointerCount() * 3];
+
+ for (int i = 0; i < event.getPointerCount(); i++) {
+
+ arr[i * 3 + 0] = (int)event.getPointerId(i);
+ arr[i * 3 + 1] = (int)event.getX(i);
+ arr[i * 3 + 2] = (int)event.getY(i);
+ }
+ final int pointer_idx = event.getPointerId(event.getActionIndex());
+
+ //System.out.printf("gaction: %d\n",event.getAction());
+ final int action = event.getAction() & MotionEvent.ACTION_MASK;
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ switch (action) {
+ case MotionEvent.ACTION_DOWN: {
+ GodotLib.touch(0, 0, evcount, arr);
+ //System.out.printf("action down at: %f,%f\n", event.getX(),event.getY());
+ } break;
+ case MotionEvent.ACTION_MOVE: {
+ GodotLib.touch(1, 0, evcount, arr);
+ /*
+ for(int i=0;i<event.getPointerCount();i++) {
+ System.out.printf("%d - moved to: %f,%f\n",i, event.getX(i),event.getY(i));
+ }
+ */
+ } break;
+ case MotionEvent.ACTION_POINTER_UP: {
+ GodotLib.touch(4, pointer_idx, evcount, arr);
+ //System.out.printf("%d - s.up at: %f,%f\n",pointer_idx, event.getX(pointer_idx),event.getY(pointer_idx));
+ } break;
+ case MotionEvent.ACTION_POINTER_DOWN: {
+ GodotLib.touch(3, pointer_idx, evcount, arr);
+ //System.out.printf("%d - s.down at: %f,%f\n",pointer_idx, event.getX(pointer_idx),event.getY(pointer_idx));
+ } break;
+ case MotionEvent.ACTION_CANCEL:
+ case MotionEvent.ACTION_UP: {
+ GodotLib.touch(2, 0, evcount, arr);
+ /*
+ for(int i=0;i<event.getPointerCount();i++) {
+ System.out.printf("%d - up! %f,%f\n",i, event.getX(i),event.getY(i));
+ }
+ */
+ } break;
+ }
+ }
+ });
+ }
+ return true;
+ }
+
+ @Override
+ public boolean onKeyMultiple(final int inKeyCode, int repeatCount, KeyEvent event) {
+ String s = event.getCharacters();
+ if (s == null || s.length() == 0)
+ return super.onKeyMultiple(inKeyCode, repeatCount, event);
+
+ final char[] cc = s.toCharArray();
+ int cnt = 0;
+ for (int i = cc.length; --i >= 0; cnt += cc[i] != 0 ? 1 : 0)
+ ;
+ if (cnt == 0) return super.onKeyMultiple(inKeyCode, repeatCount, event);
+ mView.queueEvent(new Runnable() {
+ // This method will be called on the rendering thread:
+ public void run() {
+ for (int i = 0, n = cc.length; i < n; i++) {
+ int keyCode;
+ if ((keyCode = cc[i]) != 0) {
+ // Simulate key down and up...
+ GodotLib.key(0, keyCode, true);
+ GodotLib.key(0, keyCode, false);
+ }
+ }
+ }
+ });
+ return true;
+ }
+
+ public PaymentsManager getPaymentsManager() {
+ return mPaymentsManager;
+ }
+
+ public boolean requestPermission(String p_name) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
+ // Not necessary, asked on install already
+ return true;
+ }
+
+ if (p_name.equals("RECORD_AUDIO")) {
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
+ requestPermissions(new String[] { Manifest.permission.RECORD_AUDIO }, REQUEST_RECORD_AUDIO_PERMISSION);
+ return false;
+ }
+ }
+
+ if (p_name.equals("CAMERA")) {
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
+ requestPermissions(new String[] { Manifest.permission.CAMERA }, REQUEST_CAMERA_PERMISSION);
+ return false;
+ }
+ }
+
+ if (p_name.equals("VIBRATE")) {
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED) {
+ requestPermissions(new String[] { Manifest.permission.VIBRATE }, REQUEST_VIBRATE_PERMISSION);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * The download state should trigger changes in the UI --- it may be useful
+ * to show the state as being indeterminate at times. This sample can be
+ * considered a guideline.
+ */
+ @Override
+ public void onDownloadStateChanged(int newState) {
+ setState(newState);
+ boolean showDashboard = true;
+ boolean showCellMessage = false;
+ boolean paused;
+ boolean indeterminate;
+ switch (newState) {
+ case IDownloaderClient.STATE_IDLE:
+ // STATE_IDLE means the service is listening, so it's
+ // safe to start making remote service calls.
+ paused = false;
+ indeterminate = true;
+ break;
+ case IDownloaderClient.STATE_CONNECTING:
+ case IDownloaderClient.STATE_FETCHING_URL:
+ showDashboard = true;
+ paused = false;
+ indeterminate = true;
+ break;
+ case IDownloaderClient.STATE_DOWNLOADING:
+ paused = false;
+ showDashboard = true;
+ indeterminate = false;
+ break;
+
+ case IDownloaderClient.STATE_FAILED_CANCELED:
+ case IDownloaderClient.STATE_FAILED:
+ case IDownloaderClient.STATE_FAILED_FETCHING_URL:
+ case IDownloaderClient.STATE_FAILED_UNLICENSED:
+ paused = true;
+ showDashboard = false;
+ indeterminate = false;
+ break;
+ case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
+ case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
+ showDashboard = false;
+ paused = true;
+ indeterminate = false;
+ showCellMessage = true;
+ break;
+
+ case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
+ paused = true;
+ indeterminate = false;
+ break;
+ case IDownloaderClient.STATE_PAUSED_ROAMING:
+ case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
+ paused = true;
+ indeterminate = false;
+ break;
+ case IDownloaderClient.STATE_COMPLETED:
+ showDashboard = false;
+ paused = false;
+ indeterminate = false;
+ initializeGodot();
+ return;
+ default:
+ paused = true;
+ indeterminate = true;
+ showDashboard = true;
+ }
+ int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE;
+ if (mDashboard.getVisibility() != newDashboardVisibility) {
+ mDashboard.setVisibility(newDashboardVisibility);
+ }
+ int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE;
+ if (mCellMessage.getVisibility() != cellMessageVisibility) {
+ mCellMessage.setVisibility(cellMessageVisibility);
+ }
+
+ mPB.setIndeterminate(indeterminate);
+ setButtonPausedState(paused);
+ }
+
+ @Override
+ public void onDownloadProgress(DownloadProgressInfo progress) {
+ mAverageSpeed.setText(getString(R.string.kilobytes_per_second,
+ Helpers.getSpeedString(progress.mCurrentSpeed)));
+ mTimeRemaining.setText(getString(R.string.time_remaining,
+ Helpers.getTimeRemaining(progress.mTimeRemaining)));
+
+ mPB.setMax((int)(progress.mOverallTotal >> 8));
+ mPB.setProgress((int)(progress.mOverallProgress >> 8));
+ mProgressPercent.setText(String.format(Locale.ENGLISH, "%d %%", progress.mOverallProgress * 100 / progress.mOverallTotal));
+ mProgressFraction.setText(Helpers.getDownloadProgressString(progress.mOverallProgress,
+ progress.mOverallTotal));
+ }
+ public void initInputDevices() {
+ mView.initInputDevices();
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java b/platform/android/java/lib/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java
new file mode 100644
index 0000000000..e7e2a3f808
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotDownloaderAlarmReceiver.java
@@ -0,0 +1,59 @@
+/*************************************************************************/
+/* GodotDownloaderAlarmReceiver.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.util.Log;
+import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
+
+/**
+ * You should start your derived downloader class when this receiver gets the message
+ * from the alarm service using the provided service helper function within the
+ * DownloaderClientMarshaller. This class must be then registered in your AndroidManifest.xml
+ * file with a section like this:
+ * <receiver android:name=".GodotDownloaderAlarmReceiver"/>
+ */
+public class GodotDownloaderAlarmReceiver extends BroadcastReceiver {
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ Log.d("GODOT", "Alarma recivida");
+ try {
+ DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent, GodotDownloaderService.class);
+ } catch (NameNotFoundException e) {
+ e.printStackTrace();
+ Log.d("GODOT", "Exception: " + e.getClass().getName() + ":" + e.getMessage());
+ }
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotDownloaderService.java b/platform/android/java/lib/src/org/godotengine/godot/GodotDownloaderService.java
new file mode 100644
index 0000000000..8e10710c9f
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotDownloaderService.java
@@ -0,0 +1,84 @@
+/*************************************************************************/
+/* GodotDownloaderService.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.Log;
+import com.google.android.vending.expansion.downloader.impl.DownloaderService;
+
+/**
+ * This class demonstrates the minimal client implementation of the
+ * DownloaderService from the Downloader library.
+ */
+public class GodotDownloaderService extends DownloaderService {
+ // stuff for LVL -- MODIFY FOR YOUR APPLICATION!
+ private static final String BASE64_PUBLIC_KEY = "REPLACE THIS WITH YOUR PUBLIC KEY";
+ // used by the preference obfuscater
+ private static final byte[] SALT = new byte[] {
+ 1, 43, -12, -1, 54, 98,
+ -100, -12, 43, 2, -8, -4, 9, 5, -106, -108, -33, 45, -1, 84
+ };
+
+ /**
+ * This public key comes from your Android Market publisher account, and it
+ * used by the LVL to validate responses from Market on your behalf.
+ */
+ @Override
+ public String getPublicKey() {
+ SharedPreferences prefs = getApplicationContext().getSharedPreferences("app_data_keys", Context.MODE_PRIVATE);
+ Log.d("GODOT", "getting public key:" + prefs.getString("store_public_key", null));
+ return prefs.getString("store_public_key", null);
+
+ //return BASE64_PUBLIC_KEY;
+ }
+
+ /**
+ * This is used by the preference obfuscater to make sure that your
+ * obfuscated preferences are different than the ones used by other
+ * applications.
+ */
+ @Override
+ public byte[] getSALT() {
+ return SALT;
+ }
+
+ /**
+ * Fill this in with the class name for your alarm receiver. We do this
+ * because receivers must be unique across all of Android (it's a good idea
+ * to make sure that your receiver is in your unique package)
+ */
+ @Override
+ public String getAlarmReceiverClassName() {
+ Log.d("GODOT", "getAlarmReceiverClassName()");
+ return GodotDownloaderAlarmReceiver.class.getName();
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java b/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java
new file mode 100644
index 0000000000..04566cf62c
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java
@@ -0,0 +1,631 @@
+/*************************************************************************/
+/* GodotIO.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+import android.content.*;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.res.AssetManager;
+import android.media.*;
+import android.net.Uri;
+import android.os.*;
+import android.util.DisplayMetrics;
+import android.util.Log;
+import android.util.SparseArray;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Locale;
+import org.godotengine.godot.input.*;
+//android.os.Build
+
+// Wrapper for native library
+
+public class GodotIO {
+
+ AssetManager am;
+ Godot activity;
+ GodotEditText edit;
+
+ MediaPlayer mediaPlayer;
+
+ final int SCREEN_LANDSCAPE = 0;
+ final int SCREEN_PORTRAIT = 1;
+ final int SCREEN_REVERSE_LANDSCAPE = 2;
+ final int SCREEN_REVERSE_PORTRAIT = 3;
+ final int SCREEN_SENSOR_LANDSCAPE = 4;
+ final int SCREEN_SENSOR_PORTRAIT = 5;
+ final int SCREEN_SENSOR = 6;
+
+ /////////////////////////
+ /// FILES
+ /////////////////////////
+
+ public int last_file_id = 1;
+
+ class AssetData {
+
+ public boolean eof = false;
+ public String path;
+ public InputStream is;
+ public int len;
+ public int pos;
+ }
+
+ SparseArray<AssetData> streams;
+
+ public int file_open(String path, boolean write) {
+
+ //System.out.printf("file_open: Attempt to Open %s\n",path);
+
+ //Log.v("MyApp", "TRYING TO OPEN FILE: " + path);
+ if (write)
+ return -1;
+
+ AssetData ad = new AssetData();
+
+ try {
+ ad.is = am.open(path);
+
+ } catch (Exception e) {
+
+ //System.out.printf("Exception on file_open: %s\n",path);
+ return -1;
+ }
+
+ try {
+ ad.len = ad.is.available();
+ } catch (Exception e) {
+
+ System.out.printf("Exception availabling on file_open: %s\n", path);
+ return -1;
+ }
+
+ ad.path = path;
+ ad.pos = 0;
+ ++last_file_id;
+ streams.put(last_file_id, ad);
+
+ return last_file_id;
+ }
+ public int file_get_size(int id) {
+
+ if (streams.get(id) == null) {
+ System.out.printf("file_get_size: Invalid file id: %d\n", id);
+ return -1;
+ }
+
+ return streams.get(id).len;
+ }
+ public void file_seek(int id, int bytes) {
+
+ if (streams.get(id) == null) {
+ System.out.printf("file_get_size: Invalid file id: %d\n", id);
+ return;
+ }
+ //seek sucks
+ AssetData ad = streams.get(id);
+ if (bytes > ad.len)
+ bytes = ad.len;
+ if (bytes < 0)
+ bytes = 0;
+
+ try {
+
+ if (bytes > (int)ad.pos) {
+ int todo = bytes - (int)ad.pos;
+ while (todo > 0) {
+ todo -= ad.is.skip(todo);
+ }
+ ad.pos = bytes;
+ } else if (bytes < (int)ad.pos) {
+
+ ad.is = am.open(ad.path);
+
+ ad.pos = bytes;
+ int todo = bytes;
+ while (todo > 0) {
+ todo -= ad.is.skip(todo);
+ }
+ }
+
+ ad.eof = false;
+ } catch (IOException e) {
+
+ System.out.printf("Exception on file_seek: %s\n", e);
+ return;
+ }
+ }
+
+ public int file_tell(int id) {
+
+ if (streams.get(id) == null) {
+ System.out.printf("file_read: Can't tell eof for invalid file id: %d\n", id);
+ return 0;
+ }
+
+ AssetData ad = streams.get(id);
+ return ad.pos;
+ }
+ public boolean file_eof(int id) {
+
+ if (streams.get(id) == null) {
+ System.out.printf("file_read: Can't check eof for invalid file id: %d\n", id);
+ return false;
+ }
+
+ AssetData ad = streams.get(id);
+ return ad.eof;
+ }
+
+ public byte[] file_read(int id, int bytes) {
+
+ if (streams.get(id) == null) {
+ System.out.printf("file_read: Can't read invalid file id: %d\n", id);
+ return new byte[0];
+ }
+
+ AssetData ad = streams.get(id);
+
+ if (ad.pos + bytes > ad.len) {
+
+ bytes = ad.len - ad.pos;
+ ad.eof = true;
+ }
+
+ if (bytes == 0) {
+
+ return new byte[0];
+ }
+
+ byte[] buf1 = new byte[bytes];
+ int r = 0;
+ try {
+ r = ad.is.read(buf1);
+ } catch (IOException e) {
+
+ System.out.printf("Exception on file_read: %s\n", e);
+ return new byte[bytes];
+ }
+
+ if (r == 0) {
+ return new byte[0];
+ }
+
+ ad.pos += r;
+
+ if (r < bytes) {
+
+ byte[] buf2 = new byte[r];
+ for (int i = 0; i < r; i++)
+ buf2[i] = buf1[i];
+ return buf2;
+ } else {
+
+ return buf1;
+ }
+ }
+
+ public void file_close(int id) {
+
+ if (streams.get(id) == null) {
+ System.out.printf("file_close: Can't close invalid file id: %d\n", id);
+ return;
+ }
+
+ streams.remove(id);
+ }
+
+ /////////////////////////
+ /// DIRECTORIES
+ /////////////////////////
+
+ class AssetDir {
+
+ public String[] files;
+ public int current;
+ public String path;
+ }
+
+ public int last_dir_id = 1;
+
+ SparseArray<AssetDir> dirs;
+
+ public int dir_open(String path) {
+
+ AssetDir ad = new AssetDir();
+ ad.current = 0;
+ ad.path = path;
+
+ try {
+ ad.files = am.list(path);
+ // no way to find path is directory or file exactly.
+ // but if ad.files.length==0, then it's an empty directory or file.
+ if (ad.files.length == 0) {
+ return -1;
+ }
+ } catch (IOException e) {
+
+ System.out.printf("Exception on dir_open: %s\n", e);
+ return -1;
+ }
+
+ //System.out.printf("Opened dir: %s\n",path);
+ ++last_dir_id;
+ dirs.put(last_dir_id, ad);
+
+ return last_dir_id;
+ }
+
+ public boolean dir_is_dir(int id) {
+ if (dirs.get(id) == null) {
+ System.out.printf("dir_next: invalid dir id: %d\n", id);
+ return false;
+ }
+ AssetDir ad = dirs.get(id);
+ //System.out.printf("go next: %d,%d\n",ad.current,ad.files.length);
+ int idx = ad.current;
+ if (idx > 0)
+ idx--;
+
+ if (idx >= ad.files.length)
+ return false;
+ String fname = ad.files[idx];
+
+ try {
+ if (ad.path.equals(""))
+ am.open(fname);
+ else
+ am.open(ad.path + "/" + fname);
+ return false;
+ } catch (Exception e) {
+ return true;
+ }
+ }
+
+ public String dir_next(int id) {
+
+ if (dirs.get(id) == null) {
+ System.out.printf("dir_next: invalid dir id: %d\n", id);
+ return "";
+ }
+
+ AssetDir ad = dirs.get(id);
+ //System.out.printf("go next: %d,%d\n",ad.current,ad.files.length);
+
+ if (ad.current >= ad.files.length) {
+ ad.current++;
+ return "";
+ }
+ String r = ad.files[ad.current];
+ ad.current++;
+ return r;
+ }
+
+ public void dir_close(int id) {
+
+ if (dirs.get(id) == null) {
+ System.out.printf("dir_close: invalid dir id: %d\n", id);
+ return;
+ }
+
+ dirs.remove(id);
+ }
+
+ GodotIO(Godot p_activity) {
+
+ am = p_activity.getAssets();
+ activity = p_activity;
+ //streams = new HashMap<Integer, AssetData>();
+ streams = new SparseArray<AssetData>();
+ dirs = new SparseArray<AssetDir>();
+ }
+
+ /////////////////////////
+ // AUDIO
+ /////////////////////////
+
+ private Object buf;
+ private Thread mAudioThread;
+ private AudioTrack mAudioTrack;
+
+ public Object audioInit(int sampleRate, int desiredFrames) {
+ int channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
+ int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
+ int frameSize = 4;
+
+ System.out.printf("audioInit: initializing audio:\n");
+
+ //Log.v("Godot", "Godot audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + ((float)sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
+
+ // Let the user pick a larger buffer if they really want -- but ye
+ // gods they probably shouldn't, the minimums are horrifyingly high
+ // latency already
+ desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
+
+ mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
+ channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
+
+ audioStartThread();
+
+ //Log.v("Godot", "Godot audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + ((float)mAudioTrack.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer");
+
+ buf = new short[desiredFrames * 2];
+ return buf;
+ }
+
+ public void audioStartThread() {
+ mAudioThread = new Thread(new Runnable() {
+ public void run() {
+ mAudioTrack.play();
+ GodotLib.audio();
+ }
+ });
+
+ // I'd take REALTIME if I could get it!
+ mAudioThread.setPriority(Thread.MAX_PRIORITY);
+ mAudioThread.start();
+ }
+
+ public void audioWriteShortBuffer(short[] buffer) {
+ for (int i = 0; i < buffer.length;) {
+ int result = mAudioTrack.write(buffer, i, buffer.length - i);
+ if (result > 0) {
+ i += result;
+ } else if (result == 0) {
+ try {
+ Thread.sleep(1);
+ } catch (InterruptedException e) {
+ // Nom nom
+ }
+ } else {
+ Log.w("Godot", "Godot audio: error return from write(short)");
+ return;
+ }
+ }
+ }
+
+ public void audioQuit() {
+ if (mAudioThread != null) {
+ try {
+ mAudioThread.join();
+ } catch (Exception e) {
+ Log.v("Godot", "Problem stopping audio thread: " + e);
+ }
+ mAudioThread = null;
+
+ //Log.v("Godot", "Finished waiting for audio thread");
+ }
+
+ if (mAudioTrack != null) {
+ mAudioTrack.stop();
+ mAudioTrack = null;
+ }
+ }
+
+ public void audioPause(boolean p_pause) {
+
+ if (p_pause)
+ mAudioTrack.pause();
+ else
+ mAudioTrack.play();
+ }
+
+ /////////////////////////
+ // MISCELLANEOUS OS IO
+ /////////////////////////
+
+ public int openURI(String p_uri) {
+
+ try {
+ Log.v("MyApp", "TRYING TO OPEN URI: " + p_uri);
+ String path = p_uri;
+ String type = "";
+ if (path.startsWith("/")) {
+ //absolute path to filesystem, prepend file://
+ path = "file://" + path;
+ if (p_uri.endsWith(".png") || p_uri.endsWith(".jpg") || p_uri.endsWith(".gif") || p_uri.endsWith(".webp")) {
+
+ type = "image/*";
+ }
+ }
+
+ Intent intent = new Intent();
+ intent.setAction(Intent.ACTION_VIEW);
+ if (!type.equals("")) {
+ intent.setDataAndType(Uri.parse(path), type);
+ } else {
+ intent.setData(Uri.parse(path));
+ }
+
+ activity.startActivity(intent);
+ return 0;
+ } catch (ActivityNotFoundException e) {
+
+ return 1;
+ }
+ }
+
+ public String getDataDir() {
+
+ return activity.getFilesDir().getAbsolutePath();
+ }
+
+ public String getLocale() {
+
+ return Locale.getDefault().toString();
+ }
+
+ public String getModel() {
+ return Build.MODEL;
+ }
+
+ public int getScreenDPI() {
+ DisplayMetrics metrics = activity.getApplicationContext().getResources().getDisplayMetrics();
+ return (int)(metrics.density * 160f);
+ }
+
+ public void showKeyboard(String p_existing_text) {
+ if (edit != null)
+ edit.showKeyboard(p_existing_text);
+
+ //InputMethodManager inputMgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
+ //inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
+ };
+
+ public void hideKeyboard() {
+ if (edit != null)
+ edit.hideKeyboard();
+ };
+
+ public void setScreenOrientation(int p_orientation) {
+
+ switch (p_orientation) {
+
+ case SCREEN_LANDSCAPE: {
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+ } break;
+ case SCREEN_PORTRAIT: {
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+ } break;
+ case SCREEN_REVERSE_LANDSCAPE: {
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
+ } break;
+ case SCREEN_REVERSE_PORTRAIT: {
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
+ } break;
+ case SCREEN_SENSOR_LANDSCAPE: {
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
+ } break;
+ case SCREEN_SENSOR_PORTRAIT: {
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
+ } break;
+ case SCREEN_SENSOR: {
+ activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
+ } break;
+ }
+ };
+
+ public void setEdit(GodotEditText _edit) {
+ edit = _edit;
+ }
+
+ public void playVideo(String p_path) {
+ Uri filePath = Uri.parse(p_path);
+ mediaPlayer = new MediaPlayer();
+
+ try {
+ mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
+ mediaPlayer.setDataSource(activity.getApplicationContext(), filePath);
+ mediaPlayer.prepare();
+ mediaPlayer.start();
+ } catch (IOException e) {
+ System.out.println("IOError while playing video");
+ }
+ }
+
+ public boolean isVideoPlaying() {
+ if (mediaPlayer != null) {
+ return mediaPlayer.isPlaying();
+ }
+ return false;
+ }
+
+ public void pauseVideo() {
+ if (mediaPlayer != null) {
+ mediaPlayer.pause();
+ }
+ }
+
+ public void stopVideo() {
+ if (mediaPlayer != null) {
+ mediaPlayer.release();
+ mediaPlayer = null;
+ }
+ }
+
+ public static final int SYSTEM_DIR_DESKTOP = 0;
+ public static final int SYSTEM_DIR_DCIM = 1;
+ public static final int SYSTEM_DIR_DOCUMENTS = 2;
+ public static final int SYSTEM_DIR_DOWNLOADS = 3;
+ public static final int SYSTEM_DIR_MOVIES = 4;
+ public static final int SYSTEM_DIR_MUSIC = 5;
+ public static final int SYSTEM_DIR_PICTURES = 6;
+ public static final int SYSTEM_DIR_RINGTONES = 7;
+
+ public String getSystemDir(int idx) {
+
+ String what = "";
+ switch (idx) {
+ case SYSTEM_DIR_DESKTOP: {
+ //what=Environment.DIRECTORY_DOCUMENTS;
+ what = Environment.DIRECTORY_DOWNLOADS;
+ } break;
+ case SYSTEM_DIR_DCIM: {
+ what = Environment.DIRECTORY_DCIM;
+
+ } break;
+ case SYSTEM_DIR_DOCUMENTS: {
+ what = Environment.DIRECTORY_DOWNLOADS;
+ //what=Environment.DIRECTORY_DOCUMENTS;
+ } break;
+ case SYSTEM_DIR_DOWNLOADS: {
+ what = Environment.DIRECTORY_DOWNLOADS;
+
+ } break;
+ case SYSTEM_DIR_MOVIES: {
+ what = Environment.DIRECTORY_MOVIES;
+
+ } break;
+ case SYSTEM_DIR_MUSIC: {
+ what = Environment.DIRECTORY_MUSIC;
+ } break;
+ case SYSTEM_DIR_PICTURES: {
+ what = Environment.DIRECTORY_PICTURES;
+ } break;
+ case SYSTEM_DIR_RINGTONES: {
+ what = Environment.DIRECTORY_RINGTONES;
+
+ } break;
+ }
+
+ if (what.equals(""))
+ return "";
+ return Environment.getExternalStoragePublicDirectory(what).getAbsolutePath();
+ }
+
+ protected static final String PREFS_FILE = "device_id.xml";
+ protected static final String PREFS_DEVICE_ID = "device_id";
+
+ public static String unique_id = "";
+ public String getUniqueID() {
+
+ return unique_id;
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotInstrumentation.java b/platform/android/java/lib/src/org/godotengine/godot/GodotInstrumentation.java
new file mode 100644
index 0000000000..0466f380e8
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotInstrumentation.java
@@ -0,0 +1,50 @@
+/*************************************************************************/
+/* GodotInstrumentation.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+
+import android.app.Instrumentation;
+import android.content.Intent;
+import android.os.Bundle;
+
+public class GodotInstrumentation extends Instrumentation {
+ private Intent intent;
+
+ @Override
+ public void onCreate(Bundle arguments) {
+ intent = arguments.getParcelable("intent");
+ start();
+ }
+
+ @Override
+ public void onStart() {
+ startActivitySync(intent);
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
new file mode 100644
index 0000000000..af51c840cb
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
@@ -0,0 +1,214 @@
+/*************************************************************************/
+/* GodotLib.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+
+import android.app.Activity;
+import android.hardware.SensorEvent;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+
+/**
+ * Wrapper for native library
+ */
+public class GodotLib {
+
+ public static GodotIO io;
+
+ static {
+ System.loadLibrary("godot_android");
+ }
+
+ /**
+ * Invoked on the main thread to initialize Godot native layer.
+ */
+ public static native void initialize(Godot p_instance, Object p_asset_manager, boolean use_apk_expansion);
+
+ /**
+ * Invoked on the main thread to clean up Godot native layer.
+ * @see Activity#onDestroy()
+ */
+ public static native void ondestroy(Godot p_instance);
+
+ /**
+ * Invoked on the GL thread to complete setup for the Godot native layer logic.
+ * @param p_cmdline Command line arguments used to configure Godot native layer components.
+ */
+ public static native void setup(String[] p_cmdline);
+
+ /**
+ * Invoked on the GL thread when the underlying Android surface has changed size.
+ * @param width
+ * @param height
+ * @see android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(GL10, int, int)
+ */
+ public static native void resize(int width, int height);
+
+ /**
+ * Invoked on the GL thread when the underlying Android surface is created or recreated.
+ * @param p_32_bits
+ * @see android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)
+ */
+ public static native void newcontext(boolean p_32_bits);
+
+ /**
+ * Forward {@link Activity#onBackPressed()} event from the main thread to the GL thread.
+ */
+ public static native void back();
+
+ /**
+ * Invoked on the GL thread to draw the current frame.
+ * @see android.opengl.GLSurfaceView.Renderer#onDrawFrame(GL10)
+ */
+ public static native void step();
+
+ /**
+ * Forward touch events from the main thread to the GL thread.
+ */
+ public static native void touch(int what, int pointer, int howmany, int[] arr);
+
+ /**
+ * Forward accelerometer sensor events from the main thread to the GL thread.
+ * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
+ */
+ public static native void accelerometer(float x, float y, float z);
+
+ /**
+ * Forward gravity sensor events from the main thread to the GL thread.
+ * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
+ */
+ public static native void gravity(float x, float y, float z);
+
+ /**
+ * Forward magnetometer sensor events from the main thread to the GL thread.
+ * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
+ */
+ public static native void magnetometer(float x, float y, float z);
+
+ /**
+ * Forward gyroscope sensor events from the main thread to the GL thread.
+ * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
+ */
+ public static native void gyroscope(float x, float y, float z);
+
+ /**
+ * Forward regular key events from the main thread to the GL thread.
+ */
+ public static native void key(int p_scancode, int p_unicode_char, boolean p_pressed);
+
+ /**
+ * Forward game device's key events from the main thread to the GL thread.
+ */
+ public static native void joybutton(int p_device, int p_but, boolean p_pressed);
+
+ /**
+ * Forward joystick devices axis motion events from the main thread to the GL thread.
+ */
+ public static native void joyaxis(int p_device, int p_axis, float p_value);
+
+ /**
+ * Forward joystick devices hat motion events from the main thread to the GL thread.
+ */
+ public static native void joyhat(int p_device, int p_hat_x, int p_hat_y);
+
+ /**
+ * Fires when a joystick device is added or removed.
+ */
+ public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name);
+
+ /**
+ * Invoked when the Android activity resumes.
+ * @see Activity#onResume()
+ */
+ public static native void focusin();
+
+ /**
+ * Invoked when the Android activity pauses.
+ * @see Activity#onPause()
+ */
+ public static native void focusout();
+
+ /**
+ * Invoked when the audio thread is started.
+ */
+ public static native void audio();
+
+ /**
+ * Used to setup a {@link org.godotengine.godot.Godot.SingletonBase} instance.
+ * @param p_name Name of the instance.
+ * @param p_object Reference to the singleton instance.
+ */
+ public static native void singleton(String p_name, Object p_object);
+
+ /**
+ * Used to complete registration of the {@link org.godotengine.godot.Godot.SingletonBase} instance's methods.
+ * @param p_sname Name of the instance
+ * @param p_name Name of the method to register
+ * @param p_ret Return type of the registered method
+ * @param p_params Method parameters types
+ */
+ public static native void method(String p_sname, String p_name, String p_ret, String[] p_params);
+
+ /**
+ * Used to access Godot global properties.
+ * @param p_key Property key
+ * @return String value of the property
+ */
+ public static native String getGlobal(String p_key);
+
+ /**
+ * Invoke method |p_method| on the Godot object specified by |p_id|
+ * @param p_id Id of the Godot object to invoke
+ * @param p_method Name of the method to invoke
+ * @param p_params Parameters to use for method invocation
+ */
+ public static native void callobject(int p_id, String p_method, Object[] p_params);
+
+ /**
+ * Invoke method |p_method| on the Godot object specified by |p_id| during idle time.
+ * @param p_id Id of the Godot object to invoke
+ * @param p_method Name of the method to invoke
+ * @param p_params Parameters to use for method invocation
+ */
+ public static native void calldeferred(int p_id, String p_method, Object[] p_params);
+
+ /**
+ * Forward the results from a permission request.
+ * @see Activity#onRequestPermissionsResult(int, String[], int[])
+ * @param p_permission Request permission
+ * @param p_result True if the permission was granted, false otherwise
+ */
+ public static native void requestPermissionResult(String p_permission, boolean p_result);
+
+ /**
+ * Invoked on the GL thread to configure the height of the virtual keyboard.
+ */
+ public static native void setVirtualKeyboardHeight(int p_height);
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotPaymentV3.java b/platform/android/java/lib/src/org/godotengine/godot/GodotPaymentV3.java
new file mode 100644
index 0000000000..1432cd3a67
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotPaymentV3.java
@@ -0,0 +1,230 @@
+/*************************************************************************/
+/* GodotPaymentV3.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+
+import android.app.Activity;
+import android.util.Log;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.godotengine.godot.payments.PaymentsManager;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class GodotPaymentV3 extends Godot.SingletonBase {
+
+ private Godot activity;
+ private Integer purchaseCallbackId = 0;
+ private String accessToken;
+ private String purchaseValidationUrlPrefix;
+ private String transactionId;
+ private PaymentsManager mPaymentManager;
+ private Dictionary mSkuDetails = new Dictionary();
+
+ public void purchase(final String sku, final String transactionId) {
+ activity.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mPaymentManager.requestPurchase(sku, transactionId);
+ }
+ });
+ }
+
+ static public Godot.SingletonBase initialize(Activity p_activity) {
+
+ return new GodotPaymentV3(p_activity);
+ }
+
+ public GodotPaymentV3(Activity p_activity) {
+
+ registerClass("GodotPayments", new String[] { "purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", "setAutoConsume", "consume", "querySkuDetails", "isConnected" });
+ activity = (Godot)p_activity;
+ mPaymentManager = activity.getPaymentsManager();
+ mPaymentManager.setBaseSingleton(this);
+ }
+
+ public void consumeUnconsumedPurchases() {
+ activity.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mPaymentManager.consumeUnconsumedPurchases();
+ }
+ });
+ }
+
+ private String signature;
+
+ public String getSignature() {
+ return this.signature;
+ }
+
+ public void callbackSuccess(String ticket, String signature, String sku) {
+ GodotLib.calldeferred(purchaseCallbackId, "purchase_success", new Object[] { ticket, signature, sku });
+ }
+
+ public void callbackSuccessProductMassConsumed(String ticket, String signature, String sku) {
+ Log.d(this.getClass().getName(), "callbackSuccessProductMassConsumed > " + ticket + "," + signature + "," + sku);
+ GodotLib.calldeferred(purchaseCallbackId, "consume_success", new Object[] { ticket, signature, sku });
+ }
+
+ public void callbackSuccessNoUnconsumedPurchases() {
+ GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[] {});
+ }
+
+ public void callbackFailConsume(String message) {
+ GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[] { message });
+ }
+
+ public void callbackFail(String message) {
+ GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[] { message });
+ }
+
+ public void callbackCancel() {
+ GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[] {});
+ }
+
+ public void callbackAlreadyOwned(String sku) {
+ GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[] { sku });
+ }
+
+ public int getPurchaseCallbackId() {
+ return purchaseCallbackId;
+ }
+
+ public void setPurchaseCallbackId(int purchaseCallbackId) {
+ this.purchaseCallbackId = purchaseCallbackId;
+ }
+
+ public String getPurchaseValidationUrlPrefix() {
+ return this.purchaseValidationUrlPrefix;
+ }
+
+ public void setPurchaseValidationUrlPrefix(String url) {
+ this.purchaseValidationUrlPrefix = url;
+ }
+
+ public String getAccessToken() {
+ return accessToken;
+ }
+
+ public void setAccessToken(String accessToken) {
+ this.accessToken = accessToken;
+ }
+
+ public void setTransactionId(String transactionId) {
+ this.transactionId = transactionId;
+ }
+
+ public String getTransactionId() {
+ return this.transactionId;
+ }
+
+ // request purchased items are not consumed
+ public void requestPurchased() {
+ activity.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mPaymentManager.requestPurchased();
+ }
+ });
+ }
+
+ // callback for requestPurchased()
+ public void callbackPurchased(String receipt, String signature, String sku) {
+ GodotLib.calldeferred(purchaseCallbackId, "has_purchased", new Object[] { receipt, signature, sku });
+ }
+
+ public void callbackDisconnected() {
+ GodotLib.calldeferred(purchaseCallbackId, "iap_disconnected", new Object[] {});
+ }
+
+ public void callbackConnected() {
+ GodotLib.calldeferred(purchaseCallbackId, "iap_connected", new Object[] {});
+ }
+
+ // true if connected, false otherwise
+ public boolean isConnected() {
+ return mPaymentManager.isConnected();
+ }
+
+ // consume item automatically after purchase. default is true.
+ public void setAutoConsume(boolean autoConsume) {
+ mPaymentManager.setAutoConsume(autoConsume);
+ }
+
+ // consume a specific item
+ public void consume(String sku) {
+ mPaymentManager.consume(sku);
+ }
+
+ // query in app item detail info
+ public void querySkuDetails(String[] list) {
+ List<String> nKeys = Arrays.asList(list);
+ List<String> cKeys = Arrays.asList(mSkuDetails.get_keys());
+ ArrayList<String> fKeys = new ArrayList<String>();
+ for (String key : nKeys) {
+ if (!cKeys.contains(key)) {
+ fKeys.add(key);
+ }
+ }
+ if (fKeys.size() > 0) {
+ mPaymentManager.querySkuDetails(fKeys.toArray(new String[0]));
+ } else {
+ completeSkuDetail();
+ }
+ }
+
+ public void addSkuDetail(String itemJson) {
+ JSONObject o = null;
+ try {
+ o = new JSONObject(itemJson);
+ Dictionary item = new Dictionary();
+ item.put("type", o.optString("type"));
+ item.put("product_id", o.optString("productId"));
+ item.put("title", o.optString("title"));
+ item.put("description", o.optString("description"));
+ item.put("price", o.optString("price"));
+ item.put("price_currency_code", o.optString("price_currency_code"));
+ item.put("price_amount", 0.000001d * o.optLong("price_amount_micros"));
+ mSkuDetails.put(item.get("product_id").toString(), item);
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void completeSkuDetail() {
+ GodotLib.calldeferred(purchaseCallbackId, "sku_details_complete", new Object[] { mSkuDetails });
+ }
+
+ public void errorSkuDetail(String errorMessage) {
+ GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[] { errorMessage });
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java b/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java
new file mode 100644
index 0000000000..8e3775c2a9
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotRenderer.java
@@ -0,0 +1,61 @@
+/*************************************************************************/
+/* GodotRenderer.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+
+import android.opengl.GLSurfaceView;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+import org.godotengine.godot.utils.GLUtils;
+
+/**
+ * Godot's renderer implementation.
+ */
+class GodotRenderer implements GLSurfaceView.Renderer {
+
+ public void onDrawFrame(GL10 gl) {
+ GodotLib.step();
+ for (int i = 0; i < Godot.singleton_count; i++) {
+ Godot.singletons[i].onGLDrawFrame(gl);
+ }
+ }
+
+ public void onSurfaceChanged(GL10 gl, int width, int height) {
+
+ GodotLib.resize(width, height);
+ for (int i = 0; i < Godot.singleton_count; i++) {
+ Godot.singletons[i].onGLSurfaceChanged(gl, width, height);
+ }
+ }
+
+ public void onSurfaceCreated(GL10 gl, EGLConfig config) {
+ GodotLib.newcontext(GLUtils.use_32);
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotView.java b/platform/android/java/lib/src/org/godotengine/godot/GodotView.java
new file mode 100644
index 0000000000..fc3e47e69d
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/GodotView.java
@@ -0,0 +1,170 @@
+/*************************************************************************/
+/* GodotView.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot;
+import android.annotation.SuppressLint;
+import android.graphics.PixelFormat;
+import android.opengl.GLSurfaceView;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+import org.godotengine.godot.input.GodotInputHandler;
+import org.godotengine.godot.utils.GLUtils;
+import org.godotengine.godot.xr.XRMode;
+import org.godotengine.godot.xr.ovr.OvrConfigChooser;
+import org.godotengine.godot.xr.ovr.OvrContextFactory;
+import org.godotengine.godot.xr.ovr.OvrWindowSurfaceFactory;
+import org.godotengine.godot.xr.regular.RegularConfigChooser;
+import org.godotengine.godot.xr.regular.RegularContextFactory;
+import org.godotengine.godot.xr.regular.RegularFallbackConfigChooser;
+
+/**
+ * A simple GLSurfaceView sub-class that demonstrate how to perform
+ * OpenGL ES 2.0 rendering into a GL Surface. Note the following important
+ * details:
+ *
+ * - The class must use a custom context factory to enable 2.0 rendering.
+ * See ContextFactory class definition below.
+ *
+ * - The class must use a custom EGLConfigChooser to be able to select
+ * an EGLConfig that supports 2.0. This is done by providing a config
+ * specification to eglChooseConfig() that has the attribute
+ * EGL10.ELG_RENDERABLE_TYPE containing the EGL_OPENGL_ES2_BIT flag
+ * set. See ConfigChooser class definition below.
+ *
+ * - The class must select the surface's format, then choose an EGLConfig
+ * that matches it exactly (with regards to red/green/blue/alpha channels
+ * bit depths). Failure to do so would result in an EGL_BAD_MATCH error.
+ */
+public class GodotView extends GLSurfaceView {
+
+ private static String TAG = GodotView.class.getSimpleName();
+
+ private final Godot activity;
+ private final GodotInputHandler inputHandler;
+
+ public GodotView(Godot activity, XRMode xrMode, boolean p_use_gl3, boolean p_use_32_bits, boolean p_use_debug_opengl) {
+ super(activity);
+ GLUtils.use_gl3 = p_use_gl3;
+ GLUtils.use_32 = p_use_32_bits;
+ GLUtils.use_debug_opengl = p_use_debug_opengl;
+
+ this.activity = activity;
+ this.inputHandler = new GodotInputHandler(this);
+ init(xrMode, false, 16, 0);
+ }
+
+ public void initInputDevices() {
+ this.inputHandler.initInputDevices();
+ }
+
+ @SuppressLint("ClickableViewAccessibility")
+ @Override
+ public boolean onTouchEvent(MotionEvent event) {
+ super.onTouchEvent(event);
+ return activity.gotTouchEvent(event);
+ }
+
+ @Override
+ public boolean onKeyUp(final int keyCode, KeyEvent event) {
+ return inputHandler.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
+ }
+
+ @Override
+ public boolean onKeyDown(final int keyCode, KeyEvent event) {
+ return inputHandler.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
+ }
+
+ @Override
+ public boolean onGenericMotionEvent(MotionEvent event) {
+ return inputHandler.onGenericMotionEvent(event) || super.onGenericMotionEvent(event);
+ }
+
+ private void init(XRMode xrMode, boolean translucent, int depth, int stencil) {
+
+ setPreserveEGLContextOnPause(true);
+ setFocusableInTouchMode(true);
+ switch (xrMode) {
+
+ case OVR:
+ // Replace the default egl config chooser.
+ setEGLConfigChooser(new OvrConfigChooser());
+
+ // Replace the default context factory.
+ setEGLContextFactory(new OvrContextFactory());
+
+ // Replace the default window surface factory.
+ setEGLWindowSurfaceFactory(new OvrWindowSurfaceFactory());
+ break;
+
+ case REGULAR:
+ default:
+ /* By default, GLSurfaceView() creates a RGB_565 opaque surface.
+ * If we want a translucent one, we should change the surface's
+ * format here, using PixelFormat.TRANSLUCENT for GL Surfaces
+ * is interpreted as any 32-bit surface with alpha by SurfaceFlinger.
+ */
+ if (translucent) {
+ this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
+ }
+
+ /* Setup the context factory for 2.0 rendering.
+ * See ContextFactory class definition below
+ */
+ setEGLContextFactory(new RegularContextFactory());
+
+ /* We need to choose an EGLConfig that matches the format of
+ * our surface exactly. This is going to be done in our
+ * custom config chooser. See ConfigChooser class definition
+ * below.
+ */
+
+ if (GLUtils.use_32) {
+ setEGLConfigChooser(translucent ?
+ new RegularFallbackConfigChooser(8, 8, 8, 8, 24, stencil,
+ new RegularConfigChooser(8, 8, 8, 8, 16, stencil)) :
+ new RegularFallbackConfigChooser(8, 8, 8, 8, 24, stencil,
+ new RegularConfigChooser(5, 6, 5, 0, 16, stencil)));
+
+ } else {
+ setEGLConfigChooser(translucent ?
+ new RegularConfigChooser(8, 8, 8, 8, 16, stencil) :
+ new RegularConfigChooser(5, 6, 5, 0, 16, stencil));
+ }
+ break;
+ }
+
+ /* Set the renderer responsible for frame rendering */
+ setRenderer(new GodotRenderer());
+ }
+
+ public void onBackPressed() {
+ activity.onBackPressed();
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java
new file mode 100644
index 0000000000..45b739baa0
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotEditText.java
@@ -0,0 +1,171 @@
+/*************************************************************************/
+/* GodotEditText.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.input;
+import android.content.Context;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.view.KeyEvent;
+import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.widget.EditText;
+import java.lang.ref.WeakReference;
+import org.godotengine.godot.*;
+
+public class GodotEditText extends EditText {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+ private final static int HANDLER_OPEN_IME_KEYBOARD = 2;
+ private final static int HANDLER_CLOSE_IME_KEYBOARD = 3;
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+ private GodotView mView;
+ private GodotTextInputWrapper mInputWrapper;
+ private EditHandler sHandler = new EditHandler(this);
+ private String mOriginText;
+
+ private static class EditHandler extends Handler {
+ private final WeakReference<GodotEditText> mEdit;
+ public EditHandler(GodotEditText edit) {
+ mEdit = new WeakReference<>(edit);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ GodotEditText edit = mEdit.get();
+ if (edit != null) {
+ edit.handleMessage(msg);
+ }
+ }
+ }
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+ public GodotEditText(final Context context) {
+ super(context);
+ this.initView();
+ }
+
+ public GodotEditText(final Context context, final AttributeSet attrs) {
+ super(context, attrs);
+ this.initView();
+ }
+
+ public GodotEditText(final Context context, final AttributeSet attrs, final int defStyle) {
+ super(context, attrs, defStyle);
+ this.initView();
+ }
+
+ protected void initView() {
+ this.setPadding(0, 0, 0, 0);
+ this.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
+ }
+
+ private void handleMessage(final Message msg) {
+ switch (msg.what) {
+ case HANDLER_OPEN_IME_KEYBOARD: {
+ GodotEditText edit = (GodotEditText)msg.obj;
+ String text = edit.mOriginText;
+ if (edit.requestFocus()) {
+ edit.removeTextChangedListener(edit.mInputWrapper);
+ edit.setText("");
+ edit.append(text);
+ edit.mInputWrapper.setOriginText(text);
+ edit.addTextChangedListener(edit.mInputWrapper);
+ final InputMethodManager imm = (InputMethodManager)mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+ imm.showSoftInput(edit, 0);
+ }
+ } break;
+
+ case HANDLER_CLOSE_IME_KEYBOARD: {
+ GodotEditText edit = (GodotEditText)msg.obj;
+
+ edit.removeTextChangedListener(mInputWrapper);
+ final InputMethodManager imm = (InputMethodManager)mView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+ imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
+ edit.mView.requestFocus();
+ } break;
+ }
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+ public void setView(final GodotView view) {
+ this.mView = view;
+ if (mInputWrapper == null)
+ mInputWrapper = new GodotTextInputWrapper(mView, this);
+ this.setOnEditorActionListener(mInputWrapper);
+ view.requestFocus();
+ }
+
+ // ===========================================================
+ // Methods for/from SuperClass/Interfaces
+ // ===========================================================
+ @Override
+ public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
+ super.onKeyDown(keyCode, keyEvent);
+
+ /* Let GlSurfaceView get focus if back key is input. */
+ if (keyCode == KeyEvent.KEYCODE_BACK) {
+ this.mView.requestFocus();
+ }
+
+ return true;
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+ public void showKeyboard(String p_existing_text) {
+ this.mOriginText = p_existing_text;
+
+ final Message msg = new Message();
+ msg.what = HANDLER_OPEN_IME_KEYBOARD;
+ msg.obj = this;
+ sHandler.sendMessage(msg);
+ }
+
+ public void hideKeyboard() {
+ final Message msg = new Message();
+ msg.what = HANDLER_CLOSE_IME_KEYBOARD;
+ msg.obj = this;
+ sHandler.sendMessage(msg);
+ }
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
new file mode 100644
index 0000000000..a443a0ad90
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotInputHandler.java
@@ -0,0 +1,360 @@
+/*************************************************************************/
+/* GodotInputHandler.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.input;
+
+import static org.godotengine.godot.utils.GLUtils.DEBUG;
+
+import android.util.Log;
+import android.view.InputDevice;
+import android.view.InputDevice.MotionRange;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import org.godotengine.godot.GodotLib;
+import org.godotengine.godot.GodotView;
+import org.godotengine.godot.input.InputManagerCompat.InputDeviceListener;
+
+/**
+ * Handles input related events for the {@link GodotView} view.
+ */
+public class GodotInputHandler implements InputDeviceListener {
+
+ private final ArrayList<Joystick> joysticksDevices = new ArrayList<Joystick>();
+
+ private final GodotView godotView;
+ private final InputManagerCompat inputManager;
+
+ public GodotInputHandler(GodotView godotView) {
+ this.godotView = godotView;
+ this.inputManager = InputManagerCompat.Factory.getInputManager(godotView.getContext());
+ this.inputManager.registerInputDeviceListener(this, null);
+ }
+
+ private void queueEvent(Runnable task) {
+ godotView.queueEvent(task);
+ }
+
+ private boolean isKeyEvent_GameDevice(int source) {
+ // Note that keyboards are often (SOURCE_KEYBOARD | SOURCE_DPAD)
+ if (source == (InputDevice.SOURCE_KEYBOARD | InputDevice.SOURCE_DPAD))
+ return false;
+
+ return (source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK || (source & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD || (source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD;
+ }
+
+ public boolean onKeyUp(final int keyCode, KeyEvent event) {
+ if (keyCode == KeyEvent.KEYCODE_BACK) {
+ return true;
+ }
+
+ if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
+ return false;
+ };
+
+ int source = event.getSource();
+ if (isKeyEvent_GameDevice(source)) {
+
+ final int button = getGodotButton(keyCode);
+ final int device_id = findJoystickDevice(event.getDeviceId());
+
+ // Check if the device exists
+ if (device_id > -1) {
+ queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.joybutton(device_id, button, false);
+ }
+ });
+ return true;
+ }
+ } else {
+ final int chr = event.getUnicodeChar(0);
+ queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.key(keyCode, chr, false);
+ }
+ });
+ };
+
+ return false;
+ }
+
+ public boolean onKeyDown(final int keyCode, KeyEvent event) {
+ if (keyCode == KeyEvent.KEYCODE_BACK) {
+ godotView.onBackPressed();
+ // press 'back' button should not terminate program
+ //normal handle 'back' event in game logic
+ return true;
+ }
+
+ if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
+ return false;
+ };
+
+ int source = event.getSource();
+ //Log.e(TAG, String.format("Key down! source %d, device %d, joystick %d, %d, %d", event.getDeviceId(), source, (source & InputDevice.SOURCE_JOYSTICK), (source & InputDevice.SOURCE_DPAD), (source & InputDevice.SOURCE_GAMEPAD)));
+
+ if (isKeyEvent_GameDevice(source)) {
+
+ if (event.getRepeatCount() > 0) // ignore key echo
+ return true;
+
+ final int button = getGodotButton(keyCode);
+ final int device_id = findJoystickDevice(event.getDeviceId());
+
+ // Check if the device exists
+ if (device_id > -1) {
+ queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.joybutton(device_id, button, true);
+ }
+ });
+ return true;
+ }
+ } else {
+ final int chr = event.getUnicodeChar(0);
+ queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.key(keyCode, chr, true);
+ }
+ });
+ };
+
+ return false;
+ }
+
+ public boolean onGenericMotionEvent(MotionEvent event) {
+ if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK && event.getAction() == MotionEvent.ACTION_MOVE) {
+
+ final int device_id = findJoystickDevice(event.getDeviceId());
+
+ // Check if the device exists
+ if (device_id > -1) {
+ Joystick joy = joysticksDevices.get(device_id);
+
+ for (int i = 0; i < joy.axes.size(); i++) {
+ InputDevice.MotionRange range = joy.axes.get(i);
+ final float value = (event.getAxisValue(range.getAxis()) - range.getMin()) / range.getRange() * 2.0f - 1.0f;
+ final int idx = i;
+ queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.joyaxis(device_id, idx, value);
+ }
+ });
+ }
+
+ for (int i = 0; i < joy.hats.size(); i += 2) {
+ final int hatX = Math.round(event.getAxisValue(joy.hats.get(i).getAxis()));
+ final int hatY = Math.round(event.getAxisValue(joy.hats.get(i + 1).getAxis()));
+ queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.joyhat(device_id, hatX, hatY);
+ }
+ });
+ }
+ return true;
+ }
+ };
+
+ return false;
+ }
+
+ public void initInputDevices() {
+ /* initially add input devices*/
+ int[] deviceIds = inputManager.getInputDeviceIds();
+ for (int deviceId : deviceIds) {
+ InputDevice device = inputManager.getInputDevice(deviceId);
+ if (DEBUG) {
+ Log.v("GodotView", String.format("init() deviceId:%d, Name:%s\n", deviceId, device.getName()));
+ }
+ onInputDeviceAdded(deviceId);
+ }
+ }
+
+ @Override
+ public void onInputDeviceAdded(int deviceId) {
+ int id = findJoystickDevice(deviceId);
+
+ // Check if the device has not been already added
+ if (id < 0) {
+ InputDevice device = inputManager.getInputDevice(deviceId);
+ //device can be null if deviceId is not found
+ if (device != null) {
+ int sources = device.getSources();
+ if (((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) ||
+ ((sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK)) {
+ id = joysticksDevices.size();
+
+ Joystick joy = new Joystick();
+ joy.device_id = deviceId;
+ joy.name = device.getName();
+ joy.axes = new ArrayList<InputDevice.MotionRange>();
+ joy.hats = new ArrayList<InputDevice.MotionRange>();
+
+ List<InputDevice.MotionRange> ranges = device.getMotionRanges();
+ Collections.sort(ranges, new RangeComparator());
+
+ for (InputDevice.MotionRange range : ranges) {
+ if (range.getAxis() == MotionEvent.AXIS_HAT_X || range.getAxis() == MotionEvent.AXIS_HAT_Y) {
+ joy.hats.add(range);
+ } else {
+ joy.axes.add(range);
+ }
+ }
+
+ joysticksDevices.add(joy);
+
+ final int device_id = id;
+ final String name = joy.name;
+ queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.joyconnectionchanged(device_id, true, name);
+ }
+ });
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onInputDeviceRemoved(int deviceId) {
+ final int device_id = findJoystickDevice(deviceId);
+
+ // Check if the evice has not been already removed
+ if (device_id > -1) {
+ joysticksDevices.remove(device_id);
+
+ queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ GodotLib.joyconnectionchanged(device_id, false, "");
+ }
+ });
+ }
+ }
+
+ @Override
+ public void onInputDeviceChanged(int deviceId) {
+ onInputDeviceRemoved(deviceId);
+ onInputDeviceAdded(deviceId);
+ }
+
+ private static class RangeComparator implements Comparator<MotionRange> {
+ @Override
+ public int compare(MotionRange arg0, MotionRange arg1) {
+ return arg0.getAxis() - arg1.getAxis();
+ }
+ }
+
+ public static int getGodotButton(int keyCode) {
+ int button;
+ switch (keyCode) {
+ case KeyEvent.KEYCODE_BUTTON_A: // Android A is SNES B
+ button = 0;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_B:
+ button = 1;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_X: // Android X is SNES Y
+ button = 2;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_Y:
+ button = 3;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_L1:
+ button = 9;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_L2:
+ button = 15;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_R1:
+ button = 10;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_R2:
+ button = 16;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_SELECT:
+ button = 4;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_START:
+ button = 6;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_THUMBL:
+ button = 7;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_THUMBR:
+ button = 8;
+ break;
+ case KeyEvent.KEYCODE_DPAD_UP:
+ button = 11;
+ break;
+ case KeyEvent.KEYCODE_DPAD_DOWN:
+ button = 12;
+ break;
+ case KeyEvent.KEYCODE_DPAD_LEFT:
+ button = 13;
+ break;
+ case KeyEvent.KEYCODE_DPAD_RIGHT:
+ button = 14;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_C:
+ button = 17;
+ break;
+ case KeyEvent.KEYCODE_BUTTON_Z:
+ button = 18;
+ break;
+
+ default:
+ button = keyCode - KeyEvent.KEYCODE_BUTTON_1 + 20;
+ break;
+ }
+ return button;
+ }
+
+ private int findJoystickDevice(int device_id) {
+ for (int i = 0; i < joysticksDevices.size(); i++) {
+ if (joysticksDevices.get(i).device_id == device_id) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java b/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java
new file mode 100644
index 0000000000..9b372c75e3
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/GodotTextInputWrapper.java
@@ -0,0 +1,150 @@
+/*************************************************************************/
+/* GodotTextInputWrapper.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.input;
+import android.content.Context;
+import android.text.Editable;
+import android.text.TextWatcher;
+import android.view.KeyEvent;
+import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.widget.TextView;
+import android.widget.TextView.OnEditorActionListener;
+import org.godotengine.godot.*;
+
+public class GodotTextInputWrapper implements TextWatcher, OnEditorActionListener {
+ // ===========================================================
+ // Constants
+ // ===========================================================
+ private static final String TAG = GodotTextInputWrapper.class.getSimpleName();
+
+ // ===========================================================
+ // Fields
+ // ===========================================================
+ private final GodotView mView;
+ private final GodotEditText mEdit;
+ private String mOriginText;
+
+ // ===========================================================
+ // Constructors
+ // ===========================================================
+
+ public GodotTextInputWrapper(final GodotView view, final GodotEditText edit) {
+ this.mView = view;
+ this.mEdit = edit;
+ }
+
+ // ===========================================================
+ // Getter & Setter
+ // ===========================================================
+
+ private boolean isFullScreenEdit() {
+ final TextView textField = this.mEdit;
+ final InputMethodManager imm = (InputMethodManager)textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+ return imm.isFullscreenMode();
+ }
+
+ public void setOriginText(final String originText) {
+ this.mOriginText = originText;
+ }
+
+ // ===========================================================
+ // Methods for/from SuperClass/Interfaces
+ // ===========================================================
+
+ @Override
+ public void afterTextChanged(final Editable s) {
+ }
+
+ @Override
+ public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) {
+ //Log.d(TAG, "beforeTextChanged(" + pCharSequence + ")start: " + start + ",count: " + count + ",after: " + after);
+
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ for (int i = 0; i < count; ++i) {
+ GodotLib.key(KeyEvent.KEYCODE_DEL, 0, true);
+ GodotLib.key(KeyEvent.KEYCODE_DEL, 0, false);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void onTextChanged(final CharSequence pCharSequence, final int start, final int before, final int count) {
+ //Log.d(TAG, "onTextChanged(" + pCharSequence + ")start: " + start + ",count: " + count + ",before: " + before);
+
+ final int[] newChars = new int[count];
+ for (int i = start; i < start + count; ++i) {
+ newChars[i - start] = pCharSequence.charAt(i);
+ }
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ for (int i = 0; i < count; ++i) {
+ GodotLib.key(0, newChars[i], true);
+ GodotLib.key(0, newChars[i], false);
+ }
+ }
+ });
+ }
+
+ @Override
+ public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) {
+ if (this.mEdit == pTextView && this.isFullScreenEdit()) {
+ final String characters = pKeyEvent.getCharacters();
+
+ mView.queueEvent(new Runnable() {
+ @Override
+ public void run() {
+ for (int i = 0; i < characters.length(); i++) {
+ final int ch = characters.codePointAt(i);
+ GodotLib.key(0, ch, true);
+ GodotLib.key(0, ch, false);
+ }
+ }
+ });
+ }
+
+ if (pActionID == EditorInfo.IME_ACTION_DONE) {
+ this.mView.requestFocus();
+ }
+ return false;
+ }
+
+ // ===========================================================
+ // Methods
+ // ===========================================================
+
+ // ===========================================================
+ // Inner and Anonymous Classes
+ // ===========================================================
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/InputManagerCompat.java b/platform/android/java/lib/src/org/godotengine/godot/input/InputManagerCompat.java
new file mode 100644
index 0000000000..4042c42e9d
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/InputManagerCompat.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.godotengine.godot.input;
+
+import android.content.Context;
+import android.os.Handler;
+import android.view.InputDevice;
+import android.view.MotionEvent;
+
+public interface InputManagerCompat {
+ /**
+ * Gets information about the input device with the specified id.
+ *
+ * @param id The device id
+ * @return The input device or null if not found
+ */
+ public InputDevice getInputDevice(int id);
+
+ /**
+ * Gets the ids of all input devices in the system.
+ *
+ * @return The input device ids.
+ */
+ public int[] getInputDeviceIds();
+
+ /**
+ * Registers an input device listener to receive notifications about when
+ * input devices are added, removed or changed.
+ *
+ * @param listener The listener to register.
+ * @param handler The handler on which the listener should be invoked, or
+ * null if the listener should be invoked on the calling thread's
+ * looper.
+ */
+ public void registerInputDeviceListener(InputManagerCompat.InputDeviceListener listener,
+ Handler handler);
+
+ /**
+ * Unregisters an input device listener.
+ *
+ * @param listener The listener to unregister.
+ */
+ public void unregisterInputDeviceListener(InputManagerCompat.InputDeviceListener listener);
+
+ /*
+ * The following three calls are to simulate V16 behavior on pre-Jellybean
+ * devices. If you don't call them, your callback will never be called
+ * pre-API 16.
+ */
+
+ /**
+ * Pass the motion events to the InputManagerCompat. This is used to
+ * optimize for polling for controllers. If you do not pass these events in,
+ * polling will cause regular object creation.
+ *
+ * @param event the motion event from the app
+ */
+ public void onGenericMotionEvent(MotionEvent event);
+
+ /**
+ * Tell the V9 input manager that it should stop polling for disconnected
+ * devices. You can call this during onPause in your activity, although you
+ * might want to call it whenever your game is not active (or whenever you
+ * don't care about being notified of new input devices)
+ */
+ public void onPause();
+
+ /**
+ * Tell the V9 input manager that it should start polling for disconnected
+ * devices. You can call this during onResume in your activity, although you
+ * might want to call it less often (only when the gameplay is actually
+ * active)
+ */
+ public void onResume();
+
+ public interface InputDeviceListener {
+ /**
+ * Called whenever the input manager detects that a device has been
+ * added. This will only be called in the V9 version when a motion event
+ * is detected.
+ *
+ * @param deviceId The id of the input device that was added.
+ */
+ void onInputDeviceAdded(int deviceId);
+
+ /**
+ * Called whenever the properties of an input device have changed since
+ * they were last queried. This will not be called for the V9 version of
+ * the API.
+ *
+ * @param deviceId The id of the input device that changed.
+ */
+ void onInputDeviceChanged(int deviceId);
+
+ /**
+ * Called whenever the input manager detects that a device has been
+ * removed. For the V9 version, this can take some time depending on the
+ * poll rate.
+ *
+ * @param deviceId The id of the input device that was removed.
+ */
+ void onInputDeviceRemoved(int deviceId);
+ }
+
+ /**
+ * Use this to construct a compatible InputManager.
+ */
+ public static class Factory {
+
+ /**
+ * Constructs and returns a compatible InputManger
+ *
+ * @param context the Context that will be used to get the system
+ * service from
+ * @return a compatible implementation of InputManager
+ */
+ public static InputManagerCompat getInputManager(Context context) {
+ return new InputManagerV16(context);
+ }
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/InputManagerV16.java b/platform/android/java/lib/src/org/godotengine/godot/input/InputManagerV16.java
new file mode 100644
index 0000000000..e4bafa7ff9
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/InputManagerV16.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.godotengine.godot.input;
+
+import android.annotation.TargetApi;
+import android.content.Context;
+import android.hardware.input.InputManager;
+import android.os.Build;
+import android.os.Handler;
+import android.view.InputDevice;
+import android.view.MotionEvent;
+import java.util.HashMap;
+import java.util.Map;
+
+@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
+public class InputManagerV16 implements InputManagerCompat {
+
+ private final InputManager mInputManager;
+ private final Map<InputManagerCompat.InputDeviceListener, V16InputDeviceListener> mListeners;
+
+ public InputManagerV16(Context context) {
+ mInputManager = (InputManager)context.getSystemService(Context.INPUT_SERVICE);
+ mListeners = new HashMap<InputManagerCompat.InputDeviceListener, V16InputDeviceListener>();
+ }
+
+ @Override
+ public InputDevice getInputDevice(int id) {
+ return mInputManager.getInputDevice(id);
+ }
+
+ @Override
+ public int[] getInputDeviceIds() {
+ return mInputManager.getInputDeviceIds();
+ }
+
+ static class V16InputDeviceListener implements InputManager.InputDeviceListener {
+ final InputManagerCompat.InputDeviceListener mIDL;
+
+ public V16InputDeviceListener(InputDeviceListener idl) {
+ mIDL = idl;
+ }
+
+ @Override
+ public void onInputDeviceAdded(int deviceId) {
+ mIDL.onInputDeviceAdded(deviceId);
+ }
+
+ @Override
+ public void onInputDeviceChanged(int deviceId) {
+ mIDL.onInputDeviceChanged(deviceId);
+ }
+
+ @Override
+ public void onInputDeviceRemoved(int deviceId) {
+ mIDL.onInputDeviceRemoved(deviceId);
+ }
+ }
+
+ @Override
+ public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) {
+ V16InputDeviceListener v16Listener = new V16InputDeviceListener(listener);
+ mInputManager.registerInputDeviceListener(v16Listener, handler);
+ mListeners.put(listener, v16Listener);
+ }
+
+ @Override
+ public void unregisterInputDeviceListener(InputDeviceListener listener) {
+ V16InputDeviceListener curListener = mListeners.remove(listener);
+ if (null != curListener) {
+ mInputManager.unregisterInputDeviceListener(curListener);
+ }
+ }
+
+ @Override
+ public void onGenericMotionEvent(MotionEvent event) {
+ // unused in V16
+ }
+
+ @Override
+ public void onPause() {
+ // unused in V16
+ }
+
+ @Override
+ public void onResume() {
+ // unused in V16
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/input/Joystick.java b/platform/android/java/lib/src/org/godotengine/godot/input/Joystick.java
new file mode 100644
index 0000000000..ff95bfb0c5
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/input/Joystick.java
@@ -0,0 +1,44 @@
+/*************************************************************************/
+/* Joystick.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.input;
+
+import android.view.InputDevice.MotionRange;
+import java.util.ArrayList;
+
+/**
+ * POJO class to represent a Joystick input device.
+ */
+class Joystick {
+ int device_id;
+ String name;
+ ArrayList<MotionRange> axes;
+ ArrayList<MotionRange> hats;
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/ConsumeTask.java b/platform/android/java/lib/src/org/godotengine/godot/payments/ConsumeTask.java
new file mode 100644
index 0000000000..4c1050c948
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/payments/ConsumeTask.java
@@ -0,0 +1,116 @@
+/*************************************************************************/
+/* ConsumeTask.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.payments;
+
+import android.content.Context;
+import android.os.AsyncTask;
+import android.os.RemoteException;
+import com.android.vending.billing.IInAppBillingService;
+import java.lang.ref.WeakReference;
+
+abstract public class ConsumeTask {
+
+ private Context context;
+ private IInAppBillingService mService;
+
+ private String mSku;
+ private String mToken;
+
+ private static class ConsumeAsyncTask extends AsyncTask<String, String, String> {
+
+ private WeakReference<ConsumeTask> mTask;
+
+ ConsumeAsyncTask(ConsumeTask consume) {
+ mTask = new WeakReference<>(consume);
+ }
+
+ @Override
+ protected String doInBackground(String... strings) {
+ ConsumeTask consume = mTask.get();
+ if (consume != null) {
+ return consume.doInBackground(strings);
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(String param) {
+ ConsumeTask consume = mTask.get();
+ if (consume != null) {
+ consume.onPostExecute(param);
+ }
+ }
+ }
+
+ public ConsumeTask(IInAppBillingService mService, Context context) {
+ this.context = context;
+ this.mService = mService;
+ }
+
+ public void consume(final String sku) {
+ mSku = sku;
+ PaymentsCache pc = new PaymentsCache(context);
+ Boolean isBlocked = pc.getConsumableFlag("block", sku);
+ mToken = pc.getConsumableValue("token", sku);
+ if (!isBlocked && mToken == null) {
+ // Consuming task is processing
+ } else if (!isBlocked) {
+ return;
+ } else if (mToken == null) {
+ this.error("No token for sku:" + sku);
+ return;
+ }
+ new ConsumeAsyncTask(this).execute();
+ }
+
+ private String doInBackground(String... params) {
+ try {
+ int response = mService.consumePurchase(3, context.getPackageName(), mToken);
+ if (response == 0 || response == 8) {
+ return null;
+ }
+ } catch (RemoteException e) {
+ return e.getMessage();
+ }
+ return "Some error";
+ }
+
+ private void onPostExecute(String param) {
+ if (param == null) {
+ success(new PaymentsCache(context).getConsumableValue("ticket", mSku));
+ } else {
+ error(param);
+ }
+ }
+
+ abstract protected void success(String ticket);
+ abstract protected void error(String message);
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/HandlePurchaseTask.java b/platform/android/java/lib/src/org/godotengine/godot/payments/HandlePurchaseTask.java
new file mode 100644
index 0000000000..1a914967a2
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/payments/HandlePurchaseTask.java
@@ -0,0 +1,93 @@
+/*************************************************************************/
+/* HandlePurchaseTask.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.payments;
+
+import android.app.Activity;
+import android.content.Intent;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+abstract public class HandlePurchaseTask {
+
+ private Activity context;
+
+ public HandlePurchaseTask(Activity context) {
+ this.context = context;
+ }
+
+ public void handlePurchaseRequest(int resultCode, Intent data) {
+ //Log.d("XXX", "Handling purchase response");
+ if (resultCode == Activity.RESULT_OK) {
+ try {
+ //int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
+ PaymentsCache pc = new PaymentsCache(context);
+
+ String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
+ //Log.d("XXX", "Purchase data:" + purchaseData);
+ String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
+ //Log.d("XXX", "Purchase signature:" + dataSignature);
+ //Log.d("SARLANGA", purchaseData);
+
+ JSONObject jo = new JSONObject(purchaseData);
+ //String sku = jo.getString("productId");
+ //alert("You have bought the " + sku + ". Excellent choice, aventurer!");
+ //String orderId = jo.getString("orderId");
+ //String packageName = jo.getString("packageName");
+ String productId = jo.getString("productId");
+ //Long purchaseTime = jo.getLong("purchaseTime");
+ //Integer state = jo.getInt("purchaseState");
+ String developerPayload = jo.getString("developerPayload");
+ String purchaseToken = jo.getString("purchaseToken");
+
+ if (!pc.getConsumableValue("validation_hash", productId).equals(developerPayload)) {
+ error("Untrusted callback");
+ return;
+ }
+ //Log.d("XXX", "Este es el product ID:" + productId);
+ pc.setConsumableValue("ticket_signautre", productId, dataSignature);
+ pc.setConsumableValue("ticket", productId, purchaseData);
+ pc.setConsumableFlag("block", productId, true);
+ pc.setConsumableValue("token", productId, purchaseToken);
+
+ success(productId, dataSignature, purchaseData);
+ return;
+ } catch (JSONException e) {
+ error(e.getMessage());
+ }
+ } else if (resultCode == Activity.RESULT_CANCELED) {
+ canceled();
+ }
+ }
+
+ abstract protected void success(String sku, String signature, String ticket);
+ abstract protected void error(String message);
+ abstract protected void canceled();
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsCache.java b/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsCache.java
new file mode 100644
index 0000000000..8a2facbcfb
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsCache.java
@@ -0,0 +1,72 @@
+/*************************************************************************/
+/* PaymentsCache.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.payments;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.Log;
+
+public class PaymentsCache {
+
+ public Context context;
+
+ public PaymentsCache(Context context) {
+ this.context = context;
+ }
+
+ public void setConsumableFlag(String set, String sku, Boolean flag) {
+ SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
+ SharedPreferences.Editor editor = sharedPref.edit();
+ editor.putBoolean(sku, flag);
+ editor.apply();
+ }
+
+ public boolean getConsumableFlag(String set, String sku) {
+ SharedPreferences sharedPref = context.getSharedPreferences(
+ "consumables_" + set, Context.MODE_PRIVATE);
+ return sharedPref.getBoolean(sku, false);
+ }
+
+ public void setConsumableValue(String set, String sku, String value) {
+ SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
+ SharedPreferences.Editor editor = sharedPref.edit();
+ editor.putString(sku, value);
+ //Log.d("XXX", "Setting asset: consumables_" + set + ":" + sku);
+ editor.apply();
+ }
+
+ public String getConsumableValue(String set, String sku) {
+ SharedPreferences sharedPref = context.getSharedPreferences(
+ "consumables_" + set, Context.MODE_PRIVATE);
+ //Log.d("XXX", "Getting asset: consumables_" + set + ":" + sku);
+ return sharedPref.getString(sku, null);
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsManager.java b/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsManager.java
new file mode 100644
index 0000000000..c079c55854
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsManager.java
@@ -0,0 +1,419 @@
+/*************************************************************************/
+/* PaymentsManager.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.payments;
+
+import android.app.Activity;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.text.TextUtils;
+import android.util.Log;
+import com.android.vending.billing.IInAppBillingService;
+import java.util.ArrayList;
+import java.util.Arrays;
+import org.godotengine.godot.GodotPaymentV3;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class PaymentsManager {
+
+ public static final int BILLING_RESPONSE_RESULT_OK = 0;
+ public static final int REQUEST_CODE_FOR_PURCHASE = 0x1001;
+ private static boolean auto_consume = true;
+
+ private Activity activity;
+ IInAppBillingService mService;
+
+ public void setActivity(Activity activity) {
+ this.activity = activity;
+ }
+
+ public static PaymentsManager createManager(Activity activity) {
+ PaymentsManager manager = new PaymentsManager(activity);
+ return manager;
+ }
+
+ private PaymentsManager(Activity activity) {
+ this.activity = activity;
+ }
+
+ public PaymentsManager initService() {
+ Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
+ intent.setPackage("com.android.vending");
+ activity.bindService(
+ intent,
+ mServiceConn,
+ Context.BIND_AUTO_CREATE);
+ return this;
+ }
+
+ public void destroy() {
+ if (mService != null) {
+ activity.unbindService(mServiceConn);
+ }
+ }
+
+ ServiceConnection mServiceConn = new ServiceConnection() {
+ @Override
+ public void onServiceDisconnected(ComponentName name) {
+ mService = null;
+
+ // At this stage, godotPaymentV3 might not have been initialized yet.
+ if (godotPaymentV3 != null) {
+ godotPaymentV3.callbackDisconnected();
+ }
+ }
+
+ @Override
+ public void onServiceConnected(ComponentName name, IBinder service) {
+ mService = IInAppBillingService.Stub.asInterface(service);
+
+ // At this stage, godotPaymentV3 might not have been initialized yet.
+ if (godotPaymentV3 != null) {
+ godotPaymentV3.callbackConnected();
+ }
+ }
+ };
+
+ public void requestPurchase(final String sku, String transactionId) {
+ new PurchaseTask(mService, activity) {
+ @Override
+ protected void error(String message) {
+ godotPaymentV3.callbackFail(message);
+ }
+
+ @Override
+ protected void canceled() {
+ godotPaymentV3.callbackCancel();
+ }
+
+ @Override
+ protected void alreadyOwned() {
+ godotPaymentV3.callbackAlreadyOwned(sku);
+ }
+ }
+ .purchase(sku, transactionId);
+ }
+
+ public boolean isConnected() {
+ return mService != null;
+ }
+
+ public void consumeUnconsumedPurchases() {
+ new ReleaseAllConsumablesTask(mService, activity) {
+ @Override
+ protected void success(String sku, String receipt, String signature, String token) {
+ godotPaymentV3.callbackSuccessProductMassConsumed(receipt, signature, sku);
+ }
+
+ @Override
+ protected void error(String message) {
+ Log.d("godot", "consumeUnconsumedPurchases :" + message);
+ godotPaymentV3.callbackFailConsume(message);
+ }
+
+ @Override
+ protected void notRequired() {
+ Log.d("godot", "callbackSuccessNoUnconsumedPurchases :");
+ godotPaymentV3.callbackSuccessNoUnconsumedPurchases();
+ }
+ }
+ .consumeItAll();
+ }
+
+ public void requestPurchased() {
+ try {
+ PaymentsCache pc = new PaymentsCache(activity);
+
+ String continueToken = null;
+
+ do {
+ Bundle bundle = mService.getPurchases(3, activity.getPackageName(), "inapp", continueToken);
+
+ if (bundle.getInt("RESPONSE_CODE") == 0) {
+
+ final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
+ final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
+
+ if (myPurchases == null || myPurchases.size() == 0) {
+ godotPaymentV3.callbackPurchased("", "", "");
+ return;
+ }
+
+ for (int i = 0; i < myPurchases.size(); i++) {
+
+ try {
+ String receipt = myPurchases.get(i);
+ JSONObject inappPurchaseData = new JSONObject(receipt);
+ String sku = inappPurchaseData.getString("productId");
+ String token = inappPurchaseData.getString("purchaseToken");
+ String signature = mySignatures.get(i);
+
+ pc.setConsumableValue("ticket_signautre", sku, signature);
+ pc.setConsumableValue("ticket", sku, receipt);
+ pc.setConsumableFlag("block", sku, true);
+ pc.setConsumableValue("token", sku, token);
+
+ godotPaymentV3.callbackPurchased(receipt, signature, sku);
+ } catch (JSONException e) {
+ }
+ }
+ }
+ continueToken = bundle.getString("INAPP_CONTINUATION_TOKEN");
+ Log.d("godot", "continue token = " + continueToken);
+ } while (!TextUtils.isEmpty(continueToken));
+ } catch (Exception e) {
+ Log.d("godot", "Error requesting purchased products:" + e.getClass().getName() + ":" + e.getMessage());
+ }
+ }
+
+ public void processPurchaseResponse(int resultCode, Intent data) {
+ new HandlePurchaseTask(activity) {
+ @Override
+ protected void success(final String sku, final String signature, final String ticket) {
+ godotPaymentV3.callbackSuccess(ticket, signature, sku);
+
+ if (auto_consume) {
+ new ConsumeTask(mService, activity) {
+ @Override
+ protected void success(String ticket) {
+ }
+
+ @Override
+ protected void error(String message) {
+ godotPaymentV3.callbackFail(message);
+ }
+ }
+ .consume(sku);
+ }
+ }
+
+ @Override
+ protected void error(String message) {
+ godotPaymentV3.callbackFail(message);
+ }
+
+ @Override
+ protected void canceled() {
+ godotPaymentV3.callbackCancel();
+ }
+ }
+ .handlePurchaseRequest(resultCode, data);
+ }
+
+ public void validatePurchase(String purchaseToken, final String sku) {
+
+ new ValidateTask(activity, godotPaymentV3) {
+ @Override
+ protected void success() {
+
+ new ConsumeTask(mService, activity) {
+ @Override
+ protected void success(String ticket) {
+ godotPaymentV3.callbackSuccess(ticket, null, sku);
+ }
+
+ @Override
+ protected void error(String message) {
+ godotPaymentV3.callbackFail(message);
+ }
+ }
+ .consume(sku);
+ }
+
+ @Override
+ protected void error(String message) {
+ godotPaymentV3.callbackFail(message);
+ }
+
+ @Override
+ protected void canceled() {
+ godotPaymentV3.callbackCancel();
+ }
+ }
+ .validatePurchase(sku);
+ }
+
+ public void setAutoConsume(boolean autoConsume) {
+ auto_consume = autoConsume;
+ }
+
+ public void consume(final String sku) {
+ new ConsumeTask(mService, activity) {
+ @Override
+ protected void success(String ticket) {
+ godotPaymentV3.callbackSuccessProductMassConsumed(ticket, "", sku);
+ }
+
+ @Override
+ protected void error(String message) {
+ godotPaymentV3.callbackFailConsume(message);
+ }
+ }
+ .consume(sku);
+ }
+
+ // Workaround to bug where sometimes response codes come as Long instead of Integer
+ int getResponseCodeFromBundle(Bundle b) {
+ Object o = b.get("RESPONSE_CODE");
+ if (o == null) {
+ //logDebug("Bundle with null response code, assuming OK (known issue)");
+ return BILLING_RESPONSE_RESULT_OK;
+ } else if (o instanceof Integer)
+ return ((Integer)o).intValue();
+ else if (o instanceof Long)
+ return (int)((Long)o).longValue();
+ else {
+ //logError("Unexpected type for bundle response code.");
+ //logError(o.getClass().getName());
+ throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName());
+ }
+ }
+
+ /**
+ * Returns a human-readable description for the given response code.
+ *
+ * @param code The response code
+ * @return A human-readable string explaining the result code.
+ * It also includes the result code numerically.
+ */
+ public static String getResponseDesc(int code) {
+ String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/"
+ +
+ "3:Billing Unavailable/4:Item unavailable/"
+ +
+ "5:Developer Error/6:Error/7:Item Already Owned/"
+ +
+ "8:Item not owned")
+ .split("/");
+ String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/"
+ +
+ "-1002:Bad response received/"
+ +
+ "-1003:Purchase signature verification failed/"
+ +
+ "-1004:Send intent failed/"
+ +
+ "-1005:User cancelled/"
+ +
+ "-1006:Unknown purchase response/"
+ +
+ "-1007:Missing token/"
+ +
+ "-1008:Unknown error/"
+ +
+ "-1009:Subscriptions not available/"
+ +
+ "-1010:Invalid consumption attempt")
+ .split("/");
+
+ if (code <= -1000) {
+ int index = -1000 - code;
+ if (index >= 0 && index < iabhelper_msgs.length)
+ return iabhelper_msgs[index];
+ else
+ return String.valueOf(code) + ":Unknown IAB Helper Error";
+ } else if (code < 0 || code >= iab_msgs.length)
+ return String.valueOf(code) + ":Unknown";
+ else
+ return iab_msgs[code];
+ }
+
+ public void querySkuDetails(final String[] list) {
+ (new Thread(new Runnable() {
+ @Override
+ public void run() {
+ ArrayList<String> skuList = new ArrayList<String>(Arrays.asList(list));
+ if (skuList.size() == 0) {
+ return;
+ }
+ // Split the sku list in blocks of no more than 20 elements.
+ ArrayList<ArrayList<String>> packs = new ArrayList<ArrayList<String>>();
+ ArrayList<String> tempList;
+ int n = skuList.size() / 20;
+ int mod = skuList.size() % 20;
+ for (int i = 0; i < n; i++) {
+ tempList = new ArrayList<String>();
+ for (String s : skuList.subList(i * 20, i * 20 + 20)) {
+ tempList.add(s);
+ }
+ packs.add(tempList);
+ }
+ if (mod != 0) {
+ tempList = new ArrayList<String>();
+ for (String s : skuList.subList(n * 20, n * 20 + mod)) {
+ tempList.add(s);
+ }
+ packs.add(tempList);
+ }
+ for (ArrayList<String> skuPartList : packs) {
+ Bundle querySkus = new Bundle();
+ querySkus.putStringArrayList("ITEM_ID_LIST", skuPartList);
+ Bundle skuDetails = null;
+ try {
+ skuDetails = mService.getSkuDetails(3, activity.getPackageName(), "inapp", querySkus);
+ if (!skuDetails.containsKey("DETAILS_LIST")) {
+ int response = getResponseCodeFromBundle(skuDetails);
+ if (response != BILLING_RESPONSE_RESULT_OK) {
+ godotPaymentV3.errorSkuDetail(getResponseDesc(response));
+ } else {
+ godotPaymentV3.errorSkuDetail("No error but no detail list.");
+ }
+ return;
+ }
+
+ ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
+
+ for (String thisResponse : responseList) {
+ Log.d("godot", "response = " + thisResponse);
+ godotPaymentV3.addSkuDetail(thisResponse);
+ }
+ } catch (RemoteException e) {
+ e.printStackTrace();
+ godotPaymentV3.errorSkuDetail("RemoteException error!");
+ }
+ }
+ godotPaymentV3.completeSkuDetail();
+ }
+ }))
+ .start();
+ }
+
+ private GodotPaymentV3 godotPaymentV3;
+
+ public void setBaseSingleton(GodotPaymentV3 godotPaymentV3) {
+ this.godotPaymentV3 = godotPaymentV3;
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/PurchaseTask.java b/platform/android/java/lib/src/org/godotengine/godot/payments/PurchaseTask.java
new file mode 100644
index 0000000000..9adc85e521
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/payments/PurchaseTask.java
@@ -0,0 +1,118 @@
+/*************************************************************************/
+/* PurchaseTask.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.payments;
+
+import android.app.Activity;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.content.IntentSender.SendIntentException;
+import android.os.Bundle;
+import android.os.RemoteException;
+import android.util.Log;
+import com.android.vending.billing.IInAppBillingService;
+
+abstract public class PurchaseTask {
+
+ private Activity context;
+
+ private IInAppBillingService mService;
+ public PurchaseTask(IInAppBillingService mService, Activity context) {
+ this.context = context;
+ this.mService = mService;
+ }
+
+ private boolean isLooping = false;
+
+ public void purchase(final String sku, final String transactionId) {
+ Log.d("XXX", "Starting purchase for: " + sku);
+ PaymentsCache pc = new PaymentsCache(context);
+ Boolean isBlocked = pc.getConsumableFlag("block", sku);
+ /*
+ if(isBlocked){
+ Log.d("XXX", "Is awaiting payment confirmation");
+ error("Awaiting payment confirmation");
+ return;
+ }
+ */
+ final String hash = transactionId;
+
+ Bundle buyIntentBundle;
+ try {
+ buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash);
+ } catch (RemoteException e) {
+ //Log.d("XXX", "Error: " + e.getMessage());
+ error(e.getMessage());
+ return;
+ }
+ Object rc = buyIntentBundle.get("RESPONSE_CODE");
+ int responseCode = 0;
+ if (rc == null) {
+ responseCode = PaymentsManager.BILLING_RESPONSE_RESULT_OK;
+ } else if (rc instanceof Integer) {
+ responseCode = ((Integer)rc).intValue();
+ } else if (rc instanceof Long) {
+ responseCode = (int)((Long)rc).longValue();
+ }
+ //Log.d("XXX", "Buy intent response code: " + responseCode);
+ if (responseCode == 1 || responseCode == 3 || responseCode == 4) {
+ canceled();
+ return;
+ }
+ if (responseCode == 7) {
+ alreadyOwned();
+ return;
+ }
+
+ PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
+ pc.setConsumableValue("validation_hash", sku, hash);
+ try {
+ if (context == null) {
+ //Log.d("XXX", "No context!");
+ }
+ if (pendingIntent == null) {
+ //Log.d("XXX", "No pending intent");
+ }
+ //Log.d("XXX", "Starting activity for purchase!");
+ context.startIntentSenderForResult(
+ pendingIntent.getIntentSender(),
+ PaymentsManager.REQUEST_CODE_FOR_PURCHASE,
+ new Intent(),
+ Integer.valueOf(0), Integer.valueOf(0),
+ Integer.valueOf(0));
+ } catch (SendIntentException e) {
+ error(e.getMessage());
+ }
+ }
+
+ abstract protected void error(String message);
+ abstract protected void canceled();
+ abstract protected void alreadyOwned();
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java b/platform/android/java/lib/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java
new file mode 100644
index 0000000000..daca6ef5ae
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java
@@ -0,0 +1,141 @@
+/*************************************************************************/
+/* ReleaseAllConsumablesTask.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.payments;
+
+import android.content.Context;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.util.Log;
+import com.android.vending.billing.IInAppBillingService;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+abstract public class ReleaseAllConsumablesTask {
+
+ private Context context;
+ private IInAppBillingService mService;
+
+ private static class ReleaseAllConsumablesAsyncTask extends AsyncTask<String, String, String> {
+
+ private WeakReference<ReleaseAllConsumablesTask> mTask;
+ private String mSku;
+ private String mReceipt;
+ private String mSignature;
+ private String mToken;
+
+ ReleaseAllConsumablesAsyncTask(ReleaseAllConsumablesTask task, String sku, String receipt, String signature, String token) {
+ mTask = new WeakReference<ReleaseAllConsumablesTask>(task);
+
+ mSku = sku;
+ mReceipt = receipt;
+ mSignature = signature;
+ mToken = token;
+ }
+
+ @Override
+ protected String doInBackground(String... params) {
+ ReleaseAllConsumablesTask consume = mTask.get();
+ if (consume != null) {
+ return consume.doInBackground(mToken);
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(String param) {
+ ReleaseAllConsumablesTask consume = mTask.get();
+ if (consume != null) {
+ consume.success(mSku, mReceipt, mSignature, mToken);
+ }
+ }
+ }
+
+ public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context) {
+ this.context = context;
+ this.mService = mService;
+ }
+
+ public void consumeItAll() {
+ try {
+ //Log.d("godot", "consumeItall for " + context.getPackageName());
+ Bundle bundle = mService.getPurchases(3, context.getPackageName(), "inapp", null);
+
+ if (bundle.getInt("RESPONSE_CODE") == 0) {
+
+ final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
+ final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
+
+ if (myPurchases == null || myPurchases.size() == 0) {
+ //Log.d("godot", "No purchases!");
+ notRequired();
+ return;
+ }
+
+ //Log.d("godot", "# products to be consumed:" + myPurchases.size());
+ for (int i = 0; i < myPurchases.size(); i++) {
+
+ try {
+ String receipt = myPurchases.get(i);
+ JSONObject inappPurchaseData = new JSONObject(receipt);
+ String sku = inappPurchaseData.getString("productId");
+ String token = inappPurchaseData.getString("purchaseToken");
+ String signature = mySignatures.get(i);
+ //Log.d("godot", "A punto de consumir un item con token:" + token + "\n" + receipt);
+ new ReleaseAllConsumablesAsyncTask(this, sku, receipt, signature, token).execute();
+ } catch (JSONException e) {
+ }
+ }
+ }
+ } catch (Exception e) {
+ Log.d("godot", "Error releasing products:" + e.getClass().getName() + ":" + e.getMessage());
+ }
+ }
+
+ private String doInBackground(String token) {
+ try {
+ //Log.d("godot", "Requesting to consume an item with token ." + token);
+ int response = mService.consumePurchase(3, context.getPackageName(), token);
+ //Log.d("godot", "consumePurchase response: " + response);
+ if (response == 0 || response == 8) {
+ return null;
+ }
+ } catch (Exception e) {
+ Log.d("godot", "Error " + e.getClass().getName() + ":" + e.getMessage());
+ }
+ return null;
+ }
+
+ abstract protected void success(String sku, String receipt, String signature, String token);
+ abstract protected void error(String message);
+ abstract protected void notRequired();
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/ValidateTask.java b/platform/android/java/lib/src/org/godotengine/godot/payments/ValidateTask.java
new file mode 100644
index 0000000000..17a2a197ad
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/payments/ValidateTask.java
@@ -0,0 +1,142 @@
+/*************************************************************************/
+/* ValidateTask.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.payments;
+
+import android.app.Activity;
+import android.app.ProgressDialog;
+import android.os.AsyncTask;
+import java.lang.ref.WeakReference;
+import org.godotengine.godot.GodotPaymentV3;
+import org.godotengine.godot.utils.HttpRequester;
+import org.godotengine.godot.utils.RequestParams;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+abstract public class ValidateTask {
+
+ private Activity context;
+ private GodotPaymentV3 godotPaymentsV3;
+ private ProgressDialog dialog;
+ private String mSku;
+
+ private static class ValidateAsyncTask extends AsyncTask<String, String, String> {
+ private WeakReference<ValidateTask> mTask;
+
+ ValidateAsyncTask(ValidateTask task) {
+ mTask = new WeakReference<>(task);
+ }
+
+ @Override
+ protected void onPreExecute() {
+ ValidateTask task = mTask.get();
+ if (task != null) {
+ task.onPreExecute();
+ }
+ }
+
+ @Override
+ protected String doInBackground(String... params) {
+ ValidateTask task = mTask.get();
+ if (task != null) {
+ return task.doInBackground(params);
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(String response) {
+ ValidateTask task = mTask.get();
+ if (task != null) {
+ task.onPostExecute(response);
+ }
+ }
+ }
+
+ public ValidateTask(Activity context, GodotPaymentV3 godotPaymentsV3) {
+ this.context = context;
+ this.godotPaymentsV3 = godotPaymentsV3;
+ }
+
+ public void validatePurchase(final String sku) {
+ mSku = sku;
+ new ValidateAsyncTask(this).execute();
+ }
+
+ private void onPreExecute() {
+ dialog = ProgressDialog.show(context, null, "Please wait...");
+ }
+
+ private String doInBackground(String... params) {
+ PaymentsCache pc = new PaymentsCache(context);
+ String url = godotPaymentsV3.getPurchaseValidationUrlPrefix();
+ RequestParams param = new RequestParams();
+ param.setUrl(url);
+ param.put("ticket", pc.getConsumableValue("ticket", mSku));
+ param.put("purchaseToken", pc.getConsumableValue("token", mSku));
+ param.put("sku", mSku);
+ //Log.d("XXX", "Haciendo request a " + url);
+ //Log.d("XXX", "ticket: " + pc.getConsumableValue("ticket", sku));
+ //Log.d("XXX", "purchaseToken: " + pc.getConsumableValue("token", sku));
+ //Log.d("XXX", "sku: " + sku);
+ param.put("package", context.getApplicationContext().getPackageName());
+ HttpRequester requester = new HttpRequester();
+ String jsonResponse = requester.post(param);
+ //Log.d("XXX", "Validation response:\n"+jsonResponse);
+ return jsonResponse;
+ }
+
+ private void onPostExecute(String response) {
+ if (dialog != null) {
+ dialog.dismiss();
+ dialog = null;
+ }
+ JSONObject j;
+ try {
+ j = new JSONObject(response);
+ if (j.getString("status").equals("OK")) {
+ success();
+ return;
+ } else if (j.getString("status") != null) {
+ error(j.getString("message"));
+ } else {
+ error("Connection error");
+ }
+ } catch (JSONException e) {
+ error(e.getMessage());
+ } catch (Exception e) {
+ error(e.getMessage());
+ }
+ }
+
+ abstract protected void success();
+ abstract protected void error(String message);
+ abstract protected void canceled();
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/utils/Crypt.java b/platform/android/java/lib/src/org/godotengine/godot/utils/Crypt.java
new file mode 100644
index 0000000000..4c551d1d21
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/utils/Crypt.java
@@ -0,0 +1,69 @@
+/*************************************************************************/
+/* Crypt.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.utils;
+
+import java.security.MessageDigest;
+import java.util.Random;
+
+public class Crypt {
+
+ public static String md5(String input) {
+ try {
+ // Create MD5 Hash
+ MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
+ digest.update(input.getBytes());
+ byte messageDigest[] = digest.digest();
+
+ // Create Hex String
+ StringBuffer hexString = new StringBuffer();
+ for (int i = 0; i < messageDigest.length; i++)
+ hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
+ return hexString.toString();
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return "";
+ }
+
+ public static String createRandomHash() {
+ return md5(Long.toString(createRandomLong()));
+ }
+
+ public static long createAbsRandomLong() {
+ return Math.abs(createRandomLong());
+ }
+
+ public static long createRandomLong() {
+ Random r = new Random();
+ return r.nextLong();
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java b/platform/android/java/lib/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java
new file mode 100644
index 0000000000..b61007faa3
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/utils/CustomSSLSocketFactory.java
@@ -0,0 +1,69 @@
+/*************************************************************************/
+/* CustomSSLSocketFactory.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.utils;
+import java.io.IOException;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManagerFactory;
+import org.apache.http.conn.ssl.SSLSocketFactory;
+
+/**
+ *
+ * @author Luis Linietsky <luis.linietsky@gmail.com>
+ */
+public class CustomSSLSocketFactory extends SSLSocketFactory {
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+
+ public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ super(truststore);
+
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
+ tmf.init(truststore);
+
+ sslContext.init(null, tmf.getTrustManagers(), null);
+ }
+
+ @Override
+ public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
+ return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
+ }
+
+ @Override
+ public Socket createSocket() throws IOException {
+ return sslContext.getSocketFactory().createSocket();
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/utils/GLUtils.java b/platform/android/java/lib/src/org/godotengine/godot/utils/GLUtils.java
new file mode 100644
index 0000000000..6c95494f8b
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/utils/GLUtils.java
@@ -0,0 +1,157 @@
+/*************************************************************************/
+/* GLUtils.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.utils;
+
+import android.util.Log;
+import javax.microedition.khronos.egl.EGL10;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.egl.EGLDisplay;
+
+/**
+ * Contains GL utilities methods.
+ */
+public class GLUtils {
+
+ private static final String TAG = GLUtils.class.getSimpleName();
+
+ public static final boolean DEBUG = false;
+
+ public static boolean use_gl3 = false;
+ public static boolean use_32 = false;
+ public static boolean use_debug_opengl = false;
+
+ private static final String[] ATTRIBUTES_NAMES = new String[] {
+ "EGL_BUFFER_SIZE",
+ "EGL_ALPHA_SIZE",
+ "EGL_BLUE_SIZE",
+ "EGL_GREEN_SIZE",
+ "EGL_RED_SIZE",
+ "EGL_DEPTH_SIZE",
+ "EGL_STENCIL_SIZE",
+ "EGL_CONFIG_CAVEAT",
+ "EGL_CONFIG_ID",
+ "EGL_LEVEL",
+ "EGL_MAX_PBUFFER_HEIGHT",
+ "EGL_MAX_PBUFFER_PIXELS",
+ "EGL_MAX_PBUFFER_WIDTH",
+ "EGL_NATIVE_RENDERABLE",
+ "EGL_NATIVE_VISUAL_ID",
+ "EGL_NATIVE_VISUAL_TYPE",
+ "EGL_PRESERVED_RESOURCES",
+ "EGL_SAMPLES",
+ "EGL_SAMPLE_BUFFERS",
+ "EGL_SURFACE_TYPE",
+ "EGL_TRANSPARENT_TYPE",
+ "EGL_TRANSPARENT_RED_VALUE",
+ "EGL_TRANSPARENT_GREEN_VALUE",
+ "EGL_TRANSPARENT_BLUE_VALUE",
+ "EGL_BIND_TO_TEXTURE_RGB",
+ "EGL_BIND_TO_TEXTURE_RGBA",
+ "EGL_MIN_SWAP_INTERVAL",
+ "EGL_MAX_SWAP_INTERVAL",
+ "EGL_LUMINANCE_SIZE",
+ "EGL_ALPHA_MASK_SIZE",
+ "EGL_COLOR_BUFFER_TYPE",
+ "EGL_RENDERABLE_TYPE",
+ "EGL_CONFORMANT"
+ };
+
+ private static final int[] ATTRIBUTES = new int[] {
+ EGL10.EGL_BUFFER_SIZE,
+ EGL10.EGL_ALPHA_SIZE,
+ EGL10.EGL_BLUE_SIZE,
+ EGL10.EGL_GREEN_SIZE,
+ EGL10.EGL_RED_SIZE,
+ EGL10.EGL_DEPTH_SIZE,
+ EGL10.EGL_STENCIL_SIZE,
+ EGL10.EGL_CONFIG_CAVEAT,
+ EGL10.EGL_CONFIG_ID,
+ EGL10.EGL_LEVEL,
+ EGL10.EGL_MAX_PBUFFER_HEIGHT,
+ EGL10.EGL_MAX_PBUFFER_PIXELS,
+ EGL10.EGL_MAX_PBUFFER_WIDTH,
+ EGL10.EGL_NATIVE_RENDERABLE,
+ EGL10.EGL_NATIVE_VISUAL_ID,
+ EGL10.EGL_NATIVE_VISUAL_TYPE,
+ 0x3030, // EGL10.EGL_PRESERVED_RESOURCES,
+ EGL10.EGL_SAMPLES,
+ EGL10.EGL_SAMPLE_BUFFERS,
+ EGL10.EGL_SURFACE_TYPE,
+ EGL10.EGL_TRANSPARENT_TYPE,
+ EGL10.EGL_TRANSPARENT_RED_VALUE,
+ EGL10.EGL_TRANSPARENT_GREEN_VALUE,
+ EGL10.EGL_TRANSPARENT_BLUE_VALUE,
+ 0x3039, // EGL10.EGL_BIND_TO_TEXTURE_RGB,
+ 0x303A, // EGL10.EGL_BIND_TO_TEXTURE_RGBA,
+ 0x303B, // EGL10.EGL_MIN_SWAP_INTERVAL,
+ 0x303C, // EGL10.EGL_MAX_SWAP_INTERVAL,
+ EGL10.EGL_LUMINANCE_SIZE,
+ EGL10.EGL_ALPHA_MASK_SIZE,
+ EGL10.EGL_COLOR_BUFFER_TYPE,
+ EGL10.EGL_RENDERABLE_TYPE,
+ 0x3042 // EGL10.EGL_CONFORMANT
+ };
+
+ private GLUtils() {}
+
+ public static void checkEglError(String tag, String prompt, EGL10 egl) {
+ int error;
+ while ((error = egl.eglGetError()) != EGL10.EGL_SUCCESS) {
+ Log.e(tag, String.format("%s: EGL error: 0x%x", prompt, error));
+ }
+ }
+
+ public static void printConfigs(EGL10 egl, EGLDisplay display,
+ EGLConfig[] configs) {
+ int numConfigs = configs.length;
+ Log.v(TAG, String.format("%d configurations", numConfigs));
+ for (int i = 0; i < numConfigs; i++) {
+ Log.v(TAG, String.format("Configuration %d:\n", i));
+ printConfig(egl, display, configs[i]);
+ }
+ }
+
+ private static void printConfig(EGL10 egl, EGLDisplay display,
+ EGLConfig config) {
+ int[] value = new int[1];
+ for (int i = 0; i < ATTRIBUTES.length; i++) {
+ int attribute = ATTRIBUTES[i];
+ String name = ATTRIBUTES_NAMES[i];
+ if (egl.eglGetConfigAttrib(display, config, attribute, value)) {
+ Log.i(TAG, String.format(" %s: %d\n", name, value[0]));
+ } else {
+ // Log.w(TAG, String.format(" %s: failed\n", name));
+ while (egl.eglGetError() != EGL10.EGL_SUCCESS)
+ ;
+ }
+ }
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/utils/HttpRequester.java b/platform/android/java/lib/src/org/godotengine/godot/utils/HttpRequester.java
new file mode 100644
index 0000000000..02ae753b3e
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/utils/HttpRequester.java
@@ -0,0 +1,227 @@
+/*************************************************************************/
+/* HttpRequester.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.utils;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.Log;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.security.KeyStore;
+import java.util.Date;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpVersion;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.conn.ClientConnectionManager;
+import org.apache.http.conn.scheme.PlainSocketFactory;
+import org.apache.http.conn.scheme.Scheme;
+import org.apache.http.conn.scheme.SchemeRegistry;
+import org.apache.http.conn.ssl.SSLSocketFactory;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.params.HttpParams;
+import org.apache.http.params.HttpProtocolParams;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.util.EntityUtils;
+
+/**
+ *
+ * @author Luis Linietsky <luis.linietsky@gmail.com>
+ */
+public class HttpRequester {
+
+ private Context context;
+ private static final int TTL = 600000; // 10 minutos
+ private long cttl = 0;
+
+ public HttpRequester() {
+ //Log.d("XXX", "Creando http request sin contexto");
+ }
+
+ public HttpRequester(Context context) {
+ this.context = context;
+ //Log.d("XXX", "Creando http request con contexto");
+ }
+
+ public String post(RequestParams params) {
+ HttpPost httppost = new HttpPost(params.getUrl());
+ try {
+ httppost.setEntity(new UrlEncodedFormEntity(params.toPairsList()));
+ return request(httppost);
+ } catch (UnsupportedEncodingException e) {
+ return null;
+ }
+ }
+
+ public String get(RequestParams params) {
+ String response = getResponseFromCache(params.getUrl());
+ if (response == null) {
+ //Log.d("XXX", "Cache miss!");
+ HttpGet httpget = new HttpGet(params.getUrl());
+ long timeInit = new Date().getTime();
+ response = request(httpget);
+ long delay = new Date().getTime() - timeInit;
+ Log.d("HttpRequest::get(url)", "Url: " + params.getUrl() + " downloaded in " + String.format("%.03f", delay / 1000.0f) + " seconds");
+ if (response == null || response.length() == 0) {
+ response = "";
+ } else {
+ saveResponseIntoCache(params.getUrl(), response);
+ }
+ }
+ Log.d("XXX", "Req: " + params.getUrl());
+ Log.d("XXX", "Resp: " + response);
+ return response;
+ }
+
+ private String request(HttpUriRequest request) {
+ //Log.d("XXX", "Haciendo request a: " + request.getURI() );
+ Log.d("PPP", "Haciendo request a: " + request.getURI());
+ long init = new Date().getTime();
+ HttpClient httpclient = getNewHttpClient();
+ HttpParams httpParameters = httpclient.getParams();
+ HttpConnectionParams.setConnectionTimeout(httpParameters, 0);
+ HttpConnectionParams.setSoTimeout(httpParameters, 0);
+ HttpConnectionParams.setTcpNoDelay(httpParameters, true);
+ try {
+ HttpResponse response = httpclient.execute(request);
+ Log.d("PPP", "Fin de request (" + (new Date().getTime() - init) + ") a: " + request.getURI());
+ //Log.d("XXX1", "Status:" + response.getStatusLine().toString());
+ if (response.getStatusLine().getStatusCode() == 200) {
+ String strResponse = EntityUtils.toString(response.getEntity());
+ //Log.d("XXX2", strResponse);
+ return strResponse;
+ } else {
+ Log.d("XXX3", "Response status code:" + response.getStatusLine().getStatusCode() + "\n" + EntityUtils.toString(response.getEntity()));
+ return null;
+ }
+
+ } catch (ClientProtocolException e) {
+ Log.d("XXX3", e.getMessage());
+ } catch (IOException e) {
+ Log.d("XXX4", e.getMessage());
+ }
+ return null;
+ }
+
+ private HttpClient getNewHttpClient() {
+ try {
+ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ trustStore.load(null, null);
+
+ SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
+ sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
+
+ HttpParams params = new BasicHttpParams();
+ HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
+ HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
+
+ SchemeRegistry registry = new SchemeRegistry();
+ registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
+ registry.register(new Scheme("https", sf, 443));
+
+ ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
+
+ return new DefaultHttpClient(ccm, params);
+ } catch (Exception e) {
+ return new DefaultHttpClient();
+ }
+ }
+
+ private static String convertStreamToString(InputStream is) {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(is));
+ StringBuilder sb = new StringBuilder();
+ String line = null;
+ try {
+ while ((line = reader.readLine()) != null) {
+ sb.append((line + "\n"));
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ is.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ return sb.toString();
+ }
+
+ public void saveResponseIntoCache(String request, String response) {
+ if (context == null) {
+ //Log.d("XXX", "No context, cache failed!");
+ return;
+ }
+ SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE);
+ SharedPreferences.Editor editor = sharedPref.edit();
+ editor.putString("request_" + Crypt.md5(request), response);
+ editor.putLong("request_" + Crypt.md5(request) + "_ttl", new Date().getTime() + getTtl());
+ editor.apply();
+ }
+
+ public String getResponseFromCache(String request) {
+ if (context == null) {
+ Log.d("XXX", "No context, cache miss");
+ return null;
+ }
+ SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE);
+ long ttl = getResponseTtl(request);
+ if (ttl == 0l || (new Date().getTime() - ttl) > 0l) {
+ Log.d("XXX", "Cache invalid ttl:" + ttl + " vs now:" + new Date().getTime());
+ return null;
+ }
+ return sharedPref.getString("request_" + Crypt.md5(request), null);
+ }
+
+ public long getResponseTtl(String request) {
+ SharedPreferences sharedPref = context.getSharedPreferences(
+ "http_get_cache", Context.MODE_PRIVATE);
+ return sharedPref.getLong("request_" + Crypt.md5(request) + "_ttl", 0l);
+ }
+
+ public long getTtl() {
+ return cttl > 0 ? cttl : TTL;
+ }
+
+ public void setTtl(long ttl) {
+ this.cttl = (ttl * 1000) + new Date().getTime();
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/utils/RequestParams.java b/platform/android/java/lib/src/org/godotengine/godot/utils/RequestParams.java
new file mode 100644
index 0000000000..b9fe0dd0c9
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/utils/RequestParams.java
@@ -0,0 +1,85 @@
+/*************************************************************************/
+/* RequestParams.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.utils;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import org.apache.http.NameValuePair;
+import org.apache.http.message.BasicNameValuePair;
+
+/**
+ *
+ * @author Luis Linietsky <luis.linietsky@gmail.com>
+ */
+public class RequestParams {
+
+ private HashMap<String, String> params;
+ private String url;
+
+ public RequestParams() {
+ params = new HashMap<String, String>();
+ }
+
+ public void put(String key, String value) {
+ params.put(key, value);
+ }
+
+ public String get(String key) {
+ return params.get(key);
+ }
+
+ public void remove(Object key) {
+ params.remove(key);
+ }
+
+ public boolean has(String key) {
+ return params.containsKey(key);
+ }
+
+ public List<NameValuePair> toPairsList() {
+ List<NameValuePair> fields = new ArrayList<NameValuePair>();
+
+ for (String key : params.keySet()) {
+ fields.add(new BasicNameValuePair(key, this.get(key)));
+ }
+ return fields;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/XRMode.java b/platform/android/java/lib/src/org/godotengine/godot/xr/XRMode.java
new file mode 100644
index 0000000000..5896b23ac3
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/xr/XRMode.java
@@ -0,0 +1,51 @@
+/*************************************************************************/
+/* XRMode.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.xr;
+
+/**
+ * Godot available XR modes.
+ */
+public enum XRMode {
+ REGULAR(0, "Regular", "--xr_mode_regular", "Default Android Gamepad"), // Regular/flatscreen
+ OVR(1, "Oculus Mobile VR", "--xr_mode_ovr", "");
+
+ final int index;
+ final String label;
+ public final String cmdLineArg;
+ public final String inputFallbackMapping;
+
+ XRMode(int index, String label, String cmdLineArg, String inputFallbackMapping) {
+ this.index = index;
+ this.label = label;
+ this.cmdLineArg = cmdLineArg;
+ this.inputFallbackMapping = inputFallbackMapping;
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrConfigChooser.java b/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrConfigChooser.java
new file mode 100644
index 0000000000..ff836a31ca
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrConfigChooser.java
@@ -0,0 +1,112 @@
+/*************************************************************************/
+/* OvrConfigChooser.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.xr.ovr;
+
+import android.opengl.EGLExt;
+import android.opengl.GLSurfaceView;
+import javax.microedition.khronos.egl.EGL10;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.egl.EGLDisplay;
+
+/**
+ * EGL config chooser for the Oculus Mobile VR SDK.
+ */
+public class OvrConfigChooser implements GLSurfaceView.EGLConfigChooser {
+
+ private static final int[] CONFIG_ATTRIBS = {
+ EGL10.EGL_RED_SIZE, 8,
+ EGL10.EGL_GREEN_SIZE, 8,
+ EGL10.EGL_BLUE_SIZE, 8,
+ EGL10.EGL_ALPHA_SIZE, 8, // Need alpha for the multi-pass timewarp compositor
+ EGL10.EGL_DEPTH_SIZE, 0,
+ EGL10.EGL_STENCIL_SIZE, 0,
+ EGL10.EGL_SAMPLES, 0,
+ EGL10.EGL_NONE
+ };
+
+ @Override
+ public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
+ // Do NOT use eglChooseConfig, because the Android EGL code pushes in
+ // multisample flags in eglChooseConfig if the user has selected the "force 4x
+ // MSAA" option in settings, and that is completely wasted for our warp
+ // target.
+ int[] numConfig = new int[1];
+ if (!egl.eglGetConfigs(display, null, 0, numConfig)) {
+ throw new IllegalArgumentException("eglGetConfigs failed.");
+ }
+
+ int configsCount = numConfig[0];
+ if (configsCount <= 0) {
+ throw new IllegalArgumentException("No configs match configSpec");
+ }
+
+ EGLConfig[] configs = new EGLConfig[configsCount];
+ if (!egl.eglGetConfigs(display, configs, configsCount, numConfig)) {
+ throw new IllegalArgumentException("eglGetConfigs #2 failed.");
+ }
+
+ int[] value = new int[1];
+ for (EGLConfig config : configs) {
+ egl.eglGetConfigAttrib(display, config, EGL10.EGL_RENDERABLE_TYPE, value);
+ if ((value[0] & EGLExt.EGL_OPENGL_ES3_BIT_KHR) != EGLExt.EGL_OPENGL_ES3_BIT_KHR) {
+ continue;
+ }
+
+ // The pbuffer config also needs to be compatible with normal window rendering
+ // so it can share textures with the window context.
+ egl.eglGetConfigAttrib(display, config, EGL10.EGL_SURFACE_TYPE, value);
+ if ((value[0] & (EGL10.EGL_WINDOW_BIT | EGL10.EGL_PBUFFER_BIT)) != (EGL10.EGL_WINDOW_BIT | EGL10.EGL_PBUFFER_BIT)) {
+ continue;
+ }
+
+ // Check each attribute in CONFIG_ATTRIBS (which are the attributes we care about)
+ // and ensure the value in config matches.
+ int attribIndex = 0;
+ while (CONFIG_ATTRIBS[attribIndex] != EGL10.EGL_NONE) {
+ egl.eglGetConfigAttrib(display, config, CONFIG_ATTRIBS[attribIndex], value);
+ if (value[0] != CONFIG_ATTRIBS[attribIndex + 1]) {
+ // Attribute key's value does not match the configs value.
+ // Start checking next config.
+ break;
+ }
+
+ // Step by two because CONFIG_ATTRIBS is in key/value pairs.
+ attribIndex += 2;
+ }
+
+ if (CONFIG_ATTRIBS[attribIndex] == EGL10.EGL_NONE) {
+ // All relevant attributes match, set the config and stop checking the rest.
+ return config;
+ }
+ }
+ return null;
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrContextFactory.java b/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrContextFactory.java
new file mode 100644
index 0000000000..5f6da8c672
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrContextFactory.java
@@ -0,0 +1,58 @@
+/*************************************************************************/
+/* OvrContextFactory.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.xr.ovr;
+
+import android.opengl.EGL14;
+import android.opengl.GLSurfaceView;
+import javax.microedition.khronos.egl.EGL10;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.egl.EGLContext;
+import javax.microedition.khronos.egl.EGLDisplay;
+
+/**
+ * EGL Context factory for the Oculus mobile VR SDK.
+ */
+public class OvrContextFactory implements GLSurfaceView.EGLContextFactory {
+
+ private static final int[] CONTEXT_ATTRIBS = {
+ EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL10.EGL_NONE
+ };
+
+ @Override
+ public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) {
+ return egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, CONTEXT_ATTRIBS);
+ }
+
+ @Override
+ public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) {
+ egl.eglDestroyContext(display, context);
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrWindowSurfaceFactory.java b/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrWindowSurfaceFactory.java
new file mode 100644
index 0000000000..f1e38c35d8
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/xr/ovr/OvrWindowSurfaceFactory.java
@@ -0,0 +1,60 @@
+/*************************************************************************/
+/* OvrWindowSurfaceFactory.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.xr.ovr;
+
+import android.opengl.GLSurfaceView;
+import javax.microedition.khronos.egl.EGL10;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.egl.EGLDisplay;
+import javax.microedition.khronos.egl.EGLSurface;
+
+/**
+ * EGL window surface factory for the Oculus mobile VR SDK.
+ */
+public class OvrWindowSurfaceFactory implements GLSurfaceView.EGLWindowSurfaceFactory {
+
+ private final static int[] SURFACE_ATTRIBS = {
+ EGL10.EGL_WIDTH, 16,
+ EGL10.EGL_HEIGHT, 16,
+ EGL10.EGL_NONE
+ };
+
+ @Override
+ public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
+ Object nativeWindow) {
+ return egl.eglCreatePbufferSurface(display, config, SURFACE_ATTRIBS);
+ }
+
+ @Override
+ public void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface) {
+ egl.eglDestroySurface(display, surface);
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularConfigChooser.java b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularConfigChooser.java
new file mode 100644
index 0000000000..3836967f86
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularConfigChooser.java
@@ -0,0 +1,151 @@
+/*************************************************************************/
+/* RegularConfigChooser.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.xr.regular;
+
+import android.opengl.GLSurfaceView;
+import javax.microedition.khronos.egl.EGL10;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.egl.EGLDisplay;
+import org.godotengine.godot.utils.GLUtils;
+
+/**
+ * Used to select the egl config for pancake games.
+ */
+public class RegularConfigChooser implements GLSurfaceView.EGLConfigChooser {
+
+ private static final String TAG = RegularConfigChooser.class.getSimpleName();
+
+ private int[] mValue = new int[1];
+
+ /* This EGL config specification is used to specify 2.0 rendering.
+ * We use a minimum size of 4 bits for red/green/blue, but will
+ * perform actual matching in chooseConfig() below.
+ */
+ private static int EGL_OPENGL_ES2_BIT = 4;
+ private static int[] s_configAttribs2 = {
+ EGL10.EGL_RED_SIZE, 4,
+ EGL10.EGL_GREEN_SIZE, 4,
+ EGL10.EGL_BLUE_SIZE, 4,
+ // EGL10.EGL_DEPTH_SIZE, 16,
+ // EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE,
+ EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
+ EGL10.EGL_NONE
+ };
+ private static int[] s_configAttribs3 = {
+ EGL10.EGL_RED_SIZE, 4,
+ EGL10.EGL_GREEN_SIZE, 4,
+ EGL10.EGL_BLUE_SIZE, 4,
+ // EGL10.EGL_DEPTH_SIZE, 16,
+ // EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE,
+ EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //apparently there is no EGL_OPENGL_ES3_BIT
+ EGL10.EGL_NONE
+ };
+
+ public RegularConfigChooser(int r, int g, int b, int a, int depth, int stencil) {
+ mRedSize = r;
+ mGreenSize = g;
+ mBlueSize = b;
+ mAlphaSize = a;
+ mDepthSize = depth;
+ mStencilSize = stencil;
+ }
+
+ public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
+
+ /* Get the number of minimally matching EGL configurations
+ */
+ int[] num_config = new int[1];
+ egl.eglChooseConfig(display, GLUtils.use_gl3 ? s_configAttribs3 : s_configAttribs2, null, 0, num_config);
+
+ int numConfigs = num_config[0];
+
+ if (numConfigs <= 0) {
+ throw new IllegalArgumentException("No configs match configSpec");
+ }
+
+ /* Allocate then read the array of minimally matching EGL configs
+ */
+ EGLConfig[] configs = new EGLConfig[numConfigs];
+ egl.eglChooseConfig(display, GLUtils.use_gl3 ? s_configAttribs3 : s_configAttribs2, configs, numConfigs, num_config);
+
+ if (GLUtils.DEBUG) {
+ GLUtils.printConfigs(egl, display, configs);
+ }
+ /* Now return the "best" one
+ */
+ return chooseConfig(egl, display, configs);
+ }
+
+ public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
+ EGLConfig[] configs) {
+ for (EGLConfig config : configs) {
+ int d = findConfigAttrib(egl, display, config,
+ EGL10.EGL_DEPTH_SIZE, 0);
+ int s = findConfigAttrib(egl, display, config,
+ EGL10.EGL_STENCIL_SIZE, 0);
+
+ // We need at least mDepthSize and mStencilSize bits
+ if (d < mDepthSize || s < mStencilSize)
+ continue;
+
+ // We want an *exact* match for red/green/blue/alpha
+ int r = findConfigAttrib(egl, display, config,
+ EGL10.EGL_RED_SIZE, 0);
+ int g = findConfigAttrib(egl, display, config,
+ EGL10.EGL_GREEN_SIZE, 0);
+ int b = findConfigAttrib(egl, display, config,
+ EGL10.EGL_BLUE_SIZE, 0);
+ int a = findConfigAttrib(egl, display, config,
+ EGL10.EGL_ALPHA_SIZE, 0);
+
+ if (r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize)
+ return config;
+ }
+ return null;
+ }
+
+ private int findConfigAttrib(EGL10 egl, EGLDisplay display,
+ EGLConfig config, int attribute, int defaultValue) {
+
+ if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
+ return mValue[0];
+ }
+ return defaultValue;
+ }
+
+ // Subclasses can adjust these values:
+ protected int mRedSize;
+ protected int mGreenSize;
+ protected int mBlueSize;
+ protected int mAlphaSize;
+ protected int mDepthSize;
+ protected int mStencilSize;
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java
new file mode 100644
index 0000000000..4f1e9a696b
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularContextFactory.java
@@ -0,0 +1,81 @@
+/*************************************************************************/
+/* RegularContextFactory.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.xr.regular;
+
+import android.opengl.GLSurfaceView;
+import android.util.Log;
+import javax.microedition.khronos.egl.EGL10;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.egl.EGLContext;
+import javax.microedition.khronos.egl.EGLDisplay;
+import org.godotengine.godot.GodotLib;
+import org.godotengine.godot.utils.GLUtils;
+
+/**
+ * Factory used to setup the opengl context for pancake games.
+ */
+public class RegularContextFactory implements GLSurfaceView.EGLContextFactory {
+ private static final String TAG = RegularContextFactory.class.getSimpleName();
+
+ private static final int _EGL_CONTEXT_FLAGS_KHR = 0x30FC;
+ private static final int _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR = 0x00000001;
+
+ private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
+
+ public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) {
+ String driver_name = GodotLib.getGlobal("rendering/quality/driver/driver_name");
+ if (GLUtils.use_gl3 && !driver_name.equals("GLES3")) {
+ GLUtils.use_gl3 = false;
+ }
+ if (GLUtils.use_gl3)
+ Log.w(TAG, "creating OpenGL ES 3.0 context :");
+ else
+ Log.w(TAG, "creating OpenGL ES 2.0 context :");
+
+ GLUtils.checkEglError(TAG, "Before eglCreateContext", egl);
+ EGLContext context;
+ if (GLUtils.use_debug_opengl) {
+ int[] attrib_list2 = { EGL_CONTEXT_CLIENT_VERSION, 2, _EGL_CONTEXT_FLAGS_KHR, _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL10.EGL_NONE };
+ int[] attrib_list3 = { EGL_CONTEXT_CLIENT_VERSION, 3, _EGL_CONTEXT_FLAGS_KHR, _EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL10.EGL_NONE };
+ context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, GLUtils.use_gl3 ? attrib_list3 : attrib_list2);
+ } else {
+ int[] attrib_list2 = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
+ int[] attrib_list3 = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL10.EGL_NONE };
+ context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, GLUtils.use_gl3 ? attrib_list3 : attrib_list2);
+ }
+ GLUtils.checkEglError(TAG, "After eglCreateContext", egl);
+ return context;
+ }
+
+ public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) {
+ egl.eglDestroyContext(display, context);
+ }
+}
diff --git a/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularFallbackConfigChooser.java b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularFallbackConfigChooser.java
new file mode 100644
index 0000000000..f5718ef2b3
--- /dev/null
+++ b/platform/android/java/lib/src/org/godotengine/godot/xr/regular/RegularFallbackConfigChooser.java
@@ -0,0 +1,61 @@
+/*************************************************************************/
+/* RegularFallbackConfigChooser.java */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+package org.godotengine.godot.xr.regular;
+
+import android.util.Log;
+import javax.microedition.khronos.egl.EGL10;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.egl.EGLDisplay;
+import org.godotengine.godot.utils.GLUtils;
+
+/* Fallback if 32bit View is not supported*/
+public class RegularFallbackConfigChooser extends RegularConfigChooser {
+
+ private static final String TAG = RegularFallbackConfigChooser.class.getSimpleName();
+
+ private RegularConfigChooser fallback;
+
+ public RegularFallbackConfigChooser(int r, int g, int b, int a, int depth, int stencil, RegularConfigChooser fallback) {
+ super(r, g, b, a, depth, stencil);
+ this.fallback = fallback;
+ }
+
+ @Override
+ public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display, EGLConfig[] configs) {
+ EGLConfig ec = super.chooseConfig(egl, display, configs);
+ if (ec == null) {
+ Log.w(TAG, "Trying ConfigChooser fallback");
+ ec = fallback.chooseConfig(egl, display, configs);
+ GLUtils.use_32 = false;
+ }
+ return ec;
+ }
+}