SDLActivity.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. // Modified by Lasse Oorni and Yao Wei Tjong for Urho3D
  2. package org.libsdl.app;
  3. import java.io.File;
  4. import java.util.Arrays;
  5. import java.util.Comparator;
  6. import javax.microedition.khronos.egl.EGL10;
  7. import javax.microedition.khronos.egl.EGLConfig;
  8. import javax.microedition.khronos.egl.EGLContext;
  9. import javax.microedition.khronos.egl.EGLDisplay;
  10. import javax.microedition.khronos.egl.EGLSurface;
  11. import android.app.*;
  12. import android.content.*;
  13. import android.view.*;
  14. import android.view.inputmethod.BaseInputConnection;
  15. import android.view.inputmethod.EditorInfo;
  16. import android.view.inputmethod.InputConnection;
  17. import android.view.inputmethod.InputMethodManager;
  18. import android.widget.AbsoluteLayout;
  19. import android.os.*;
  20. import android.util.Log;
  21. import android.graphics.*;
  22. import android.media.*;
  23. import android.hardware.*;
  24. /**
  25. SDL Activity
  26. */
  27. public class SDLActivity extends Activity {
  28. // Urho3D: adjust log level, no verbose in production code, first check log level for non-trivial message construction
  29. private static final String TAG = "SDL";
  30. // Keep track of the paused state
  31. public static boolean mIsPaused = false, mIsSurfaceReady = false, mHasFocus = true;
  32. // Main components
  33. protected static SDLActivity mSingleton;
  34. protected static SDLSurface mSurface;
  35. protected static View mTextEdit;
  36. protected static ViewGroup mLayout;
  37. // This is what SDL runs in. It invokes SDL_main(), eventually
  38. protected static Thread mSDLThread;
  39. // Audio
  40. protected static Thread mAudioThread;
  41. protected static AudioTrack mAudioTrack;
  42. // EGL objects
  43. protected static EGLContext mEGLContext;
  44. protected static EGLSurface mEGLSurface;
  45. protected static EGLDisplay mEGLDisplay;
  46. protected static EGLConfig mEGLConfig;
  47. protected static int mGLMajor, mGLMinor;
  48. // Urho3D: flag to load the .so
  49. private static boolean mIsSharedLibraryLoaded = false;
  50. // Setup
  51. @Override
  52. protected void onCreate(Bundle savedInstanceState) {
  53. //Log.v(TAG, "onCreate()");
  54. super.onCreate(savedInstanceState);
  55. // So we can call stuff from static callbacks
  56. mSingleton = this;
  57. // Urho3D: auto load all the shared libraries available in the library path
  58. // FIXME: use getApplicationInfo().nativeLibraryDir directly when min target API is 9 or above
  59. String libraryPath = getApplicationInfo().dataDir + "/lib";
  60. //Log.v(TAG, "library path: " + libraryPath);
  61. if (!mIsSharedLibraryLoaded) {
  62. File[] files = new File(libraryPath).listFiles();
  63. Arrays.sort(files, new Comparator<File>() {
  64. @Override
  65. public int compare(File lhs, File rhs) {
  66. return Long.valueOf(lhs.lastModified()).compareTo(rhs.lastModified());
  67. }
  68. });
  69. for (final File libraryFilename : files) {
  70. String name = libraryFilename.getName().replaceAll("^lib(.*)\\.so$", "$1");
  71. //Log.v(TAG, "library name: " + name);
  72. System.loadLibrary(name);
  73. }
  74. mIsSharedLibraryLoaded = true;
  75. }
  76. // Set up the surface
  77. mEGLSurface = EGL10.EGL_NO_SURFACE;
  78. mSurface = new SDLSurface(getApplication());
  79. mEGLContext = EGL10.EGL_NO_CONTEXT;
  80. mLayout = new AbsoluteLayout(this);
  81. mLayout.addView(mSurface);
  82. setContentView(mLayout);
  83. }
  84. // Events
  85. @Override
  86. protected void onPause() {
  87. //Log.v(TAG, "onPause()");
  88. super.onPause();
  89. SDLActivity.handlePause();
  90. }
  91. @Override
  92. protected void onResume() {
  93. //Log.v(TAG, "onResume()");
  94. super.onResume();
  95. SDLActivity.handleResume();
  96. }
  97. @Override
  98. public void onWindowFocusChanged(boolean hasFocus) {
  99. //Log.v(TAG, "onWindowFocusChanged(): " + hasFocus);
  100. super.onWindowFocusChanged(hasFocus);
  101. SDLActivity.mHasFocus = hasFocus;
  102. if (hasFocus) {
  103. SDLActivity.handleResume();
  104. }
  105. }
  106. @Override
  107. public void onLowMemory() {
  108. //Log.v(TAG, "onLowMemory()");
  109. super.onLowMemory();
  110. SDLActivity.nativeLowMemory();
  111. }
  112. @Override
  113. protected void onDestroy() {
  114. //Log.v(TAG, "onDestroy()");
  115. super.onDestroy();
  116. // Send a quit message to the application
  117. SDLActivity.nativeQuit();
  118. // Now wait for the SDL thread to quit
  119. if (mSDLThread != null) {
  120. try {
  121. mSDLThread.join();
  122. } catch(Exception e) {
  123. if (Log.isLoggable(TAG, Log.ERROR))
  124. Log.e(TAG, "Problem stopping thread: " + e);
  125. }
  126. mSDLThread = null;
  127. //Log.v(TAG, "Finished waiting for SDL thread");
  128. }
  129. }
  130. @Override
  131. public boolean dispatchKeyEvent(KeyEvent event) {
  132. int keyCode = event.getKeyCode();
  133. // Ignore volume keys so they're handled by Android
  134. // Urho3D: also ignore the Home key
  135. if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
  136. keyCode == KeyEvent.KEYCODE_VOLUME_UP ||
  137. keyCode == KeyEvent.KEYCODE_HOME) {
  138. return false;
  139. }
  140. return super.dispatchKeyEvent(event);
  141. }
  142. /** Called by onPause or surfaceDestroyed. Even if surfaceDestroyed
  143. * is the first to be called, mIsSurfaceReady should still be set
  144. * to 'true' during the call to onPause (in a usual scenario).
  145. */
  146. public static void handlePause() {
  147. if (!SDLActivity.mIsPaused && SDLActivity.mIsSurfaceReady) {
  148. SDLActivity.mIsPaused = true;
  149. SDLActivity.nativePause();
  150. mSurface.enableSensor(Sensor.TYPE_ACCELEROMETER, false);
  151. }
  152. }
  153. /** Called by onResume or surfaceCreated. An actual resume should be done only when the surface is ready.
  154. * Note: Some Android variants may send multiple surfaceChanged events, so we don't need to resume
  155. * every time we get one of those events, only if it comes after surfaceDestroyed
  156. */
  157. public static void handleResume() {
  158. if (SDLActivity.mIsPaused && SDLActivity.mIsSurfaceReady && SDLActivity.mHasFocus) {
  159. SDLActivity.mIsPaused = false;
  160. SDLActivity.nativeResume();
  161. mSurface.enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  162. }
  163. }
  164. // Messages from the SDLMain thread
  165. static final int COMMAND_CHANGE_TITLE = 1;
  166. static final int COMMAND_UNUSED = 2;
  167. static final int COMMAND_TEXTEDIT_HIDE = 3;
  168. // Urho3D: added
  169. static final int COMMAND_FINISH = 4;
  170. protected static final int COMMAND_USER = 0x8000;
  171. /**
  172. * This method is called by SDL if SDL did not handle a message itself.
  173. * This happens if a received message contains an unsupported command.
  174. * Method can be overwritten to handle Messages in a different class.
  175. * @param command the command of the message.
  176. * @param param the parameter of the message. May be null.
  177. * @return if the message was handled in overridden method.
  178. */
  179. protected boolean onUnhandledMessage(int command, Object param) {
  180. return false;
  181. }
  182. /**
  183. * A Handler class for Messages from native SDL applications.
  184. * It uses current Activities as target (e.g. for the title).
  185. * static to prevent implicit references to enclosing object.
  186. */
  187. protected static class SDLCommandHandler extends Handler {
  188. @Override
  189. public void handleMessage(Message msg) {
  190. Context context = getContext();
  191. if (context == null) {
  192. Log.e(TAG, "error handling message, getContext() returned null");
  193. return;
  194. }
  195. switch (msg.arg1) {
  196. case COMMAND_CHANGE_TITLE:
  197. if (context instanceof Activity) {
  198. ((Activity) context).setTitle((String)msg.obj);
  199. } else {
  200. Log.e(TAG, "error handling message, getContext() returned no Activity");
  201. }
  202. break;
  203. case COMMAND_TEXTEDIT_HIDE:
  204. if (mTextEdit != null) {
  205. mTextEdit.setVisibility(View.GONE);
  206. InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
  207. imm.hideSoftInputFromWindow(mTextEdit.getWindowToken(), 0);
  208. }
  209. break;
  210. // Urho3D: added
  211. case COMMAND_FINISH:
  212. if (context instanceof Activity)
  213. ((Activity) context).finish();
  214. break;
  215. default:
  216. if ((context instanceof SDLActivity) && !((SDLActivity) context).onUnhandledMessage(msg.arg1, msg.obj)) {
  217. if (Log.isLoggable(TAG, Log.ERROR))
  218. Log.e(TAG, "error handling message, command is " + msg.arg1);
  219. }
  220. }
  221. }
  222. }
  223. // Handler for the messages
  224. Handler commandHandler = new SDLCommandHandler();
  225. // Send a message from the SDLMain thread
  226. boolean sendCommand(int command, Object data) {
  227. Message msg = commandHandler.obtainMessage();
  228. msg.arg1 = command;
  229. msg.obj = data;
  230. return commandHandler.sendMessage(msg);
  231. }
  232. // C functions we call
  233. public static native void nativeInit(String filesDir);
  234. public static native void nativeLowMemory();
  235. public static native void nativeQuit();
  236. public static native void nativePause();
  237. public static native void nativeResume();
  238. public static native void onNativeResize(int x, int y, int format);
  239. public static native void onNativeKeyDown(int keycode);
  240. public static native void onNativeKeyUp(int keycode);
  241. public static native void onNativeKeyboardFocusLost();
  242. public static native void onNativeTouch(int touchDevId, int pointerFingerId,
  243. int action, float x,
  244. float y, float p);
  245. public static native void onNativeAccel(float x, float y, float z);
  246. // Java functions called from C
  247. public static boolean createGLContext(int majorVersion, int minorVersion, int[] attribs) {
  248. return initEGL(majorVersion, minorVersion, attribs);
  249. }
  250. public static void deleteGLContext() {
  251. if (SDLActivity.mEGLDisplay != null && SDLActivity.mEGLContext != EGL10.EGL_NO_CONTEXT) {
  252. EGL10 egl = (EGL10)EGLContext.getEGL();
  253. egl.eglMakeCurrent(SDLActivity.mEGLDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
  254. egl.eglDestroyContext(SDLActivity.mEGLDisplay, SDLActivity.mEGLContext);
  255. SDLActivity.mEGLContext = EGL10.EGL_NO_CONTEXT;
  256. if (SDLActivity.mEGLSurface != EGL10.EGL_NO_SURFACE) {
  257. egl.eglDestroySurface(SDLActivity.mEGLDisplay, SDLActivity.mEGLSurface);
  258. SDLActivity.mEGLSurface = EGL10.EGL_NO_SURFACE;
  259. }
  260. }
  261. }
  262. public static void flipBuffers() {
  263. flipEGL();
  264. }
  265. public static boolean setActivityTitle(String title) {
  266. // Called from SDLMain() thread and can't directly affect the view
  267. return mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title);
  268. }
  269. public static void finishActivity()
  270. {
  271. mSingleton.sendCommand(COMMAND_FINISH, null);
  272. }
  273. public static boolean sendMessage(int command, int param) {
  274. return mSingleton.sendCommand(command, Integer.valueOf(param));
  275. }
  276. public static Context getContext() {
  277. return mSingleton;
  278. }
  279. static class ShowTextInputTask implements Runnable {
  280. /*
  281. * This is used to regulate the pan&scan method to have some offset from
  282. * the bottom edge of the input region and the top edge of an input
  283. * method (soft keyboard)
  284. */
  285. static final int HEIGHT_PADDING = 15;
  286. public int x, y, w, h;
  287. public ShowTextInputTask(int x, int y, int w, int h) {
  288. this.x = x;
  289. this.y = y;
  290. this.w = w;
  291. this.h = h;
  292. }
  293. @Override
  294. public void run() {
  295. AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(
  296. w, h + HEIGHT_PADDING, x, y);
  297. if (mTextEdit == null) {
  298. mTextEdit = new DummyEdit(getContext());
  299. mLayout.addView(mTextEdit, params);
  300. } else {
  301. mTextEdit.setLayoutParams(params);
  302. }
  303. mTextEdit.setVisibility(View.VISIBLE);
  304. mTextEdit.requestFocus();
  305. InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
  306. imm.showSoftInput(mTextEdit, 0);
  307. }
  308. }
  309. public static boolean showTextInput(int x, int y, int w, int h) {
  310. // Transfer the task to the main thread as a Runnable
  311. return mSingleton.commandHandler.post(new ShowTextInputTask(x, y, w, h));
  312. }
  313. // EGL functions
  314. public static boolean initEGL(int majorVersion, int minorVersion, int[] attribs) {
  315. try {
  316. EGL10 egl = (EGL10)EGLContext.getEGL();
  317. if (SDLActivity.mEGLDisplay == null) {
  318. SDLActivity.mEGLDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
  319. int[] version = new int[2];
  320. egl.eglInitialize(SDLActivity.mEGLDisplay, version);
  321. }
  322. if (SDLActivity.mEGLDisplay != null && SDLActivity.mEGLContext == EGL10.EGL_NO_CONTEXT) {
  323. // No current GL context exists, we will create a new one.
  324. if (Log.isLoggable(TAG, Log.DEBUG))
  325. Log.d(TAG, "Starting up OpenGL ES " + majorVersion + "." + minorVersion);
  326. EGLConfig[] configs = new EGLConfig[128];
  327. int[] num_config = new int[1];
  328. if (!egl.eglChooseConfig(SDLActivity.mEGLDisplay, attribs, configs, 1, num_config) || num_config[0] == 0) {
  329. Log.e("SDL", "No EGL config available");
  330. return false;
  331. }
  332. EGLConfig config = null;
  333. int bestdiff = -1, bitdiff;
  334. int[] value = new int[1];
  335. // eglChooseConfig returns a number of configurations that match or exceed the requested attribs.
  336. // From those, we select the one that matches our requirements more closely
  337. if (Log.isLoggable(TAG, Log.DEBUG))
  338. Log.d(TAG, "Got " + num_config[0] + " valid modes from egl");
  339. for(int i = 0; i < num_config[0]; i++) {
  340. bitdiff = 0;
  341. // Go through some of the attributes and compute the bit difference between what we want and what we get.
  342. for (int j = 0; ; j += 2) {
  343. if (attribs[j] == EGL10.EGL_NONE)
  344. break;
  345. if (attribs[j+1] != EGL10.EGL_DONT_CARE && (attribs[j] == EGL10.EGL_RED_SIZE ||
  346. attribs[j] == EGL10.EGL_GREEN_SIZE ||
  347. attribs[j] == EGL10.EGL_BLUE_SIZE ||
  348. attribs[j] == EGL10.EGL_ALPHA_SIZE ||
  349. attribs[j] == EGL10.EGL_DEPTH_SIZE ||
  350. attribs[j] == EGL10.EGL_STENCIL_SIZE)) {
  351. egl.eglGetConfigAttrib(SDLActivity.mEGLDisplay, configs[i], attribs[j], value);
  352. bitdiff += value[0] - attribs[j + 1]; // value is always >= attrib
  353. }
  354. }
  355. if (bitdiff < bestdiff || bestdiff == -1) {
  356. config = configs[i];
  357. bestdiff = bitdiff;
  358. }
  359. if (bitdiff == 0) break; // we found an exact match!
  360. }
  361. if (Log.isLoggable(TAG, Log.DEBUG))
  362. Log.d("SDL", "Selected mode with a total bit difference of " + bestdiff);
  363. SDLActivity.mEGLConfig = config;
  364. SDLActivity.mGLMajor = majorVersion;
  365. SDLActivity.mGLMinor = minorVersion;
  366. }
  367. return SDLActivity.createEGLSurface();
  368. } catch(Exception e) {
  369. if (Log.isLoggable(TAG, Log.ERROR))
  370. Log.e(TAG, "initEGL(): " + e);
  371. if (Log.isLoggable(TAG, Log.DEBUG)) {
  372. for (StackTraceElement s : e.getStackTrace()) {
  373. Log.d(TAG, s.toString());
  374. }
  375. }
  376. return false;
  377. }
  378. }
  379. public static boolean createEGLContext() {
  380. EGL10 egl = (EGL10)EGLContext.getEGL();
  381. int EGL_CONTEXT_CLIENT_VERSION=0x3098;
  382. int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, SDLActivity.mGLMajor, EGL10.EGL_NONE };
  383. SDLActivity.mEGLContext = egl.eglCreateContext(SDLActivity.mEGLDisplay, SDLActivity.mEGLConfig, EGL10.EGL_NO_CONTEXT, contextAttrs);
  384. if (SDLActivity.mEGLContext == EGL10.EGL_NO_CONTEXT) {
  385. Log.e("SDL", "Couldn't create context");
  386. return false;
  387. }
  388. return true;
  389. }
  390. public static boolean createEGLSurface() {
  391. if (SDLActivity.mEGLDisplay != null && SDLActivity.mEGLConfig != null) {
  392. EGL10 egl = (EGL10)EGLContext.getEGL();
  393. if (SDLActivity.mEGLContext == EGL10.EGL_NO_CONTEXT) createEGLContext();
  394. if (SDLActivity.mEGLSurface == EGL10.EGL_NO_SURFACE) {
  395. Log.d(TAG, "Creating new EGL Surface");
  396. SDLActivity.mEGLSurface = egl.eglCreateWindowSurface(SDLActivity.mEGLDisplay, SDLActivity.mEGLConfig, SDLActivity.mSurface, null);
  397. if (SDLActivity.mEGLSurface == EGL10.EGL_NO_SURFACE) {
  398. Log.e("SDL", "Couldn't create surface");
  399. return false;
  400. }
  401. }
  402. else Log.d(TAG, "EGL Surface remains valid");
  403. if (egl.eglGetCurrentContext() != SDLActivity.mEGLContext) {
  404. if (!egl.eglMakeCurrent(SDLActivity.mEGLDisplay, SDLActivity.mEGLSurface, SDLActivity.mEGLSurface, SDLActivity.mEGLContext)) {
  405. Log.e("SDL", "Old EGL Context doesnt work, trying with a new one");
  406. // TODO: Notify the user via a message that the old context could not be restored, and that textures need to be manually restored.
  407. createEGLContext();
  408. if (!egl.eglMakeCurrent(SDLActivity.mEGLDisplay, SDLActivity.mEGLSurface, SDLActivity.mEGLSurface, SDLActivity.mEGLContext)) {
  409. Log.e("SDL", "Failed making EGL Context current");
  410. return false;
  411. }
  412. }
  413. else Log.d(TAG, "EGL Context made current");
  414. }
  415. else Log.d(TAG, "EGL Context remains current");
  416. return true;
  417. } else {
  418. if (Log.isLoggable(TAG, Log.ERROR))
  419. Log.e("SDL", "Surface creation failed, display = " + SDLActivity.mEGLDisplay + ", config = " + SDLActivity.mEGLConfig);
  420. return false;
  421. }
  422. }
  423. // EGL buffer flip
  424. public static void flipEGL() {
  425. try {
  426. EGL10 egl = (EGL10)EGLContext.getEGL();
  427. egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, null);
  428. // drawing here
  429. egl.eglWaitGL();
  430. egl.eglSwapBuffers(SDLActivity.mEGLDisplay, SDLActivity.mEGLSurface);
  431. } catch(Exception e) {
  432. if (Log.isLoggable(TAG, Log.ERROR))
  433. Log.e(TAG, "flipEGL(): " + e);
  434. if (Log.isLoggable(TAG, Log.DEBUG)) {
  435. for (StackTraceElement s : e.getStackTrace()) {
  436. Log.d(TAG, s.toString());
  437. }
  438. }
  439. }
  440. }
  441. // Audio
  442. public static int audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
  443. int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
  444. int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
  445. int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
  446. if (Log.isLoggable(TAG, Log.DEBUG))
  447. Log.d(TAG, "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + (sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  448. // Let the user pick a larger buffer if they really want -- but ye
  449. // gods they probably shouldn't, the minimums are horrifyingly high
  450. // latency already
  451. desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
  452. if (mAudioTrack == null) {
  453. mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
  454. channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
  455. // Instantiating AudioTrack can "succeed" without an exception and the track may still be invalid
  456. // Ref: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/media/java/android/media/AudioTrack.java
  457. // Ref: http://developer.android.com/reference/android/media/AudioTrack.html#getState()
  458. if (mAudioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
  459. Log.e("SDL", "Failed during initialization of Audio Track");
  460. mAudioTrack = null;
  461. return -1;
  462. }
  463. mAudioTrack.play();
  464. }
  465. if (Log.isLoggable(TAG, Log.DEBUG))
  466. Log.d(TAG, "SDL audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + (mAudioTrack.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  467. return 0;
  468. }
  469. public static void audioWriteShortBuffer(short[] buffer) {
  470. for (int i = 0; i < buffer.length; ) {
  471. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  472. if (result > 0) {
  473. i += result;
  474. } else if (result == 0) {
  475. try {
  476. Thread.sleep(1);
  477. } catch(InterruptedException e) {
  478. // Nom nom
  479. }
  480. } else {
  481. Log.w("SDL", "SDL audio: error return from write(short)");
  482. return;
  483. }
  484. }
  485. }
  486. public static void audioWriteByteBuffer(byte[] buffer) {
  487. for (int i = 0; i < buffer.length; ) {
  488. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  489. if (result > 0) {
  490. i += result;
  491. } else if (result == 0) {
  492. try {
  493. Thread.sleep(1);
  494. } catch(InterruptedException e) {
  495. // Nom nom
  496. }
  497. } else {
  498. Log.w("SDL", "SDL audio: error return from write(byte)");
  499. return;
  500. }
  501. }
  502. }
  503. public static void audioQuit() {
  504. if (mAudioTrack != null) {
  505. mAudioTrack.stop();
  506. mAudioTrack = null;
  507. }
  508. }
  509. }
  510. /**
  511. Simple nativeInit() runnable
  512. */
  513. class SDLMain implements Runnable {
  514. @Override
  515. public void run() {
  516. // Runs SDL_main()
  517. // Urho3D: pass filesDir
  518. SDLActivity.nativeInit(((Activity)SDLActivity.getContext()).getFilesDir().getAbsolutePath());
  519. //Log.v("SDL", "SDL thread terminated");
  520. // Urho3D: finish activity when SDL_main returns
  521. SDLActivity.finishActivity();
  522. }
  523. }
  524. /**
  525. SDLSurface. This is what we draw on, so we need to know when it's created
  526. in order to do anything useful.
  527. Because of this, that's where we set up the SDL thread
  528. */
  529. class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
  530. View.OnKeyListener, View.OnTouchListener, SensorEventListener {
  531. private static final String TAG = "SDL";
  532. // Sensors
  533. protected static SensorManager mSensorManager;
  534. // Keep track of the surface size to normalize touch events
  535. protected static float mWidth, mHeight;
  536. // Startup
  537. public SDLSurface(Context context) {
  538. super(context);
  539. getHolder().addCallback(this);
  540. setFocusable(true);
  541. setFocusableInTouchMode(true);
  542. requestFocus();
  543. setOnKeyListener(this);
  544. setOnTouchListener(this);
  545. mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
  546. // Some arbitrary defaults to avoid a potential division by zero
  547. mWidth = 1.0f;
  548. mHeight = 1.0f;
  549. }
  550. // Called when we have a valid drawing surface
  551. @Override
  552. public void surfaceCreated(SurfaceHolder holder) {
  553. //Log.v(TAG, "surfaceCreated()");
  554. holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
  555. // Set mIsSurfaceReady to 'true' *before* any call to handleResume
  556. SDLActivity.mIsSurfaceReady = true;
  557. }
  558. // Called when we lose the surface
  559. @Override
  560. public void surfaceDestroyed(SurfaceHolder holder) {
  561. //Log.v(TAG, "surfaceDestroyed()");
  562. // Call this *before* setting mIsSurfaceReady to 'false'
  563. SDLActivity.handlePause();
  564. SDLActivity.mIsSurfaceReady = false;
  565. /* We have to clear the current context and destroy the egl surface here
  566. * Otherwise there's BAD_NATIVE_WINDOW errors coming from eglCreateWindowSurface on resume
  567. * Ref: http://stackoverflow.com/questions/8762589/eglcreatewindowsurface-on-ics-and-switching-from-2d-to-3d
  568. */
  569. EGL10 egl = (EGL10)EGLContext.getEGL();
  570. egl.eglMakeCurrent(SDLActivity.mEGLDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
  571. egl.eglDestroySurface(SDLActivity.mEGLDisplay, SDLActivity.mEGLSurface);
  572. SDLActivity.mEGLSurface = EGL10.EGL_NO_SURFACE;
  573. }
  574. // Called when the surface is resized
  575. @Override
  576. public void surfaceChanged(SurfaceHolder holder,
  577. int format, int width, int height) {
  578. //Log.v(TAG, "surfaceChanged()");
  579. int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
  580. switch (format) {
  581. case PixelFormat.A_8:
  582. Log.d(TAG, "pixel format A_8");
  583. break;
  584. case PixelFormat.LA_88:
  585. Log.d(TAG, "pixel format LA_88");
  586. break;
  587. case PixelFormat.L_8:
  588. Log.d(TAG, "pixel format L_8");
  589. break;
  590. case PixelFormat.RGBA_4444:
  591. Log.d(TAG, "pixel format RGBA_4444");
  592. sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
  593. break;
  594. case PixelFormat.RGBA_5551:
  595. Log.d(TAG, "pixel format RGBA_5551");
  596. sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
  597. break;
  598. case PixelFormat.RGBA_8888:
  599. Log.d(TAG, "pixel format RGBA_8888");
  600. sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
  601. break;
  602. case PixelFormat.RGBX_8888:
  603. Log.d(TAG, "pixel format RGBX_8888");
  604. sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
  605. break;
  606. case PixelFormat.RGB_332:
  607. Log.d(TAG, "pixel format RGB_332");
  608. sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
  609. break;
  610. case PixelFormat.RGB_565:
  611. Log.d(TAG, "pixel format RGB_565");
  612. sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
  613. break;
  614. case PixelFormat.RGB_888:
  615. Log.d(TAG, "pixel format RGB_888");
  616. // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
  617. sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
  618. break;
  619. default:
  620. if (Log.isLoggable(TAG, Log.DEBUG))
  621. Log.d(TAG, "pixel format unknown " + format);
  622. break;
  623. }
  624. mWidth = width;
  625. mHeight = height;
  626. SDLActivity.onNativeResize(width, height, sdlFormat);
  627. if (Log.isLoggable(TAG, Log.DEBUG))
  628. Log.d(TAG, "Window size: " + width + "x" + height);
  629. // Set mIsSurfaceReady to 'true' *before* making a call to handleResume
  630. SDLActivity.mIsSurfaceReady = true;
  631. if (SDLActivity.mSDLThread == null) {
  632. // This is the entry point to the C app.
  633. // Start up the C app thread and enable sensor input for the first time
  634. SDLActivity.mSDLThread = new Thread(new SDLMain(), "SDLThread");
  635. enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  636. SDLActivity.mSDLThread.start();
  637. }
  638. }
  639. // unused
  640. @Override
  641. public void onDraw(Canvas canvas) {}
  642. // Key events
  643. @Override
  644. public boolean onKey(View v, int keyCode, KeyEvent event) {
  645. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  646. //Log.v(TAG, "key down: " + keyCode);
  647. SDLActivity.onNativeKeyDown(keyCode);
  648. return true;
  649. }
  650. else if (event.getAction() == KeyEvent.ACTION_UP) {
  651. //Log.v(TAG, "key up: " + keyCode);
  652. SDLActivity.onNativeKeyUp(keyCode);
  653. return true;
  654. }
  655. return false;
  656. }
  657. // Touch events
  658. @Override
  659. public boolean onTouch(View v, MotionEvent event) {
  660. final int touchDevId = event.getDeviceId();
  661. final int pointerCount = event.getPointerCount();
  662. // touchId, pointerId, action, x, y, pressure
  663. int actionPointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT; /* API 8: event.getActionIndex(); */
  664. int pointerFingerId = event.getPointerId(actionPointerIndex);
  665. int action = (event.getAction() & MotionEvent.ACTION_MASK); /* API 8: event.getActionMasked(); */
  666. float x = event.getX(actionPointerIndex) / mWidth;
  667. float y = event.getY(actionPointerIndex) / mHeight;
  668. float p = event.getPressure(actionPointerIndex);
  669. if (action == MotionEvent.ACTION_MOVE && pointerCount > 1) {
  670. // TODO send motion to every pointer if its position has
  671. // changed since prev event.
  672. for (int i = 0; i < pointerCount; i++) {
  673. pointerFingerId = event.getPointerId(i);
  674. x = event.getX(i) / mWidth;
  675. y = event.getY(i) / mHeight;
  676. p = event.getPressure(i);
  677. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  678. }
  679. } else {
  680. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  681. }
  682. return true;
  683. }
  684. // Sensor events
  685. public void enableSensor(int sensortype, boolean enabled) {
  686. // TODO: This uses getDefaultSensor - what if we have >1 accels?
  687. if (enabled) {
  688. mSensorManager.registerListener(this,
  689. mSensorManager.getDefaultSensor(sensortype),
  690. SensorManager.SENSOR_DELAY_GAME, null);
  691. } else {
  692. mSensorManager.unregisterListener(this,
  693. mSensorManager.getDefaultSensor(sensortype));
  694. }
  695. }
  696. @Override
  697. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  698. // TODO
  699. }
  700. @Override
  701. public void onSensorChanged(SensorEvent event) {
  702. if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
  703. SDLActivity.onNativeAccel(event.values[0] / SensorManager.GRAVITY_EARTH,
  704. event.values[1] / SensorManager.GRAVITY_EARTH,
  705. event.values[2] / SensorManager.GRAVITY_EARTH);
  706. }
  707. }
  708. }
  709. /* This is a fake invisible editor view that receives the input and defines the
  710. * pan&scan region
  711. */
  712. class DummyEdit extends View implements View.OnKeyListener {
  713. InputConnection ic;
  714. public DummyEdit(Context context) {
  715. super(context);
  716. setFocusableInTouchMode(true);
  717. setFocusable(true);
  718. setOnKeyListener(this);
  719. }
  720. @Override
  721. public boolean onCheckIsTextEditor() {
  722. return true;
  723. }
  724. @Override
  725. public boolean onKey(View v, int keyCode, KeyEvent event) {
  726. // This handles the hardware keyboard input
  727. if (event.isPrintingKey()) {
  728. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  729. ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  730. }
  731. return true;
  732. }
  733. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  734. SDLActivity.onNativeKeyDown(keyCode);
  735. return true;
  736. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  737. SDLActivity.onNativeKeyUp(keyCode);
  738. return true;
  739. }
  740. return false;
  741. }
  742. //
  743. @Override
  744. public boolean onKeyPreIme (int keyCode, KeyEvent event) {
  745. // As seen on StackOverflow: http://stackoverflow.com/questions/7634346/keyboard-hide-event
  746. // FIXME: Discussion at http://bugzilla.libsdl.org/show_bug.cgi?id=1639
  747. // FIXME: This is not a 100% effective solution to the problem of detecting if the keyboard is showing or not
  748. // FIXME: A more effective solution would be to change our Layout from AbsoluteLayout to Relative or Linear
  749. // FIXME: And determine the keyboard presence doing this: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
  750. // FIXME: An even more effective way would be if Android provided this out of the box, but where would the fun be in that :)
  751. if (event.getAction()==KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
  752. if (SDLActivity.mTextEdit != null && SDLActivity.mTextEdit.getVisibility() == View.VISIBLE) {
  753. SDLActivity.onNativeKeyboardFocusLost();
  754. }
  755. }
  756. return super.onKeyPreIme(keyCode, event);
  757. }
  758. @Override
  759. public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
  760. ic = new SDLInputConnection(this, true);
  761. outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
  762. | 33554432 /* API 11: EditorInfo.IME_FLAG_NO_FULLSCREEN */;
  763. return ic;
  764. }
  765. }
  766. class SDLInputConnection extends BaseInputConnection {
  767. public SDLInputConnection(View targetView, boolean fullEditor) {
  768. super(targetView, fullEditor);
  769. }
  770. @Override
  771. public boolean sendKeyEvent(KeyEvent event) {
  772. /*
  773. * This handles the keycodes from soft keyboard (and IME-translated
  774. * input from hardkeyboard)
  775. */
  776. int keyCode = event.getKeyCode();
  777. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  778. if (event.isPrintingKey()) {
  779. commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  780. }
  781. SDLActivity.onNativeKeyDown(keyCode);
  782. return true;
  783. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  784. SDLActivity.onNativeKeyUp(keyCode);
  785. return true;
  786. }
  787. return super.sendKeyEvent(event);
  788. }
  789. @Override
  790. public boolean commitText(CharSequence text, int newCursorPosition) {
  791. nativeCommitText(text.toString(), newCursorPosition);
  792. return super.commitText(text, newCursorPosition);
  793. }
  794. @Override
  795. public boolean setComposingText(CharSequence text, int newCursorPosition) {
  796. nativeSetComposingText(text.toString(), newCursorPosition);
  797. return super.setComposingText(text, newCursorPosition);
  798. }
  799. public native void nativeCommitText(String text, int newCursorPosition);
  800. public native void nativeSetComposingText(String text, int newCursorPosition);
  801. }