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