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