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