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