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