michael@0: /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.gfx; michael@0: michael@0: import android.opengl.GLES20; michael@0: import android.util.Log; michael@0: michael@0: import java.util.concurrent.ArrayBlockingQueue; michael@0: michael@0: import javax.microedition.khronos.egl.EGL10; michael@0: import javax.microedition.khronos.egl.EGLContext; michael@0: michael@0: public class TextureGenerator { michael@0: private static final String LOGTAG = "TextureGenerator"; michael@0: private static final int POOL_SIZE = 5; michael@0: michael@0: private static TextureGenerator sSharedInstance; michael@0: michael@0: private ArrayBlockingQueue mTextureIds; michael@0: private EGLContext mContext; michael@0: michael@0: private TextureGenerator() { mTextureIds = new ArrayBlockingQueue(POOL_SIZE); } michael@0: michael@0: public static TextureGenerator get() { michael@0: if (sSharedInstance == null) michael@0: sSharedInstance = new TextureGenerator(); michael@0: return sSharedInstance; michael@0: } michael@0: michael@0: public synchronized int take() { michael@0: try { michael@0: // Will block until one becomes available michael@0: return (int)mTextureIds.take(); michael@0: } catch (InterruptedException e) { michael@0: return 0; michael@0: } michael@0: } michael@0: michael@0: public synchronized void fill() { michael@0: EGL10 egl = (EGL10)EGLContext.getEGL(); michael@0: EGLContext context = egl.eglGetCurrentContext(); michael@0: michael@0: if (mContext != null && mContext != context) { michael@0: mTextureIds.clear(); michael@0: } michael@0: michael@0: mContext = context; michael@0: michael@0: int numNeeded = mTextureIds.remainingCapacity(); michael@0: if (numNeeded == 0) michael@0: return; michael@0: michael@0: // Clear existing GL errors michael@0: int error; michael@0: while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { michael@0: Log.w(LOGTAG, String.format("Clearing GL error: %#x", error)); michael@0: } michael@0: michael@0: int[] textures = new int[numNeeded]; michael@0: GLES20.glGenTextures(numNeeded, textures, 0); michael@0: michael@0: error = GLES20.glGetError(); michael@0: if (error != GLES20.GL_NO_ERROR) { michael@0: Log.e(LOGTAG, String.format("Failed to generate textures: %#x", error), new Exception()); michael@0: return; michael@0: } michael@0: michael@0: for (int i = 0; i < numNeeded; i++) { michael@0: mTextureIds.offer(textures[i]); michael@0: } michael@0: } michael@0: } michael@0: michael@0: