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