OpenGLRenderer.h revision 8dfaa4904205772cdceee63ef3989bcdedf1a914
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_HWUI_OPENGL_RENDERER_H
18#define ANDROID_HWUI_OPENGL_RENDERER_H
19
20#include <GLES2/gl2.h>
21#include <GLES2/gl2ext.h>
22
23#include <SkBitmap.h>
24#include <SkCanvas.h>
25#include <SkColorFilter.h>
26#include <SkMatrix.h>
27#include <SkPaint.h>
28#include <SkRegion.h>
29#include <SkXfermode.h>
30
31#include <utils/Blur.h>
32#include <utils/Functor.h>
33#include <utils/RefBase.h>
34#include <utils/SortedVector.h>
35#include <utils/Vector.h>
36
37#include <cutils/compiler.h>
38
39#include <androidfw/ResourceTypes.h>
40
41#include "CanvasState.h"
42#include "Debug.h"
43#include "Extensions.h"
44#include "Matrix.h"
45#include "Program.h"
46#include "Rect.h"
47#include "Renderer.h"
48#include "Snapshot.h"
49#include "UvMapper.h"
50#include "Vertex.h"
51#include "Caches.h"
52#include "utils/PaintUtils.h"
53
54class SkShader;
55
56namespace android {
57namespace uirenderer {
58
59class DeferredDisplayState;
60class RenderState;
61class RenderNode;
62class TextSetupFunctor;
63class VertexBuffer;
64
65struct DrawModifiers {
66    DrawModifiers()
67        : mOverrideLayerAlpha(0.0f) {}
68
69    void reset() {
70        mOverrideLayerAlpha = 0.0f;
71    }
72
73    float mOverrideLayerAlpha;
74};
75
76enum StateDeferFlags {
77    kStateDeferFlag_Draw = 0x1,
78    kStateDeferFlag_Clip = 0x2
79};
80
81enum ClipSideFlags {
82    kClipSide_None = 0x0,
83    kClipSide_Left = 0x1,
84    kClipSide_Top = 0x2,
85    kClipSide_Right = 0x4,
86    kClipSide_Bottom = 0x8,
87    kClipSide_Full = 0xF,
88    kClipSide_ConservativeFull = 0x1F
89};
90
91enum VertexBufferDisplayFlags {
92    kVertexBuffer_Offset = 0x1,
93    kVertexBuffer_ShadowInterp = 0x2,
94};
95
96/**
97 * Defines additional transformation that should be applied by the model view matrix, beyond that of
98 * the currentTransform()
99 */
100enum ModelViewMode {
101    /**
102     * Used when the model view should simply translate geometry passed to the shader. The resulting
103     * matrix will be a simple translation.
104     */
105    kModelViewMode_Translate = 0,
106
107    /**
108     * Used when the model view should translate and scale geometry. The resulting matrix will be a
109     * translation + scale. This is frequently used together with VBO 0, the (0,0,1,1) rect.
110     */
111    kModelViewMode_TranslateAndScale = 1,
112};
113
114///////////////////////////////////////////////////////////////////////////////
115// Renderer
116///////////////////////////////////////////////////////////////////////////////
117/**
118 * OpenGL Renderer implementation.
119 */
120class OpenGLRenderer : public Renderer, public CanvasStateClient {
121public:
122    OpenGLRenderer(RenderState& renderState);
123    virtual ~OpenGLRenderer();
124
125    void initProperties();
126    void initLight(const Vector3& lightCenter, float lightRadius,
127            uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha);
128
129    virtual void prepareDirty(float left, float top, float right, float bottom,
130            bool opaque) override;
131    virtual void prepare(bool opaque) override {
132        prepareDirty(0.0f, 0.0f, mState.getWidth(), mState.getHeight(), opaque);
133    }
134    virtual bool finish() override;
135
136    virtual void callDrawGLFunction(Functor* functor, Rect& dirty) override;
137
138    void pushLayerUpdate(Layer* layer);
139    void cancelLayerUpdate(Layer* layer);
140    void flushLayerUpdates();
141    void markLayersAsBuildLayers();
142
143    virtual int saveLayer(float left, float top, float right, float bottom,
144            const SkPaint* paint, int flags) override {
145        return saveLayer(left, top, right, bottom, paint, flags, nullptr);
146    }
147
148    // Specialized saveLayer implementation, which will pass the convexMask to an FBO layer, if
149    // created, which will in turn clip to that mask when drawn back/restored.
150    int saveLayer(float left, float top, float right, float bottom,
151            const SkPaint* paint, int flags, const SkPath* convexMask);
152
153    int saveLayerDeferred(float left, float top, float right, float bottom,
154            const SkPaint* paint, int flags);
155
156    virtual void drawRenderNode(RenderNode* displayList, Rect& dirty,
157            int32_t replayFlags = 1) override;
158    virtual void drawLayer(Layer* layer, float x, float y);
159    virtual void drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) override;
160    void drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, int bitmapCount,
161            TextureVertex* vertices, bool pureTranslate, const Rect& bounds, const SkPaint* paint);
162    virtual void drawBitmap(const SkBitmap* bitmap, float srcLeft, float srcTop,
163            float srcRight, float srcBottom, float dstLeft, float dstTop,
164            float dstRight, float dstBottom, const SkPaint* paint) override;
165    virtual void drawBitmapData(const SkBitmap* bitmap, const SkPaint* paint) override;
166    virtual void drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
167            const float* vertices, const int* colors, const SkPaint* paint) override;
168    void drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
169            TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint);
170    virtual void drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch,
171            float left, float top, float right, float bottom, const SkPaint* paint) override;
172    void drawPatch(const SkBitmap* bitmap, const Patch* mesh, AssetAtlas::Entry* entry,
173            float left, float top, float right, float bottom, const SkPaint* paint);
174    virtual void drawColor(int color, SkXfermode::Mode mode) override;
175    virtual void drawRect(float left, float top, float right, float bottom,
176            const SkPaint* paint) override;
177    virtual void drawRoundRect(float left, float top, float right, float bottom,
178            float rx, float ry, const SkPaint* paint) override;
179    virtual void drawCircle(float x, float y, float radius, const SkPaint* paint) override;
180    virtual void drawOval(float left, float top, float right, float bottom,
181            const SkPaint* paint) override;
182    virtual void drawArc(float left, float top, float right, float bottom,
183            float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint) override;
184    virtual void drawPath(const SkPath* path, const SkPaint* paint) override;
185    virtual void drawLines(const float* points, int count, const SkPaint* paint) override;
186    virtual void drawPoints(const float* points, int count, const SkPaint* paint) override;
187    virtual void drawTextOnPath(const char* text, int bytesCount, int count, const SkPath* path,
188            float hOffset, float vOffset, const SkPaint* paint) override;
189    virtual void drawPosText(const char* text, int bytesCount, int count,
190            const float* positions, const SkPaint* paint) override;
191    virtual void drawText(const char* text, int bytesCount, int count, float x, float y,
192            const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
193            DrawOpMode drawOpMode = kDrawOpMode_Immediate) override;
194    virtual void drawRects(const float* rects, int count, const SkPaint* paint) override;
195
196    void drawShadow(float casterAlpha,
197            const VertexBuffer* ambientShadowVertexBuffer,
198            const VertexBuffer* spotShadowVertexBuffer);
199
200    virtual void setDrawFilter(SkDrawFilter* filter) override;
201
202    // If this value is set to < 1.0, it overrides alpha set on layer (see drawBitmap, drawLayer)
203    void setOverrideLayerAlpha(float alpha) { mDrawModifiers.mOverrideLayerAlpha = alpha; }
204
205    /**
206     * Store the current display state (most importantly, the current clip and transform), and
207     * additionally map the state's bounds from local to window coordinates.
208     *
209     * Returns true if quick-rejected
210     */
211    bool storeDisplayState(DeferredDisplayState& state, int stateDeferFlags);
212    void restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore = false);
213    void setupMergedMultiDraw(const Rect* clipRect);
214
215    const DrawModifiers& getDrawModifiers() { return mDrawModifiers; }
216    void setDrawModifiers(const DrawModifiers& drawModifiers) { mDrawModifiers = drawModifiers; }
217
218    bool isCurrentTransformSimple() {
219        return currentTransform()->isSimple();
220    }
221
222    Caches& getCaches() {
223        return mCaches;
224    }
225
226    // simple rect clip
227    bool isCurrentClipSimple() { return mState.isCurrentClipSimple(); }
228
229    int getViewportWidth() { return mState.getViewportWidth(); }
230    int getViewportHeight() { return mState.getViewportHeight(); }
231
232    /**
233     * Scales the alpha on the current snapshot. This alpha value will be modulated
234     * with other alpha values when drawing primitives.
235     */
236    void scaleAlpha(float alpha) { mState.scaleAlpha(alpha); }
237
238    /**
239     * Inserts a named event marker in the stream of GL commands.
240     */
241    void eventMark(const char* name) const;
242
243    /**
244     * Inserts a formatted event marker in the stream of GL commands.
245     */
246    void eventMarkDEBUG(const char *fmt, ...) const;
247
248    /**
249     * Inserts a named group marker in the stream of GL commands. This marker
250     * can be used by tools to group commands into logical groups. A call to
251     * this method must always be followed later on by a call to endMark().
252     */
253    void startMark(const char* name) const;
254
255    /**
256     * Closes the last group marker opened by startMark().
257     */
258    void endMark() const;
259
260    /**
261     * Gets the alpha and xfermode out of a paint object. If the paint is null
262     * alpha will be 255 and the xfermode will be SRC_OVER. This method does
263     * not multiply the paint's alpha by the current snapshot's alpha, and does
264     * not replace the alpha with the overrideLayerAlpha
265     *
266     * @param paint The paint to extract values from
267     * @param alpha Where to store the resulting alpha
268     * @param mode Where to store the resulting xfermode
269     */
270    static inline void getAlphaAndModeDirect(const SkPaint* paint, int* alpha,
271            SkXfermode::Mode* mode) {
272        *mode = getXfermodeDirect(paint);
273        *alpha = getAlphaDirect(paint);
274    }
275
276    static inline SkXfermode::Mode getXfermodeDirect(const SkPaint* paint) {
277        if (!paint) return SkXfermode::kSrcOver_Mode;
278        return PaintUtils::getXfermode(paint->getXfermode());
279    }
280
281    static inline int getAlphaDirect(const SkPaint* paint) {
282        if (!paint) return 255;
283        return paint->getAlpha();
284    }
285
286    struct TextShadow {
287        SkScalar radius;
288        float dx;
289        float dy;
290        SkColor color;
291    };
292
293    static inline bool getTextShadow(const SkPaint* paint, TextShadow* textShadow) {
294        SkDrawLooper::BlurShadowRec blur;
295        if (paint && paint->getLooper() && paint->getLooper()->asABlurShadow(&blur)) {
296            if (textShadow) {
297                textShadow->radius = Blur::convertSigmaToRadius(blur.fSigma);
298                textShadow->dx = blur.fOffset.fX;
299                textShadow->dy = blur.fOffset.fY;
300                textShadow->color = blur.fColor;
301            }
302            return true;
303        }
304        return false;
305    }
306
307    static inline bool hasTextShadow(const SkPaint* paint) {
308        return getTextShadow(paint, nullptr);
309    }
310
311    /**
312     * Build the best transform to use to rasterize text given a full
313     * transform matrix, and whether filteration is needed.
314     *
315     * Returns whether filtration is needed
316     */
317    bool findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const;
318
319#if DEBUG_MERGE_BEHAVIOR
320    void drawScreenSpaceColorRect(float left, float top, float right, float bottom, int color) {
321        mCaches.setScissorEnabled(false);
322
323        // should only be called outside of other draw ops, so stencil can only be in test state
324        bool stencilWasEnabled = mCaches.stencil.isTestEnabled();
325        mCaches.stencil.disable();
326
327        drawColorRect(left, top, right, bottom, color, SkXfermode::kSrcOver_Mode, true);
328
329        if (stencilWasEnabled) mCaches.stencil.enableTest();
330        mDirty = true;
331    }
332#endif
333
334    const Vector3& getLightCenter() const { return mState.currentLightCenter(); }
335    float getLightRadius() const { return mLightRadius; }
336    uint8_t getAmbientShadowAlpha() const { return mAmbientShadowAlpha; }
337    uint8_t getSpotShadowAlpha() const { return mSpotShadowAlpha; }
338
339    ///////////////////////////////////////////////////////////////////
340    /// State manipulation
341
342    virtual void setViewport(int width, int height) override { mState.setViewport(width, height); }
343
344    virtual int getSaveCount() const override;
345    virtual int save(int flags) override;
346    virtual void restore() override;
347    virtual void restoreToCount(int saveCount) override;
348
349    virtual void getMatrix(SkMatrix* outMatrix) const override { mState.getMatrix(outMatrix); }
350    virtual void setMatrix(const SkMatrix& matrix) override { mState.setMatrix(matrix); }
351    virtual void concatMatrix(const SkMatrix& matrix) override { mState.concatMatrix(matrix); }
352
353    virtual void translate(float dx, float dy, float dz = 0.0f) override;
354    virtual void rotate(float degrees) override;
355    virtual void scale(float sx, float sy) override;
356    virtual void skew(float sx, float sy) override;
357
358    void setMatrix(const Matrix4& matrix); // internal only convenience method
359    void concatMatrix(const Matrix4& matrix); // internal only convenience method
360
361    virtual const Rect& getLocalClipBounds() const override { return mState.getLocalClipBounds(); }
362    const Rect& getRenderTargetClipBounds() const { return mState.getRenderTargetClipBounds(); }
363    virtual bool quickRejectConservative(float left, float top,
364            float right, float bottom) const override {
365        return mState.quickRejectConservative(left, top, right, bottom);
366    }
367
368    virtual bool clipRect(float left, float top,
369            float right, float bottom, SkRegion::Op op) override;
370    virtual bool clipPath(const SkPath* path, SkRegion::Op op) override;
371    virtual bool clipRegion(const SkRegion* region, SkRegion::Op op) override;
372
373    /**
374     * Does not support different clipping Ops (that is, every call to setClippingOutline is
375     * effectively using SkRegion::kReplaceOp)
376     *
377     * The clipping outline is independent from the regular clip.
378     */
379    void setClippingOutline(LinearAllocator& allocator, const Outline* outline);
380    void setClippingRoundRect(LinearAllocator& allocator,
381            const Rect& rect, float radius, bool highPriority = true);
382
383    inline bool hasRectToRectTransform() const { return mState.hasRectToRectTransform(); }
384    inline const mat4* currentTransform() const { return mState.currentTransform(); }
385
386    ///////////////////////////////////////////////////////////////////
387    /// CanvasStateClient interface
388
389    virtual void onViewportInitialized() override;
390    virtual void onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) override;
391    virtual GLuint onGetTargetFbo() const override { return 0; }
392
393    SkPath* allocPathForFrame() {
394        std::unique_ptr<SkPath> path(new SkPath());
395        SkPath* returnPath = path.get();
396        mTempPaths.push_back(std::move(path));
397        return returnPath;
398    }
399
400protected:
401    /**
402     * Perform the setup specific to a frame. This method does not
403     * issue any OpenGL commands.
404     */
405    void setupFrameState(float left, float top, float right, float bottom, bool opaque);
406
407    /**
408     * Indicates the start of rendering. This method will setup the
409     * initial OpenGL state (viewport, clearing the buffer, etc.)
410     */
411    void startFrame();
412
413    /**
414     * Clears the underlying surface if needed.
415     */
416    virtual void clear(float left, float top, float right, float bottom, bool opaque);
417
418    /**
419     * Call this method after updating a layer during a drawing pass.
420     */
421    void resumeAfterLayer();
422
423    /**
424     * This method is called whenever a stencil buffer is required. Subclasses
425     * should override this method and call attachStencilBufferToLayer() on the
426     * appropriate layer(s).
427     */
428    virtual void ensureStencilBuffer();
429
430    /**
431     * Obtains a stencil render buffer (allocating it if necessary) and
432     * attaches it to the specified layer.
433     */
434    void attachStencilBufferToLayer(Layer* layer);
435
436    bool quickRejectSetupScissor(float left, float top, float right, float bottom,
437            const SkPaint* paint = nullptr);
438    bool quickRejectSetupScissor(const Rect& bounds, const SkPaint* paint = nullptr) {
439        return quickRejectSetupScissor(bounds.left, bounds.top,
440                bounds.right, bounds.bottom, paint);
441    }
442
443    /**
444     * Compose the layer defined in the current snapshot with the layer
445     * defined by the previous snapshot.
446     *
447     * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
448     *
449     * @param curent The current snapshot containing the layer to compose
450     * @param previous The previous snapshot to compose the current layer with
451     */
452    virtual void composeLayer(const Snapshot& current, const Snapshot& previous);
453
454    /**
455     * Marks the specified region as dirty at the specified bounds.
456     */
457    void dirtyLayerUnchecked(Rect& bounds, Region* region);
458
459    /**
460     * Returns the region of the current layer.
461     */
462    virtual Region* getRegion() const {
463        return mState.currentRegion();
464    }
465
466    /**
467     * Indicates whether rendering is currently targeted at a layer.
468     */
469    virtual bool hasLayer() const {
470        return (mState.currentFlags() & Snapshot::kFlagFboTarget) && mState.currentRegion();
471    }
472
473
474    /**
475     * Renders the specified layer as a textured quad.
476     *
477     * @param layer The layer to render
478     * @param rect The bounds of the layer
479     */
480    void drawTextureLayer(Layer* layer, const Rect& rect);
481
482    /**
483     * Gets the alpha and xfermode out of a paint object. If the paint is null
484     * alpha will be 255 and the xfermode will be SRC_OVER. Accounts for both
485     * snapshot alpha, and overrideLayerAlpha
486     *
487     * @param paint The paint to extract values from
488     * @param alpha Where to store the resulting alpha
489     * @param mode Where to store the resulting xfermode
490     */
491    inline void getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const;
492
493    /**
494     * Gets the alpha from a layer, accounting for snapshot alpha and overrideLayerAlpha
495     *
496     * @param layer The layer from which the alpha is extracted
497     */
498    inline float getLayerAlpha(const Layer* layer) const;
499
500    /**
501     * Safely retrieves the ColorFilter from the given Paint. If the paint is
502     * null then null is returned.
503     */
504    static inline SkColorFilter* getColorFilter(const SkPaint* paint) {
505        return paint ? paint->getColorFilter() : nullptr;
506    }
507
508    /**
509     * Safely retrieves the Shader from the given Paint. If the paint is
510     * null then null is returned.
511     */
512    static inline const SkShader* getShader(const SkPaint* paint) {
513        return paint ? paint->getShader() : nullptr;
514    }
515
516    /**
517     * Set to true to suppress error checks at the end of a frame.
518     */
519    virtual bool suppressErrorChecks() const {
520        return false;
521    }
522
523    inline RenderState& renderState() { return mRenderState; }
524
525    CanvasState mState;
526
527private:
528    /**
529     * Discards the content of the framebuffer if supported by the driver.
530     * This method should be called at the beginning of a frame to optimize
531     * rendering on some tiler architectures.
532     */
533    void discardFramebuffer(float left, float top, float right, float bottom);
534
535    /**
536     * Ensures the state of the renderer is the same as the state of
537     * the GL context.
538     */
539    void syncState();
540
541    /**
542     * Tells the GPU what part of the screen is about to be redrawn.
543     * This method will use the current layer space clip rect.
544     * This method needs to be invoked every time getTargetFbo() is
545     * bound again.
546     */
547    void startTilingCurrentClip(bool opaque = false, bool expand = false);
548
549    /**
550     * Tells the GPU what part of the screen is about to be redrawn.
551     * This method needs to be invoked every time getTargetFbo() is
552     * bound again.
553     */
554    void startTiling(const Rect& clip, int windowHeight, bool opaque = false, bool expand = false);
555
556    /**
557     * Tells the GPU that we are done drawing the frame or that we
558     * are switching to another render target.
559     */
560    void endTiling();
561
562    /**
563     * Sets the clipping rectangle using glScissor. The clip is defined by
564     * the current snapshot's clipRect member.
565     */
566    void setScissorFromClip();
567
568    /**
569     * Sets the clipping region using the stencil buffer. The clip region
570     * is defined by the current snapshot's clipRegion member.
571     */
572    void setStencilFromClip();
573
574    /**
575     * Given the local bounds of the layer, calculates ...
576     */
577    void calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer);
578
579    /**
580     * Given the local bounds + clip of the layer, updates current snapshot's empty/invisible
581     */
582    void updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
583            bool fboLayer, int alpha);
584
585    /**
586     * Creates a new layer stored in the specified snapshot.
587     *
588     * @param snapshot The snapshot associated with the new layer
589     * @param left The left coordinate of the layer
590     * @param top The top coordinate of the layer
591     * @param right The right coordinate of the layer
592     * @param bottom The bottom coordinate of the layer
593     * @param alpha The translucency of the layer
594     * @param mode The blending mode of the layer
595     * @param flags The layer save flags
596     * @param mask A mask to use when drawing the layer back, may be empty
597     *
598     * @return True if the layer was successfully created, false otherwise
599     */
600    bool createLayer(float left, float top, float right, float bottom,
601            const SkPaint* paint, int flags, const SkPath* convexMask);
602
603    /**
604     * Creates a new layer stored in the specified snapshot as an FBO.
605     *
606     * @param layer The layer to store as an FBO
607     * @param snapshot The snapshot associated with the new layer
608     * @param bounds The bounds of the layer
609     */
610    bool createFboLayer(Layer* layer, Rect& bounds, Rect& clip);
611
612    /**
613     * Compose the specified layer as a region.
614     *
615     * @param layer The layer to compose
616     * @param rect The layer's bounds
617     */
618    void composeLayerRegion(Layer* layer, const Rect& rect);
619
620    /**
621     * Compose the specified layer as a simple rectangle.
622     *
623     * @param layer The layer to compose
624     * @param rect The layer's bounds
625     * @param swap If true, the source and destination are swapped
626     */
627    void composeLayerRect(Layer* layer, const Rect& rect, bool swap = false);
628
629    /**
630     * Clears all the regions corresponding to the current list of layers.
631     * This method MUST be invoked before any drawing operation.
632     */
633    void clearLayerRegions();
634
635    /**
636     * Mark the layer as dirty at the specified coordinates. The coordinates
637     * are transformed with the supplied matrix.
638     */
639    void dirtyLayer(const float left, const float top,
640            const float right, const float bottom, const mat4 transform);
641
642    /**
643     * Mark the layer as dirty at the specified coordinates.
644     */
645    void dirtyLayer(const float left, const float top,
646            const float right, const float bottom);
647
648    /**
649     * Draws a colored rectangle with the specified color. The specified coordinates
650     * are transformed by the current snapshot's transform matrix unless specified
651     * otherwise.
652     *
653     * @param left The left coordinate of the rectangle
654     * @param top The top coordinate of the rectangle
655     * @param right The right coordinate of the rectangle
656     * @param bottom The bottom coordinate of the rectangle
657     * @param paint The paint containing the color, blending mode, etc.
658     * @param ignoreTransform True if the current transform should be ignored
659     */
660    void drawColorRect(float left, float top, float right, float bottom,
661            const SkPaint* paint, bool ignoreTransform = false);
662
663    /**
664     * Draws a series of colored rectangles with the specified color. The specified
665     * coordinates are transformed by the current snapshot's transform matrix unless
666     * specified otherwise.
667     *
668     * @param rects A list of rectangles, 4 floats (left, top, right, bottom)
669     *              per rectangle
670     * @param paint The paint containing the color, blending mode, etc.
671     * @param ignoreTransform True if the current transform should be ignored
672     * @param dirty True if calling this method should dirty the current layer
673     * @param clip True if the rects should be clipped, false otherwise
674     */
675    void drawColorRects(const float* rects, int count, const SkPaint* paint,
676            bool ignoreTransform = false, bool dirty = true, bool clip = true);
677
678    /**
679     * Draws the shape represented by the specified path texture.
680     * This method invokes drawPathTexture() but takes into account
681     * the extra left/top offset and the texture offset to correctly
682     * position the final shape.
683     *
684     * @param left The left coordinate of the shape to render
685     * @param top The top coordinate of the shape to render
686     * @param texture The texture reprsenting the shape
687     * @param paint The paint to draw the shape with
688     */
689    void drawShape(float left, float top, const PathTexture* texture, const SkPaint* paint);
690
691    /**
692     * Draws the specified texture as an alpha bitmap. Alpha bitmaps obey
693     * different compositing rules.
694     *
695     * @param texture The texture to draw with
696     * @param left The x coordinate of the bitmap
697     * @param top The y coordinate of the bitmap
698     * @param paint The paint to render with
699     */
700    void drawAlphaBitmap(Texture* texture, float left, float top, const SkPaint* paint);
701
702    /**
703     * Renders a strip of polygons with the specified paint, used for tessellated geometry.
704     *
705     * @param vertexBuffer The VertexBuffer to be drawn
706     * @param paint The paint to render with
707     * @param flags flags with which to draw
708     */
709    void drawVertexBuffer(float translateX, float translateY, const VertexBuffer& vertexBuffer,
710            const SkPaint* paint, int flags = 0);
711
712    /**
713     * Convenience for translating method
714     */
715    void drawVertexBuffer(const VertexBuffer& vertexBuffer,
716            const SkPaint* paint, int flags = 0) {
717        drawVertexBuffer(0.0f, 0.0f, vertexBuffer, paint, flags);
718    }
719
720    /**
721     * Renders the convex hull defined by the specified path as a strip of polygons.
722     *
723     * @param path The hull of the path to draw
724     * @param paint The paint to render with
725     */
726    void drawConvexPath(const SkPath& path, const SkPaint* paint);
727
728    /**
729     * Draws a textured rectangle with the specified texture. The specified coordinates
730     * are transformed by the current snapshot's transform matrix.
731     *
732     * @param left The left coordinate of the rectangle
733     * @param top The top coordinate of the rectangle
734     * @param right The right coordinate of the rectangle
735     * @param bottom The bottom coordinate of the rectangle
736     * @param texture The texture to use
737     * @param paint The paint containing the alpha, blending mode, etc.
738     */
739    void drawTextureRect(float left, float top, float right, float bottom,
740            Texture* texture, const SkPaint* paint);
741
742    /**
743     * Draws a textured mesh with the specified texture. If the indices are omitted,
744     * the mesh is drawn as a simple quad. The mesh pointers become offsets when a
745     * VBO is bound.
746     *
747     * @param left The left coordinate of the rectangle
748     * @param top The top coordinate of the rectangle
749     * @param right The right coordinate of the rectangle
750     * @param bottom The bottom coordinate of the rectangle
751     * @param texture The texture name to map onto the rectangle
752     * @param paint The paint containing the alpha, blending mode, colorFilter, etc.
753     * @param blend True if the texture contains an alpha channel
754     * @param vertices The vertices that define the mesh
755     * @param texCoords The texture coordinates of each vertex
756     * @param elementsCount The number of elements in the mesh, required by indices
757     * @param swapSrcDst Whether or not the src and dst blending operations should be swapped
758     * @param ignoreTransform True if the current transform should be ignored
759     * @param vbo The VBO used to draw the mesh
760     * @param modelViewMode Defines whether the model view matrix should be scaled
761     * @param dirty True if calling this method should dirty the current layer
762     */
763    void drawTextureMesh(float left, float top, float right, float bottom, GLuint texture,
764            const SkPaint* paint, bool blend,
765            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
766            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
767            ModelViewMode modelViewMode = kModelViewMode_TranslateAndScale, bool dirty = true);
768
769    void drawIndexedTextureMesh(float left, float top, float right, float bottom, GLuint texture,
770            const SkPaint* paint, bool blend,
771            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
772            bool swapSrcDst = false, bool ignoreTransform = false, GLuint vbo = 0,
773            ModelViewMode modelViewMode = kModelViewMode_TranslateAndScale, bool dirty = true);
774
775    void drawAlpha8TextureMesh(float left, float top, float right, float bottom,
776            GLuint texture, const SkPaint* paint,
777            GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
778            bool ignoreTransform, ModelViewMode modelViewMode = kModelViewMode_TranslateAndScale,
779            bool dirty = true);
780
781    /**
782     * Draws the specified list of vertices as quads using indexed GL_TRIANGLES.
783     * If the number of vertices to draw exceeds the number of indices we have
784     * pre-allocated, this method will generate several glDrawElements() calls.
785     */
786    void issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount);
787
788    /**
789     * Draws text underline and strike-through if needed.
790     *
791     * @param text The text to decor
792     * @param bytesCount The number of bytes in the text
793     * @param totalAdvance The total advance in pixels, defines underline/strikethrough length
794     * @param x The x coordinate where the text will be drawn
795     * @param y The y coordinate where the text will be drawn
796     * @param paint The paint to draw the text with
797     */
798    void drawTextDecorations(float totalAdvance, float x, float y, const SkPaint* paint);
799
800   /**
801     * Draws shadow layer on text (with optional positions).
802     *
803     * @param paint The paint to draw the shadow with
804     * @param text The text to draw
805     * @param bytesCount The number of bytes in the text
806     * @param count The number of glyphs in the text
807     * @param positions The x, y positions of individual glyphs (or NULL)
808     * @param fontRenderer The font renderer object
809     * @param alpha The alpha value for drawing the shadow
810     * @param x The x coordinate where the shadow will be drawn
811     * @param y The y coordinate where the shadow will be drawn
812     */
813    void drawTextShadow(const SkPaint* paint, const char* text, int bytesCount, int count,
814            const float* positions, FontRenderer& fontRenderer, int alpha,
815            float x, float y);
816
817    /**
818     * Draws a path texture. Path textures are alpha8 bitmaps that need special
819     * compositing to apply colors/filters/etc.
820     *
821     * @param texture The texture to render
822     * @param x The x coordinate where the texture will be drawn
823     * @param y The y coordinate where the texture will be drawn
824     * @param paint The paint to draw the texture with
825     */
826     void drawPathTexture(const PathTexture* texture, float x, float y, const SkPaint* paint);
827
828    /**
829     * Resets the texture coordinates stored in mMeshVertices. Setting the values
830     * back to default is achieved by calling:
831     *
832     * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
833     *
834     * @param u1 The left coordinate of the texture
835     * @param v1 The bottom coordinate of the texture
836     * @param u2 The right coordinate of the texture
837     * @param v2 The top coordinate of the texture
838     */
839    void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
840
841    /**
842     * Returns true if the specified paint will draw invisible text.
843     */
844    bool canSkipText(const SkPaint* paint) const;
845
846    /**
847     * Binds the specified texture. The texture unit must have been selected
848     * prior to calling this method.
849     */
850    inline void bindTexture(GLuint texture) {
851        mCaches.bindTexture(texture);
852    }
853
854    /**
855     * Binds the specified EGLImage texture. The texture unit must have been selected
856     * prior to calling this method.
857     */
858    inline void bindExternalTexture(GLuint texture) {
859        mCaches.bindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
860    }
861
862    /**
863     * Enable or disable blending as necessary. This function sets the appropriate
864     * blend function based on the specified xfermode.
865     */
866    inline void chooseBlending(bool blend, SkXfermode::Mode mode, ProgramDescription& description,
867            bool swapSrcDst = false);
868
869    /**
870     * Use the specified program with the current GL context. If the program is already
871     * in use, it will not be bound again. If it is not in use, the current program is
872     * marked unused and the specified program becomes used and becomes the new
873     * current program.
874     *
875     * @param program The program to use
876     *
877     * @return true If the specified program was already in use, false otherwise.
878     */
879    inline bool useProgram(Program* program);
880
881    /**
882     * Invoked before any drawing operation. This sets required state.
883     */
884    void setupDraw(bool clear = true);
885
886    /**
887     * Various methods to setup OpenGL rendering.
888     */
889    void setupDrawWithTexture(bool isAlpha8 = false);
890    void setupDrawWithTextureAndColor(bool isAlpha8 = false);
891    void setupDrawWithExternalTexture();
892    void setupDrawNoTexture();
893    void setupDrawVertexAlpha(bool useShadowAlphaInterp);
894    void setupDrawColor(int color, int alpha);
895    void setupDrawColor(float r, float g, float b, float a);
896    void setupDrawAlpha8Color(int color, int alpha);
897    void setupDrawTextGamma(const SkPaint* paint);
898    void setupDrawShader(const SkShader* shader);
899    void setupDrawColorFilter(const SkColorFilter* filter);
900    void setupDrawBlending(const Layer* layer, bool swapSrcDst = false);
901    void setupDrawBlending(const SkPaint* paint, bool blend = true, bool swapSrcDst = false);
902    void setupDrawProgram();
903    void setupDrawDirtyRegionsDisabled();
904
905    /**
906     * Setup the current program matrices based upon the nature of the geometry.
907     *
908     * @param mode If kModelViewMode_Translate, the geometry must be translated by the left and top
909     * parameters. If kModelViewMode_TranslateAndScale, the geometry that exists in the (0,0, 1,1)
910     * space must be scaled up and translated to fill the quad provided in (l,t,r,b). These
911     * transformations are stored in the modelView matrix and uploaded to the shader.
912     *
913     * @param offset Set to true if the the matrix should be fudged (translated) slightly to
914     * disambiguate geometry pixel positioning. See Vertex::GeometryFudgeFactor().
915     *
916     * @param ignoreTransform Set to true if l,t,r,b coordinates already in layer space,
917     * currentTransform() will be ignored. (e.g. when drawing clip in layer coordinates to stencil,
918     * or when simple translation has been extracted)
919     */
920    void setupDrawModelView(ModelViewMode mode, bool offset,
921            float left, float top, float right, float bottom, bool ignoreTransform = false);
922    void setupDrawColorUniforms(bool hasShader);
923    void setupDrawPureColorUniforms();
924
925    /**
926     * Setup uniforms for the current shader.
927     *
928     * @param shader SkShader on the current paint.
929     *
930     * @param ignoreTransform Set to true to ignore the transform in shader.
931     */
932    void setupDrawShaderUniforms(const SkShader* shader, bool ignoreTransform = false);
933    void setupDrawColorFilterUniforms(const SkColorFilter* paint);
934    void setupDrawSimpleMesh();
935    void setupDrawTexture(GLuint texture);
936    void setupDrawExternalTexture(GLuint texture);
937    void setupDrawTextureTransform();
938    void setupDrawTextureTransformUniforms(mat4& transform);
939    void setupDrawTextGammaUniforms();
940    void setupDrawMesh(const GLvoid* vertices, const GLvoid* texCoords = nullptr, GLuint vbo = 0);
941    void setupDrawMesh(const GLvoid* vertices, const GLvoid* texCoords, const GLvoid* colors);
942    void setupDrawMeshIndices(const GLvoid* vertices, const GLvoid* texCoords, GLuint vbo = 0);
943    void setupDrawIndexedVertices(GLvoid* vertices);
944    void accountForClear(SkXfermode::Mode mode);
945
946    bool updateLayer(Layer* layer, bool inFrame);
947    void updateLayers();
948    void flushLayers();
949
950#if DEBUG_LAYERS_AS_REGIONS
951    /**
952     * Renders the specified region as a series of rectangles. This method
953     * is used for debugging only.
954     */
955    void drawRegionRectsDebug(const Region& region);
956#endif
957
958    /**
959     * Renders the specified region as a series of rectangles. The region
960     * must be in screen-space coordinates.
961     */
962    void drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty = false);
963
964    /**
965     * Draws the current clip region if any. Only when DEBUG_CLIP_REGIONS
966     * is turned on.
967     */
968    void debugClip();
969
970    void debugOverdraw(bool enable, bool clear);
971    void renderOverdraw();
972    void countOverdraw();
973
974    /**
975     * Should be invoked every time the glScissor is modified.
976     */
977    inline void dirtyClip() { mState.setDirtyClip(true); }
978
979    inline const UvMapper& getMapper(const Texture* texture) {
980        return texture && texture->uvMapper ? *texture->uvMapper : mUvMapper;
981    }
982
983    /**
984     * Returns a texture object for the specified bitmap. The texture can
985     * come from the texture cache or an atlas. If this method returns
986     * NULL, the texture could not be found and/or allocated.
987     */
988    Texture* getTexture(const SkBitmap* bitmap);
989
990    bool reportAndClearDirty() { bool ret = mDirty; mDirty = false; return ret; }
991    inline Snapshot* writableSnapshot() { return mState.writableSnapshot(); }
992    inline const Snapshot* currentSnapshot() const { return mState.currentSnapshot(); }
993
994    /**
995     * Model-view matrix used to position/size objects
996     *
997     * Stores operation-local modifications to the draw matrix that aren't incorporated into the
998     * currentTransform().
999     *
1000     * If generated with kModelViewMode_Translate, mModelViewMatrix will reflect an x/y offset,
1001     * e.g. the offset in drawLayer(). If generated with kModelViewMode_TranslateAndScale,
1002     * mModelViewMatrix will reflect a translation and scale, e.g. the translation and scale
1003     * required to make VBO 0 (a rect of (0,0,1,1)) scaled to match the x,y offset, and width/height
1004     * of a bitmap.
1005     *
1006     * Used as input to SkiaShader transformation.
1007     */
1008    mat4 mModelViewMatrix;
1009
1010    // State used to define the clipping region
1011    Rect mTilingClip;
1012    // Is the target render surface opaque
1013    bool mOpaque;
1014    // Is a frame currently being rendered
1015    bool mFrameStarted;
1016
1017    // Used to draw textured quads
1018    TextureVertex mMeshVertices[4];
1019
1020    // Default UV mapper
1021    const UvMapper mUvMapper;
1022
1023    // shader, filters, and shadow
1024    DrawModifiers mDrawModifiers;
1025    SkPaint mFilteredPaint;
1026
1027    // Various caches
1028    Caches& mCaches;
1029    Extensions& mExtensions;
1030    RenderState& mRenderState;
1031
1032    // List of rectangles to clear after saveLayer() is invoked
1033    std::vector<Rect> mLayers;
1034    // List of layers to update at the beginning of a frame
1035    Vector< sp<Layer> > mLayerUpdates;
1036
1037    // The following fields are used to setup drawing
1038    // Used to describe the shaders to generate
1039    ProgramDescription mDescription;
1040    // Color description
1041    bool mColorSet;
1042    float mColorA, mColorR, mColorG, mColorB;
1043    // Indicates that the shader should get a color
1044    bool mSetShaderColor;
1045    // Current texture unit
1046    GLuint mTextureUnit;
1047    // Track dirty regions, true by default
1048    bool mTrackDirtyRegions;
1049    // Indicate whether we are drawing an opaque frame
1050    bool mOpaqueFrame;
1051
1052    // See PROPERTY_DISABLE_SCISSOR_OPTIMIZATION in
1053    // Properties.h
1054    bool mScissorOptimizationDisabled;
1055
1056    // No-ops start/endTiling when set
1057    bool mSuppressTiling;
1058    bool mFirstFrameAfterResize;
1059
1060    bool mSkipOutlineClip;
1061
1062    // True if anything has been drawn since the last call to
1063    // reportAndClearDirty()
1064    bool mDirty;
1065
1066    // Lighting + shadows
1067    Vector3 mLightCenter;
1068    float mLightRadius;
1069    uint8_t mAmbientShadowAlpha;
1070    uint8_t mSpotShadowAlpha;
1071
1072    // Paths kept alive for the duration of the frame
1073    std::vector<std::unique_ptr<SkPath>> mTempPaths;
1074
1075    friend class Layer;
1076    friend class TextSetupFunctor;
1077    friend class DrawBitmapOp;
1078    friend class DrawPatchOp;
1079
1080}; // class OpenGLRenderer
1081
1082}; // namespace uirenderer
1083}; // namespace android
1084
1085#endif // ANDROID_HWUI_OPENGL_RENDERER_H
1086