OpenGLRenderer.h revision 8df5ffa9ae0667d9e0241adf4675753156fcef84
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 "CanvasState.h"
21#include "Debug.h"
22#include "Extensions.h"
23#include "Matrix.h"
24#include "Program.h"
25#include "Rect.h"
26#include "Snapshot.h"
27#include "UvMapper.h"
28#include "Vertex.h"
29#include "Caches.h"
30#include "utils/PaintUtils.h"
31
32#include <GLES2/gl2.h>
33#include <GLES2/gl2ext.h>
34
35#include <SkBitmap.h>
36#include <SkCanvas.h>
37#include <SkColorFilter.h>
38#include <SkMatrix.h>
39#include <SkPaint.h>
40#include <SkRegion.h>
41#include <SkXfermode.h>
42
43#include <utils/Blur.h>
44#include <utils/Functor.h>
45#include <utils/RefBase.h>
46#include <utils/SortedVector.h>
47#include <utils/Vector.h>
48
49#include <cutils/compiler.h>
50
51#include <androidfw/ResourceTypes.h>
52
53class SkShader;
54
55namespace android {
56namespace uirenderer {
57
58enum class DrawOpMode {
59    kImmediate,
60    kDefer,
61    kFlush
62};
63
64class DeferredDisplayState;
65struct Glop;
66class RenderState;
67class RenderNode;
68class TextDrawFunctor;
69class VertexBuffer;
70
71enum StateDeferFlags {
72    kStateDeferFlag_Draw = 0x1,
73    kStateDeferFlag_Clip = 0x2
74};
75
76enum ClipSideFlags {
77    kClipSide_None = 0x0,
78    kClipSide_Left = 0x1,
79    kClipSide_Top = 0x2,
80    kClipSide_Right = 0x4,
81    kClipSide_Bottom = 0x8,
82    kClipSide_Full = 0xF,
83    kClipSide_ConservativeFull = 0x1F
84};
85
86enum VertexBufferDisplayFlags {
87    kVertexBuffer_Offset = 0x1,
88    kVertexBuffer_ShadowInterp = 0x2,
89};
90
91/**
92 * Defines additional transformation that should be applied by the model view matrix, beyond that of
93 * the currentTransform()
94 */
95enum ModelViewMode {
96    /**
97     * Used when the model view should simply translate geometry passed to the shader. The resulting
98     * matrix will be a simple translation.
99     */
100    kModelViewMode_Translate = 0,
101
102    /**
103     * Used when the model view should translate and scale geometry. The resulting matrix will be a
104     * translation + scale. This is frequently used together with VBO 0, the (0,0,1,1) rect.
105     */
106    kModelViewMode_TranslateAndScale = 1,
107};
108
109///////////////////////////////////////////////////////////////////////////////
110// Renderer
111///////////////////////////////////////////////////////////////////////////////
112/**
113 * OpenGL Renderer implementation.
114 */
115class OpenGLRenderer : public CanvasStateClient {
116public:
117    OpenGLRenderer(RenderState& renderState);
118    virtual ~OpenGLRenderer();
119
120    /**
121     * Sets the dimension of the underlying drawing surface. This method must
122     * be called at least once every time the drawing surface changes size.
123     *
124     * @param width The width in pixels of the underlysing surface
125     * @param height The height in pixels of the underlysing surface
126     */
127    void setViewport(int width, int height) { mState.setViewport(width, height); }
128
129    void initProperties();
130    void initLight(const Vector3& lightCenter, float lightRadius,
131            uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
132
133    /*
134     * Prepares the renderer to draw a frame. This method must be invoked
135     * at the beginning of each frame. Only the specified rectangle of the
136     * frame is assumed to be dirty. A clip will automatically be set to
137     * the specified rectangle.
138     *
139     * @param opaque If true, the target surface is considered opaque
140     *               and will not be cleared. If false, the target surface
141     *               will be cleared
142     */
143    virtual void prepareDirty(float left, float top, float right, float bottom,
144            bool opaque);
145
146    /**
147     * Prepares the renderer to draw a frame. This method must be invoked
148     * at the beginning of each frame. When this method is invoked, the
149     * entire drawing surface is assumed to be redrawn.
150     *
151     * @param opaque If true, the target surface is considered opaque
152     *               and will not be cleared. If false, the target surface
153     *               will be cleared
154     */
155    void prepare(bool opaque) {
156        prepareDirty(0.0f, 0.0f, mState.getWidth(), mState.getHeight(), opaque);
157    }
158
159    /**
160     * Indicates the end of a frame. This method must be invoked whenever
161     * the caller is done rendering a frame.
162     * Returns true if any drawing was done during the frame (the output
163     * has changed / is "dirty" and should be displayed to the user).
164     */
165    virtual bool finish();
166
167    void callDrawGLFunction(Functor* functor, Rect& dirty);
168
169    void pushLayerUpdate(Layer* layer);
170    void cancelLayerUpdate(Layer* layer);
171    void flushLayerUpdates();
172    void markLayersAsBuildLayers();
173
174    virtual int saveLayer(float left, float top, float right, float bottom,
175            const SkPaint* paint, int flags) {
176        return saveLayer(left, top, right, bottom, paint, flags, nullptr);
177    }
178
179    // Specialized saveLayer implementation, which will pass the convexMask to an FBO layer, if
180    // created, which will in turn clip to that mask when drawn back/restored.
181    int saveLayer(float left, float top, float right, float bottom,
182            const SkPaint* paint, int flags, const SkPath* convexMask);
183
184    int saveLayerDeferred(float left, float top, float right, float bottom,
185            const SkPaint* paint, int flags);
186
187    void drawRenderNode(RenderNode* displayList, Rect& dirty, int32_t replayFlags = 1);
188    void drawLayer(Layer* layer, float x, float y);
189    void drawBitmap(const SkBitmap* bitmap, const SkPaint* paint);
190    void drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, int bitmapCount,
191            TextureVertex* vertices, bool pureTranslate, const Rect& bounds, const SkPaint* paint);
192    void drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst,
193            const SkPaint* paint);
194    void drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
195            const float* vertices, const int* colors, const SkPaint* paint);
196    void drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
197            TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint);
198    void drawPatch(const SkBitmap* bitmap, const Patch* mesh, AssetAtlas::Entry* entry,
199            float left, float top, float right, float bottom, const SkPaint* paint);
200    void drawColor(int color, SkXfermode::Mode mode);
201    void drawRect(float left, float top, float right, float bottom,
202            const SkPaint* paint);
203    void drawRoundRect(float left, float top, float right, float bottom,
204            float rx, float ry, const SkPaint* paint);
205    void drawCircle(float x, float y, float radius, const SkPaint* paint);
206    void drawOval(float left, float top, float right, float bottom,
207            const SkPaint* paint);
208    void drawArc(float left, float top, float right, float bottom,
209            float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint);
210    void drawPath(const SkPath* path, const SkPaint* paint);
211    void drawLines(const float* points, int count, const SkPaint* paint);
212    void drawPoints(const float* points, int count, const SkPaint* paint);
213    void drawTextOnPath(const char* text, int bytesCount, int count, const SkPath* path,
214            float hOffset, float vOffset, const SkPaint* paint);
215    void drawPosText(const char* text, int bytesCount, int count,
216            const float* positions, const SkPaint* paint);
217    void drawText(const char* text, int bytesCount, int count, float x, float y,
218            const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
219            DrawOpMode drawOpMode = DrawOpMode::kImmediate);
220    void drawRects(const float* rects, int count, const SkPaint* paint);
221
222    void drawShadow(float casterAlpha,
223            const VertexBuffer* ambientShadowVertexBuffer,
224            const VertexBuffer* spotShadowVertexBuffer);
225
226    void setDrawFilter(SkDrawFilter* filter);
227
228    /**
229     * Store the current display state (most importantly, the current clip and transform), and
230     * additionally map the state's bounds from local to window coordinates.
231     *
232     * Returns true if quick-rejected
233     */
234    bool storeDisplayState(DeferredDisplayState& state, int stateDeferFlags);
235    void restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore = false);
236    void setupMergedMultiDraw(const Rect* clipRect);
237
238    bool isCurrentTransformSimple() {
239        return currentTransform()->isSimple();
240    }
241
242    Caches& getCaches() {
243        return mCaches;
244    }
245
246    RenderState& renderState() {
247        return mRenderState;
248    }
249
250    int getViewportWidth() { return mState.getViewportWidth(); }
251    int getViewportHeight() { return mState.getViewportHeight(); }
252
253    /**
254     * Scales the alpha on the current snapshot. This alpha value will be modulated
255     * with other alpha values when drawing primitives.
256     */
257    void scaleAlpha(float alpha) { mState.scaleAlpha(alpha); }
258
259    /**
260     * Inserts a named event marker in the stream of GL commands.
261     */
262    void eventMark(const char* name) const;
263
264    /**
265     * Inserts a formatted event marker in the stream of GL commands.
266     */
267    void eventMarkDEBUG(const char *fmt, ...) const;
268
269    /**
270     * Inserts a named group marker in the stream of GL commands. This marker
271     * can be used by tools to group commands into logical groups. A call to
272     * this method must always be followed later on by a call to endMark().
273     */
274    void startMark(const char* name) const;
275
276    /**
277     * Closes the last group marker opened by startMark().
278     */
279    void endMark() const;
280
281    /**
282     * Gets the alpha and xfermode out of a paint object. If the paint is null
283     * alpha will be 255 and the xfermode will be SRC_OVER. This method does
284     * not multiply the paint's alpha by the current snapshot's alpha, and does
285     * not replace the alpha with the overrideLayerAlpha
286     *
287     * @param paint The paint to extract values from
288     * @param alpha Where to store the resulting alpha
289     * @param mode Where to store the resulting xfermode
290     */
291    static inline void getAlphaAndModeDirect(const SkPaint* paint, int* alpha,
292            SkXfermode::Mode* mode) {
293        *mode = getXfermodeDirect(paint);
294        *alpha = getAlphaDirect(paint);
295    }
296
297    static inline SkXfermode::Mode getXfermodeDirect(const SkPaint* paint) {
298        if (!paint) return SkXfermode::kSrcOver_Mode;
299        return PaintUtils::getXfermode(paint->getXfermode());
300    }
301
302    static inline int getAlphaDirect(const SkPaint* paint) {
303        if (!paint) return 255;
304        return paint->getAlpha();
305    }
306
307    struct TextShadow {
308        SkScalar radius;
309        float dx;
310        float dy;
311        SkColor color;
312    };
313
314    static inline bool getTextShadow(const SkPaint* paint, TextShadow* textShadow) {
315        SkDrawLooper::BlurShadowRec blur;
316        if (paint && paint->getLooper() && paint->getLooper()->asABlurShadow(&blur)) {
317            if (textShadow) {
318                textShadow->radius = Blur::convertSigmaToRadius(blur.fSigma);
319                textShadow->dx = blur.fOffset.fX;
320                textShadow->dy = blur.fOffset.fY;
321                textShadow->color = blur.fColor;
322            }
323            return true;
324        }
325        return false;
326    }
327
328    static inline bool hasTextShadow(const SkPaint* paint) {
329        return getTextShadow(paint, nullptr);
330    }
331
332    /**
333     * Build the best transform to use to rasterize text given a full
334     * transform matrix, and whether filteration is needed.
335     *
336     * Returns whether filtration is needed
337     */
338    bool findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const;
339
340#if DEBUG_MERGE_BEHAVIOR
341    void drawScreenSpaceColorRect(float left, float top, float right, float bottom, int color) {
342        mCaches.setScissorEnabled(false);
343
344        // should only be called outside of other draw ops, so stencil can only be in test state
345        bool stencilWasEnabled = mCaches.stencil.isTestEnabled();
346        mCaches.stencil.disable();
347
348        drawColorRect(left, top, right, bottom, color, SkXfermode::kSrcOver_Mode, true);
349
350        if (stencilWasEnabled) mCaches.stencil.enableTest();
351        mDirty = true;
352    }
353#endif
354
355    const Vector3& getLightCenter() const { return mState.currentLightCenter(); }
356    float getLightRadius() const { return mLightRadius; }
357    uint8_t getAmbientShadowAlpha() const { return mAmbientShadowAlpha; }
358    uint8_t getSpotShadowAlpha() const { return mSpotShadowAlpha; }
359
360    ///////////////////////////////////////////////////////////////////
361    /// State manipulation
362
363    int getSaveCount() const;
364    int save(int flags);
365    void restore();
366    void restoreToCount(int saveCount);
367
368    void getMatrix(SkMatrix* outMatrix) const { mState.getMatrix(outMatrix); }
369    void setMatrix(const SkMatrix& matrix) { mState.setMatrix(matrix); }
370    void concatMatrix(const SkMatrix& matrix) { mState.concatMatrix(matrix); }
371
372    void translate(float dx, float dy, float dz = 0.0f);
373    void rotate(float degrees);
374    void scale(float sx, float sy);
375    void skew(float sx, float sy);
376
377    void setMatrix(const Matrix4& matrix); // internal only convenience method
378    void concatMatrix(const Matrix4& matrix); // internal only convenience method
379
380    const Rect& getLocalClipBounds() const { return mState.getLocalClipBounds(); }
381    const Rect& getRenderTargetClipBounds() const { return mState.getRenderTargetClipBounds(); }
382    bool quickRejectConservative(float left, float top,
383            float right, float bottom) const {
384        return mState.quickRejectConservative(left, top, right, bottom);
385    }
386
387    bool clipRect(float left, float top,
388            float right, float bottom, SkRegion::Op op);
389    bool clipPath(const SkPath* path, SkRegion::Op op);
390    bool clipRegion(const SkRegion* region, SkRegion::Op op);
391
392    /**
393     * Does not support different clipping Ops (that is, every call to setClippingOutline is
394     * effectively using SkRegion::kReplaceOp)
395     *
396     * The clipping outline is independent from the regular clip.
397     */
398    void setClippingOutline(LinearAllocator& allocator, const Outline* outline);
399    void setClippingRoundRect(LinearAllocator& allocator,
400            const Rect& rect, float radius, bool highPriority = true);
401
402    inline bool hasRectToRectTransform() const { return mState.hasRectToRectTransform(); }
403    inline const mat4* currentTransform() const { return mState.currentTransform(); }
404
405    ///////////////////////////////////////////////////////////////////
406    /// CanvasStateClient interface
407
408    virtual void onViewportInitialized() override;
409    virtual void onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) override;
410    virtual GLuint getTargetFbo() const override { return 0; }
411
412    SkPath* allocPathForFrame() {
413        std::unique_ptr<SkPath> path(new SkPath());
414        SkPath* returnPath = path.get();
415        mTempPaths.push_back(std::move(path));
416        return returnPath;
417    }
418
419protected:
420    /**
421     * Perform the setup specific to a frame. This method does not
422     * issue any OpenGL commands.
423     */
424    void setupFrameState(float left, float top, float right, float bottom, bool opaque);
425
426    /**
427     * Indicates the start of rendering. This method will setup the
428     * initial OpenGL state (viewport, clearing the buffer, etc.)
429     */
430    void startFrame();
431
432    /**
433     * Clears the underlying surface if needed.
434     */
435    virtual void clear(float left, float top, float right, float bottom, bool opaque);
436
437    /**
438     * Call this method after updating a layer during a drawing pass.
439     */
440    void resumeAfterLayer();
441
442    /**
443     * This method is called whenever a stencil buffer is required. Subclasses
444     * should override this method and call attachStencilBufferToLayer() on the
445     * appropriate layer(s).
446     */
447    virtual void ensureStencilBuffer();
448
449    /**
450     * Obtains a stencil render buffer (allocating it if necessary) and
451     * attaches it to the specified layer.
452     */
453    void attachStencilBufferToLayer(Layer* layer);
454
455    /**
456     * Draw a rectangle list. Currently only used for the the stencil buffer so that the stencil
457     * will have a value of 'n' in every unclipped pixel, where 'n' is the number of rectangles
458     * in the list.
459     */
460    void drawRectangleList(const RectangleList& rectangleList);
461
462    bool quickRejectSetupScissor(float left, float top, float right, float bottom,
463            const SkPaint* paint = nullptr);
464    bool quickRejectSetupScissor(const Rect& bounds, const SkPaint* paint = nullptr) {
465        return quickRejectSetupScissor(bounds.left, bounds.top,
466                bounds.right, bounds.bottom, paint);
467    }
468
469    /**
470     * Compose the layer defined in the current snapshot with the layer
471     * defined by the previous snapshot.
472     *
473     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
474     *
475     * @param curent The current snapshot containing the layer to compose
476     * @param previous The previous snapshot to compose the current layer with
477     */
478    virtual void composeLayer(const Snapshot& current, const Snapshot& previous);
479
480    /**
481     * Marks the specified region as dirty at the specified bounds.
482     */
483    void dirtyLayerUnchecked(Rect& bounds, Region* region);
484
485    /**
486     * Returns the region of the current layer.
487     */
488    virtual Region* getRegion() const {
489        return mState.currentRegion();
490    }
491
492    /**
493     * Indicates whether rendering is currently targeted at a layer.
494     */
495    virtual bool hasLayer() const {
496        return (mState.currentFlags() & Snapshot::kFlagFboTarget) && mState.currentRegion();
497    }
498
499    /**
500     * Renders the specified layer as a textured quad.
501     *
502     * @param layer The layer to render
503     * @param rect The bounds of the layer
504     */
505    void drawTextureLayer(Layer* layer, const Rect& rect);
506
507    /**
508     * Gets the alpha and xfermode out of a paint object. If the paint is null
509     * alpha will be 255 and the xfermode will be SRC_OVER. Accounts for snapshot alpha.
510     *
511     * @param paint The paint to extract values from
512     * @param alpha Where to store the resulting alpha
513     * @param mode Where to store the resulting xfermode
514     */
515    inline void getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const;
516
517    /**
518     * Gets the alpha from a layer, accounting for snapshot alpha
519     *
520     * @param layer The layer from which the alpha is extracted
521     */
522    inline float getLayerAlpha(const Layer* layer) const;
523
524    /**
525     * Safely retrieves the ColorFilter from the given Paint. If the paint is
526     * null then null is returned.
527     */
528    static inline SkColorFilter* getColorFilter(const SkPaint* paint) {
529        return paint ? paint->getColorFilter() : nullptr;
530    }
531
532    /**
533     * Safely retrieves the Shader from the given Paint. If the paint is
534     * null then null is returned.
535     */
536    static inline const SkShader* getShader(const SkPaint* paint) {
537        return paint ? paint->getShader() : nullptr;
538    }
539
540    /**
541     * Set to true to suppress error checks at the end of a frame.
542     */
543    virtual bool suppressErrorChecks() const {
544        return false;
545    }
546
547    CanvasState mState;
548    Caches& mCaches;
549    RenderState& mRenderState;
550
551private:
552    void renderGlop(const Glop& glop, bool clearLayer = true);
553
554    /**
555     * Discards the content of the framebuffer if supported by the driver.
556     * This method should be called at the beginning of a frame to optimize
557     * rendering on some tiler architectures.
558     */
559    void discardFramebuffer(float left, float top, float right, float bottom);
560
561    /**
562     * Tells the GPU what part of the screen is about to be redrawn.
563     * This method will use the current layer space clip rect.
564     * This method needs to be invoked every time getTargetFbo() is
565     * bound again.
566     */
567    void startTilingCurrentClip(bool opaque = false, bool expand = false);
568
569    /**
570     * Tells the GPU what part of the screen is about to be redrawn.
571     * This method needs to be invoked every time getTargetFbo() is
572     * bound again.
573     */
574    void startTiling(const Rect& clip, int windowHeight, bool opaque = false, bool expand = false);
575
576    /**
577     * Tells the GPU that we are done drawing the frame or that we
578     * are switching to another render target.
579     */
580    void endTiling();
581
582    /**
583     * Sets the clipping rectangle using glScissor. The clip is defined by
584     * the current snapshot's clipRect member.
585     */
586    void setScissorFromClip();
587
588    /**
589     * Sets the clipping region using the stencil buffer. The clip region
590     * is defined by the current snapshot's clipRegion member.
591     */
592    void setStencilFromClip();
593
594    /**
595     * Given the local bounds of the layer, calculates ...
596     */
597    void calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer);
598
599    /**
600     * Given the local bounds + clip of the layer, updates current snapshot's empty/invisible
601     */
602    void updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
603            bool fboLayer, int alpha);
604
605    /**
606     * Creates a new layer stored in the specified snapshot.
607     *
608     * @param snapshot The snapshot associated with the new layer
609     * @param left The left coordinate of the layer
610     * @param top The top coordinate of the layer
611     * @param right The right coordinate of the layer
612     * @param bottom The bottom coordinate of the layer
613     * @param alpha The translucency of the layer
614     * @param mode The blending mode of the layer
615     * @param flags The layer save flags
616     * @param mask A mask to use when drawing the layer back, may be empty
617     *
618     * @return True if the layer was successfully created, false otherwise
619     */
620    bool createLayer(float left, float top, float right, float bottom,
621            const SkPaint* paint, int flags, const SkPath* convexMask);
622
623    /**
624     * Creates a new layer stored in the specified snapshot as an FBO.
625     *
626     * @param layer The layer to store as an FBO
627     * @param snapshot The snapshot associated with the new layer
628     * @param bounds The bounds of the layer
629     */
630    bool createFboLayer(Layer* layer, Rect& bounds, Rect& clip);
631
632    /**
633     * Compose the specified layer as a region.
634     *
635     * @param layer The layer to compose
636     * @param rect The layer's bounds
637     */
638    void composeLayerRegion(Layer* layer, const Rect& rect);
639
640    /**
641     * Compose the specified layer as a simple rectangle.
642     *
643     * @param layer The layer to compose
644     * @param rect The layer's bounds
645     * @param swap If true, the source and destination are swapped
646     */
647    void composeLayerRect(Layer* layer, const Rect& rect, bool swap = false);
648
649    /**
650     * Clears all the regions corresponding to the current list of layers.
651     * This method MUST be invoked before any drawing operation.
652     */
653    void clearLayerRegions();
654
655    /**
656     * Mark the layer as dirty at the specified coordinates. The coordinates
657     * are transformed with the supplied matrix.
658     */
659    void dirtyLayer(const float left, const float top,
660            const float right, const float bottom, const Matrix4& transform);
661
662    /**
663     * Mark the layer as dirty at the specified coordinates.
664     */
665    void dirtyLayer(const float left, const float top,
666            const float right, const float bottom);
667
668    /**
669     * Draws a colored rectangle with the specified color. The specified coordinates
670     * are transformed by the current snapshot's transform matrix unless specified
671     * otherwise.
672     *
673     * @param left The left coordinate of the rectangle
674     * @param top The top coordinate of the rectangle
675     * @param right The right coordinate of the rectangle
676     * @param bottom The bottom coordinate of the rectangle
677     * @param paint The paint containing the color, blending mode, etc.
678     * @param ignoreTransform True if the current transform should be ignored
679     */
680    void drawColorRect(float left, float top, float right, float bottom,
681            const SkPaint* paint, bool ignoreTransform = false);
682
683    /**
684     * Draws a series of colored rectangles with the specified color. The specified
685     * coordinates are transformed by the current snapshot's transform matrix unless
686     * specified otherwise.
687     *
688     * @param rects A list of rectangles, 4 floats (left, top, right, bottom)
689     *              per rectangle
690     * @param paint The paint containing the color, blending mode, etc.
691     * @param ignoreTransform True if the current transform should be ignored
692     * @param dirty True if calling this method should dirty the current layer
693     * @param clip True if the rects should be clipped, false otherwise
694     */
695    void drawColorRects(const float* rects, int count, const SkPaint* paint,
696            bool ignoreTransform = false, bool dirty = true, bool clip = true);
697
698    /**
699     * Draws the shape represented by the specified path texture.
700     * This method invokes drawPathTexture() but takes into account
701     * the extra left/top offset and the texture offset to correctly
702     * position the final shape.
703     *
704     * @param left The left coordinate of the shape to render
705     * @param top The top coordinate of the shape to render
706     * @param texture The texture reprsenting the shape
707     * @param paint The paint to draw the shape with
708     */
709    void drawShape(float left, float top, PathTexture* texture, const SkPaint* paint);
710
711    /**
712     * Renders a strip of polygons with the specified paint, used for tessellated geometry.
713     *
714     * @param vertexBuffer The VertexBuffer to be drawn
715     * @param paint The paint to render with
716     * @param flags flags with which to draw
717     */
718    void drawVertexBuffer(float translateX, float translateY, const VertexBuffer& vertexBuffer,
719            const SkPaint* paint, int flags = 0);
720
721    /**
722     * Convenience for translating method
723     */
724    void drawVertexBuffer(const VertexBuffer& vertexBuffer,
725            const SkPaint* paint, int flags = 0) {
726        drawVertexBuffer(0.0f, 0.0f, vertexBuffer, paint, flags);
727    }
728
729    /**
730     * Renders the convex hull defined by the specified path as a strip of polygons.
731     *
732     * @param path The hull of the path to draw
733     * @param paint The paint to render with
734     */
735    void drawConvexPath(const SkPath& path, const SkPaint* paint);
736
737    /**
738     * Draws text underline and strike-through if needed.
739     *
740     * @param text The text to decor
741     * @param bytesCount The number of bytes in the text
742     * @param totalAdvance The total advance in pixels, defines underline/strikethrough length
743     * @param x The x coordinate where the text will be drawn
744     * @param y The y coordinate where the text will be drawn
745     * @param paint The paint to draw the text with
746     */
747    void drawTextDecorations(float totalAdvance, float x, float y, const SkPaint* paint);
748
749   /**
750     * Draws shadow layer on text (with optional positions).
751     *
752     * @param paint The paint to draw the shadow with
753     * @param text The text to draw
754     * @param bytesCount The number of bytes in the text
755     * @param count The number of glyphs in the text
756     * @param positions The x, y positions of individual glyphs (or NULL)
757     * @param fontRenderer The font renderer object
758     * @param alpha The alpha value for drawing the shadow
759     * @param x The x coordinate where the shadow will be drawn
760     * @param y The y coordinate where the shadow will be drawn
761     */
762    void drawTextShadow(const SkPaint* paint, const char* text, int bytesCount, int count,
763            const float* positions, FontRenderer& fontRenderer, int alpha,
764            float x, float y);
765
766    /**
767     * Draws a path texture. Path textures are alpha8 bitmaps that need special
768     * compositing to apply colors/filters/etc.
769     *
770     * @param texture The texture to render
771     * @param x The x coordinate where the texture will be drawn
772     * @param y The y coordinate where the texture will be drawn
773     * @param paint The paint to draw the texture with
774     */
775     void drawPathTexture(PathTexture* texture, float x, float y, const SkPaint* paint);
776
777    /**
778     * Resets the texture coordinates stored in mMeshVertices. Setting the values
779     * back to default is achieved by calling:
780     *
781     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
782     *
783     * @param u1 The left coordinate of the texture
784     * @param v1 The bottom coordinate of the texture
785     * @param u2 The right coordinate of the texture
786     * @param v2 The top coordinate of the texture
787     */
788    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
789
790    /**
791     * Returns true if the specified paint will draw invisible text.
792     */
793    bool canSkipText(const SkPaint* paint) const;
794
795    bool updateLayer(Layer* layer, bool inFrame);
796    void updateLayers();
797    void flushLayers();
798
799#if DEBUG_LAYERS_AS_REGIONS
800    /**
801     * Renders the specified region as a series of rectangles. This method
802     * is used for debugging only.
803     */
804    void drawRegionRectsDebug(const Region& region);
805#endif
806
807    /**
808     * Renders the specified region as a series of rectangles. The region
809     * must be in screen-space coordinates.
810     */
811    void drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty = false);
812
813    /**
814     * Draws the current clip region if any. Only when DEBUG_CLIP_REGIONS
815     * is turned on.
816     */
817    void debugClip();
818
819    void debugOverdraw(bool enable, bool clear);
820    void renderOverdraw();
821    void countOverdraw();
822
823    /**
824     * Should be invoked every time the glScissor is modified.
825     */
826    inline void dirtyClip() { mState.setDirtyClip(true); }
827
828    inline const UvMapper& getMapper(const Texture* texture) {
829        return texture && texture->uvMapper ? *texture->uvMapper : mUvMapper;
830    }
831
832    /**
833     * Returns a texture object for the specified bitmap. The texture can
834     * come from the texture cache or an atlas. If this method returns
835     * NULL, the texture could not be found and/or allocated.
836     */
837    Texture* getTexture(const SkBitmap* bitmap);
838
839    bool reportAndClearDirty() { bool ret = mDirty; mDirty = false; return ret; }
840    inline Snapshot* writableSnapshot() { return mState.writableSnapshot(); }
841    inline const Snapshot* currentSnapshot() const { return mState.currentSnapshot(); }
842
843    // State used to define the clipping region
844    Rect mTilingClip;
845    // Is the target render surface opaque
846    bool mOpaque;
847    // Is a frame currently being rendered
848    bool mFrameStarted;
849
850    // Default UV mapper
851    const UvMapper mUvMapper;
852
853    // List of rectangles to clear after saveLayer() is invoked
854    std::vector<Rect> mLayers;
855    // List of layers to update at the beginning of a frame
856    Vector< sp<Layer> > mLayerUpdates;
857
858    // See PROPERTY_DISABLE_SCISSOR_OPTIMIZATION in
859    // Properties.h
860    bool mScissorOptimizationDisabled;
861
862    // No-ops start/endTiling when set
863    bool mSuppressTiling;
864    bool mFirstFrameAfterResize;
865
866    bool mSkipOutlineClip;
867
868    // True if anything has been drawn since the last call to
869    // reportAndClearDirty()
870    bool mDirty;
871
872    // Lighting + shadows
873    Vector3 mLightCenter;
874    float mLightRadius;
875    uint8_t mAmbientShadowAlpha;
876    uint8_t mSpotShadowAlpha;
877
878    // Paths kept alive for the duration of the frame
879    std::vector<std::unique_ptr<SkPath>> mTempPaths;
880
881    friend class Layer;
882    friend class TextDrawFunctor;
883    friend class DrawBitmapOp;
884    friend class DrawPatchOp;
885
886}; // class OpenGLRenderer
887
888}; // namespace uirenderer
889}; // namespace android
890
891#endif // ANDROID_HWUI_OPENGL_RENDERER_H
892