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