| 1 |
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- |
| 2 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 3 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 4 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 5 |
|
| 6 |
package org.mozilla.gecko.gfx; |
| 7 |
|
| 8 |
import android.opengl.GLES20; |
| 9 |
import android.util.Log; |
| 10 |
|
| 11 |
import java.util.concurrent.ArrayBlockingQueue; |
| 12 |
|
| 13 |
import javax.microedition.khronos.egl.EGL10; |
| 14 |
import javax.microedition.khronos.egl.EGLContext; |
| 15 |
|
| 16 |
public class TextureGenerator { |
| 17 |
private static final String LOGTAG = "TextureGenerator"; |
| 18 |
private static final int POOL_SIZE = 5; |
| 19 |
|
| 20 |
private static TextureGenerator sSharedInstance; |
| 21 |
|
| 22 |
private final ArrayBlockingQueue<Integer> mTextureIds; |
| 23 |
private EGLContext mContext; |
| 24 |
|
| 25 |
private TextureGenerator() { |
| 26 |
mTextureIds = new ArrayBlockingQueue<Integer>(POOL_SIZE); |
| 27 |
} |
| 28 |
|
| 29 |
public static TextureGenerator get() { |
| 30 |
if (sSharedInstance == null) |
| 31 |
sSharedInstance = new TextureGenerator(); |
| 32 |
return sSharedInstance; |
| 33 |
} |
| 34 |
|
| 35 |
public synchronized int take() { |
| 36 |
try { |
| 37 |
// Will block until one becomes available |
| 38 |
return mTextureIds.take(); |
| 39 |
} catch (InterruptedException e) { |
| 40 |
return 0; |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
public synchronized void fill() { |
| 45 |
EGL10 egl = (EGL10) EGLContext.getEGL(); |
| 46 |
EGLContext context = egl.eglGetCurrentContext(); |
| 47 |
|
| 48 |
if (mContext != null && mContext != context) { |
| 49 |
mTextureIds.clear(); |
| 50 |
} |
| 51 |
|
| 52 |
mContext = context; |
| 53 |
|
| 54 |
int numNeeded = mTextureIds.remainingCapacity(); |
| 55 |
if (numNeeded == 0) |
| 56 |
return; |
| 57 |
|
| 58 |
// Clear existing GL errors |
| 59 |
int error; |
| 60 |
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { |
| 61 |
Log.w(LOGTAG, String.format("Clearing GL error: %#x", error)); |
| 62 |
} |
| 63 |
|
| 64 |
int[] textures = new int[numNeeded]; |
| 65 |
GLES20.glGenTextures(numNeeded, textures, 0); |
| 66 |
|
| 67 |
error = GLES20.glGetError(); |
| 68 |
if (error != GLES20.GL_NO_ERROR) { |
| 69 |
Log.e(LOGTAG, String.format("Failed to generate textures: %#x", error), new Exception()); |
| 70 |
return; |
| 71 |
} |
| 72 |
|
| 73 |
for (int i = 0; i < numNeeded; i++) { |
| 74 |
mTextureIds.offer(textures[i]); |
| 75 |
} |
| 76 |
} |
| 77 |
} |