OpenGLRenderer.h revision f9764a4f532561f6e2e985ff3b25112f1132ce44
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_UI_OPENGL_RENDERER_H
18#define ANDROID_UI_OPENGL_RENDERER_H
19
20#include <GLES2/gl2.h>
21#include <GLES2/gl2ext.h>
22
23#include <SkBitmap.h>
24#include <SkMatrix.h>
25#include <SkPaint.h>
26#include <SkRegion.h>
27#include <SkShader.h>
28#include <SkXfermode.h>
29
30#include <utils/RefBase.h>
31#include <utils/ResourceTypes.h>
32
33#include "Matrix.h"
34#include "Program.h"
35#include "Rect.h"
36#include "Snapshot.h"
37#include "TextureCache.h"
38#include "LayerCache.h"
39#include "PatchCache.h"
40#include "Vertex.h"
41
42namespace android {
43namespace uirenderer {
44
45///////////////////////////////////////////////////////////////////////////////
46// Support
47///////////////////////////////////////////////////////////////////////////////
48
49/**
50 * Structure mapping Skia xfermodes to OpenGL blending factors.
51 */
52struct Blender {
53    SkXfermode::Mode mode;
54    GLenum src;
55    GLenum dst;
56}; // struct Blender
57
58///////////////////////////////////////////////////////////////////////////////
59// Renderer
60///////////////////////////////////////////////////////////////////////////////
61
62/**
63 * OpenGL renderer used to draw accelerated 2D graphics. The API is a
64 * simplified version of Skia's Canvas API.
65 */
66class OpenGLRenderer {
67public:
68    OpenGLRenderer();
69    ~OpenGLRenderer();
70
71    void setViewport(int width, int height);
72    void prepare();
73
74    int getSaveCount() const;
75    int save(int flags);
76    void restore();
77    void restoreToCount(int saveCount);
78
79    int saveLayer(float left, float top, float right, float bottom, const SkPaint* p, int flags);
80    int saveLayerAlpha(float left, float top, float right, float bottom, int alpha, int flags);
81
82    void translate(float dx, float dy);
83    void rotate(float degrees);
84    void scale(float sx, float sy);
85
86    void setMatrix(SkMatrix* matrix);
87    void getMatrix(SkMatrix* matrix);
88    void concatMatrix(SkMatrix* matrix);
89
90    const Rect& getClipBounds();
91    bool quickReject(float left, float top, float right, float bottom);
92    bool clipRect(float left, float top, float right, float bottom, SkRegion::Op op);
93
94    void drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint);
95    void drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint);
96    void drawBitmap(SkBitmap* bitmap, float srcLeft, float srcTop, float srcRight, float srcBottom,
97            float dstLeft, float dstTop, float dstRight, float dstBottom, const SkPaint* paint);
98    void drawPatch(SkBitmap* bitmap, Res_png_9patch* patch, float left, float top,
99            float right, float bottom, const SkPaint* paint);
100    void drawColor(int color, SkXfermode::Mode mode);
101    void drawRect(float left, float top, float right, float bottom, const SkPaint* paint);
102
103    void resetShader();
104    void setupBitmapShader(SkBitmap* bitmap, SkShader::TileMode tileX, SkShader::TileMode tileY,
105            SkMatrix* matrix, bool hasAlpha);
106    void setupLinearGradientShader(SkShader* shader, float* bounds, uint32_t* colors,
107            float* positions, SkShader::TileMode tileMode, SkMatrix* matrix, bool hasAlpha);
108
109private:
110    /**
111     * Type of Skia shader in use.
112     */
113    enum ShaderType {
114        kShaderNone,
115        kShaderBitmap,
116        kShaderLinearGradient,
117        kShaderCircularGradient,
118        kShaderSweepGradient
119    };
120
121    /**
122     * Saves the current state of the renderer as a new snapshot.
123     * The new snapshot is saved in mSnapshot and the previous snapshot
124     * is linked from mSnapshot->previous.
125     *
126     * @return The new save count. This value can be passed to #restoreToCount()
127     */
128    int saveSnapshot();
129
130    /**
131     * Restores the current snapshot; mSnapshot becomes mSnapshot->previous.
132     *
133     * @return True if the clip should be also reapplied by calling
134     *         #setScissorFromClip().
135     */
136    bool restoreSnapshot();
137
138    /**
139     * Sets the clipping rectangle using glScissor. The clip is defined by
140     * the current snapshot's clipRect member.
141     */
142    void setScissorFromClip();
143
144    /**
145     * Compose the layer defined in the current snapshot with the layer
146     * defined by the previous snapshot.
147     *
148     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
149     *
150     * @param curent The current snapshot containing the layer to compose
151     * @param previous The previous snapshot to compose the current layer with
152     */
153    void composeLayer(sp<Snapshot> current, sp<Snapshot> previous);
154
155    /**
156     * Creates a new layer stored in the specified snapshot.
157     *
158     * @param snapshot The snapshot associated with the new layer
159     * @param left The left coordinate of the layer
160     * @param top The top coordinate of the layer
161     * @param right The right coordinate of the layer
162     * @param bottom The bottom coordinate of the layer
163     * @param alpha The translucency of the layer
164     * @param mode The blending mode of the layer
165     * @param flags The layer save flags
166     *
167     * @return True if the layer was successfully created, false otherwise
168     */
169    bool createLayer(sp<Snapshot> snapshot, float left, float top, float right, float bottom,
170            int alpha, SkXfermode::Mode mode, int flags);
171
172    /**
173     * Draws a colored rectangle with the specified color. The specified coordinates
174     * are transformed by the current snapshot's transform matrix.
175     *
176     * @param left The left coordinate of the rectangle
177     * @param top The top coordinate of the rectangle
178     * @param right The right coordinate of the rectangle
179     * @param bottom The bottom coordinate of the rectangle
180     * @param color The rectangle's ARGB color, defined as a packed 32 bits word
181     * @param mode The Skia xfermode to use
182     * @param ignoreTransform True if the current transform should be ignored
183     */
184    void drawColorRect(float left, float top, float right, float bottom,
185    		int color, SkXfermode::Mode mode, bool ignoreTransform = false);
186
187    /**
188     * Draws a textured rectangle with the specified texture. The specified coordinates
189     * are transformed by the current snapshot's transform matrix.
190     *
191     * @param left The left coordinate of the rectangle
192     * @param top The top coordinate of the rectangle
193     * @param right The right coordinate of the rectangle
194     * @param bottom The bottom coordinate of the rectangle
195     * @param texture The texture name to map onto the rectangle
196     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
197     * @param mode The blending mode
198     * @param blend True if the texture contains an alpha channel
199     */
200    void drawTextureRect(float left, float top, float right, float bottom, GLuint texture,
201            float alpha, SkXfermode::Mode mode, bool blend);
202
203    /**
204     * Draws a textured rectangle with the specified texture. The specified coordinates
205     * are transformed by the current snapshot's transform matrix.
206     *
207     * @param left The left coordinate of the rectangle
208     * @param top The top coordinate of the rectangle
209     * @param right The right coordinate of the rectangle
210     * @param bottom The bottom coordinate of the rectangle
211     * @param texture The texture to use
212     * @param paint The paint containing the alpha, blending mode, etc.
213     */
214    void drawTextureRect(float left, float top, float right, float bottom,
215            const Texture* texture, const SkPaint* paint);
216
217    /**
218     * Draws a textured mesh with the specified texture. If the indices are omitted, the
219     * mesh is drawn as a simple quad.
220     *
221     * @param left The left coordinate of the rectangle
222     * @param top The top coordinate of the rectangle
223     * @param right The right coordinate of the rectangle
224     * @param bottom The bottom coordinate of the rectangle
225     * @param texture The texture name to map onto the rectangle
226     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
227     * @param mode The blending mode
228     * @param blend True if the texture contains an alpha channel
229     * @param vertices The vertices that define the mesh
230     * @param texCoords The texture coordinates of each vertex
231     * @param indices The indices of the vertices, can be NULL
232     * @param elementsCount The number of elements in the mesh, required by indices
233     */
234    void drawTextureMesh(float left, float top, float right, float bottom, GLuint texture,
235            float alpha, SkXfermode::Mode mode, bool blend,
236            GLvoid* vertices, GLvoid* texCoords, GLvoid* indices, GLsizei elementsCount = 0);
237
238    /**
239     * Fills the specified rectangle with the currently set bitmap shader.
240     *
241     * @param left The left coordinate of the rectangle
242     * @param top The top coordinate of the rectangle
243     * @param right The right coordinate of the rectangle
244     * @param bottom The bottom coordinate of the rectangle
245     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
246     * @param mode The blending mode
247     */
248    void drawBitmapShader(float left, float top, float right, float bottom, float alpha,
249            SkXfermode::Mode mode);
250
251    /**
252     * Resets the texture coordinates stored in mDrawTextureVertices. Setting the values
253     * back to default is achieved by calling:
254     *
255     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
256     *
257     * @param u1 The left coordinate of the texture
258     * @param v1 The bottom coordinate of the texture
259     * @param u2 The right coordinate of the texture
260     * @param v2 The top coordinate of the texture
261     */
262    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
263
264    /**
265     * Gets the alpha and xfermode out of a paint object. If the paint is null
266     * alpha will be 255 and the xfermode will be SRC_OVER.
267     *
268     * @param paint The paint to extract values from
269     * @param alpha Where to store the resulting alpha
270     * @param mode Where to store the resulting xfermode
271     */
272    inline void getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode);
273
274    /**
275     * Enable or disable blending as necessary. This function sets the appropriate
276     * blend function based on the specified xfermode.
277     */
278    inline void chooseBlending(bool blend, SkXfermode::Mode mode, bool isPremultiplied = true);
279
280    /**
281     * Use the specified program with the current GL context. If the program is already
282     * in use, it will not be bound again. If it is not in use, the current program is
283     * marked unused and the specified program becomes used and becomes the new
284     * current program.
285     *
286     * @param program The program to use
287     *
288     * @return true If the specified program was already in use, false otherwise.
289     */
290    inline bool useProgram(const sp<Program>& program);
291
292    // Dimensions of the drawing surface
293    int mWidth, mHeight;
294
295    // Matrix used for ortho projection in shaders
296    mat4 mOrthoMatrix;
297
298    // Model-view matrix used to position/size objects
299    mat4 mModelView;
300
301    // Number of saved states
302    int mSaveCount;
303    // Base state
304    Snapshot mFirstSnapshot;
305    // Current state
306    sp<Snapshot> mSnapshot;
307
308    // Shaders
309    sp<Program> mCurrentProgram;
310    sp<DrawColorProgram> mDrawColorProgram;
311    sp<DrawTextureProgram> mDrawTextureProgram;
312    sp<DrawLinearGradientProgram> mDrawLinearGradientProgram;
313
314    // Used to draw textured quads
315    TextureVertex mDrawTextureVertices[4];
316
317    // Current texture state
318    GLuint mLastTexture;
319
320    // Last known blend state
321    bool mBlend;
322    GLenum mLastSrcMode;
323    GLenum mLastDstMode;
324
325    // Skia shaders
326    ShaderType mShader;
327    SkShader* mShaderKey;
328    bool mShaderBlend;
329    SkShader::TileMode mShaderTileX;
330    SkShader::TileMode mShaderTileY;
331    SkMatrix* mShaderMatrix;
332    // Bitmaps
333    SkBitmap* mShaderBitmap;
334    // Gradients
335    float* mShaderBounds;
336    uint32_t* mShaderColors;
337    float* mShaderPositions;
338
339    // Various caches
340    TextureCache mTextureCache;
341    LayerCache mLayerCache;
342    PatchCache mPatchCache;
343}; // class OpenGLRenderer
344
345}; // namespace uirenderer
346}; // namespace android
347
348#endif // ANDROID_UI_OPENGL_RENDERER_H
349