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