OpenGLRenderer.h revision 6c319ca1275c8db892c39b48fc54864c949f9171
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_HWUI_OPENGL_RENDERER_H
18#define ANDROID_HWUI_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/Vector.h>
32
33#include "Debug.h"
34#include "Extensions.h"
35#include "Matrix.h"
36#include "Program.h"
37#include "Rect.h"
38#include "Snapshot.h"
39#include "Vertex.h"
40#include "SkiaShader.h"
41#include "SkiaColorFilter.h"
42#include "Caches.h"
43
44namespace android {
45namespace uirenderer {
46
47///////////////////////////////////////////////////////////////////////////////
48// Renderer
49///////////////////////////////////////////////////////////////////////////////
50
51class DisplayList;
52
53/**
54 * OpenGL renderer used to draw accelerated 2D graphics. The API is a
55 * simplified version of Skia's Canvas API.
56 */
57class OpenGLRenderer {
58public:
59    OpenGLRenderer();
60    virtual ~OpenGLRenderer();
61
62    virtual void setViewport(int width, int height);
63
64    virtual void prepare(bool opaque);
65    virtual void finish();
66
67    // These two calls must not be recorded in display lists
68    void interrupt();
69    void resume();
70
71    virtual void acquireContext();
72    virtual void releaseContext();
73
74    int getSaveCount() const;
75    virtual int save(int flags);
76    virtual void restore();
77    virtual void restoreToCount(int saveCount);
78
79    virtual int saveLayer(float left, float top, float right, float bottom,
80            SkPaint* p, int flags);
81    virtual int saveLayerAlpha(float left, float top, float right, float bottom,
82            int alpha, int flags);
83
84    virtual void translate(float dx, float dy);
85    virtual void rotate(float degrees);
86    virtual void scale(float sx, float sy);
87
88    const float* getMatrix() const;
89    void getMatrix(SkMatrix* matrix);
90    virtual void setMatrix(SkMatrix* matrix);
91    virtual void concatMatrix(SkMatrix* matrix);
92
93    const Rect& getClipBounds();
94    bool quickReject(float left, float top, float right, float bottom);
95    virtual bool clipRect(float left, float top, float right, float bottom, SkRegion::Op op);
96
97    virtual void drawDisplayList(DisplayList* displayList);
98    virtual void drawLayer(int texture, float left, float top, float right, float bottom,
99            float u, float v, SkPaint* paint);
100    virtual void drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint);
101    virtual void drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint);
102    virtual void drawBitmap(SkBitmap* bitmap, float srcLeft, float srcTop,
103            float srcRight, float srcBottom, float dstLeft, float dstTop,
104            float dstRight, float dstBottom, SkPaint* paint);
105    virtual void drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
106            const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
107            float left, float top, float right, float bottom, SkPaint* paint);
108    virtual void drawColor(int color, SkXfermode::Mode mode);
109    virtual void drawRect(float left, float top, float right, float bottom, SkPaint* paint);
110    virtual void drawPath(SkPath* path, SkPaint* paint);
111    virtual void drawLines(float* points, int count, SkPaint* paint);
112    virtual void drawText(const char* text, int bytesCount, int count, float x, float y,
113            SkPaint* paint);
114
115    virtual void resetShader();
116    virtual void setupShader(SkiaShader* shader);
117
118    virtual void resetColorFilter();
119    virtual void setupColorFilter(SkiaColorFilter* filter);
120
121    virtual void resetShadow();
122    virtual void setupShadow(float radius, float dx, float dy, int color);
123
124protected:
125    /**
126     * Compose the layer defined in the current snapshot with the layer
127     * defined by the previous snapshot.
128     *
129     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
130     *
131     * @param curent The current snapshot containing the layer to compose
132     * @param previous The previous snapshot to compose the current layer with
133     */
134    virtual void composeLayer(sp<Snapshot> current, sp<Snapshot> previous);
135
136private:
137    /**
138     * Saves the current state of the renderer as a new snapshot.
139     * The new snapshot is saved in mSnapshot and the previous snapshot
140     * is linked from mSnapshot->previous.
141     *
142     * @param flags The save flags; see SkCanvas for more information
143     *
144     * @return The new save count. This value can be passed to #restoreToCount()
145     */
146    int saveSnapshot(int flags);
147
148    /**
149     * Restores the current snapshot; mSnapshot becomes mSnapshot->previous.
150     *
151     * @return True if the clip was modified.
152     */
153    bool restoreSnapshot();
154
155    /**
156     * Sets the clipping rectangle using glScissor. The clip is defined by
157     * the current snapshot's clipRect member.
158     */
159    void setScissorFromClip();
160
161    /**
162     * Creates a new layer stored in the specified snapshot.
163     *
164     * @param snapshot The snapshot associated with the new layer
165     * @param left The left coordinate of the layer
166     * @param top The top coordinate of the layer
167     * @param right The right coordinate of the layer
168     * @param bottom The bottom coordinate of the layer
169     * @param alpha The translucency of the layer
170     * @param mode The blending mode of the layer
171     * @param flags The layer save flags
172     * @param previousFbo The name of the current framebuffer
173     *
174     * @return True if the layer was successfully created, false otherwise
175     */
176    bool createLayer(sp<Snapshot> snapshot, float left, float top, float right, float bottom,
177            int alpha, SkXfermode::Mode mode, int flags, GLuint previousFbo);
178
179    /**
180     * Creates a new layer stored in the specified snapshot as an FBO.
181     *
182     * @param layer The layer to store as an FBO
183     * @param snapshot The snapshot associated with the new layer
184     * @param bounds The bounds of the layer
185     * @param previousFbo The name of the current framebuffer
186     */
187    bool createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot,
188            GLuint previousFbo);
189
190    /**
191     * Compose the specified layer as a region.
192     *
193     * @param layer The layer to compose
194     * @param rect The layer's bounds
195     */
196    void composeLayerRegion(Layer* layer, const Rect& rect);
197
198    /**
199     * Compose the specified layer as a simple rectangle.
200     *
201     * @param layer The layer to compose
202     * @param rect The layer's bounds
203     * @param swap If true, the source and destination are swapped
204     */
205    void composeLayerRect(Layer* layer, const Rect& rect, bool swap = false);
206
207    /**
208     * Clears all the regions corresponding to the current list of layers.
209     * This method MUST be invoked before any drawing operation.
210     */
211    void clearLayerRegions();
212
213    /**
214     * Draws a colored rectangle with the specified color. The specified coordinates
215     * are transformed by the current snapshot's transform matrix.
216     *
217     * @param left The left coordinate of the rectangle
218     * @param top The top coordinate of the rectangle
219     * @param right The right coordinate of the rectangle
220     * @param bottom The bottom coordinate of the rectangle
221     * @param color The rectangle's ARGB color, defined as a packed 32 bits word
222     * @param mode The Skia xfermode to use
223     * @param ignoreTransform True if the current transform should be ignored
224     * @param ignoreBlending True if the blending is set by the caller
225     */
226    void drawColorRect(float left, float top, float right, float bottom,
227            int color, SkXfermode::Mode mode, bool ignoreTransform = false);
228
229    /**
230     * Draws a textured rectangle with the specified texture. The specified coordinates
231     * are transformed by the current snapshot's transform matrix.
232     *
233     * @param left The left coordinate of the rectangle
234     * @param top The top coordinate of the rectangle
235     * @param right The right coordinate of the rectangle
236     * @param bottom The bottom coordinate of the rectangle
237     * @param texture The texture name to map onto the rectangle
238     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
239     * @param mode The blending mode
240     * @param blend True if the texture contains an alpha channel
241     */
242    void drawTextureRect(float left, float top, float right, float bottom, GLuint texture,
243            float alpha, SkXfermode::Mode mode, bool blend);
244
245    /**
246     * Draws a textured rectangle with the specified texture. The specified coordinates
247     * are transformed by the current snapshot's transform matrix.
248     *
249     * @param left The left coordinate of the rectangle
250     * @param top The top coordinate of the rectangle
251     * @param right The right coordinate of the rectangle
252     * @param bottom The bottom coordinate of the rectangle
253     * @param texture The texture to use
254     * @param paint The paint containing the alpha, blending mode, etc.
255     */
256    void drawTextureRect(float left, float top, float right, float bottom,
257            Texture* texture, SkPaint* paint);
258
259    /**
260     * Draws a textured mesh with the specified texture. If the indices are omitted,
261     * the mesh is drawn as a simple quad. The mesh pointers become offsets when a
262     * VBO is bound.
263     *
264     * @param left The left coordinate of the rectangle
265     * @param top The top coordinate of the rectangle
266     * @param right The right coordinate of the rectangle
267     * @param bottom The bottom coordinate of the rectangle
268     * @param texture The texture name to map onto the rectangle
269     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
270     * @param mode The blending mode
271     * @param blend True if the texture contains an alpha channel
272     * @param vertices The vertices that define the mesh
273     * @param texCoords The texture coordinates of each vertex
274     * @param elementsCount The number of elements in the mesh, required by indices
275     * @param swapSrcDst Whether or not the src and dst blending operations should be swapped
276     * @param ignoreTransform True if the current transform should be ignored
277     * @param vbo The VBO used to draw the mesh
278     * @param ignoreScale True if the model view matrix should not be scaled
279     * @param dirty True if calling this method should dirty the current layer
280     */
281    void drawTextureMesh(float left, float top, float right, float bottom, GLuint texture,
282            float alpha, SkXfermode::Mode mode, bool blend,
283            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
284            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
285            bool ignoreScale = false, bool dirty = true);
286
287    /**
288     * Draws text underline and strike-through if needed.
289     *
290     * @param text The text to decor
291     * @param bytesCount The number of bytes in the text
292     * @param length The length in pixels of the text, can be <= 0.0f to force a measurement
293     * @param x The x coordinate where the text will be drawn
294     * @param y The y coordinate where the text will be drawn
295     * @param paint The paint to draw the text with
296     */
297    void drawTextDecorations(const char* text, int bytesCount, float length,
298            float x, float y, SkPaint* paint);
299
300    /**
301     * Resets the texture coordinates stored in mMeshVertices. Setting the values
302     * back to default is achieved by calling:
303     *
304     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
305     *
306     * @param u1 The left coordinate of the texture
307     * @param v1 The bottom coordinate of the texture
308     * @param u2 The right coordinate of the texture
309     * @param v2 The top coordinate of the texture
310     */
311    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
312
313    /**
314     * Gets the alpha and xfermode out of a paint object. If the paint is null
315     * alpha will be 255 and the xfermode will be SRC_OVER.
316     *
317     * @param paint The paint to extract values from
318     * @param alpha Where to store the resulting alpha
319     * @param mode Where to store the resulting xfermode
320     */
321    inline void getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode);
322
323    /**
324     * Binds the specified texture. The texture unit must have been selected
325     * prior to calling this method.
326     */
327    inline void bindTexture(GLuint texture) {
328        glBindTexture(GL_TEXTURE_2D, texture);
329    }
330
331    /**
332     * Sets the wrap modes for the specified texture. The wrap modes are modified
333     * only when needed.
334     */
335    inline void setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT);
336
337    /**
338     * Enable or disable blending as necessary. This function sets the appropriate
339     * blend function based on the specified xfermode.
340     */
341    inline void chooseBlending(bool blend, SkXfermode::Mode mode, ProgramDescription& description,
342            bool swapSrcDst = false);
343
344    /**
345     * Safely retrieves the mode from the specified xfermode. If the specified
346     * xfermode is null, the mode is assumed to be SkXfermode::kSrcOver_Mode.
347     */
348    inline SkXfermode::Mode getXfermode(SkXfermode* mode);
349
350    /**
351     * Use the specified program with the current GL context. If the program is already
352     * in use, it will not be bound again. If it is not in use, the current program is
353     * marked unused and the specified program becomes used and becomes the new
354     * current program.
355     *
356     * @param program The program to use
357     *
358     * @return true If the specified program was already in use, false otherwise.
359     */
360    inline bool useProgram(Program* program);
361
362    /**
363     * Invoked before any drawing operation. This sets required state.
364     */
365    void setupDraw();
366    /**
367     * Various methods to setup OpenGL rendering.
368     */
369    void setupDrawWithTexture(bool isAlpha8 = false);
370    void setupDrawColor(int color);
371    void setupDrawColor(int color, int alpha);
372    void setupDrawColor(float r, float g, float b, float a);
373    void setupDrawAlpha8Color(int color, int alpha);
374    void setupDrawAlpha8Color(float r, float g, float b, float a);
375    void setupDrawShader();
376    void setupDrawColorFilter();
377    void setupDrawBlending(SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode,
378            bool swapSrcDst = false);
379    void setupDrawBlending(bool blend = true, SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode,
380            bool swapSrcDst = false);
381    void setupDrawProgram();
382    void setupDrawDirtyRegionsDisabled();
383    void setupDrawModelViewIdentity();
384    void setupDrawModelView(float left, float top, float right, float bottom,
385            bool ignoreTransform = false, bool ignoreModelView = false);
386    void setupDrawModelViewTranslate(float left, float top, float right, float bottom,
387            bool ignoreTransform = false);
388    void setupDrawColorUniforms();
389    void setupDrawPureColorUniforms();
390    void setupDrawShaderIdentityUniforms();
391    void setupDrawShaderUniforms(bool ignoreTransform = false);
392    void setupDrawColorFilterUniforms();
393    void setupDrawSimpleMesh();
394    void setupDrawTexture(GLuint texture);
395    void setupDrawMesh(GLvoid* vertices, GLvoid* texCoords = NULL, GLuint vbo = 0);
396    void finishDrawTexture();
397
398    /**
399     * Should be invoked every time the glScissor is modified.
400     */
401    inline void dirtyClip() {
402        mDirtyClip = true;
403    }
404
405    /**
406     * Mark the layer as dirty at the specified coordinates. The coordinates
407     * are transformed with the supplied matrix.
408     */
409    void dirtyLayer(const float left, const float top, const float right, const float bottom,
410            const mat4 transform);
411
412    /**
413     * Mark the layer as dirty at the specified coordinates.
414     */
415    void dirtyLayer(const float left, const float top, const float right, const float bottom);
416
417    // Dimensions of the drawing surface
418    int mWidth, mHeight;
419
420    // Matrix used for ortho projection in shaders
421    mat4 mOrthoMatrix;
422
423    // Model-view matrix used to position/size objects
424    mat4 mModelView;
425
426    // Number of saved states
427    int mSaveCount;
428    // Base state
429    sp<Snapshot> mFirstSnapshot;
430    // Current state
431    sp<Snapshot> mSnapshot;
432
433    // Shaders
434    SkiaShader* mShader;
435
436    // Color filters
437    SkiaColorFilter* mColorFilter;
438
439    // Used to draw textured quads
440    TextureVertex mMeshVertices[4];
441
442    // Drop shadow
443    bool mHasShadow;
444    float mShadowRadius;
445    float mShadowDx;
446    float mShadowDy;
447    int mShadowColor;
448
449    // Various caches
450    Caches& mCaches;
451
452    // List of rectangles to clear due to calls to saveLayer()
453    Vector<Rect*> mLayers;
454
455    // Indentity matrix
456    const mat4 mIdentity;
457
458    // Indicates whether the clip must be restored
459    bool mDirtyClip;
460
461    // The following fields are used to setup drawing
462    // Used to describe the shaders to generate
463    ProgramDescription mDescription;
464    // Color description
465    bool mColorSet;
466    float mColorA, mColorR, mColorG, mColorB;
467    // Indicates that the shader should get a color
468    bool mSetShaderColor;
469    // Current texture unit
470    GLuint mTextureUnit;
471    // Track dirty regions, true by default
472    bool mTrackDirtyRegions;
473    // Texture coordinates slot
474    int mTexCoordsSlot;
475
476    friend class DisplayListRenderer;
477
478}; // class OpenGLRenderer
479
480}; // namespace uirenderer
481}; // namespace android
482
483#endif // ANDROID_HWUI_OPENGL_RENDERER_H
484