OpenGLRenderer.h revision d72b73cea49f29c41661e55eb6bfdbc04f09d809
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 <androidfw/ResourceTypes.h>
38
39#include "Debug.h"
40#include "Extensions.h"
41#include "Matrix.h"
42#include "Program.h"
43#include "Rect.h"
44#include "Snapshot.h"
45#include "Vertex.h"
46#include "SkiaShader.h"
47#include "SkiaColorFilter.h"
48#include "UvMapper.h"
49#include "Caches.h"
50
51namespace android {
52namespace uirenderer {
53
54struct DrawModifiers {
55    SkiaShader* mShader;
56    SkiaColorFilter* mColorFilter;
57    float mOverrideLayerAlpha;
58
59    // Drop shadow
60    bool mHasShadow;
61    float mShadowRadius;
62    float mShadowDx;
63    float mShadowDy;
64    int mShadowColor;
65
66    // Draw filters
67    bool mHasDrawFilter;
68    int mPaintFilterClearBits;
69    int mPaintFilterSetBits;
70};
71
72enum StateDeferFlags {
73    kStateDeferFlag_Draw = 0x1,
74    kStateDeferFlag_Clip = 0x2
75};
76
77enum DrawOpMode {
78    kDrawOpMode_Immediate,
79    kDrawOpMode_Defer,
80    kDrawOpMode_Flush
81};
82
83enum ClipSideFlags {
84    kClipSide_Unclipped = 0x0,
85    kClipSide_Left = 0x1,
86    kClipSide_Top = 0x2,
87    kClipSide_Right = 0x4,
88    kClipSide_Bottom = 0x8,
89    kClipSide_Full = 0xF,
90    kClipSide_ConservativeFull = 0x1F
91};
92
93struct DeferredDisplayState {
94    // global op bounds, mapped by mMatrix to be in screen space coordinates, clipped
95    Rect mBounds;
96
97    // the below are set and used by the OpenGLRenderer at record and deferred playback
98    bool mClipValid;
99    Rect mClip;
100    int mClipSideFlags; // specifies which sides of the bounds are clipped, unclipped if cleared
101    bool mClipped;
102    mat4 mMatrix;
103    DrawModifiers mDrawModifiers;
104    float mAlpha;
105};
106
107///////////////////////////////////////////////////////////////////////////////
108// Renderer
109///////////////////////////////////////////////////////////////////////////////
110
111class DisplayList;
112class TextSetupFunctor;
113class VertexBuffer;
114
115/**
116 * OpenGL renderer used to draw accelerated 2D graphics. The API is a
117 * simplified version of Skia's Canvas API.
118 */
119class OpenGLRenderer {
120public:
121    ANDROID_API OpenGLRenderer();
122    virtual ~OpenGLRenderer();
123
124    /**
125     * Sets the name of this renderer. The name is optional and
126     * empty by default. If the pointer is null the name is set
127     * to the empty string.
128     */
129    ANDROID_API void setName(const char* name);
130
131    /**
132     * Returns the name of this renderer as UTF8 string.
133     * The returned pointer is never null.
134     */
135    ANDROID_API const char* getName() const;
136
137    /**
138     * Read externally defined properties to control the behavior
139     * of the renderer.
140     */
141    ANDROID_API void initProperties();
142
143    /**
144     * Indicates whether this renderer executes drawing commands immediately.
145     * If this method returns true, the drawing commands will be executed
146     * later.
147     */
148    virtual bool isDeferred();
149
150    /**
151     * Sets the dimension of the underlying drawing surface. This method must
152     * be called at least once every time the drawing surface changes size.
153     *
154     * @param width The width in pixels of the underlysing surface
155     * @param height The height in pixels of the underlysing surface
156     */
157    virtual void setViewport(int width, int height);
158
159    /**
160     * Prepares the renderer to draw a frame. This method must be invoked
161     * at the beginning of each frame. When this method is invoked, the
162     * entire drawing surface is assumed to be redrawn.
163     *
164     * @param opaque If true, the target surface is considered opaque
165     *               and will not be cleared. If false, the target surface
166     *               will be cleared
167     */
168    ANDROID_API status_t prepare(bool opaque);
169
170    /**
171     * Prepares the renderer to draw a frame. This method must be invoked
172     * at the beginning of each frame. Only the specified rectangle of the
173     * frame is assumed to be dirty. A clip will automatically be set to
174     * the specified rectangle.
175     *
176     * @param left The left coordinate of the dirty rectangle
177     * @param top The top coordinate of the dirty rectangle
178     * @param right The right coordinate of the dirty rectangle
179     * @param bottom The bottom coordinate of the dirty rectangle
180     * @param opaque If true, the target surface is considered opaque
181     *               and will not be cleared. If false, the target surface
182     *               will be cleared in the specified dirty rectangle
183     */
184    virtual status_t prepareDirty(float left, float top, float right, float bottom, bool opaque);
185
186    /**
187     * Indicates the end of a frame. This method must be invoked whenever
188     * the caller is done rendering a frame.
189     */
190    virtual void finish();
191
192    /**
193     * This method must be invoked before handing control over to a draw functor.
194     * See callDrawGLFunction() for instance.
195     *
196     * This command must not be recorded inside display lists.
197     */
198    virtual void interrupt();
199
200    /**
201     * This method must be invoked after getting control back from a draw functor.
202     *
203     * This command must not be recorded inside display lists.
204     */
205    virtual void resume();
206
207    ANDROID_API void setCountOverdrawEnabled(bool enabled) {
208        mCountOverdraw = enabled;
209    }
210
211    ANDROID_API float getOverdraw() {
212        return mCountOverdraw ? mOverdraw : 0.0f;
213    }
214
215    ANDROID_API status_t invokeFunctors(Rect& dirty);
216    ANDROID_API void detachFunctor(Functor* functor);
217    ANDROID_API void attachFunctor(Functor* functor);
218    virtual status_t callDrawGLFunction(Functor* functor, Rect& dirty);
219
220    ANDROID_API void pushLayerUpdate(Layer* layer);
221    ANDROID_API void clearLayerUpdates();
222    ANDROID_API void flushLayerUpdates();
223
224    ANDROID_API int getSaveCount() const;
225    virtual int save(int flags);
226    virtual void restore();
227    virtual void restoreToCount(int saveCount);
228
229    ANDROID_API int saveLayer(float left, float top, float right, float bottom,
230            SkPaint* paint, int flags) {
231        SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode;
232        if (paint) mode = getXfermode(paint->getXfermode());
233        return saveLayer(left, top, right, bottom, paint ? paint->getAlpha() : 255, mode, flags);
234    }
235    ANDROID_API int saveLayerAlpha(float left, float top, float right, float bottom,
236            int alpha, int flags) {
237        return saveLayer(left, top, right, bottom, alpha, SkXfermode::kSrcOver_Mode, flags);
238    }
239    virtual int saveLayer(float left, float top, float right, float bottom,
240            int alpha, SkXfermode::Mode mode, int flags);
241
242    int saveLayerDeferred(float left, float top, float right, float bottom,
243            int alpha, SkXfermode::Mode mode, int flags);
244
245    virtual void translate(float dx, float dy);
246    virtual void rotate(float degrees);
247    virtual void scale(float sx, float sy);
248    virtual void skew(float sx, float sy);
249
250    bool hasRectToRectTransform();
251    ANDROID_API void getMatrix(SkMatrix* matrix);
252    virtual void setMatrix(SkMatrix* matrix);
253    virtual void concatMatrix(SkMatrix* matrix);
254
255    ANDROID_API const Rect& getClipBounds();
256
257    /**
258     * Performs a quick reject but adjust the bounds to account for stroke width if necessary
259     */
260    bool quickRejectPreStroke(float left, float top, float right, float bottom, SkPaint* paint);
261
262    /**
263     * Returns false and sets scissor based upon bounds if drawing won't be clipped out
264     */
265    bool quickReject(float left, float top, float right, float bottom);
266    bool quickReject(const Rect& bounds) {
267        return quickReject(bounds.left, bounds.top, bounds.right, bounds.bottom);
268    }
269
270    /**
271     * Same as quickReject, without the scissor, instead returning clipRequired through pointer.
272     * clipRequired will be only set if not rejected
273     */
274    ANDROID_API bool quickRejectNoScissor(float left, float top, float right, float bottom,
275            bool* clipRequired = NULL);
276    bool quickRejectNoScissor(const Rect& bounds, bool* clipRequired = NULL) {
277        return quickRejectNoScissor(bounds.left, bounds.top, bounds.right, bounds.bottom,
278                clipRequired);
279    }
280
281    virtual bool clipRect(float left, float top, float right, float bottom, SkRegion::Op op);
282    virtual bool clipPath(SkPath* path, SkRegion::Op op);
283    virtual bool clipRegion(SkRegion* region, SkRegion::Op op);
284    virtual Rect* getClipRect();
285
286    virtual status_t drawDisplayList(DisplayList* displayList, Rect& dirty, int32_t replayFlags);
287    virtual void outputDisplayList(DisplayList* displayList);
288    virtual status_t drawLayer(Layer* layer, float x, float y);
289    virtual status_t drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint);
290    status_t drawBitmaps(SkBitmap* bitmap, int bitmapCount, TextureVertex* vertices,
291            bool transformed, const Rect& bounds, SkPaint* paint);
292    virtual status_t drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint);
293    virtual status_t drawBitmap(SkBitmap* bitmap, float srcLeft, float srcTop,
294            float srcRight, float srcBottom, float dstLeft, float dstTop,
295            float dstRight, float dstBottom, SkPaint* paint);
296    virtual status_t drawBitmapData(SkBitmap* bitmap, float left, float top, SkPaint* paint);
297    virtual status_t drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
298            float* vertices, int* colors, SkPaint* paint);
299    virtual status_t drawPatch(SkBitmap* bitmap, Res_png_9patch* patch,
300            float left, float top, float right, float bottom, SkPaint* paint);
301    status_t drawPatch(SkBitmap* bitmap, const Patch* mesh, AssetAtlas::Entry* entry,
302            float left, float top, float right, float bottom, int alpha, SkXfermode::Mode mode);
303    virtual status_t drawColor(int color, SkXfermode::Mode mode);
304    virtual status_t drawRect(float left, float top, float right, float bottom, SkPaint* paint);
305    virtual status_t drawRoundRect(float left, float top, float right, float bottom,
306            float rx, float ry, SkPaint* paint);
307    virtual status_t drawCircle(float x, float y, float radius, SkPaint* paint);
308    virtual status_t drawOval(float left, float top, float right, float bottom, SkPaint* paint);
309    virtual status_t drawArc(float left, float top, float right, float bottom,
310            float startAngle, float sweepAngle, bool useCenter, SkPaint* paint);
311    virtual status_t drawPath(SkPath* path, SkPaint* paint);
312    virtual status_t drawLines(float* points, int count, SkPaint* paint);
313    virtual status_t drawPoints(float* points, int count, SkPaint* paint);
314    virtual status_t drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
315            float hOffset, float vOffset, SkPaint* paint);
316    virtual status_t drawPosText(const char* text, int bytesCount, int count,
317            const float* positions, SkPaint* paint);
318    virtual status_t drawText(const char* text, int bytesCount, int count, float x, float y,
319            const float* positions, SkPaint* paint, float totalAdvance, const Rect& bounds,
320            DrawOpMode drawOpMode = kDrawOpMode_Immediate);
321    virtual status_t drawRects(const float* rects, int count, SkPaint* paint);
322
323    virtual void resetShader();
324    virtual void setupShader(SkiaShader* shader);
325
326    virtual void resetColorFilter();
327    virtual void setupColorFilter(SkiaColorFilter* filter);
328
329    virtual void resetShadow();
330    virtual void setupShadow(float radius, float dx, float dy, int color);
331
332    virtual void resetPaintFilter();
333    virtual void setupPaintFilter(int clearBits, int setBits);
334
335    // If this value is set to < 1.0, it overrides alpha set on layer (see drawBitmap, drawLayer)
336    void setOverrideLayerAlpha(float alpha) { mDrawModifiers.mOverrideLayerAlpha = alpha; }
337
338    SkPaint* filterPaint(SkPaint* paint);
339
340    bool storeDisplayState(DeferredDisplayState& state, int stateDeferFlags);
341    void restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore = false);
342    void setupMergedMultiDraw(const Rect* clipRect);
343
344    const DrawModifiers& getDrawModifiers() { return mDrawModifiers; }
345    void setDrawModifiers(const DrawModifiers& drawModifiers) { mDrawModifiers = drawModifiers; }
346
347    ANDROID_API bool isCurrentTransformSimple() {
348        return mSnapshot->transform->isSimple();
349    }
350
351    Caches& getCaches() {
352        return mCaches;
353    }
354
355    // simple rect clip
356    bool isCurrentClipSimple() {
357        return mSnapshot->clipRegion->isEmpty();
358    }
359
360    /**
361     * Scales the alpha on the current snapshot. This alpha value will be modulated
362     * with other alpha values when drawing primitives.
363     */
364    void scaleAlpha(float alpha) {
365        mSnapshot->alpha *= alpha;
366    }
367
368    /**
369     * Inserts a named event marker in the stream of GL commands.
370     */
371    void eventMark(const char* name) const;
372
373    /**
374     * Inserts a named group marker in the stream of GL commands. This marker
375     * can be used by tools to group commands into logical groups. A call to
376     * this method must always be followed later on by a call to endMark().
377     */
378    void startMark(const char* name) const;
379
380    /**
381     * Closes the last group marker opened by startMark().
382     */
383    void endMark() const;
384
385    /**
386     * Gets the alpha and xfermode out of a paint object. If the paint is null
387     * alpha will be 255 and the xfermode will be SRC_OVER. This method does
388     * not multiply the paint's alpha by the current snapshot's alpha, and does
389     * not replace the alpha with the overrideLayerAlpha
390     *
391     * @param paint The paint to extract values from
392     * @param alpha Where to store the resulting alpha
393     * @param mode Where to store the resulting xfermode
394     */
395    static inline void getAlphaAndModeDirect(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) {
396        *mode = getXfermodeDirect(paint);
397        *alpha = getAlphaDirect(paint);
398    }
399
400    static inline SkXfermode::Mode getXfermodeDirect(SkPaint* paint) {
401        if (!paint) return SkXfermode::kSrcOver_Mode;
402        return getXfermode(paint->getXfermode());
403    }
404
405    static inline int getAlphaDirect(SkPaint* paint) {
406        if (!paint) return 255;
407        return paint->getAlpha();
408    }
409
410    /**
411     * Return the best transform to use to rasterize text given a full
412     * transform matrix.
413     */
414    mat4 findBestFontTransform(const mat4& transform) const;
415
416#if DEBUG_MERGE_BEHAVIOR
417    void drawScreenSpaceColorRect(float left, float top, float right, float bottom, int color) {
418        mCaches.setScissorEnabled(false);
419
420        // should only be called outside of other draw ops, so stencil can only be in test state
421        bool stencilWasEnabled = mCaches.stencil.isTestEnabled();
422        mCaches.stencil.disable();
423
424        drawColorRect(left, top, right, bottom, color, SkXfermode::kSrcOver_Mode, true);
425
426        if (stencilWasEnabled) mCaches.stencil.enableTest();
427    }
428#endif
429
430protected:
431    /**
432     * Computes the projection matrix, initialize the first snapshot
433     * and stores the dimensions of the render target.
434     */
435    void initViewport(int width, int height);
436
437    /**
438     * Perform the setup specific to a frame. This method does not
439     * issue any OpenGL commands.
440     */
441    void setupFrameState(float left, float top, float right, float bottom, bool opaque);
442
443    /**
444     * Indicates the start of rendering. This method will setup the
445     * initial OpenGL state (viewport, clearing the buffer, etc.)
446     */
447    status_t startFrame();
448
449    /**
450     * Clears the underlying surface if needed.
451     */
452    virtual status_t clear(float left, float top, float right, float bottom, bool opaque);
453
454    /**
455     * Call this method after updating a layer during a drawing pass.
456     */
457    void resumeAfterLayer();
458
459    /**
460     * This method is called whenever a stencil buffer is required. Subclasses
461     * should override this method and call attachStencilBufferToLayer() on the
462     * appropriate layer(s).
463     */
464    virtual void ensureStencilBuffer();
465
466    /**
467     * Obtains a stencil render buffer (allocating it if necessary) and
468     * attaches it to the specified layer.
469     */
470    void attachStencilBufferToLayer(Layer* layer);
471
472    /**
473     * Compose the layer defined in the current snapshot with the layer
474     * defined by the previous snapshot.
475     *
476     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
477     *
478     * @param curent The current snapshot containing the layer to compose
479     * @param previous The previous snapshot to compose the current layer with
480     */
481    virtual void composeLayer(sp<Snapshot> current, sp<Snapshot> previous);
482
483    /**
484     * Marks the specified region as dirty at the specified bounds.
485     */
486    void dirtyLayerUnchecked(Rect& bounds, Region* region);
487
488    /**
489     * Returns the current snapshot.
490     */
491    sp<Snapshot> getSnapshot() const {
492        return mSnapshot;
493    }
494
495    /**
496     * Returns the region of the current layer.
497     */
498    virtual Region* getRegion() const {
499        return mSnapshot->region;
500    }
501
502    /**
503     * Indicates whether rendering is currently targeted at a layer.
504     */
505    virtual bool hasLayer() const {
506        return (mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region;
507    }
508
509    /**
510     * Returns the name of the FBO this renderer is rendering into.
511     */
512    virtual GLint getTargetFbo() const {
513        return 0;
514    }
515
516    /**
517     * Renders the specified layer as a textured quad.
518     *
519     * @param layer The layer to render
520     * @param rect The bounds of the layer
521     */
522    void drawTextureLayer(Layer* layer, const Rect& rect);
523
524    /**
525     * Gets the alpha and xfermode out of a paint object. If the paint is null
526     * alpha will be 255 and the xfermode will be SRC_OVER. Accounts for both
527     * snapshot alpha, and overrideLayerAlpha
528     *
529     * @param paint The paint to extract values from
530     * @param alpha Where to store the resulting alpha
531     * @param mode Where to store the resulting xfermode
532     */
533    inline void getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const;
534
535    /**
536     * Gets the alpha from a layer, accounting for snapshot alpha and overrideLayerAlpha
537     *
538     * @param layer The layer from which the alpha is extracted
539     */
540    inline float getLayerAlpha(Layer* layer) const;
541
542    /**
543     * Safely retrieves the mode from the specified xfermode. If the specified
544     * xfermode is null, the mode is assumed to be SkXfermode::kSrcOver_Mode.
545     */
546    static inline SkXfermode::Mode getXfermode(SkXfermode* mode) {
547        SkXfermode::Mode resultMode;
548        if (!SkXfermode::AsMode(mode, &resultMode)) {
549            resultMode = SkXfermode::kSrcOver_Mode;
550        }
551        return resultMode;
552    }
553
554    /**
555     * Set to true to suppress error checks at the end of a frame.
556     */
557    virtual bool suppressErrorChecks() const {
558        return false;
559    }
560
561private:
562    /**
563     * Discards the content of the framebuffer if supported by the driver.
564     * This method should be called at the beginning of a frame to optimize
565     * rendering on some tiler architectures.
566     */
567    void discardFramebuffer(float left, float top, float right, float bottom);
568
569    /**
570     * Ensures the state of the renderer is the same as the state of
571     * the GL context.
572     */
573    void syncState();
574
575    /**
576     * Tells the GPU what part of the screen is about to be redrawn.
577     * This method will use the clip rect that we started drawing the
578     * frame with.
579     * This method needs to be invoked every time getTargetFbo() is
580     * bound again.
581     */
582    void startTiling(const sp<Snapshot>& snapshot, bool opaque = false);
583
584    /**
585     * Tells the GPU what part of the screen is about to be redrawn.
586     * This method needs to be invoked every time getTargetFbo() is
587     * bound again.
588     */
589    void startTiling(const Rect& clip, int windowHeight, bool opaque = false);
590
591    /**
592     * Tells the GPU that we are done drawing the frame or that we
593     * are switching to another render target.
594     */
595    void endTiling();
596
597    /**
598     * Saves the current state of the renderer as a new snapshot.
599     * The new snapshot is saved in mSnapshot and the previous snapshot
600     * is linked from mSnapshot->previous.
601     *
602     * @param flags The save flags; see SkCanvas for more information
603     *
604     * @return The new save count. This value can be passed to #restoreToCount()
605     */
606    int saveSnapshot(int flags);
607
608    /**
609     * Restores the current snapshot; mSnapshot becomes mSnapshot->previous.
610     *
611     * @return True if the clip was modified.
612     */
613    bool restoreSnapshot();
614
615    /**
616     * Sets the clipping rectangle using glScissor. The clip is defined by
617     * the current snapshot's clipRect member.
618     */
619    void setScissorFromClip();
620
621    /**
622     * Sets the clipping region using the stencil buffer. The clip region
623     * is defined by the current snapshot's clipRegion member.
624     */
625    void setStencilFromClip();
626
627    /**
628     * Given the local bounds of the layer, calculates ...
629     */
630    void calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer);
631
632    /**
633     * Given the local bounds + clip of the layer, updates current snapshot's empty/invisible
634     */
635    void updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
636            bool fboLayer, int alpha);
637
638    /**
639     * Creates a new layer stored in the specified snapshot.
640     *
641     * @param snapshot The snapshot associated with the new layer
642     * @param left The left coordinate of the layer
643     * @param top The top coordinate of the layer
644     * @param right The right coordinate of the layer
645     * @param bottom The bottom coordinate of the layer
646     * @param alpha The translucency of the layer
647     * @param mode The blending mode of the layer
648     * @param flags The layer save flags
649     * @param previousFbo The name of the current framebuffer
650     *
651     * @return True if the layer was successfully created, false otherwise
652     */
653    bool createLayer(float left, float top, float right, float bottom,
654            int alpha, SkXfermode::Mode mode, int flags, GLuint previousFbo);
655
656    /**
657     * Creates a new layer stored in the specified snapshot as an FBO.
658     *
659     * @param layer The layer to store as an FBO
660     * @param snapshot The snapshot associated with the new layer
661     * @param bounds The bounds of the layer
662     * @param previousFbo The name of the current framebuffer
663     */
664    bool createFboLayer(Layer* layer, Rect& bounds, Rect& clip, GLuint previousFbo);
665
666    /**
667     * Compose the specified layer as a region.
668     *
669     * @param layer The layer to compose
670     * @param rect The layer's bounds
671     */
672    void composeLayerRegion(Layer* layer, const Rect& rect);
673
674    /**
675     * Compose the specified layer as a simple rectangle.
676     *
677     * @param layer The layer to compose
678     * @param rect The layer's bounds
679     * @param swap If true, the source and destination are swapped
680     */
681    void composeLayerRect(Layer* layer, const Rect& rect, bool swap = false);
682
683    /**
684     * Clears all the regions corresponding to the current list of layers.
685     * This method MUST be invoked before any drawing operation.
686     */
687    void clearLayerRegions();
688
689    /**
690     * Mark the layer as dirty at the specified coordinates. The coordinates
691     * are transformed with the supplied matrix.
692     */
693    void dirtyLayer(const float left, const float top,
694            const float right, const float bottom, const mat4 transform);
695
696    /**
697     * Mark the layer as dirty at the specified coordinates.
698     */
699    void dirtyLayer(const float left, const float top,
700            const float right, const float bottom);
701
702    /**
703     * Draws a colored rectangle with the specified color. The specified coordinates
704     * are transformed by the current snapshot's transform matrix unless specified
705     * otherwise.
706     *
707     * @param left The left coordinate of the rectangle
708     * @param top The top coordinate of the rectangle
709     * @param right The right coordinate of the rectangle
710     * @param bottom The bottom coordinate of the rectangle
711     * @param color The rectangle's ARGB color, defined as a packed 32 bits word
712     * @param mode The Skia xfermode to use
713     * @param ignoreTransform True if the current transform should be ignored
714     */
715    void drawColorRect(float left, float top, float right, float bottom,
716            int color, SkXfermode::Mode mode, bool ignoreTransform = false);
717
718    /**
719     * Draws a series of colored rectangles with the specified color. The specified
720     * coordinates are transformed by the current snapshot's transform matrix unless
721     * specified otherwise.
722     *
723     * @param rects A list of rectangles, 4 floats (left, top, right, bottom)
724     *              per rectangle
725     * @param color The rectangles' ARGB color, defined as a packed 32 bits word
726     * @param mode The Skia xfermode to use
727     * @param ignoreTransform True if the current transform should be ignored
728     * @param dirty True if calling this method should dirty the current layer
729     * @param clip True if the rects should be clipped, false otherwise
730     */
731    status_t drawColorRects(const float* rects, int count, int color,
732            SkXfermode::Mode mode, bool ignoreTransform = false,
733            bool dirty = true, bool clip = true);
734
735    /**
736     * Draws the shape represented by the specified path texture.
737     * This method invokes drawPathTexture() but takes into account
738     * the extra left/top offset and the texture offset to correctly
739     * position the final shape.
740     *
741     * @param left The left coordinate of the shape to render
742     * @param top The top coordinate of the shape to render
743     * @param texture The texture reprsenting the shape
744     * @param paint The paint to draw the shape with
745     */
746    status_t drawShape(float left, float top, const PathTexture* texture, SkPaint* paint);
747
748    /**
749     * Draws the specified texture as an alpha bitmap. Alpha bitmaps obey
750     * different compositing rules.
751     *
752     * @param texture The texture to draw with
753     * @param left The x coordinate of the bitmap
754     * @param top The y coordinate of the bitmap
755     * @param paint The paint to render with
756     */
757    void drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint);
758
759    /**
760     * Renders a strip of polygons with the specified paint, used for tessellated geometry.
761     *
762     * @param vertexBuffer The VertexBuffer to be drawn
763     * @param paint The paint to render with
764     * @param useOffset Offset the vertexBuffer (used in drawing non-AA lines)
765     */
766    status_t drawVertexBuffer(const VertexBuffer& vertexBuffer, SkPaint* paint,
767            bool useOffset = false);
768
769    /**
770     * Renders the convex hull defined by the specified path as a strip of polygons.
771     *
772     * @param path The hull of the path to draw
773     * @param paint The paint to render with
774     */
775    status_t drawConvexPath(const SkPath& path, SkPaint* paint);
776
777    /**
778     * Draws a textured rectangle with the specified texture. The specified coordinates
779     * are transformed by the current snapshot's transform matrix.
780     *
781     * @param left The left coordinate of the rectangle
782     * @param top The top coordinate of the rectangle
783     * @param right The right coordinate of the rectangle
784     * @param bottom The bottom coordinate of the rectangle
785     * @param texture The texture name to map onto the rectangle
786     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
787     * @param mode The blending mode
788     * @param blend True if the texture contains an alpha channel
789     */
790    void drawTextureRect(float left, float top, float right, float bottom, GLuint texture,
791            float alpha, SkXfermode::Mode mode, bool blend);
792
793    /**
794     * Draws a textured rectangle with the specified texture. The specified coordinates
795     * are transformed by the current snapshot's transform matrix.
796     *
797     * @param left The left coordinate of the rectangle
798     * @param top The top coordinate of the rectangle
799     * @param right The right coordinate of the rectangle
800     * @param bottom The bottom coordinate of the rectangle
801     * @param texture The texture to use
802     * @param paint The paint containing the alpha, blending mode, etc.
803     */
804    void drawTextureRect(float left, float top, float right, float bottom,
805            Texture* texture, SkPaint* paint);
806
807    /**
808     * Draws a textured mesh with the specified texture. If the indices are omitted,
809     * the mesh is drawn as a simple quad. The mesh pointers become offsets when a
810     * VBO is bound.
811     *
812     * @param left The left coordinate of the rectangle
813     * @param top The top coordinate of the rectangle
814     * @param right The right coordinate of the rectangle
815     * @param bottom The bottom coordinate of the rectangle
816     * @param texture The texture name to map onto the rectangle
817     * @param alpha An additional translucency parameter, between 0.0f and 1.0f
818     * @param mode The blending mode
819     * @param blend True if the texture contains an alpha channel
820     * @param vertices The vertices that define the mesh
821     * @param texCoords The texture coordinates of each vertex
822     * @param elementsCount The number of elements in the mesh, required by indices
823     * @param swapSrcDst Whether or not the src and dst blending operations should be swapped
824     * @param ignoreTransform True if the current transform should be ignored
825     * @param vbo The VBO used to draw the mesh
826     * @param ignoreScale True if the model view matrix should not be scaled
827     * @param dirty True if calling this method should dirty the current layer
828     */
829    void drawTextureMesh(float left, float top, float right, float bottom, GLuint texture,
830            float alpha, SkXfermode::Mode mode, bool blend,
831            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
832            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
833            bool ignoreScale = false, bool dirty = true);
834
835    void drawIndexedTextureMesh(float left, float top, float right, float bottom, GLuint texture,
836            float alpha, SkXfermode::Mode mode, bool blend,
837            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
838            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
839            bool ignoreScale = false, bool dirty = true);
840
841    void drawAlpha8TextureMesh(float left, float top, float right, float bottom,
842            GLuint texture, bool hasColor, int color, int alpha, SkXfermode::Mode mode,
843            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
844            bool ignoreTransform, bool ignoreScale = false, bool dirty = true);
845
846    /**
847     * Draws text underline and strike-through if needed.
848     *
849     * @param text The text to decor
850     * @param bytesCount The number of bytes in the text
851     * @param totalAdvance The total advance in pixels, defines underline/strikethrough length
852     * @param x The x coordinate where the text will be drawn
853     * @param y The y coordinate where the text will be drawn
854     * @param paint The paint to draw the text with
855     */
856    void drawTextDecorations(const char* text, int bytesCount, float totalAdvance,
857            float x, float y, SkPaint* paint);
858
859   /**
860     * Draws shadow layer on text (with optional positions).
861     *
862     * @param paint The paint to draw the shadow with
863     * @param text The text to draw
864     * @param bytesCount The number of bytes in the text
865     * @param count The number of glyphs in the text
866     * @param positions The x, y positions of individual glyphs (or NULL)
867     * @param fontRenderer The font renderer object
868     * @param alpha The alpha value for drawing the shadow
869     * @param mode The xfermode for drawing the shadow
870     * @param x The x coordinate where the shadow will be drawn
871     * @param y The y coordinate where the shadow will be drawn
872     */
873    void drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count,
874            const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode,
875            float x, float y);
876
877    /**
878     * Draws a path texture. Path textures are alpha8 bitmaps that need special
879     * compositing to apply colors/filters/etc.
880     *
881     * @param texture The texture to render
882     * @param x The x coordinate where the texture will be drawn
883     * @param y The y coordinate where the texture will be drawn
884     * @param paint The paint to draw the texture with
885     */
886     void drawPathTexture(const PathTexture* texture, float x, float y, SkPaint* paint);
887
888    /**
889     * Resets the texture coordinates stored in mMeshVertices. Setting the values
890     * back to default is achieved by calling:
891     *
892     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
893     *
894     * @param u1 The left coordinate of the texture
895     * @param v1 The bottom coordinate of the texture
896     * @param u2 The right coordinate of the texture
897     * @param v2 The top coordinate of the texture
898     */
899    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
900
901    /**
902     * Returns true if the specified paint will draw invisible text.
903     */
904    bool canSkipText(const SkPaint* paint) const;
905
906    /**
907     * Binds the specified texture. The texture unit must have been selected
908     * prior to calling this method.
909     */
910    inline void bindTexture(GLuint texture) {
911        mCaches.bindTexture(texture);
912    }
913
914    /**
915     * Binds the specified EGLImage texture. The texture unit must have been selected
916     * prior to calling this method.
917     */
918    inline void bindExternalTexture(GLuint texture) {
919        mCaches.bindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
920    }
921
922    /**
923     * Enable or disable blending as necessary. This function sets the appropriate
924     * blend function based on the specified xfermode.
925     */
926    inline void chooseBlending(bool blend, SkXfermode::Mode mode, ProgramDescription& description,
927            bool swapSrcDst = false);
928
929    /**
930     * Use the specified program with the current GL context. If the program is already
931     * in use, it will not be bound again. If it is not in use, the current program is
932     * marked unused and the specified program becomes used and becomes the new
933     * current program.
934     *
935     * @param program The program to use
936     *
937     * @return true If the specified program was already in use, false otherwise.
938     */
939    inline bool useProgram(Program* program);
940
941    /**
942     * Invoked before any drawing operation. This sets required state.
943     */
944    void setupDraw(bool clear = true);
945
946    /**
947     * Various methods to setup OpenGL rendering.
948     */
949    void setupDrawWithTexture(bool isAlpha8 = false);
950    void setupDrawWithTextureAndColor(bool isAlpha8 = false);
951    void setupDrawWithExternalTexture();
952    void setupDrawNoTexture();
953    void setupDrawAA();
954    void setupDrawColor(int color, int alpha);
955    void setupDrawColor(float r, float g, float b, float a);
956    void setupDrawAlpha8Color(int color, int alpha);
957    void setupDrawTextGamma(const SkPaint* paint);
958    void setupDrawShader();
959    void setupDrawColorFilter();
960    void setupDrawBlending(SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode,
961            bool swapSrcDst = false);
962    void setupDrawBlending(bool blend = true, SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode,
963            bool swapSrcDst = false);
964    void setupDrawProgram();
965    void setupDrawDirtyRegionsDisabled();
966    void setupDrawModelViewIdentity(bool offset = false);
967    void setupDrawModelView(float left, float top, float right, float bottom,
968            bool ignoreTransform = false, bool ignoreModelView = false);
969    void setupDrawModelViewTranslate(float left, float top, float right, float bottom,
970            bool ignoreTransform = false);
971    void setupDrawColorUniforms();
972    void setupDrawPureColorUniforms();
973    void setupDrawShaderIdentityUniforms();
974    void setupDrawShaderUniforms(bool ignoreTransform = false);
975    void setupDrawColorFilterUniforms();
976    void setupDrawSimpleMesh();
977    void setupDrawTexture(GLuint texture);
978    void setupDrawExternalTexture(GLuint texture);
979    void setupDrawTextureTransform();
980    void setupDrawTextureTransformUniforms(mat4& transform);
981    void setupDrawTextGammaUniforms();
982    void setupDrawMesh(GLvoid* vertices, GLvoid* texCoords = NULL, GLuint vbo = 0);
983    void setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLvoid* colors);
984    void setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords, GLuint vbo = 0);
985    void setupDrawVertices(GLvoid* vertices);
986    void finishDrawTexture();
987    void accountForClear(SkXfermode::Mode mode);
988
989    bool updateLayer(Layer* layer, bool inFrame);
990    void updateLayers();
991    void flushLayers();
992
993    /**
994     * Renders the specified region as a series of rectangles. This method
995     * is used for debugging only.
996     */
997    void drawRegionRects(const Region& region);
998
999    /**
1000     * Renders the specified region as a series of rectangles. The region
1001     * must be in screen-space coordinates.
1002     */
1003    void drawRegionRects(const SkRegion& region, int color, SkXfermode::Mode mode,
1004            bool dirty = false);
1005
1006    /**
1007     * Draws the current clip region if any. Only when DEBUG_CLIP_REGIONS
1008     * is turned on.
1009     */
1010    void debugClip();
1011
1012    void debugOverdraw(bool enable, bool clear);
1013    void renderOverdraw();
1014    void countOverdraw();
1015
1016    /**
1017     * Should be invoked every time the glScissor is modified.
1018     */
1019    inline void dirtyClip() {
1020        mDirtyClip = true;
1021    }
1022
1023    inline mat4& currentTransform() const {
1024        return *mSnapshot->transform;
1025    }
1026
1027    inline const UvMapper& getMapper(const Texture* texture) {
1028        return texture && texture->uvMapper ? *texture->uvMapper : mUvMapper;
1029    }
1030
1031    /**
1032     * Returns a texture object for the specified bitmap. The texture can
1033     * come from the texture cache or an atlas. If this method returns
1034     * NULL, the texture could not be found and/or allocated.
1035     */
1036    Texture* getTexture(SkBitmap* bitmap);
1037
1038    // Dimensions of the drawing surface
1039    int mWidth, mHeight;
1040
1041    // Matrix used for ortho projection in shaders
1042    mat4 mOrthoMatrix;
1043
1044    // Model-view matrix used to position/size objects
1045    mat4 mModelView;
1046
1047    // Number of saved states
1048    int mSaveCount;
1049    // Base state
1050    sp<Snapshot> mFirstSnapshot;
1051    // Current state
1052    sp<Snapshot> mSnapshot;
1053    // State used to define the clipping region
1054    Rect mTilingClip;
1055    // Is the target render surface opaque
1056    bool mOpaque;
1057    // Is a frame currently being rendered
1058    bool mFrameStarted;
1059
1060    // Used to draw textured quads
1061    TextureVertex mMeshVertices[4];
1062
1063    // Default UV mapper
1064    const UvMapper mUvMapper;
1065
1066    // shader, filters, and shadow
1067    DrawModifiers mDrawModifiers;
1068    SkPaint mFilteredPaint;
1069
1070    // Various caches
1071    Caches& mCaches;
1072    Extensions& mExtensions;
1073
1074    // List of rectangles to clear after saveLayer() is invoked
1075    Vector<Rect*> mLayers;
1076    // List of functors to invoke after a frame is drawn
1077    SortedVector<Functor*> mFunctors;
1078    // List of layers to update at the beginning of a frame
1079    Vector<Layer*> mLayerUpdates;
1080
1081    // Indicates whether the clip must be restored
1082    bool mDirtyClip;
1083
1084    // The following fields are used to setup drawing
1085    // Used to describe the shaders to generate
1086    ProgramDescription mDescription;
1087    // Color description
1088    bool mColorSet;
1089    float mColorA, mColorR, mColorG, mColorB;
1090    // Indicates that the shader should get a color
1091    bool mSetShaderColor;
1092    // Current texture unit
1093    GLuint mTextureUnit;
1094    // Track dirty regions, true by default
1095    bool mTrackDirtyRegions;
1096    // Indicate whether we are drawing an opaque frame
1097    bool mOpaqueFrame;
1098
1099    // See PROPERTY_DISABLE_SCISSOR_OPTIMIZATION in
1100    // Properties.h
1101    bool mScissorOptimizationDisabled;
1102
1103    // No-ops start/endTiling when set
1104    bool mSuppressTiling;
1105
1106    // If true, this renderer will setup drawing to emulate
1107    // an increment stencil buffer in the color buffer
1108    bool mCountOverdraw;
1109    float mOverdraw;
1110
1111    // Optional name of the renderer
1112    String8 mName;
1113
1114    friend class DisplayListRenderer;
1115    friend class Layer;
1116    friend class TextSetupFunctor;
1117
1118}; // class OpenGLRenderer
1119
1120}; // namespace uirenderer
1121}; // namespace android
1122
1123#endif // ANDROID_HWUI_OPENGL_RENDERER_H
1124