code:
/*
    Copyright 2011 Google Inc.

    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.
 */

#ifndef GrGLInterface_DEFINED
#define GrGLInterface_DEFINED

#include "GrGLConfig.h"
#include "GrTypes.h"

#if !defined(GR_GL_FUNCTION_TYPE)
    #define GR_GL_FUNCTION_TYPE
#endif

////////////////////////////////////////////////////////////////////////////////

/**
 * Helpers for glGetString()
 */

void gl_version_from_string(int* major, int* minor,
                            const char* versionString);
bool has_gl_extension_from_string(const char* ext,
                                  const char* extensionString);

bool has_gl_extension(const char* ext);
void gl_version(int* major, int* minor);

////////////////////////////////////////////////////////////////////////////////

/*
 * Routines managing the global interface used to invoke OpenGL calls.
 */
struct GrGLInterface;
GR_API GrGLInterface* GrGLGetGLInterface();
GR_API void GrGLSetGLInterface(GrGLInterface* gl_interface);

/*
 * This is called when GrGLSetGLInterface() hasn't been called before creating
 * a GrGpuGL object. It provides a default implementation. The actual
 * implementation depends on which GrGLDefaultInterface_*.cpp has been linked.
 * There are some platform-specific implementations provided as well as
 * GrGLDefaultInterface_none.cpp which does nothing (effectively requiring an
 * explicit GrGLSetGLInterface call by the host).
 */
void GrGLSetDefaultGLInterface();

typedef unsigned int GrGLenum;
typedef unsigned char GrGLboolean;
typedef unsigned int GrGLbitfield;
typedef signed char GrGLbyte;
typedef char GrGLchar;
typedef short GrGLshort;
typedef int GrGLint;
typedef int GrGLsizei;
typedef unsigned char GrGLubyte;
typedef unsigned short GrGLushort;
typedef unsigned int GrGLuint;
typedef float GrGLfloat;
typedef float GrGLclampf;
typedef double GrGLdouble;
typedef double GrGLclampd;
typedef void GrGLvoid;
typedef long GrGLintptr;
typedef long GrGLsizeiptr;
typedef char GrGLchar;

enum GrGLBinding {
    kDesktop_GrGLBinding = 0x01,
    kES1_GrGLBinding = 0x02,
    kES2_GrGLBinding = 0x04
};

extern "C" {
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLActiveTextureProc)(GrGLenum texture);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLAttachShaderProc)(GrGLuint program, GrGLuint shader);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindAttribLocationProc)(GrGLuint program, GrGLuint index, const char* name);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindBufferProc)(GrGLenum target, GrGLuint buffer);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindTextureProc)(GrGLenum target, GrGLuint texture);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlendColorProc)(GrGLclampf red, GrGLclampf green, GrGLclampf blue, GrGLclampf alpha);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlendFuncProc)(GrGLenum sfactor, GrGLenum dfactor);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBufferDataProc)(GrGLenum target, GrGLsizeiptr size, const GrGLvoid* data, GrGLenum usage);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBufferSubDataProc)(GrGLenum target, GrGLintptr offset, GrGLsizeiptr size, const GrGLvoid* data);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLClearProc)(GrGLbitfield mask);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLClearColorProc)(GrGLclampf red, GrGLclampf green, GrGLclampf blue, GrGLclampf alpha);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLClearStencilProc)(GrGLint s);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLClientActiveTextureProc)(GrGLenum texture);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLColor4ubProc)(GrGLubyte red, GrGLubyte green, GrGLubyte blue, GrGLubyte alpha);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLColorMaskProc)(GrGLboolean red, GrGLboolean green, GrGLboolean blue, GrGLboolean alpha);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLColorPointerProc)(GrGLint size, GrGLenum type, GrGLsizei stride, const GrGLvoid* pointer);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCompileShaderProc)(GrGLuint shader);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCompressedTexImage2DProc)(GrGLenum target, GrGLint level, GrGLenum internalformat, GrGLsizei width, GrGLsizei height, GrGLint border, GrGLsizei imageSize, const GrGLvoid* data);
    typedef GrGLuint (GR_GL_FUNCTION_TYPE *GrGLCreateProgramProc)(void);
    typedef GrGLuint (GR_GL_FUNCTION_TYPE *GrGLCreateShaderProc)(GrGLenum type);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCullFaceProc)(GrGLenum mode);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteBuffersProc)(GrGLsizei n, const GrGLuint* buffers);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteProgramProc)(GrGLuint program);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteShaderProc)(GrGLuint shader);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteTexturesProc)(GrGLsizei n, const GrGLuint* textures);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDepthMaskProc)(GrGLboolean flag);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDisableProc)(GrGLenum cap);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDisableClientStateProc)(GrGLenum array);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDisableVertexAttribArrayProc)(GrGLuint index);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDrawArraysProc)(GrGLenum mode, GrGLint first, GrGLsizei count);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDrawElementsProc)(GrGLenum mode, GrGLsizei count, GrGLenum type, const GrGLvoid* indices);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLEnableProc)(GrGLenum cap);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLEnableClientStateProc)(GrGLenum cap);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLEnableVertexAttribArrayProc)(GrGLuint index);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFrontFaceProc)(GrGLenum mode);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenBuffersProc)(GrGLsizei n, GrGLuint* buffers);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenTexturesProc)(GrGLsizei n, GrGLuint* textures);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetBufferParameterivProc)(GrGLenum target, GrGLenum pname, GrGLint* params);
    typedef GrGLenum (GR_GL_FUNCTION_TYPE *GrGLGetErrorProc)(void);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetIntegervProc)(GrGLenum pname, GrGLint* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetProgramInfoLogProc)(GrGLuint program, GrGLsizei bufsize, GrGLsizei* length, char* infolog);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetProgramivProc)(GrGLuint program, GrGLenum pname, GrGLint* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetShaderInfoLogProc)(GrGLuint shader, GrGLsizei bufsize, GrGLsizei* length, char* infolog);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetShaderivProc)(GrGLuint shader, GrGLenum pname, GrGLint* params);
    typedef const GrGLubyte* (GR_GL_FUNCTION_TYPE *GrGLGetStringProc)(GrGLenum name);
    typedef GrGLint (GR_GL_FUNCTION_TYPE *GrGLGetUniformLocationProc)(GrGLuint program, const char* name);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLLineWidthProc)(GrGLfloat width);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLLinkProgramProc)(GrGLuint program);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLLoadMatrixfProc)(const GrGLfloat* m);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLMatrixModeProc)(GrGLenum mode);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLPixelStoreiProc)(GrGLenum pname, GrGLint param);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLPointSizeProc)(GrGLfloat size);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLReadPixelsProc)(GrGLint x, GrGLint y, GrGLsizei width, GrGLsizei height, GrGLenum format, GrGLenum type, GrGLvoid* pixels);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLScissorProc)(GrGLint x, GrGLint y, GrGLsizei width, GrGLsizei height);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLShadeModelProc)(GrGLenum mode);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLShaderSourceProc)(GrGLuint shader, GrGLsizei count, const char** str, const GrGLint* length);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilFuncProc)(GrGLenum func, GrGLint ref, GrGLuint mask);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilFuncSeparateProc)(GrGLenum face, GrGLenum func, GrGLint ref, GrGLuint mask);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilMaskProc)(GrGLuint mask);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilMaskSeparateProc)(GrGLenum face, GrGLuint mask);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilOpProc)(GrGLenum fail, GrGLenum zfail, GrGLenum zpass);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLStencilOpSeparateProc)(GrGLenum face, GrGLenum fail, GrGLenum zfail, GrGLenum zpass);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexCoordPointerProc)(GrGLint size, GrGLenum type, GrGLsizei stride, const GrGLvoid* pointer);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexEnviProc)(GrGLenum target, GrGLenum pname, GrGLint param);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexImage2DProc)(GrGLenum target, GrGLint level, GrGLint internalformat, GrGLsizei width, GrGLsizei height, GrGLint border, GrGLenum format, GrGLenum type, const GrGLvoid* pixels);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexParameteriProc)(GrGLenum target, GrGLenum pname, GrGLint param);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexSubImage2DProc)(GrGLenum target, GrGLint level, GrGLint xoffset, GrGLint yoffset, GrGLsizei width, GrGLsizei height, GrGLenum format, GrGLenum type, const GrGLvoid* pixels);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1fProc)(GrGLint location, GrGLfloat v0);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1iProc)(GrGLint location, GrGLint v0);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2fProc)(GrGLint location, GrGLfloat v0, GrGLfloat v1);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2iProc)(GrGLint location, GrGLint v0, GrGLint v1);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3fProc)(GrGLint location, GrGLfloat v0, GrGLfloat v1, GrGLfloat v2);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3iProc)(GrGLint location, GrGLint v0, GrGLint v1, GrGLint v2);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4fProc)(GrGLint location, GrGLfloat v0, GrGLfloat v1, GrGLfloat v2, GrGLfloat v3);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4iProc)(GrGLint location, GrGLint v0, GrGLint v1, GrGLint v2, GrGLint v3);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniformMatrix2fvProc)(GrGLint location, GrGLsizei count, GrGLboolean transpose, const GrGLfloat* value);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniformMatrix3fvProc)(GrGLint location, GrGLsizei count, GrGLboolean transpose, const GrGLfloat* value);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniformMatrix4fvProc)(GrGLint location, GrGLsizei count, GrGLboolean transpose, const GrGLfloat* value);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUseProgramProc)(GrGLuint program);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib4fvProc)(GrGLuint indx, const GrGLfloat* values);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttribPointerProc)(GrGLuint indx, GrGLint size, GrGLenum type, GrGLboolean normalized, GrGLsizei stride, const GrGLvoid* ptr);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexPointerProc)(GrGLint size, GrGLenum type, GrGLsizei stride, const GrGLvoid* pointer);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLViewportProc)(GrGLint x, GrGLint y, GrGLsizei width, GrGLsizei height);

    // FBO Extension Functions
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindFramebufferProc)(GrGLenum target, GrGLuint framebuffer);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindRenderbufferProc)(GrGLenum target, GrGLuint renderbuffer);
    typedef GrGLenum (GR_GL_FUNCTION_TYPE *GrGLCheckFramebufferStatusProc)(GrGLenum target);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteFramebuffersProc)(GrGLsizei n, const GrGLuint *framebuffers);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDeleteRenderbuffersProc)(GrGLsizei n, const GrGLuint *renderbuffers);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFramebufferRenderbufferProc)(GrGLenum target, GrGLenum attachment, GrGLenum renderbuffertarget, GrGLuint renderbuffer);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFramebufferTexture2DProc)(GrGLenum target, GrGLenum attachment, GrGLenum textarget, GrGLuint texture, GrGLint level);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenFramebuffersProc)(GrGLsizei n, GrGLuint *framebuffers);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenRenderbuffersProc)(GrGLsizei n, GrGLuint *renderbuffers);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLRenderbufferStorageProc)(GrGLenum target, GrGLenum internalformat, GrGLsizei width, GrGLsizei height);

    // Multisampling Extension Functions
    // same prototype for ARB_FBO, EXT_FBO, GL 3.0, & Apple ES extension
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLRenderbufferStorageMultisampleProc)(GrGLenum target, GrGLsizei samples, GrGLenum internalformat, GrGLsizei width, GrGLsizei height);
    // desktop: ext_fbo_blit, arb_fbo, gl 3.0
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlitFramebufferProc)(GrGLint srcX0, GrGLint srcY0, GrGLint srcX1, GrGLint srcY1, GrGLint dstX0, GrGLint dstY0, GrGLint dstX1, GrGLint dstY1, GrGLbitfield mask, GrGLenum filter);
    // IMG's ES extension
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFramebufferTexture2DMultisampleProc)(GrGLenum target, GrGLenum attachment, GrGLenum textarget, GrGLuint texture, GrGLint level, GrGLsizei samples);
    // apple's es extension
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLResolveMultisampleFramebufferProc)();

    // Buffer mapping (extension in ES).
    typedef GrGLvoid* (GR_GL_FUNCTION_TYPE *GrGLMapBufferProc)(GrGLenum target, GrGLenum access);
    typedef GrGLboolean (GR_GL_FUNCTION_TYPE *GrGLUnmapBufferProc)(GrGLenum target);

    // Dual source blending
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBindFragDataLocationIndexedProc)(GrGLuint program, GrGLuint colorNumber, GrGLuint index, const GrGLchar * name);

    // Additional typedefs for GLES2
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlendEquationProc)( GrGLenum target );
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlendEquationSeparateProc)( GrGLenum modeRBG, GrGLenum modeAlpha );
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLBlendFuncSeparateProc)(GrGLenum srcRGB, GrGLenum dstRGB, GrGLenum srcAlpha, GrGLenum dstAlpha);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLClearDepthfProc)(GrGLclampf depth);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCompressedTexSubImage2DProc)(GrGLenum target, GrGLint level, GrGLint xoffset, GrGLint yoffset, GrGLsizei width, GrGLsizei height, GrGLenum format, GrGLsizei imageSize, const GrGLvoid* data);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCopyTexImage2DProc)(GrGLenum target, GrGLint level, GrGLenum internalformat, GrGLint x, GrGLint y, GrGLsizei width, GrGLsizei height, GrGLint border);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLCopyTexSubImage2DProc)(GrGLenum target, GrGLint level, GrGLint xoffset, GrGLint yoffset, GrGLint x, GrGLint y, GrGLsizei width, GrGLsizei height);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDepthFuncProc)(GrGLenum func);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDepthRangefProc)(GrGLclampf zNear, GrGLclampf zFar);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLDetachShaderProc)(GrGLuint program, GrGLuint shader);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFinishProc)();
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLFlushProc)();
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGenerateMipmapProc)(GrGLenum target);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetActiveAttribProc)(GrGLuint program, GrGLuint index, GrGLsizei bufsize, GrGLsizei* length, GrGLint* size, GrGLenum* type, GrGLchar* name);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetActiveUniformProc)(GrGLuint program, GrGLuint index, GrGLsizei bufsize, GrGLsizei* length, GrGLint* size, GrGLenum* type, GrGLchar* name);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetAttachedShadersProc)(GrGLuint program, GrGLsizei maxcount, GrGLsizei* count, GrGLuint* shaders);
    typedef GrGLint (GR_GL_FUNCTION_TYPE *GrGLGetAttribLocationProc)(GrGLuint program, const GrGLchar* name);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetBooleanvProc)(GrGLenum pname, GrGLboolean* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetFloatvProc)(GrGLenum pname, GrGLfloat* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetFramebufferAttachmentParameterivProc)(GrGLenum target, GrGLenum attachment, GrGLenum pname, GrGLint* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetRenderbufferParameterivProc)(GrGLenum target, GrGLenum pname, GrGLint* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetShaderPrecisionFormatProc)(GrGLenum shadertype, GrGLenum precisiontype, GrGLint* range, GrGLint* precision);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetShaderSourceProc)(GrGLuint shader, GrGLsizei bufsize, GrGLsizei* length, GrGLchar* source);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetTexParameterfvProc)(GrGLenum target, GrGLenum pname, GrGLfloat* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetTexParameterivProc)(GrGLenum target, GrGLenum pname, GrGLint* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetUniformfvProc)(GrGLuint program, GrGLint location, GrGLfloat* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetUniformivProc)(GrGLuint program, GrGLint location, GrGLint* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetVertexAttribfvProc)(GrGLuint index, GrGLenum pname, GrGLfloat* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetVertexAttribivProc)(GrGLuint index, GrGLenum pname, GrGLint* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLGetVertexAttribPointervProc)(GrGLuint index, GrGLenum pname, GrGLvoid** pointer);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLHintProc)(GrGLenum target, GrGLenum mode);
    typedef GrGLboolean (GR_GL_FUNCTION_TYPE *GrGLIsBufferProc)(GrGLuint buffer);
    typedef GrGLboolean (GR_GL_FUNCTION_TYPE *GrGLIsEnabledProc)(GrGLenum cap);
    typedef GrGLboolean(GR_GL_FUNCTION_TYPE *GrGLIsFramebufferProc)(GrGLuint framebuffer);
    typedef GrGLboolean (GR_GL_FUNCTION_TYPE *GrGLIsProgramProc)(GrGLuint program);
    typedef GrGLboolean (GR_GL_FUNCTION_TYPE *GrGLfIsRenderbufferProc)(GrGLuint renderbuffer);
    typedef GrGLboolean (GR_GL_FUNCTION_TYPE *GrGLIsShaderProc)(GrGLuint shader);
    typedef GrGLboolean (GR_GL_FUNCTION_TYPE *GrGLIsTextureProc)(GrGLuint texture);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLPolygonOffsetProc)(GrGLfloat factor, GrGLfloat units);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLReleaseShaderCompilerProc)();
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLSampleCoverageProc)(GrGLclampf value, GrGLboolean invert);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLShaderBinaryProc)(GrGLsizei n, const GrGLuint* shaders, GrGLenum binaryformat, const GrGLvoid* binary, GrGLsizei length);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexParameterfProc)(GrGLenum target, GrGLenum pname, GrGLfloat param);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexParameterfvProc)(GrGLenum target, GrGLenum pname, const GrGLfloat* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLTexParameterivProc)(GrGLenum target, GrGLenum pname, const GrGLint* params);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1fProc)(GrGLint location, GrGLfloat x);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform1ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2fProc)(GrGLint location, GrGLfloat x, GrGLfloat y);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2iProc)(GrGLint location, GrGLint x, GrGLint y);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform2ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3fProc)(GrGLint location, GrGLfloat x, GrGLfloat y, GrGLfloat z);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3fvProc)(GrGLint location, GrGLsizei count, const GrGLfloat* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3iProc)(GrGLint location, GrGLint x, GrGLint y, GrGLint z);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform3ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4fProc)(GrGLint location, GrGLfloat x, GrGLfloat y, GrGLfloat z, GrGLfloat w);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4iProc)(GrGLint location, GrGLint x, GrGLint y, GrGLint z, GrGLint w);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniform4ivProc)(GrGLint location, GrGLsizei count, const GrGLint* v);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniformMatrix2fvProc)(GrGLint location, GrGLsizei count, GrGLboolean transpose, const GrGLfloat* value);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLUniformMatrix4fvProc)(GrGLint location, GrGLsizei count, GrGLboolean transpose, const GrGLfloat* value);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLValidateProgramProc)(GrGLuint program);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib1fProc)(GrGLuint indx, GrGLfloat x);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib1fvProc)(GrGLuint indx, const GrGLfloat* values);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib2fProc)(GrGLuint indx, GrGLfloat x, GrGLfloat y);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib2fvProc)(GrGLuint indx, const GrGLfloat* values);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib3fProc)(GrGLuint indx, GrGLfloat x, GrGLfloat y, GrGLfloat z);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib3fvProc)(GrGLuint indx, const GrGLfloat* values);
    typedef GrGLvoid (GR_GL_FUNCTION_TYPE *GrGLVertexAttrib4fProc)(GrGLuint indx, GrGLfloat x, GrGLfloat y, GrGLfloat z, GrGLfloat w);

}  // extern "C"

enum GrGLCapability {
    kProbe_GrGLCapability = -1
};

/*
 * The following interface exports the OpenGL entry points used by the system.
 * Use of OpenGL calls is disallowed.  All calls should be invoked through
 * the global instance of this struct, defined above.
 *
 * IMPORTANT NOTE: The OpenGL entry points exposed here include both core GL
 * functions, and extensions.  The system assumes that the address of the
 * extension pointer will be valid across contexts.
 */
struct GrGLInterface {
    bool validate(GrEngine engine) const;

    // Indicator variable specifying the type of GL implementation
    // exported:  GLES{1|2} or Desktop.
    GrGLBinding fBindingsExported;

    /// Does this GL support NPOT textures on FBOs?
    /// boolean value, or kProbe_GrGLCapability to probe (slowly) at context creation.
    int fNPOTRenderTargetSupport;

    /// Some GL implementations (PowerVR SGX devices like the iPhone 4)
    /// have restrictions on the size of small render targets.
    /// kProbe_GrGLCapability to probe (slowly) at context creation.
    int fMinRenderTargetHeight;
    int fMinRenderTargetWidth;

    GrGLActiveTextureProc fActiveTexture;
    GrGLAttachShaderProc fAttachShader;
    GrGLBindAttribLocationProc fBindAttribLocation;
    GrGLBindBufferProc fBindBuffer;
    GrGLBindTextureProc fBindTexture;
    GrGLBlendColorProc fBlendColor;
    GrGLBlendFuncProc fBlendFunc;
    GrGLBufferDataProc fBufferData;
    GrGLBufferSubDataProc fBufferSubData;
    GrGLClearProc fClear;
    GrGLClearColorProc fClearColor;
    GrGLClearStencilProc fClearStencil;
    GrGLClientActiveTextureProc fClientActiveTexture;
    GrGLColor4ubProc fColor4ub;
    GrGLColorMaskProc fColorMask;
    GrGLColorPointerProc fColorPointer;
    GrGLCompileShaderProc fCompileShader;
    GrGLCompressedTexImage2DProc fCompressedTexImage2D;
    GrGLCreateProgramProc fCreateProgram;
    GrGLCreateShaderProc fCreateShader;
    GrGLCullFaceProc fCullFace;
    GrGLDeleteBuffersProc fDeleteBuffers;
    GrGLDeleteProgramProc fDeleteProgram;
    GrGLDeleteShaderProc fDeleteShader;
    GrGLDeleteTexturesProc fDeleteTextures;
    GrGLDepthMaskProc fDepthMask;
    GrGLDisableProc fDisable;
    GrGLDisableClientStateProc fDisableClientState;
    GrGLDisableVertexAttribArrayProc fDisableVertexAttribArray;
    GrGLDrawArraysProc fDrawArrays;
    GrGLDrawElementsProc fDrawElements;
    GrGLEnableProc fEnable;
    GrGLEnableClientStateProc fEnableClientState;
    GrGLEnableVertexAttribArrayProc fEnableVertexAttribArray;
    GrGLFrontFaceProc fFrontFace;
    GrGLGenBuffersProc fGenBuffers;
    GrGLGenTexturesProc fGenTextures;
    GrGLGetBufferParameterivProc fGetBufferParameteriv;
    GrGLGetErrorProc fGetError;
    GrGLGetIntegervProc fGetIntegerv;
    GrGLGetProgramInfoLogProc fGetProgramInfoLog;
    GrGLGetProgramivProc fGetProgramiv;
    GrGLGetShaderInfoLogProc fGetShaderInfoLog;
    GrGLGetShaderivProc fGetShaderiv;
    GrGLGetStringProc fGetString;
    GrGLGetUniformLocationProc fGetUniformLocation;
    GrGLLineWidthProc fLineWidth;
    GrGLLinkProgramProc fLinkProgram;
    GrGLLoadMatrixfProc fLoadMatrixf;
    GrGLMatrixModeProc fMatrixMode;
    GrGLPixelStoreiProc fPixelStorei;
    GrGLPointSizeProc fPointSize;
    GrGLReadPixelsProc fReadPixels;
    GrGLScissorProc fScissor;
    GrGLShadeModelProc fShadeModel;
    GrGLShaderSourceProc fShaderSource;
    GrGLStencilFuncProc fStencilFunc;
    GrGLStencilFuncSeparateProc fStencilFuncSeparate;
    GrGLStencilMaskProc fStencilMask;
    GrGLStencilMaskSeparateProc fStencilMaskSeparate;
    GrGLStencilOpProc fStencilOp;
    GrGLStencilOpSeparateProc fStencilOpSeparate;
    GrGLTexCoordPointerProc fTexCoordPointer;
    GrGLTexEnviProc fTexEnvi;
    GrGLTexImage2DProc fTexImage2D;
    GrGLTexParameteriProc fTexParameteri;
    GrGLTexSubImage2DProc fTexSubImage2D;
    GrGLUniform1fProc fUniform1f;
    GrGLUniform1iProc fUniform1i;
    GrGLUniform1fvProc fUniform1fv;
    GrGLUniform1ivProc fUniform1iv;
    GrGLUniform2fProc fUniform2f;
    GrGLUniform2iProc fUniform2i;
    GrGLUniform2fvProc  fUniform2fv;
    GrGLUniform2ivProc fUniform2iv;
    GrGLUniform3fProc fUniform3f;
    GrGLUniform3iProc fUniform3i;
    GrGLUniform3fvProc fUniform3fv;
    GrGLUniform3ivProc fUniform3iv;
    GrGLUniform4fProc fUniform4f;
    GrGLUniform4iProc fUniform4i;
    GrGLUniform4fvProc fUniform4fv;
    GrGLUniform4ivProc fUniform4iv;
    GrGLUniformMatrix2fvProc fUniformMatrix2fv;
    GrGLUniformMatrix3fvProc fUniformMatrix3fv;
    GrGLUniformMatrix4fvProc fUniformMatrix4fv;
    GrGLUseProgramProc fUseProgram;
    GrGLVertexAttrib4fvProc fVertexAttrib4fv;
    GrGLVertexAttribPointerProc fVertexAttribPointer;
    GrGLVertexPointerProc fVertexPointer;
    GrGLViewportProc fViewport;

    // Additional Bindings for GLES2
    GrGLBlendEquationProc fBlendEquation;
    GrGLBlendEquationSeparateProc fBlendEquationSeparate;
    GrGLBlendFuncSeparateProc fBlendFuncSeparate;
    GrGLClearDepthfProc fClearDepthf;
    GrGLCompressedTexSubImage2DProc fCompressedTexSubImage2D;
    GrGLCopyTexImage2DProc fCopyTexImage2D;
    GrGLCopyTexSubImage2DProc fCopyTexSubImage2D;
    GrGLDepthFuncProc fDepthFunc;
    GrGLDepthRangefProc fDepthRangef;
    GrGLDetachShaderProc fDetachShader;
    GrGLFinishProc fFinish;
    GrGLFlushProc fFlush;
    GrGLGenerateMipmapProc fGenerateMipmap;
    GrGLGetActiveAttribProc fGetActiveAttrib;
    GrGLGetActiveUniformProc fGetActiveUniform;
    GrGLGetAttachedShadersProc fGetAttachedShaders;
    GrGLGetAttribLocationProc fGetAttribLocation;
    GrGLGetBooleanvProc fGetBooleanv;
    GrGLGetFloatvProc fGetFloatv;
    GrGLGetFramebufferAttachmentParameterivProc fGetFramebufferAttachmentParameteriv;
    GrGLGetRenderbufferParameterivProc fGetRenderbufferParameteriv;
    GrGLGetShaderPrecisionFormatProc fGetShaderPrecisionFormat;
    GrGLGetShaderSourceProc fGetShaderSource;
    GrGLGetTexParameterfvProc fGetTexParameterfv;
    GrGLGetTexParameterivProc fGetTexParameteriv;
    GrGLGetUniformfvProc fGetUniformfv;
    GrGLGetUniformivProc fGetUniformiv;
    GrGLGetVertexAttribfvProc fGetVertexAttribfv;
    GrGLGetVertexAttribivProc fGetVertexAttribiv;
    GrGLGetVertexAttribPointervProc fGetVertexAttribPointerv;
    GrGLHintProc fHint;
    GrGLIsBufferProc fIsBuffer;
    GrGLIsEnabledProc fIsEnabled;
    GrGLIsFramebufferProc fIsFramebuffer;
    GrGLIsProgramProc fIsProgram;
    GrGLfIsRenderbufferProc fIsRenderbuffer;
    GrGLIsShaderProc fIsShader;
    GrGLIsTextureProc fIsTexture;
    GrGLPolygonOffsetProc fPolygonOffset;
    GrGLReleaseShaderCompilerProc fReleaseShaderCompiler;
    GrGLSampleCoverageProc fSampleCoverage;
    GrGLShaderBinaryProc fShaderBinary;
    GrGLTexParameterfProc fTexParameterf;
    GrGLTexParameterfvProc fTexParameterfv;
    GrGLTexParameterivProc fTexParameteriv;
    GrGLValidateProgramProc fValidateProgram;
    GrGLVertexAttrib1fProc fVertexAttrib1f;
    GrGLVertexAttrib1fvProc fVertexAttrib1fv;
    GrGLVertexAttrib2fProc fVertexAttrib2f;
    GrGLVertexAttrib2fvProc fVertexAttrib2fv;
    GrGLVertexAttrib3fProc fVertexAttrib3f;
    GrGLVertexAttrib3fvProc fVertexAttrib3fv;
    GrGLVertexAttrib4fProc fVertexAttrib4f;

    // FBO Extension Functions
    GrGLBindFramebufferProc fBindFramebuffer;
    GrGLBindRenderbufferProc fBindRenderbuffer;
    GrGLCheckFramebufferStatusProc fCheckFramebufferStatus;
    GrGLDeleteFramebuffersProc fDeleteFramebuffers;
    GrGLDeleteRenderbuffersProc fDeleteRenderbuffers;
    GrGLFramebufferRenderbufferProc fFramebufferRenderbuffer;
    GrGLFramebufferTexture2DProc fFramebufferTexture2D;
    GrGLGenFramebuffersProc fGenFramebuffers;
    GrGLGenRenderbuffersProc fGenRenderbuffers;
    GrGLRenderbufferStorageProc fRenderbufferStorage;

    // Multisampling Extension Functions
    // same prototype for ARB_FBO, EXT_FBO, GL 3.0, & Apple ES extension
    GrGLRenderbufferStorageMultisampleProc fRenderbufferStorageMultisample;
    // desktop: ext_fbo_blit, arb_fbo, gl 3.0
    GrGLBlitFramebufferProc fBlitFramebuffer;
    // IMG's ES extension
    GrGLFramebufferTexture2DMultisampleProc fFramebufferTexture2DMultisample;
    // apple's es extension
    GrGLResolveMultisampleFramebufferProc fResolveMultisampleFramebuffer;

    // Buffer mapping (extension in ES).
    GrGLMapBufferProc fMapBuffer;
    GrGLUnmapBufferProc fUnmapBuffer;

    // Dual Source Blending
    GrGLBindFragDataLocationIndexedProc fBindFragDataLocationIndexed;

    // Code that initializes this struct using a static initializer should
    // make this the last entry in the static initializer. It can help to guard
    // against failing to initialize newly-added members of this struct.
    enum { kStaticInitEndGuard } fStaticInitEndGuard;

private:
    bool validateShaderFunctions() const;
    bool validateFixedFunctions() const;
};

#endif


code:
/*
    Copyright 2011 Google Inc.

    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.
 */

#ifndef GrGLProgram_DEFINED
#define GrGLProgram_DEFINED

#include "GrGLInterface.h"
#include "GrSamplerState.h"
#include "GrStringBuilder.h"
#include "GrGpu.h"

#include "SkXfermode.h"

class GrBinHashKeyBuilder;

struct ShaderCodeSegments {
    GrStringBuilder fHeader; // VS+FS, GLSL version, etc
    GrStringBuilder fVSUnis;
    GrStringBuilder fVSAttrs;
    GrStringBuilder fVaryings;
    GrStringBuilder fFSUnis;
    GrStringBuilder fFSOutputs;
    GrStringBuilder fFSFunctions;
    GrStringBuilder fVSCode;
    GrStringBuilder fFSCode;
};

/**
 * This class manages a GPU program and records per-program information.
 * We can specify the attribute locations so that they are constant
 * across our shaders. But the driver determines the uniform locations
 * at link time. We don't need to remember the sampler uniform location
 * because we will bind a texture slot to it and never change it
 * Uniforms are program-local so we can't rely on fHWState to hold the
 * previous uniform state after a program change.
 */
class GrGLProgram {
public:
    class CachedData;

    GrGLProgram();
    ~GrGLProgram();

    /**
     *  Streams data that can uniquely identifies the generated
     *  gpu program into a key, for cache indexing purposes.
     *
     *  @param key The key object to receive the key data
     */
    void buildKey(GrBinHashKeyBuilder& key) const;

    /**
     *  This is the heavy initilization routine for building a GLProgram.
     *  The result of heavy init is not stored in datamembers of GrGLProgam,
     *  but in a separate cacheable container.
     */
    bool genProgram(CachedData* programData) const;

     /**
      * The shader may modify the blend coeffecients. Params are in/out
      */
     void overrideBlend(GrBlendCoeff* srcCoeff, GrBlendCoeff* dstCoeff) const;

    /**
     * Attribute indices
     */
    static int PositionAttributeIdx() { return 0; }
    static int TexCoordAttributeIdx(int tcIdx) { return 1 + tcIdx; }
    static int ColorAttributeIdx() { return 1 + GrDrawTarget::kMaxTexCoords; }
    static int ViewMatrixAttributeIdx() {
        return 2 + GrDrawTarget::kMaxTexCoords;
    }
    static int TextureMatrixAttributeIdx(int stage) {
        return 5 + GrDrawTarget::kMaxTexCoords + 3 * stage;
    }

private:

    // Parameters that affect code generation
    // These structs should be kept compact; they are the input to an
    // expensive hash key generator.
    struct ProgramDesc {
        ProgramDesc() {
            // since we use this as part of a key we can't have any unitialized
            // padding
            memset(this, 0, sizeof(ProgramDesc));
        }

        struct StageDesc {
            enum OptFlagBits {
                kNoPerspective_OptFlagBit       = 1 << 0,
                kIdentityMatrix_OptFlagBit      = 1 << 1,
                kCustomTextureDomain_OptFlagBit = 1 << 2,
                kIsEnabled_OptFlagBit           = 1 << 7
            };
            enum Modulation {
                kColor_Modulation,
                kAlpha_Modulation
            };
            enum FetchMode {
                kSingle_FetchMode,
                k2x2_FetchMode
            };
            enum CoordMapping {
                kIdentity_CoordMapping,
                kRadialGradient_CoordMapping,
                kSweepGradient_CoordMapping,
                kRadial2Gradient_CoordMapping
            };

            uint8_t fOptFlags;
            uint8_t fModulation;  // casts to enum Modulation
            uint8_t fFetchMode;  // casts to enum FetchMode
            uint8_t fCoordMapping;  // casts to enum CoordMapping

            inline bool isEnabled() const {
                return fOptFlags & kIsEnabled_OptFlagBit;
            }
            inline void setEnabled(bool newValue) {
                if (newValue) {
                    fOptFlags |= kIsEnabled_OptFlagBit;
                } else {
                    fOptFlags &= ~kIsEnabled_OptFlagBit;
                }
            }

            uint8_t fWrapModeHorizontal; // casts to enum GrSamplerState::WrapMode
            uint8_t fWrapModeVertical;
        };

        enum ColorType {
            kNone_ColorType         = 0,
            kAttribute_ColorType    = 1,
            kUniform_ColorType      = 2,
        };
        // Dual-src blending makes use of a secondary output color that can be
        // used as a per-pixel blend coeffecient. This controls whether a
        // secondary source is output and what value it holds.
        enum DualSrcOutput {
            kNone_DualSrcOutput,
            kCoverage_DualSrcOutput,
            kCoverageISA_DualSrcOutput,
            kCoverageISC_DualSrcOutput,
            kDualSrcOutputCnt
        };

        // stripped of bits that don't affect prog generation
        GrVertexLayout fVertexLayout;

        StageDesc fStages[GrDrawTarget::kNumStages];

        uint8_t fColorType;  // casts to enum ColorType
        uint8_t fDualSrcOutput;  // casts to enum DualSrcOutput
        int8_t fFirstCoverageStage;
        SkBool8 fEmitsPointSize;
        SkBool8 fEdgeAAConcave;

        int8_t fEdgeAANumEdges;
        uint8_t fColorFilterXfermode;  // casts to enum SkXfermode::Mode

        uint8_t fPadTo32bLengthMultiple [1];

    } fProgramDesc;

    const ProgramDesc& getDesc() { return fProgramDesc; }

public:
    enum {
        kUnusedUniform = -1,
        kSetAsAttribute = 1000,
    };

    struct StageUniLocations {
        GrGLint fTextureMatrixUni;
        GrGLint fNormalizedTexelSizeUni;
        GrGLint fSamplerUni;
        GrGLint fRadial2Uni;
        GrGLint fTexDomUni;
        void reset() {
            fTextureMatrixUni = kUnusedUniform;
            fNormalizedTexelSizeUni = kUnusedUniform;
            fSamplerUni = kUnusedUniform;
            fRadial2Uni = kUnusedUniform;
            fTexDomUni = kUnusedUniform;
        }
    };

    struct UniLocations {
        GrGLint fViewMatrixUni;
        GrGLint fColorUni;
        GrGLint fEdgesUni;
        GrGLint fColorFilterUni;
        StageUniLocations fStages[GrDrawTarget::kNumStages];
        void reset() {
            fViewMatrixUni = kUnusedUniform;
            fColorUni = kUnusedUniform;
            fEdgesUni = kUnusedUniform;
            fColorFilterUni = kUnusedUniform;
            for (int s = 0; s < GrDrawTarget::kNumStages; ++s) {
                fStages[s].reset();
            }
        }
    };

    class CachedData : public ::GrNoncopyable {
    public:
        CachedData() {
        }

        ~CachedData() {
        }

        void copyAndTakeOwnership(CachedData& other) {
            memcpy(this, &other, sizeof(*this));
        }

    public:

        // IDs
        GrGLuint    fVShaderID;
        GrGLuint    fFShaderID;
        GrGLuint    fProgramID;
        // shader uniform locations (-1 if shader doesn't use them)
        UniLocations fUniLocations;

        GrMatrix  fViewMatrix;

        // these reflect the current values of uniforms
        // (GL uniform values travel with program)
        GrColor                     fColor;
        GrColor                     fColorFilterColor;
        GrMatrix                    fTextureMatrices[GrDrawTarget::kNumStages];
        // width and height used for normalized texel size
        int                         fTextureWidth[GrDrawTarget::kNumStages];
        int                         fTextureHeight[GrDrawTarget::kNumStages];
        GrScalar                    fRadial2CenterX1[GrDrawTarget::kNumStages];
        GrScalar                    fRadial2Radius0[GrDrawTarget::kNumStages];
        bool                        fRadial2PosRoot[GrDrawTarget::kNumStages];
        GrRect                      fTextureDomain[GrDrawTarget::kNumStages];

    private:
        enum Constants {
            kUniLocationPreAllocSize = 8
        };

    }; // CachedData

private:
    enum {
        kUseUniform = 2000
    };

    // should set all fields in locations var to kUseUniform if the
    // corresponding uniform is required for the program.
    void genStageCode(int stageNum,
                      const ProgramDesc::StageDesc& desc,
                      const char* fsInColor, // NULL means no incoming color
                      const char* fsOutColor,
                      const char* vsInCoord,
                      ShaderCodeSegments* segments,
                      StageUniLocations* locations) const;

    static bool CompileFSAndVS(const ShaderCodeSegments& segments,
                               CachedData* programData);

    // Compiles a GL shader, returns shader ID or 0 if failed
    // params have same meaning as glShaderSource
    static GrGLuint CompileShader(GrGLenum type, int stringCnt,
                                  const char** strings,
                                  int* stringLengths);

    // Creates a GL program ID, binds shader attributes to GL vertex attrs, and
    // links the program
    bool bindOutputsAttribsAndLinkProgram(
                GrStringBuilder texCoordAttrNames[GrDrawTarget::kMaxTexCoords],
                bool bindColorOut,
                bool bindDualSrcOut,
                CachedData* programData) const;

    // Gets locations for all uniforms set to kUseUniform and initializes cache
    // to invalid values.
    void getUniformLocationsAndInitCache(CachedData* programData) const;

    friend class GrGpuGLShaders;
};

#endif

license: mit


code:
/*
    Copyright 2011 Google Inc.

    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.
 */

#ifndef GrGLTexture_DEFINED
#define GrGLTexture_DEFINED

#include "GrTexture.h"
#include "GrScalar.h"
#include "GrGLIRect.h"

class GrGpuGL;
class GrGLTexture;

/**
 * A ref counted tex id that deletes the texture in its destructor.
 */
class GrGLTexID : public GrRefCnt {

public:
    GrGLTexID(GrGLuint texID, bool ownsID) : fTexID(texID), fOwnsID(ownsID) {}

    virtual ~GrGLTexID() {
        if (0 != fTexID && fOwnsID) {
            GR_GL(DeleteTextures(1, &fTexID));
        }
    }

    void abandon() { fTexID = 0; }
    GrGLuint id() const { return fTexID; }

private:
    GrGLuint      fTexID;
    bool          fOwnsID;
};

////////////////////////////////////////////////////////////////////////////////

class GrGLRenderTarget : public GrRenderTarget {

public:
    // set fTexFBOID to this value to indicate that it is multisampled but
    // Gr doesn't know how to resolve it.
    enum { kUnresolvableFBOID = 0 };

    struct GLRenderTargetIDs {
        GrGLuint      fRTFBOID;
        GrGLuint      fTexFBOID;
        GrGLuint      fStencilRenderbufferID;
        GrGLuint      fMSColorRenderbufferID;
        bool          fOwnIDs;
        void reset() { memset(this, 0, sizeof(GLRenderTargetIDs)); }
    };

    GrGLRenderTarget(GrGpuGL* gpu,
                     const GLRenderTargetIDs& ids,
                     GrGLTexID* texID,
                     GrGLuint stencilBits,
                     bool isMultisampled,
                     const GrGLIRect& fViewport,
                     GrGLTexture* texture);

    virtual ~GrGLRenderTarget() { this->release(); }

    void setViewport(const GrGLIRect& rect) { fViewport = rect; }
    const GrGLIRect& getViewport() const { return fViewport; }

    // The following two functions return the same ID when a
    // texture-rendertarget is multisampled, and different IDs when
    // it is.
    // FBO ID used to render into
    GrGLuint renderFBOID() const { return fRTFBOID; }
    // FBO ID that has texture ID attached.
    GrGLuint textureFBOID() const { return fTexFBOID; }

    // override of GrRenderTarget
    virtual ResolveType getResolveType() const {
        if (fRTFBOID == fTexFBOID) {
            // catches FBO 0 and non MSAA case
            return kAutoResolves_ResolveType;
        } else if (kUnresolvableFBOID == fTexFBOID) {
            return kCantResolve_ResolveType;
        } else {
            return kCanResolve_ResolveType;
        }
    }

protected:
    // override of GrResource
    virtual void onAbandon();
    virtual void onRelease();

private:
    GrGLuint      fRTFBOID;
    GrGLuint      fTexFBOID;
    GrGLuint      fStencilRenderbufferID;
    GrGLuint      fMSColorRenderbufferID;

    // Should this object delete IDs when it is destroyed or does someone
    // else own them.
    bool        fOwnIDs;

    // when we switch to this rendertarget we want to set the viewport to
    // only render to to content area (as opposed to the whole allocation) and
    // we want the rendering to be at top left (GL has origin in bottom left)
    GrGLIRect fViewport;

    // non-NULL if this RT was created by Gr with an associated GrGLTexture.
    GrGLTexID* fTexIDObj;

    typedef GrRenderTarget INHERITED;
};

////////////////////////////////////////////////////////////////////////////////

class GrGLTexture : public GrTexture {

public:
    enum Orientation {
        kBottomUp_Orientation,
        kTopDown_Orientation,
    };

    struct TexParams {
        GrGLenum fFilter;
        GrGLenum fWrapS;
        GrGLenum fWrapT;
        bool fUseGpuRepeat;
        void invalidate() { memset(this, 0xff, sizeof(TexParams)); }
    };

    struct GLTextureDesc {
        int             fContentWidth;
        int             fContentHeight;
        int             fAllocWidth;
        int             fAllocHeight;
        GrPixelConfig   fFormat;
        GrGLuint        fTextureID;
        bool            fOwnsID;
        GrGLenum        fUploadFormat;
        GrGLenum        fUploadByteCount;
        GrGLenum        fUploadType;
        GrGLuint        fStencilBits;
        Orientation     fOrientation;
    };

    typedef GrGLRenderTarget::GLRenderTargetIDs GLRenderTargetIDs;

    GrGLTexture(GrGpuGL* gpu,
                const GLTextureDesc& textureDesc,
                const GLRenderTargetIDs& rtIDs,
                const TexParams& initialTexParams);

    virtual ~GrGLTexture() { this->release(); }

    // overrides of GrTexture
    virtual void uploadTextureData(int x,
                                   int y,
                                   int width,
                                   int height,
                                   const void* srcData);
    virtual intptr_t getTextureHandle();

    const TexParams& getTexParams() const { return fTexParams; }
    void setTexParams(const TexParams& texParams) { fTexParams = texParams; }
    GrGLuint textureID() const { return fTexIDObj->id(); }

    GrGLenum uploadFormat() const { return fUploadFormat; }
    GrGLenum uploadByteCount() const { return fUploadByteCount; }
    GrGLenum uploadType() const { return fUploadType; }

    /**
     * Retrieves the texture width actually allocated in texels.
     *
     * @return the width in texels
     */
    int allocWidth() const { return fAllocWidth; }

    /**
     * Retrieves the texture height actually allocated in texels.
     *
     * @return the height in texels
     */
    int allocHeight() const { return fAllocHeight; }

    /**
     * @return width() / allocWidth()
     */
    GrScalar contentScaleX() const { return fScaleX; }

    /**
     * @return height() / allocHeight()
     */
    GrScalar contentScaleY() const { return fScaleY; }

    // Ganesh assumes texture coordinates have their origin
    // in the top-left corner of the image. OpenGL, however,
    // has the origin in the lower-left corner. For content that
    // is loaded by Ganesh we just push the content "upside down"
    // (by GL's understanding of the world ) in glTex*Image and the
    // addressing just works out. However, content generated by GL
    // (FBO or externally imported texture) will be updside down
    // and it is up to the GrGpuGL derivative to handle y-mirroing.
    Orientation orientation() const { return fOrientation; }

    static const GrGLenum* WrapMode2GLWrap();

protected:

    // overrides of GrTexture
    virtual void onAbandon();
    virtual void onRelease();

private:
    TexParams           fTexParams;
    GrGLTexID*          fTexIDObj;
    GrGLenum            fUploadFormat;
    GrGLenum            fUploadByteCount;
    GrGLenum            fUploadType;
    int                 fAllocWidth;
    int                 fAllocHeight;
    // precomputed content / alloc ratios
    GrScalar            fScaleX;
    GrScalar            fScaleY;
    Orientation         fOrientation;
    GrGpuGL*            fGpuGL;

    typedef GrTexture INHERITED;
};

#endif


code:
/*
    Copyright 2011 Google Inc.

    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.
 */

#ifndef GrGLVertexBuffer_DEFINED
#define GrGLVertexBuffer_DEFINED

#include "GrVertexBuffer.h"
#include "GrGLInterface.h"

class GrGpuGL;

class GrGLVertexBuffer : public GrVertexBuffer {

public:
    virtual ~GrGLVertexBuffer() { this->release(); }
    // overrides of GrVertexBuffer
    virtual void* lock();
    virtual void* lockPtr() const;
    virtual void unlock();
    virtual bool isLocked() const;
    virtual bool updateData(const void* src, size_t srcSizeInBytes);
    virtual bool updateSubData(const void* src,
                               size_t srcSizeInBytes,
                               size_t offset);
    GrGLuint bufferID() const;

protected:
    GrGLVertexBuffer(GrGpuGL* gpu,
                     GrGLuint id,
                     size_t sizeInBytes,
                     bool dynamic);

    // overrides of GrResource
    virtual void onAbandon();
    virtual void onRelease();

private:
    void bind() const;

    GrGLuint     fBufferID;
    void*        fLockPtr;

    friend class GrGpuGL;

    typedef GrVertexBuffer INHERITED;
};

#endif


code:
/*
 Copyright 2011 Google Inc.

 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.
 */

#ifndef GrGeometryBuffer_DEFINED
#define GrGeometryBuffer_DEFINED

#include "GrResource.h"

class GrGpu;

/**
 * Parent class for vertex and index buffers
 */
class GrGeometryBuffer : public GrResource {
public:
    /**
     * Retrieves the size of the buffer
     *
     * @return the size of the buffer in bytes
     */
    size_t size() const { return fSizeInBytes; }

    /**
     *Retrieves whether the buffer was created with the dynamic flag
     *
     * @return true if the buffer was created with the dynamic flag
     */
    bool dynamic() const { return fDynamic; }

    /**
     * Locks the buffer to be written by the CPU.
     *
     * The previous content of the buffer is invalidated. It is an error
     * to draw from the buffer while it is locked. It is an error to call lock
     * on an already locked buffer.
     *
     * @return a pointer to the data or NULL if the lock fails.
     */
    virtual void* lock() = 0;

    /**
     * Returns the same ptr that lock() returned at time of lock or NULL if the
     * is not locked.
     *
     * @return ptr to locked buffer data or undefined if buffer is not locked.
     */
    virtual void* lockPtr() const = 0;

    /**
     * Unlocks the buffer.
     *
     * The pointer returned by the previous lock call will no longer be valid.
     */
    virtual void unlock() = 0;

    /**
     Queries whether the buffer has been locked.

     @return true if the buffer is locked, false otherwise.
     */
    virtual bool isLocked() const = 0;

    /**
     * Updates the buffer data.
     *
     * The size of the buffer will be preserved. The src data will be
     * placed at the begining of the buffer and any remaining contents will
     * be undefined.
     *
     * @return returns true if the update succeeds, false otherwise.
     */
    virtual bool updateData(const void* src, size_t srcSizeInBytes) = 0;

    /**
     * Updates a portion of the buffer data.
     *
     * The contents of the buffer outside the update region are preserved.
     *
     * @return returns true if the update succeeds, false otherwise.
     */
    virtual bool updateSubData(const void* src,
                               size_t srcSizeInBytes,
                               size_t offset) = 0;
protected:
    GrGeometryBuffer(GrGpu* gpu, size_t sizeInBytes, bool dynamic)
        : INHERITED(gpu)
        , fSizeInBytes(sizeInBytes)
        , fDynamic(dynamic) {}

private:
    size_t   fSizeInBytes;
    bool     fDynamic;

    typedef GrResource INHERITED;
};

#endif


code:
/*
    Copyright 2010 Google Inc.

    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.
 */

#ifndef GrGlyph_DEFINED
#define GrGlyph_DEFINED

#include "GrPath.h"
#include "GrRect.h"

class GrAtlas;

/*  Need this to be quad-state:
    - complete w/ image
    - just metrics
    - failed to get image, but has metrics
    - failed to get metrics
 */
struct GrGlyph {
    typedef uint32_t PackedID;

    GrAtlas*    fAtlas;
    GrPath*     fPath;
    PackedID    fPackedID;
    GrIRect16   fBounds;
    GrIPoint16  fAtlasLocation;

    void init(GrGlyph::PackedID packed, const GrIRect& bounds) {
        fAtlas = NULL;
        fPath = NULL;
        fPackedID = packed;
        fBounds.set(bounds);
        fAtlasLocation.set(0, 0);
    }

    void free() {
        if (fPath) {
            delete fPath;
            fPath = NULL;
        }
    }

    int width() const { return fBounds.width(); }
    int height() const { return fBounds.height(); }
    bool isEmpty() const { return fBounds.isEmpty(); }
    uint16_t glyphID() const { return UnpackID(fPackedID); }

    ///////////////////////////////////////////////////////////////////////////

    static inline unsigned ExtractSubPixelBitsFromFixed(GrFixed pos) {
        // two most significant fraction bits from fixed-point
        return (pos >> 14) & 3;
    }

    static inline PackedID Pack(uint16_t glyphID, GrFixed x, GrFixed y) {
        x = ExtractSubPixelBitsFromFixed(x);
        y = ExtractSubPixelBitsFromFixed(y);
        return (x << 18) | (y << 16) | glyphID;
    }

    static inline GrFixed UnpackFixedX(PackedID packed) {
        return ((packed >> 18) & 3) << 14;
    }

    static inline GrFixed UnpackFixedY(PackedID packed) {
        return ((packed >> 16) & 3) << 14;
    }

    static inline uint16_t UnpackID(PackedID packed) {
        return (uint16_t)packed;
    }
};

#endif


code:
/*
    Copyright 2011 Google Inc.

    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.
 */

#ifndef GrGpu_DEFINED
#define GrGpu_DEFINED

#include "GrDrawTarget.h"
#include "GrPathRenderer.h"
#include "GrRect.h"
#include "GrRefCnt.h"
#include "GrTexture.h"

class GrContext;
class GrIndexBufferAllocPool;
class GrResource;
class GrVertexBufferAllocPool;

/**
 * Gpu usage statistics.
 */
struct GrGpuStats {
    uint32_t fVertexCnt;  //<! Number of vertices drawn
    uint32_t fIndexCnt;   //<! Number of indices drawn
    uint32_t fDrawCnt;    //<! Number of draws

    uint32_t fProgChngCnt;//<! Number of program changes (N/A for fixed)

    /*
        *  Number of times the texture is set in 3D API
        */
    uint32_t fTextureChngCnt;
    /*
        *  Number of times the render target is set in 3D API
        */
    uint32_t fRenderTargetChngCnt;
    /*
        *  Number of textures created (includes textures that are rendertargets).
        */
    uint32_t fTextureCreateCnt;
    /*
        *  Number of rendertargets created.
        */
    uint32_t fRenderTargetCreateCnt;
};

class GrGpu : public GrDrawTarget {

public:
    /**
     * Additional blend coeffecients for dual source blending, not exposed
     * through GrPaint/GrContext.
     */
    enum ExtendedBlendCoeffs {
        // source 2 refers to second output color when
        // using dual source blending.
        kS2C_BlendCoeff = kPublicBlendCoeffCount,
        kIS2C_BlendCoeff,
        kS2A_BlendCoeff,
        kIS2A_BlendCoeff,

        kTotalBlendCoeffCount
    };

    /**
     *  Create an instance of GrGpu that matches the specified Engine backend.
     *  If the requested engine is not supported (at compile-time or run-time)
     *  this returns NULL.
     */
    static GrGpu* Create(GrEngine, GrPlatform3DContext context3D);

    ////////////////////////////////////////////////////////////////////////////

    GrGpu();
    virtual ~GrGpu();

    // The GrContext sets itself as the owner of this Gpu object
    void setContext(GrContext* context) {
        GrAssert(NULL == fContext);
        fContext = context;
    }
    GrContext* getContext() { return fContext; }
    const GrContext* getContext() const { return fContext; }

    /**
     * The GrGpu object normally assumes that no outsider is setting state
     * within the underlying 3D API's context/device/whatever. This call informs
     * the GrGpu that the state was modified and it shouldn't make assumptions
     * about the state.
     */
    void markContextDirty() { fContextIsDirty = true; }

    void unimpl(const char[]);

    /**
     * Creates a texture object. If desc width or height is not a power of
     * two but underlying API requires a power of two texture then srcData
     * will be embedded in a power of two texture. The extra width and height
     * is filled as though srcData were rendered clamped into the texture.
     *
     * If kRenderTarget_TextureFlag is specified the GrRenderTarget is
     * accessible via GrTexture::asRenderTarget(). The texture will hold a ref
     * on the render target until its releaseRenderTarget() is called or it is
     * destroyed.
     *
     * @param desc        describes the texture to be created.
     * @param srcData     texel data to load texture. Begins with full-size
     *                    palette data for paletted textures. Contains width*
     *                    height texels. If NULL texture data is uninitialized.
     *
     * @return    The texture object if successful, otherwise NULL.
     */
    GrTexture* createTexture(const GrTextureDesc& desc,
                             const void* srcData, size_t rowBytes);

    GrResource* createPlatformSurface(const GrPlatformSurfaceDesc& desc);

    /**
     * Reads the current target object (e.g. FBO or IDirect3DSurface9*) and
     * viewport state from the underlying 3D API and wraps it in a
     * GrRenderTarget. The GrRenderTarget will not attempt to delete/destroy the
     * underlying object in its destructor and it is up to caller to guarantee
     * that it remains valid while the GrRenderTarget is used.
     *
     * @return the newly created GrRenderTarget
     */
    GrRenderTarget* createRenderTargetFrom3DApiState();

    /**
     * Creates a vertex buffer.
     *
     * @param size    size in bytes of the vertex buffer
     * @param dynamic hints whether the data will be frequently changed
     *                by either GrVertexBuffer::lock or
     *                GrVertexBuffer::updateData.
     *
     * @return    The vertex buffer if successful, otherwise NULL.
     */
    GrVertexBuffer* createVertexBuffer(uint32_t size, bool dynamic);

    /**
     * Creates an index buffer.
     *
     * @param size    size in bytes of the index buffer
     * @param dynamic hints whether the data will be frequently changed
     *                by either GrIndexBuffer::lock or
     *                GrIndexBuffer::updateData.
     *
     * @return The index buffer if successful, otherwise NULL.
     */
    GrIndexBuffer* createIndexBuffer(uint32_t size, bool dynamic);

    /**
     * Are 8 bit paletted textures supported.
     *
     * @return    true if 8bit palette textures are supported, false otherwise
     */
    bool supports8BitPalette() const { return f8bitPaletteSupport; }

    /**
     * returns true if two sided stenciling is supported. If false then only
     * the front face values of the GrStencilSettings
     * @return    true if only a single stencil pass is needed.
     */
    bool supportsTwoSidedStencil() const
                                        { return fTwoSidedStencilSupport; }

    /**
     * returns true if stencil wrap is supported. If false then
     * kIncWrap_StencilOp and kDecWrap_StencilOp are treated as
     * kIncClamp_StencilOp and kDecClamp_StencilOp, respectively.
     * @return    true if stencil wrap ops are supported.
     */
    bool supportsStencilWrapOps() const
                                        { return fStencilWrapOpsSupport; }

    /**
     * Checks whether locking vertex and index buffers is supported.
     *
     * @return true if locking is supported.
     */
    bool supportsBufferLocking() const { return fBufferLockSupport; }

    /**
     * Does the 3D API support anti-aliased lines. If so then line primitive
     * types will use this functionality when the AA state flag is set.
     */
    bool supportsAALines() const { return fAALineSupport; }

    /**
     * Does the subclass support GrSamplerState::k4x4Downsample_Filter
     */
    bool supports4x4DownsampleFilter() const { return f4X4DownsampleFilterSupport; }

    /**
     * Does this instance support dual-source blending? Required for proper
     * blending with partial coverage with certain blend modes (dst coeff is
     * not 1, ISA, or ISC)
     */
    bool supportsDualSourceBlending() const {
        return fDualSourceBlendingSupport;
    }

    /**
     * Gets the minimum width of a render target. If a texture/rt is created
     * with a width less than this size the GrGpu object will clamp it to this
     * value.
     */
    int minRenderTargetWidth() const { return fMinRenderTargetWidth; }

    /**
     * Gets the minimum width of a render target. If a texture/rt is created
     * with a height less than this size the GrGpu object will clamp it to this
     * value.
     */
    int minRenderTargetHeight() const  { return fMinRenderTargetHeight; }

    /**
     * Reports whether full scene anti-aliasing is supported.
     */
    bool supportsFullsceneAA() const { return fFSAASupport; }

    /**
     * Returns true if NPOT textures can be created
     *
     * @return    true if NPOT textures can be created
     */
    bool npotTextureSupport() const { return fNPOTTextureSupport; }

    /**
     * Returns true if NPOT textures can be repeat/mirror tiled.
     *
     * @return    true if NPOT textures can be tiled
     */
    bool npotTextureTileSupport() const { return fNPOTTextureTileSupport; }

    /**
     * Returns true if a NPOT texture can be a rendertarget
     *
     * @return    the true if NPOT texture/rendertarget can be created.
     */
    bool npotRenderTargetSupport() const { return fNPOTRenderTargetSupport; }

    /**
     * Gets the largest allowed width and height of a texture.
     */
    int maxTextureSize() const { return fMaxTextureSize; }
    /**
     * Gets the largest allowed width and height of a render target.
     */
    int maxRenderTargetSize() const { return fMaxRenderTargetSize; }

    int maxRenderTargetCount() const { return fMaxRenderTargetCnt; }

    int renderTargetCount() const { return fRenderTargetCnt; }

    virtual void clear(const GrIRect* rect, GrColor color);

    /**
     * Installs a path renderer that will be used to draw paths that are
     * part of the clip.
     */
    void setClipPathRenderer(GrPathRenderer* pathRenderer) {
        GrSafeAssign(fClientPathRenderer, pathRenderer);
    }

    /**
     * Returns an index buffer that can be used to render quads.
     * Six indices per quad: 0, 1, 2, 0, 2, 3, etc.
     * The max number of quads can be queried using GrIndexBuffer::maxQuads().
     * Draw with kTriangles_PrimitiveType
     * @ return the quad index buffer
     */
    const GrIndexBuffer* getQuadIndexBuffer() const;

    /**
     * Returns a vertex buffer with four position-only vertices [(0,0), (1,0),
     * (1,1), (0,1)].
     * @ return unit square vertex buffer
     */
    const GrVertexBuffer* getUnitSquareVertexBuffer() const;

    /**
     * Ensures that the current render target is actually set in the
     * underlying 3D API. Used when client wants to use 3D API to directly
     * render to the RT.
     */
    void forceRenderTargetFlush();

    /**
     * Reads a rectangle of pixels from a render target.
     * @param renderTarget  the render target to read from. NULL means the
     *                      current render target.
     * @param left          left edge of the rectangle to read (inclusive)
     * @param top           top edge of the rectangle to read (inclusive)
     * @param width         width of rectangle to read in pixels.
     * @param height        height of rectangle to read in pixels.
     * @param config        the pixel config of the destination buffer
     * @param buffer        memory to read the rectangle into.
     *
     * @return true if the read succeeded, false if not. The read can fail
     *              because of a unsupported pixel config or because no render
     *              target is currently set.
     */
    bool readPixels(GrRenderTarget* renderTarget,
                    int left, int top, int width, int height,
                    GrPixelConfig config, void* buffer);

    const GrGpuStats& getStats() const;
    void resetStats();
    void printStats() const;

    /**
     * Called to tell Gpu object that all GrResources have been lost and should
     * be abandoned.
     */
    virtual void abandonResources();

    /**
     * Called to tell Gpu object to release all GrResources.
     */
    void releaseResources();

    /**
     * Add resource to list of resources. Should only be called by GrResource.
     * @param resource  the resource to add.
     */
    void insertResource(GrResource* resource);

    /**
     * Remove resource from list of resources. Should only be called by
     * GrResource.
     * @param resource  the resource to remove.
     */
    void removeResource(GrResource* resource);

protected:
    enum PrivateStateBits {
        kFirstBit = (kLastPublicStateBit << 1),

        kModifyStencilClip_StateBit = kFirstBit, // allows draws to modify
                                                 // stencil bits used for
                                                 // clipping.
    };

    /**
     * Extensions to GrDrawTarget::StateBits to implement stencil clipping
     */
    struct ClipState {
        bool            fClipInStencil;
        bool            fClipIsDirty;
    } fClipState;

    // GrDrawTarget override
    virtual void clipWillBeSet(const GrClip& newClip);

    // prepares clip flushes gpu state before a draw
    bool setupClipAndFlushState(GrPrimitiveType type);

    // Functions used to map clip-respecting stencil tests into normal
    // stencil funcs supported by GPUs.
    static GrStencilFunc ConvertStencilFunc(bool stencilInClip,
                                            GrStencilFunc func);
    static void ConvertStencilFuncAndMask(GrStencilFunc func,
                                          bool clipInStencil,
                                          unsigned int clipBit,
                                          unsigned int userBits,
                                          unsigned int* ref,
                                          unsigned int* mask);

    // stencil settings to clip drawing when stencil clipping is in effect
    // and the client isn't using the stencil test.
    static const GrStencilSettings gClipStencilSettings;

    // defaults to false, subclass can set true to support palleted textures
    bool f8bitPaletteSupport;

    // set by subclass
    bool fNPOTTextureSupport;
    bool fNPOTTextureTileSupport;
    bool fNPOTRenderTargetSupport;
    bool fTwoSidedStencilSupport;
    bool fStencilWrapOpsSupport;
    bool fAALineSupport;
    bool fFSAASupport;
    bool f4X4DownsampleFilterSupport; // supports GrSamplerState::k4x4Downsample_Filter
    bool fDualSourceBlendingSupport;

    // set by subclass to true if index and vertex buffers can be locked, false
    // otherwise.
    bool fBufferLockSupport;

    // set by subclass
    int fMinRenderTargetWidth;
    int fMinRenderTargetHeight;
    int fMaxRenderTargetSize;
    int fMaxTextureSize;
    int fRenderTargetCnt;
    int fMaxRenderTargetCnt;

    GrGpuStats fStats;

    struct GeometryPoolState {
        const GrVertexBuffer* fPoolVertexBuffer;
        int                   fPoolStartVertex;

        const GrIndexBuffer*  fPoolIndexBuffer;
        int                   fPoolStartIndex;
    };
    const GeometryPoolState& getGeomPoolState() {
        return fGeomPoolStateStack.back();
    }

    // GrDrawTarget overrides
    virtual bool onReserveVertexSpace(GrVertexLayout vertexLayout,
                                      int vertexCount,
                                      void** vertices);
    virtual bool onReserveIndexSpace(int indexCount, void** indices);
    virtual void releaseReservedVertexSpace();
    virtual void releaseReservedIndexSpace();
    virtual void onSetVertexSourceToArray(const void* vertexArray,
                                          int vertexCount);
    virtual void onSetIndexSourceToArray(const void* indexArray,
                                         int indexCount);
    virtual void releaseVertexArray();
    virtual void releaseIndexArray();
    virtual void geometrySourceWillPush();
    virtual void geometrySourceWillPop(const GeometrySrcState& restoredState);

    // Helpers for setting up geometry state
    void finalizeReservedVertices();
    void finalizeReservedIndices();

    // overridden by API-specific derived class to handle re-emitting 3D API
    // preample and dirtying state cache.
    virtual void resetContext() = 0;

    // overridden by API-specific derived class to create objects.
    virtual GrTexture* onCreateTexture(const GrTextureDesc& desc,
                                       const void* srcData,
                                       size_t rowBytes) = 0;
    virtual GrResource* onCreatePlatformSurface(const GrPlatformSurfaceDesc& desc) = 0;
    virtual GrRenderTarget* onCreateRenderTargetFrom3DApiState() = 0;
    virtual GrVertexBuffer* onCreateVertexBuffer(uint32_t size,
                                                 bool dynamic) = 0;
    virtual GrIndexBuffer* onCreateIndexBuffer(uint32_t size,
                                               bool dynamic) = 0;

    // overridden by API-specific derivated class to perform the clear and
    // clearRect. NULL rect means clear whole target.
    virtual void onClear(const GrIRect* rect, GrColor color) = 0;

    // overridden by API-specific derived class to perform the draw call.
    virtual void onGpuDrawIndexed(GrPrimitiveType type,
                                  uint32_t startVertex,
                                  uint32_t startIndex,
                                  uint32_t vertexCount,
                                  uint32_t indexCount) = 0;

    virtual void onGpuDrawNonIndexed(GrPrimitiveType type,
                                     uint32_t vertexCount,
                                     uint32_t numVertices) = 0;

    // overridden by API-specific derived class to perform flush
    virtual void onForceRenderTargetFlush() = 0;

    // overridden by API-specific derived class to perform the read pixels.
    virtual bool onReadPixels(GrRenderTarget* target,
                              int left, int top, int width, int height,
                              GrPixelConfig, void* buffer) = 0;

    // called to program the vertex data, indexCount will be 0 if drawing non-
    // indexed geometry. The subclass may adjust the startVertex and/or
    // startIndex since it may have already accounted for these in the setup.
    virtual void setupGeometry(int* startVertex,
                               int* startIndex,
                               int vertexCount,
                               int indexCount) = 0;

    // The GrGpu typically records the clients requested state and then flushes
    // deltas from previous state at draw time. This function does the
    // API-specific flush of the state
    // returns false if current state is unsupported.
    virtual bool flushGraphicsState(GrPrimitiveType type) = 0;

    // Sets the scissor rect, or disables if rect is NULL.
    virtual void flushScissor(const GrIRect* rect) = 0;

    // GrGpu subclass removes the clip from the stencil buffer
    virtual void clearStencilClip(const GrIRect& rect) = 0;

private:
    GrContext*                  fContext; // not reffed (context refs gpu)

    GrVertexBufferAllocPool*    fVertexPool;

    GrIndexBufferAllocPool*     fIndexPool;

    // counts number of uses of vertex/index pool in the geometry stack
    int                         fVertexPoolUseCnt;
    int                         fIndexPoolUseCnt;

    enum {
        kPreallocGeomPoolStateStackCnt = 4,
    };
    GrAlignedSTStorage<kPreallocGeomPoolStateStackCnt,
                       GeometryPoolState>           fGeoSrcStateStackStorage;
    GrTArray<GeometryPoolState, true>               fGeomPoolStateStack;

    mutable GrIndexBuffer*      fQuadIndexBuffer; // mutable so it can be
                                                  // created on-demand

    mutable GrVertexBuffer*     fUnitSquareVertexBuffer; // mutable so it can be
                                                         // created on-demand

    GrDefaultPathRenderer*      fDefaultPathRenderer;
    GrPathRenderer*             fClientPathRenderer;

    bool                        fContextIsDirty;

    GrResource*                 fResourceHead;

    // GrDrawTarget overrides
    virtual void onDrawIndexed(GrPrimitiveType type,
                               int startVertex,
                               int startIndex,
                               int vertexCount,
                               int indexCount);
    virtual void onDrawNonIndexed(GrPrimitiveType type,
                                  int startVertex,
                                  int vertexCount);

    // readies the pools to provide vertex/index data.
    void prepareVertexPool();
    void prepareIndexPool();

    // determines the path renderer used to draw a clip path element.
    GrPathRenderer* getClipPathRenderer(const SkPath& path, GrPathFill fill);

    void handleDirtyContext() {
        if (fContextIsDirty) {
            this->resetContext();
            fContextIsDirty = false;
        }
    }

    typedef GrDrawTarget INHERITED;
};

#endif


code:
/*
    Copyright 2011 Google Inc.

    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.
 */

#ifndef GrGpuGL_DEFINED
#define GrGpuGL_DEFINED

#include "GrGpu.h"
#include "GrGLIRect.h"
#include "GrGLTexture.h"

#include "GrGLVertexBuffer.h"
#include "GrGLIndexBuffer.h"

class GrGpuGL : public GrGpu {
public:
    virtual ~GrGpuGL();

protected:
    GrGpuGL();

    struct {
        size_t                  fVertexOffset;
        GrVertexLayout          fVertexLayout;
        const GrVertexBuffer*   fVertexBuffer;
        const GrIndexBuffer*    fIndexBuffer;
        bool                    fArrayPtrsDirty;
    } fHWGeometryState;

    struct AAState {
        bool fMSAAEnabled;
        bool fSmoothLineEnabled;
    } fHWAAState;

    DrState   fHWDrawState;
    bool      fHWStencilClip;

    // As flush of GL state proceeds it updates fHDrawState
    // to reflect the new state. Later parts of the state flush
    // may perform cascaded changes but cannot refer to fHWDrawState.
    // These code paths can refer to the dirty flags. Subclass should
    // call resetDirtyFlags after its flush is complete
    struct {
        bool fRenderTargetChanged : 1;
        int  fTextureChangedMask;
    } fDirtyFlags;
    GR_STATIC_ASSERT(8 * sizeof(int) >= kNumStages);

    // clears the dirty flags
    void resetDirtyFlags();

    // last scissor / viewport scissor state seen by the GL.
    struct {
        bool        fScissorEnabled;
        GrGLIRect   fScissorRect;
        GrGLIRect   fViewportRect;
    } fHWBounds;

    // GrGpu overrides
    // overrides from GrGpu
    virtual void resetContext();

    virtual GrTexture* onCreateTexture(const GrTextureDesc& desc,
                                       const void* srcData,
                                       size_t rowBytes);
    virtual GrVertexBuffer* onCreateVertexBuffer(uint32_t size,
                                                 bool dynamic);
    virtual GrIndexBuffer* onCreateIndexBuffer(uint32_t size,
                                               bool dynamic);
    virtual GrResource* onCreatePlatformSurface(const GrPlatformSurfaceDesc& desc);
    virtual GrRenderTarget* onCreateRenderTargetFrom3DApiState();

    virtual void onClear(const GrIRect* rect, GrColor color);

    virtual void onForceRenderTargetFlush();

    virtual bool onReadPixels(GrRenderTarget* target,
                              int left, int top, int width, int height,
                              GrPixelConfig, void* buffer);

    virtual void onGpuDrawIndexed(GrPrimitiveType type,
                                  uint32_t startVertex,
                                  uint32_t startIndex,
                                  uint32_t vertexCount,
                                  uint32_t indexCount);
    virtual void onGpuDrawNonIndexed(GrPrimitiveType type,
                                     uint32_t vertexCount,
                                     uint32_t numVertices);
    virtual void flushScissor(const GrIRect* rect);
    void clearStencil(uint32_t value, uint32_t mask);
    virtual void clearStencilClip(const GrIRect& rect);
    virtual int getMaxEdges() const;

    // binds texture unit in GL
    void setTextureUnit(int unitIdx);

    // binds appropriate vertex and index buffers, also returns any extra
    // extra verts or indices to offset by.
    void setBuffers(bool indexed,
                    int* extraVertexOffset,
                    int* extraIndexOffset);

    // flushes state that is common to fixed and programmable GL
    // dither
    // line smoothing
    // texture binding
    // sampler state (filtering, tiling)
    // FBO binding
    // line width
    bool flushGLStateCommon(GrPrimitiveType type);

    // subclass should call this to flush the blend state
    void flushBlend(GrPrimitiveType type,
                    GrBlendCoeff srcCoeff,
                    GrBlendCoeff dstCoeff);

    // adjusts texture matrix to account for orientation, size, and npotness
    static void AdjustTextureMatrix(const GrGLTexture* texture,
                                    GrSamplerState::SampleMode mode,
                                    GrMatrix* matrix);

    // subclass may try to take advantage of identity tex matrices.
    // This helper determines if matrix will be identity after all
    // adjustments are applied.
    static bool TextureMatrixIsIdentity(const GrGLTexture* texture,
                                        const GrSamplerState& sampler);

    static bool BlendCoeffReferencesConstant(GrBlendCoeff coeff);

private:

    // notify callbacks to update state tracking when related
    // objects are bound to GL or deleted outside of the class
    void notifyVertexBufferBind(const GrGLVertexBuffer* buffer);
    void notifyVertexBufferDelete(const GrGLVertexBuffer* buffer);
    void notifyIndexBufferBind(const GrGLIndexBuffer* buffer);
    void notifyIndexBufferDelete(const GrGLIndexBuffer* buffer);
    void notifyTextureDelete(GrGLTexture* texture);
    void notifyRenderTargetDelete(GrRenderTarget* renderTarget);

    void setSpareTextureUnit();

    bool useSmoothLines();

    // bound is region that may be modified and therefore has to be resolved.
    // NULL means whole target. Can be an empty rect.
    void flushRenderTarget(const GrIRect* bound);
    void flushStencil();
    void flushAAState(GrPrimitiveType type);

    void resolveRenderTarget(GrGLRenderTarget* texture);

    bool canBeTexture(GrPixelConfig config,
                      GrGLenum* internalFormat,
                      GrGLenum* format,
                      GrGLenum* type);

    bool fboInternalFormat(GrPixelConfig config, GrGLenum* format);

    friend class GrGLVertexBuffer;
    friend class GrGLIndexBuffer;
    friend class GrGLTexture;
    friend class GrGLRenderTarget;

    bool fHWBlendDisabled;

    GrGLuint fAASamples[4];
    enum {
        kNone_MSFBO = 0,  //<! no support for MSAA FBOs
        kDesktopARB_MSFBO,//<! GL3.0-style MSAA FBO (GL_ARB_framebuffer_object)
        kDesktopEXT_MSFBO,//<! earlier GL_EXT_framebuffer* extensions
        kAppleES_MSFBO,   //<! GL_APPLE_framebuffer_multisample ES extension
        kIMG_MSFBO,       //<! GL_IMG_multisampled_render_to_texture ES extension
    } fMSFBOType;

    // Do we have stencil wrap ops.
    bool fHasStencilWrap;

    // The maximum number of fragment uniform vectors (GLES has min. 16).
    int fMaxFragmentUniformVectors;

    // ES requires an extension to support RGBA8 in RenderBufferStorage
    bool fRGBA8Renderbuffer;

    int fActiveTextureUnitIdx;

    // we record what stencil format worked last time to hopefully exit early
    // from our loop that tries stencil formats and calls check fb status.
    int fLastSuccessfulStencilFmtIdx;

    typedef GrGpu INHERITED;
};

#endif


code:
/*
    Copyright 2010 Google Inc.

    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.
 */

#ifndef GrGpuGLFixed_DEFINED
#define GrGpuGLFixed_DEFINED

#include "GrGpuGL.h"

// Fixed Pipeline OpenGL or OpenGL ES 1.x
class GrGpuGLFixed : public GrGpuGL {
public:
             GrGpuGLFixed();
    virtual ~GrGpuGLFixed();

protected:
    // overrides from GrGpu
    virtual bool flushGraphicsState(GrPrimitiveType type);
    virtual void setupGeometry(int* startVertex,
                               int* startIndex,
                               int vertexCount,
                               int indexCount);

private:
    virtual void resetContext();

    // Helpers to make code more readable
    const GrMatrix& getHWSamplerMatrix(int stage) const {
        return fHWDrawState.fSamplerStates[stage].getMatrix();
    }
    void recordHWSamplerMatrix(int stage, const GrMatrix& matrix) {
        fHWDrawState.fSamplerStates[stage].setMatrix(matrix);
    }

    // when the texture is GL_RGBA we set the GL_COMBINE texture
    // environment rgb operand 0 to be GL_COLOR to modulate each incoming
    // R,G, & B by the texture's R, G, & B. When the texture is alpha-only we
    // set the operand to GL_ALPHA so that the incoming frag's R, G, &B are all
    // modulated by the texture's A.
    enum TextureEnvRGBOperands {
        kAlpha_TextureEnvRGBOperand,
        kColor_TextureEnvRGBOperand,
    };
    TextureEnvRGBOperands fHWRGBOperand0[kNumStages];

    void flushProjectionMatrix();

    // are the currently bound vertex buffers/arrays laid
    // out for text or other drawing.
    bool fTextVerts;

    // On GL we have to build the base vertex offset into the
    // glVertexPointer/glTexCoordPointer/etc
    int fBaseVertex;

    typedef GrGpuGL INHERITED;
};

#endif


code:
/*
    Copyright 2011 Google Inc.

    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.
 */

#ifndef GrGpuGLShaders_DEFINED
#define GrGpuGLShaders_DEFINED

#include "GrGpuGL.h"
#include "GrGLProgram.h"

class GrGpuGLProgram;

// Programmable OpenGL or OpenGL ES 2.0
class GrGpuGLShaders : public GrGpuGL {
public:
             GrGpuGLShaders();
    virtual ~GrGpuGLShaders();

    virtual void resetContext();

    virtual void abandonResources();

protected:
    // overrides from GrGpu
    virtual bool flushGraphicsState(GrPrimitiveType type);
    virtual void setupGeometry(int* startVertex,
                               int* startIndex,
                               int vertexCount,
                               int indexCount);
    virtual void postDraw();

private:

    class ProgramCache;

    // Helpers to make code more readable
    const GrMatrix& getHWSamplerMatrix(int stage);
    void recordHWSamplerMatrix(int stage, const GrMatrix& matrix);

    // sets the texture matrix uniform for currently bound program
    void flushTextureMatrix(int stage);

    // sets the texture domain uniform for currently bound program
    void flushTextureDomain(int stage);

    // sets the color specified by GrDrawTarget::setColor()
    void flushColor();

    // sets the MVP matrix uniform for currently bound program
    void flushViewMatrix();

    // flushes the parameters to two point radial gradient
    void flushRadial2(int stage);

    // flushes the normalized texel size
    void flushTexelSize(int stage);

    // flushes the edges for edge AA
    void flushEdgeAAData();

    static void DeleteProgram(GrGLProgram::CachedData* programData);

    void ProgramUnitTest();

    void buildProgram(GrPrimitiveType type);

    ProgramCache*               fProgramCache;
    GrGLProgram::CachedData*    fProgramData;
    GrGLuint                    fHWProgramID;
    GrGLProgram                 fCurrentProgram;

    typedef GrGpuGL INHERITED;
};

#endif


code:
/*
    Copyright 2010 Google Inc.

    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.
 */

#ifndef GrGpuGLShaders2_DEFINED
#define GrGpuGLShaders2_DEFINED

#include "GrGpuGL.h"

// Programmable OpenGL or OpenGL ES 2.0
class GrGpuGLShaders2 : public GrGpuGL {
public:
             GrGpuGLShaders2();
    virtual ~GrGpuGLShaders2();

    virtual void resetContext();

protected:
    // overrides from GrGpu
    virtual bool flushGraphicsState(PrimitiveType type);
    virtual void setupGeometry(uint32_t startVertex,
                               uint32_t startIndex,
                               uint32_t vertexCount,
                               uint32_t indexCount);

private:

    void resetContextHelper();

    // sets the texture matrix uniform for currently bound program
    void flushTextureMatrix(int stage);

    // sets the MVP matrix uniform for currently bound program
    void flushViewMatrix();

    // flushes the parameters to two point radial gradient
    void flushRadial2(int stage);

    // called at flush time to setup the appropriate program
    void flushProgram(PrimitiveType type);

    struct Program;

    struct StageDesc;
    struct ProgramDesc;

    struct UniLocations;
    struct StageUniLocations;

    struct ShaderCodeSegments;

    class ProgramCache;

    // gets a description of needed shader
    void getProgramDesc(PrimitiveType primType, ProgramDesc* desc);

    // generates and compiles a program from a description and vertex layout
    // will change GL's bound program
    static void GenProgram(const ProgramDesc& desc, Program* program);

    // generates code for a stage of the shader
    static void GenStageCode(int stageNum,
                             const StageDesc& desc,
                             const char* psInColor,
                             const char* psOutColor,
                             const char* vsInCoord,
                             ShaderCodeSegments* segments,
                             StageUniLocations* locations);

    // Compiles a GL shader, returns shader ID or 0 if failed
    // params have same meaning as glShaderSource
    static GLuint CompileShader(GLenum type, int stringCnt,
                                             const char** strings,
                                             int* stringLengths);
    static void DeleteProgram(Program* program);

    void ProgramUnitTest();

    GrGLTexture::Orientation  fTextureOrientation;

    ProgramCache*   fProgramCache;
    Program*        fProgram;
    GLuint          fHWProgramID;

    typedef GrGpuGL INHERITED;
};

#endif


code:
/*
    Copyright 2010 Google Inc.

    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.
 */

#ifndef GrGpuVertex_DEFINED
#define GrGpuVertex_DEFINED

#include "GrGLConfig.h"
#include "GrPoint.h"

#if GR_TEXT_SCALAR_IS_USHORT
    typedef uint16_t                GrTextScalar;
    #define GrIntToTextScalar(x)    ((uint16_t)x)
    #define GrFixedToTextScalar(x)  (x)
#elif GR_TEXT_SCALAR_IS_FIXED
    typedef GrFixed                 GrTextScalar;
    #define GrIntToTextScalar(x)    GrIntToFixed(x)
    #define GrFixedToTextScalar(x)  (x)
#elif GR_TEXT_SCALAR_IS_FLOAT
    typedef float                   GrTextScalar;
    #define GrIntToTextScalar(x)    ((GrTextScalar)x)
    #define GrFixedToTextScalar(x)  GrFixedToFloat(x)
#else
    #error "Text scalar type not defined"
#endif

// text has its own vertex class, since it may want to be in fixed point (given)
// that it starts with all integers) even when the default vertices are floats
struct GrGpuTextVertex {
    GrTextScalar fX;
    GrTextScalar fY;

    void set(GrTextScalar x, GrTextScalar y) {
        fX = x;
        fY = y;
    }

    void setI(int x, int y) {
        fX = GrIntToTextScalar(x);
        fY = GrIntToTextScalar(y);
    }

    void setX(GrFixed x, GrFixed y) {
        fX = GrFixedToTextScalar(x);
        fY = GrFixedToTextScalar(y);
    }

    // rect fan is counter-clockwise

    void setRectFan(GrTextScalar l, GrTextScalar t, GrTextScalar r,
                    GrTextScalar b) {
        GrGpuTextVertex* v = this;
        v[0].set(l, t);
        v[1].set(l, b);
        v[2].set(r, b);
        v[3].set(r, t);
    }

    void setIRectFan(int l, int t, int r, int b) {
        this->setRectFan(GrIntToTextScalar(l), GrIntToTextScalar(t),
                         GrIntToTextScalar(r), GrIntToTextScalar(b));
    }

    void setIRectFan(int l, int t, int r, int b, size_t stride) {
        GrAssert(stride > sizeof(GrGpuTextVertex));
        char* v = (char*)this;
        ((GrGpuTextVertex*)(v + 0*stride))->setI(l, t);
        ((GrGpuTextVertex*)(v + 1*stride))->setI(l, b);
        ((GrGpuTextVertex*)(v + 2*stride))->setI(r, b);
        ((GrGpuTextVertex*)(v + 3*stride))->setI(r, t);
    }

    // counter-clockwise fan
    void setXRectFan(GrFixed l, GrFixed t, GrFixed r, GrFixed b) {
        this->setRectFan(GrFixedToTextScalar(l), GrFixedToTextScalar(t),
                         GrFixedToTextScalar(r), GrFixedToTextScalar(b));
    }

    void setXRectFan(GrFixed l, GrFixed t, GrFixed r, GrFixed b, size_t stride) {
        GrAssert(stride > sizeof(GrGpuTextVertex));
        char* v = (char*)this;
        ((GrGpuTextVertex*)(v + 0*stride))->setX(l, t);
        ((GrGpuTextVertex*)(v + 1*stride))->setX(l, b);
        ((GrGpuTextVertex*)(v + 2*stride))->setX(r, b);
        ((GrGpuTextVertex*)(v + 3*stride))->setX(r, t);
    }

};

#endif


code:
/*
    Copyright 2010 Google Inc.

    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.
 */

#ifndef GrIPoint_DEFINED
#define GrIPoint_DEFINED

#include "GrTypes.h"

struct GrIPoint {
public:
    int32_t fX, fY;

    GrIPoint(int32_t x, int32_t y) : fX(x), fY(y) {}

    void set(int32_t x, int32_t y) {
        fX = x;
        fY = y;
    }
};

#endif