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