OpenGLRenderer.h revision 53e51e4aa933f9603587e1780f446c18816bf9be
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     * Safely retrieves the ColorFilter from the given Paint. If the paint is
528     * null then null is returned.
529     */
530    static inline SkColorFilter* getColorFilter(const SkPaint* paint) {
531        return paint ? paint->getColorFilter() : nullptr;
532    }
533
534    /**
535     * Safely retrieves the Shader from the given Paint. If the paint is
536     * null then null is returned.
537     */
538    static inline const SkShader* getShader(const SkPaint* paint) {
539        return paint ? paint->getShader() : nullptr;
540    }
541
542    /**
543     * Set to true to suppress error checks at the end of a frame.
544     */
545    virtual bool suppressErrorChecks() const {
546        return false;
547    }
548
549    CanvasState mState;
550    Caches& mCaches;
551    RenderState& mRenderState;
552
553private:
554    void renderGlop(const Glop& glop, bool clearLayer = true);
555
556    /**
557     * Discards the content of the framebuffer if supported by the driver.
558     * This method should be called at the beginning of a frame to optimize
559     * rendering on some tiler architectures.
560     */
561    void discardFramebuffer(float left, float top, float right, float bottom);
562
563    /**
564     * Tells the GPU what part of the screen is about to be redrawn.
565     * This method will use the current layer space clip rect.
566     * This method needs to be invoked every time getTargetFbo() is
567     * bound again.
568     */
569    void startTilingCurrentClip(bool opaque = false, bool expand = false);
570
571    /**
572     * Tells the GPU what part of the screen is about to be redrawn.
573     * This method needs to be invoked every time getTargetFbo() is
574     * bound again.
575     */
576    void startTiling(const Rect& clip, int windowHeight, bool opaque = false, bool expand = false);
577
578    /**
579     * Tells the GPU that we are done drawing the frame or that we
580     * are switching to another render target.
581     */
582    void endTiling();
583
584    /**
585     * Sets the clipping rectangle using glScissor. The clip is defined by
586     * the current snapshot's clipRect member.
587     */
588    void setScissorFromClip();
589
590    /**
591     * Sets the clipping region using the stencil buffer. The clip region
592     * is defined by the current snapshot's clipRegion member.
593     */
594    void setStencilFromClip();
595
596    /**
597     * Given the local bounds of the layer, calculates ...
598     */
599    void calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer);
600
601    /**
602     * Given the local bounds + clip of the layer, updates current snapshot's empty/invisible
603     */
604    void updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
605            bool fboLayer, int alpha);
606
607    /**
608     * Creates a new layer stored in the specified snapshot.
609     *
610     * @param snapshot The snapshot associated with the new layer
611     * @param left The left coordinate of the layer
612     * @param top The top coordinate of the layer
613     * @param right The right coordinate of the layer
614     * @param bottom The bottom coordinate of the layer
615     * @param alpha The translucency of the layer
616     * @param mode The blending mode of the layer
617     * @param flags The layer save flags
618     * @param mask A mask to use when drawing the layer back, may be empty
619     *
620     * @return True if the layer was successfully created, false otherwise
621     */
622    bool createLayer(float left, float top, float right, float bottom,
623            const SkPaint* paint, int flags, const SkPath* convexMask);
624
625    /**
626     * Creates a new layer stored in the specified snapshot as an FBO.
627     *
628     * @param layer The layer to store as an FBO
629     * @param snapshot The snapshot associated with the new layer
630     * @param bounds The bounds of the layer
631     */
632    bool createFboLayer(Layer* layer, Rect& bounds, Rect& clip);
633
634    /**
635     * Compose the specified layer as a region.
636     *
637     * @param layer The layer to compose
638     * @param rect The layer's bounds
639     */
640    void composeLayerRegion(Layer* layer, const Rect& rect);
641
642    /**
643     * Restores the content in layer to the screen, swapping the blend mode,
644     * specifically used in the restore() of a saveLayerAlpha().
645     *
646     * This allows e.g. a layer that would have been drawn on top of existing content (with SrcOver)
647     * to be drawn underneath.
648     *
649     * This will always ignore the canvas transform.
650     */
651    void composeLayerRectSwapped(Layer* layer, const Rect& rect);
652
653    /**
654     * Draws the content in layer to the screen.
655     */
656    void composeLayerRect(Layer* layer, const Rect& rect);
657
658    /**
659     * Clears all the regions corresponding to the current list of layers.
660     * This method MUST be invoked before any drawing operation.
661     */
662    void clearLayerRegions();
663
664    /**
665     * Mark the layer as dirty at the specified coordinates. The coordinates
666     * are transformed with the supplied matrix.
667     */
668    void dirtyLayer(const float left, const float top,
669            const float right, const float bottom, const Matrix4& transform);
670
671    /**
672     * Mark the layer as dirty at the specified coordinates.
673     */
674    void dirtyLayer(const float left, const float top,
675            const float right, const float bottom);
676
677    /**
678     * Draws a colored rectangle with the specified color. The specified coordinates
679     * are transformed by the current snapshot's transform matrix unless specified
680     * otherwise.
681     *
682     * @param left The left coordinate of the rectangle
683     * @param top The top coordinate of the rectangle
684     * @param right The right coordinate of the rectangle
685     * @param bottom The bottom coordinate of the rectangle
686     * @param paint The paint containing the color, blending mode, etc.
687     * @param ignoreTransform True if the current transform should be ignored
688     */
689    void drawColorRect(float left, float top, float right, float bottom,
690            const SkPaint* paint, bool ignoreTransform = false);
691
692    /**
693     * Draws a series of colored rectangles with the specified color. The specified
694     * coordinates are transformed by the current snapshot's transform matrix unless
695     * specified otherwise.
696     *
697     * @param rects A list of rectangles, 4 floats (left, top, right, bottom)
698     *              per rectangle
699     * @param paint The paint containing the color, blending mode, etc.
700     * @param ignoreTransform True if the current transform should be ignored
701     * @param dirty True if calling this method should dirty the current layer
702     * @param clip True if the rects should be clipped, false otherwise
703     */
704    void drawColorRects(const float* rects, int count, const SkPaint* paint,
705            bool ignoreTransform = false, bool dirty = true, bool clip = true);
706
707    /**
708     * Draws the shape represented by the specified path texture.
709     * This method invokes drawPathTexture() but takes into account
710     * the extra left/top offset and the texture offset to correctly
711     * position the final shape.
712     *
713     * @param left The left coordinate of the shape to render
714     * @param top The top coordinate of the shape to render
715     * @param texture The texture reprsenting the shape
716     * @param paint The paint to draw the shape with
717     */
718    void drawShape(float left, float top, PathTexture* texture, const SkPaint* paint);
719
720    /**
721     * Renders a strip of polygons with the specified paint, used for tessellated geometry.
722     *
723     * @param vertexBuffer The VertexBuffer to be drawn
724     * @param paint The paint to render with
725     * @param flags flags with which to draw
726     */
727    void drawVertexBuffer(float translateX, float translateY, const VertexBuffer& vertexBuffer,
728            const SkPaint* paint, int flags = 0);
729
730    /**
731     * Convenience for translating method
732     */
733    void drawVertexBuffer(const VertexBuffer& vertexBuffer,
734            const SkPaint* paint, int flags = 0) {
735        drawVertexBuffer(0.0f, 0.0f, vertexBuffer, paint, flags);
736    }
737
738    /**
739     * Renders the convex hull defined by the specified path as a strip of polygons.
740     *
741     * @param path The hull of the path to draw
742     * @param paint The paint to render with
743     */
744    void drawConvexPath(const SkPath& path, const SkPaint* paint);
745
746    /**
747     * Draws text underline and strike-through if needed.
748     *
749     * @param text The text to decor
750     * @param bytesCount The number of bytes in the text
751     * @param totalAdvance The total advance in pixels, defines underline/strikethrough length
752     * @param x The x coordinate where the text will be drawn
753     * @param y The y coordinate where the text will be drawn
754     * @param paint The paint to draw the text with
755     */
756    void drawTextDecorations(float totalAdvance, float x, float y, const SkPaint* paint);
757
758   /**
759     * Draws shadow layer on text (with optional positions).
760     *
761     * @param paint The paint to draw the shadow with
762     * @param text The text to draw
763     * @param bytesCount The number of bytes in the text
764     * @param count The number of glyphs in the text
765     * @param positions The x, y positions of individual glyphs (or NULL)
766     * @param fontRenderer The font renderer object
767     * @param alpha The alpha value for drawing the shadow
768     * @param x The x coordinate where the shadow will be drawn
769     * @param y The y coordinate where the shadow will be drawn
770     */
771    void drawTextShadow(const SkPaint* paint, const char* text, int bytesCount, int count,
772            const float* positions, FontRenderer& fontRenderer, int alpha,
773            float x, float y);
774
775    /**
776     * Draws a path texture. Path textures are alpha8 bitmaps that need special
777     * compositing to apply colors/filters/etc.
778     *
779     * @param texture The texture to render
780     * @param x The x coordinate where the texture will be drawn
781     * @param y The y coordinate where the texture will be drawn
782     * @param paint The paint to draw the texture with
783     */
784     void drawPathTexture(PathTexture* texture, float x, float y, const SkPaint* paint);
785
786    /**
787     * Resets the texture coordinates stored in mMeshVertices. Setting the values
788     * back to default is achieved by calling:
789     *
790     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
791     *
792     * @param u1 The left coordinate of the texture
793     * @param v1 The bottom coordinate of the texture
794     * @param u2 The right coordinate of the texture
795     * @param v2 The top coordinate of the texture
796     */
797    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
798
799    /**
800     * Returns true if the specified paint will draw invisible text.
801     */
802    bool canSkipText(const SkPaint* paint) const;
803
804    bool updateLayer(Layer* layer, bool inFrame);
805    void updateLayers();
806    void flushLayers();
807
808#if DEBUG_LAYERS_AS_REGIONS
809    /**
810     * Renders the specified region as a series of rectangles. This method
811     * is used for debugging only.
812     */
813    void drawRegionRectsDebug(const Region& region);
814#endif
815
816    /**
817     * Renders the specified region as a series of rectangles. The region
818     * must be in screen-space coordinates.
819     */
820    void drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty = false);
821
822    /**
823     * Draws the current clip region if any. Only when DEBUG_CLIP_REGIONS
824     * is turned on.
825     */
826    void debugClip();
827
828    void debugOverdraw(bool enable, bool clear);
829    void renderOverdraw();
830    void countOverdraw();
831
832    /**
833     * Should be invoked every time the glScissor is modified.
834     */
835    inline void dirtyClip() { mState.setDirtyClip(true); }
836
837    inline const UvMapper& getMapper(const Texture* texture) {
838        return texture && texture->uvMapper ? *texture->uvMapper : mUvMapper;
839    }
840
841    /**
842     * Returns a texture object for the specified bitmap. The texture can
843     * come from the texture cache or an atlas. If this method returns
844     * NULL, the texture could not be found and/or allocated.
845     */
846    Texture* getTexture(const SkBitmap* bitmap);
847
848    bool reportAndClearDirty() { bool ret = mDirty; mDirty = false; return ret; }
849    inline Snapshot* writableSnapshot() { return mState.writableSnapshot(); }
850    inline const Snapshot* currentSnapshot() const { return mState.currentSnapshot(); }
851
852    // State used to define the clipping region
853    Rect mTilingClip;
854    // Is the target render surface opaque
855    bool mOpaque;
856    // Is a frame currently being rendered
857    bool mFrameStarted;
858
859    // Default UV mapper
860    const UvMapper mUvMapper;
861
862    // List of rectangles to clear after saveLayer() is invoked
863    std::vector<Rect> mLayers;
864    // List of layers to update at the beginning of a frame
865    Vector< sp<Layer> > mLayerUpdates;
866
867    // See PROPERTY_DISABLE_SCISSOR_OPTIMIZATION in
868    // Properties.h
869    bool mScissorOptimizationDisabled;
870
871    // No-ops start/endTiling when set
872    bool mSuppressTiling;
873    bool mFirstFrameAfterResize;
874
875    bool mSkipOutlineClip;
876
877    // True if anything has been drawn since the last call to
878    // reportAndClearDirty()
879    bool mDirty;
880
881    // Lighting + shadows
882    Vector3 mLightCenter;
883    float mLightRadius;
884    uint8_t mAmbientShadowAlpha;
885    uint8_t mSpotShadowAlpha;
886
887    // Paths kept alive for the duration of the frame
888    std::vector<std::unique_ptr<SkPath>> mTempPaths;
889
890    friend class Layer;
891    friend class TextDrawFunctor;
892    friend class DrawBitmapOp;
893    friend class DrawPatchOp;
894
895}; // class OpenGLRenderer
896
897}; // namespace uirenderer
898}; // namespace android
899
900#endif // ANDROID_HWUI_OPENGL_RENDERER_H
901