summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewRenderThread.java
blob: 4bba160993df0185ef954de74f7ec293b8940424 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package com.mapbox.mapboxsdk.maps.renderer.textureview;

import android.graphics.SurfaceTexture;
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.view.TextureView;
import com.mapbox.mapboxsdk.maps.renderer.egl.EGLConfigChooser;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL10;

import timber.log.Timber;

/**
 * The render thread is responsible for managing the communication between the
 * ui thread and the render thread it creates. Also, the EGL and GL contexts
 * are managed from here.
 */
class TextureViewRenderThread extends Thread implements TextureView.SurfaceTextureListener {

  private final TextureViewMapRenderer mapRenderer;
  private final EGLHolder eglHolder;

  // Lock used for synchronization
  private final Object lock = new Object();

  // Guarded by lock
  private final ArrayList<Runnable> eventQueue = new ArrayList<>();
  private SurfaceTexture surface;
  private int width;
  private int height;
  private boolean requestRender;
  private boolean sizeChanged;
  private boolean paused;
  private boolean destroyContext;
  private boolean destroySurface;
  private boolean shouldExit;
  private boolean exited;

  /**
   * Create a render thread for the given TextureView / Maprenderer combination.
   *
   * @param textureView the TextureView
   * @param mapRenderer the MapRenderer
   */
  @UiThread
  TextureViewRenderThread(@NonNull TextureView textureView, @NonNull TextureViewMapRenderer mapRenderer) {
    textureView.setOpaque(!mapRenderer.isTranslucentSurface());
    textureView.setSurfaceTextureListener(this);
    this.mapRenderer = mapRenderer;
    this.eglHolder = new EGLHolder(new WeakReference<>(textureView), mapRenderer.isTranslucentSurface());
  }

  // SurfaceTextureListener methods

  @UiThread
  @Override
  public void onSurfaceTextureAvailable(final SurfaceTexture surface, final int width, final int height) {
    synchronized (lock) {
      this.surface = surface;
      this.width = width;
      this.height = height;
      this.requestRender = true;
      lock.notifyAll();
    }
  }

  @Override
  @UiThread
  public void onSurfaceTextureSizeChanged(SurfaceTexture surface, final int width, final int height) {
    synchronized (lock) {
      this.width = width;
      this.height = height;
      this.sizeChanged = true;
      this.requestRender = true;
      lock.notifyAll();
    }
  }

  @Override
  @UiThread
  public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
    synchronized (lock) {
      this.surface = null;
      this.destroySurface = true;
      this.requestRender = false;
      lock.notifyAll();
    }
    return true;
  }

  @Override
  @UiThread
  public void onSurfaceTextureUpdated(SurfaceTexture surface) {
    // Ignored
  }

  // MapRenderer delegate methods

  /**
   * May be called from any thread
   */
  void requestRender() {
    synchronized (lock) {
      requestRender = true;
      lock.notifyAll();
    }
  }

  /**
   * May be called from any thread
   */
  void queueEvent(Runnable runnable) {
    if (runnable == null) {
      throw new IllegalArgumentException("runnable must not be null");
    }
    synchronized (lock) {
      eventQueue.add(runnable);
      lock.notifyAll();
    }
  }


  @UiThread
  void onPause() {
    synchronized (lock) {
      this.paused = true;
      lock.notifyAll();
    }
  }

  @UiThread
  void onResume() {
    synchronized (lock) {
      this.paused = false;
      lock.notifyAll();
    }
  }


  @UiThread
  void onDestroy() {
    synchronized (lock) {
      this.shouldExit = true;
      lock.notifyAll();

      // Wait for the thread to exit
      while (!this.exited) {
        try {
          lock.wait();
        } catch (InterruptedException ex) {
          Thread.currentThread().interrupt();
        }
      }
    }
  }

  // Thread implementation

  @Override
  public void run() {
    try {

      while (true) {
        Runnable event = null;
        boolean initializeEGL = false;
        boolean recreateSurface = false;
        int w = -1;
        int h = -1;

        // Guarded block
        synchronized (lock) {
          while (true) {

            if (shouldExit) {
              return;
            }

            // If any events are scheduled, pop one for processing
            if (!eventQueue.isEmpty()) {
              event = eventQueue.remove(0);
              break;
            }

            if (destroySurface) {
              eglHolder.destroySurface();
              destroySurface = false;
              break;
            }

            if (destroyContext) {
              eglHolder.destroyContext();
              destroyContext = false;
              break;
            }

            if (surface != null && !paused && requestRender) {

              w = width;
              h = height;

              // Initialize EGL if needed
              if (eglHolder.eglContext == EGL10.EGL_NO_CONTEXT) {
                initializeEGL = true;
                break;
              }

              // (re-)Initialize EGL Surface if needed
              if (eglHolder.eglSurface == EGL10.EGL_NO_SURFACE) {
                recreateSurface = true;
                break;
              }

              // Reset the request render flag now, so we can catch new requests
              // while rendering
              requestRender = false;

              // Break the guarded loop and continue to process
              break;
            }


            // Wait until needed
            lock.wait();

          } // end guarded while loop

        } // end guarded block

        // Run event, if any
        if (event != null) {
          event.run();
          continue;
        }

        GL10 gl = eglHolder.createGL();

        // Initialize EGL
        if (initializeEGL) {
          eglHolder.prepare();
          if (!eglHolder.createSurface()) {
            synchronized (lock) {
              // Cleanup the surface if one could not be created
              // and wait for another to be ready.
              destroySurface = true;
            }
            continue;
          }
          mapRenderer.onSurfaceCreated(gl, eglHolder.eglConfig);
          mapRenderer.onSurfaceChanged(gl, w, h);
          continue;
        }

        // If the surface size has changed inform the map renderer.
        if (recreateSurface) {
          eglHolder.createSurface();
          mapRenderer.onSurfaceChanged(gl, w, h);
          continue;
        }

        if (sizeChanged) {
          mapRenderer.onSurfaceChanged(gl, w, h);
          sizeChanged = false;
          continue;
        }

        // Don't continue without a surface
        if (eglHolder.eglSurface == EGL10.EGL_NO_SURFACE) {
          continue;
        }

        // Time to render a frame
        mapRenderer.onDrawFrame(gl);

        // Swap and check the result
        int swapError = eglHolder.swap();
        switch (swapError) {
          case EGL10.EGL_SUCCESS:
            break;
          case EGL11.EGL_CONTEXT_LOST:
            Timber.w("Context lost. Waiting for re-aquire");
            synchronized (lock) {
              surface = null;
              destroySurface = true;
              destroyContext = true;
            }
            break;
          default:
            Timber.w("eglSwapBuffer error: %s. Waiting or new surface", swapError);
            // Probably lost the surface. Clear the current one and
            // wait for a new one to be set
            synchronized (lock) {
              surface = null;
              destroySurface = true;
            }
        }

      }

    } catch (InterruptedException err) {
      // To be expected
    } finally {
      // Cleanup
      eglHolder.cleanup();

      // Signal we're done
      synchronized (lock) {
        this.exited = true;
        lock.notifyAll();
      }
    }
  }

  /**
   * Holds the EGL state and offers methods to mutate it.
   */
  private static class EGLHolder {
    private static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
    private final WeakReference<TextureView> textureViewWeakRef;
    private boolean translucentSurface;

    private EGL10 egl;
    private EGLConfig eglConfig;
    private EGLDisplay eglDisplay = EGL10.EGL_NO_DISPLAY;
    private EGLContext eglContext = EGL10.EGL_NO_CONTEXT;
    private EGLSurface eglSurface = EGL10.EGL_NO_SURFACE;

    EGLHolder(WeakReference<TextureView> textureViewWeakRef, boolean translucentSurface) {
      this.textureViewWeakRef = textureViewWeakRef;
      this.translucentSurface = translucentSurface;
    }

    void prepare() {
      this.egl = (EGL10) EGLContext.getEGL();

      // Only re-initialize display when needed
      if (eglDisplay == EGL10.EGL_NO_DISPLAY) {
        this.eglDisplay = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);

        if (eglDisplay == EGL10.EGL_NO_DISPLAY) {
          throw new RuntimeException("eglGetDisplay failed");
        }

        int[] version = new int[2];
        if (!egl.eglInitialize(eglDisplay, version)) {
          throw new RuntimeException("eglInitialize failed");
        }
      }

      if (textureViewWeakRef == null) {
        // No texture view present
        eglConfig = null;
        eglContext = EGL10.EGL_NO_CONTEXT;
      } else if (eglContext == EGL10.EGL_NO_CONTEXT) {
        eglConfig = new EGLConfigChooser(translucentSurface).chooseConfig(egl, eglDisplay);
        int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE};
        eglContext = egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
      }

      if (eglContext == EGL10.EGL_NO_CONTEXT) {
        throw new RuntimeException("createContext");
      }
    }

    GL10 createGL() {
      return (GL10) eglContext.getGL();
    }

    boolean createSurface() {
      // The window size has changed, so we need to create a new surface.
      destroySurface();

      // Create an EGL surface we can render into.
      TextureView view = textureViewWeakRef.get();
      if (view != null) {
        int[] surfaceAttribs = {EGL10.EGL_NONE};
        eglSurface = egl.eglCreateWindowSurface(eglDisplay, eglConfig, view.getSurfaceTexture(), surfaceAttribs);
      } else {
        eglSurface = EGL10.EGL_NO_SURFACE;
      }

      if (eglSurface == null || eglSurface == EGL10.EGL_NO_SURFACE) {
        int error = egl.eglGetError();
        if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
          Timber.e("createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
        }
        return false;
      }

      return makeCurrent();
    }

    boolean makeCurrent() {
      if (!egl.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
        // Could not make the context current, probably because the underlying
        // SurfaceView surface has been destroyed.
        Timber.w("eglMakeCurrent: %s", egl.eglGetError());
        return false;
      }

      return true;
    }

    int swap() {
      if (!egl.eglSwapBuffers(eglDisplay, eglSurface)) {
        return egl.eglGetError();
      }
      return EGL10.EGL_SUCCESS;
    }

    private void destroySurface() {
      if (eglSurface == EGL10.EGL_NO_SURFACE) {
        return;
      }

      if (!egl.eglDestroySurface(eglDisplay, eglSurface)) {
        Timber.w("Could not destroy egl surface. Display %s, Surface %s", eglDisplay, eglSurface);
      }

      eglSurface = EGL10.EGL_NO_SURFACE;
    }

    private void destroyContext() {
      if (eglContext == EGL10.EGL_NO_CONTEXT) {
        return;
      }

      if (!egl.eglDestroyContext(eglDisplay, eglContext)) {
        Timber.w("Could not destroy egl context. Display %s, Context %s", eglDisplay, eglContext);
      }

      eglContext = EGL10.EGL_NO_CONTEXT;
    }

    private void terminate() {
      if (eglDisplay == EGL10.EGL_NO_DISPLAY) {
        return;
      }

      if (!egl.eglTerminate(eglDisplay)) {
        Timber.w("Could not terminate egl. Display %s", eglDisplay);
      }
      eglDisplay = EGL10.EGL_NO_DISPLAY;
    }

    void cleanup() {
      destroySurface();
      destroyContext();
      terminate();
    }
  }
}