2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef ANDROID_HWUI_OPENGL_RENDERER_H
18 #define ANDROID_HWUI_OPENGL_RENDERER_H
20 #include "CanvasState.h"
22 #include "Extensions.h"
30 #include "utils/PaintUtils.h"
32 #include <GLES2/gl2.h>
33 #include <GLES2/gl2ext.h>
37 #include <SkColorFilter.h>
38 #include <SkDrawLooper.h>
42 #include <SkXfermode.h>
44 #include <utils/Blur.h>
45 #include <utils/Functor.h>
46 #include <utils/RefBase.h>
47 #include <utils/SortedVector.h>
49 #include <cutils/compiler.h>
51 #include <androidfw/ResourceTypes.h>
58 namespace uirenderer {
60 enum class DrawOpMode {
66 class DeferredDisplayState;
70 class TextDrawFunctor;
73 enum StateDeferFlags {
74 kStateDeferFlag_Draw = 0x1,
75 kStateDeferFlag_Clip = 0x2
82 kClipSide_Right = 0x4,
83 kClipSide_Bottom = 0x8,
85 kClipSide_ConservativeFull = 0x1F
88 enum VertexBufferDisplayFlags {
89 kVertexBuffer_Offset = 0x1,
90 kVertexBuffer_ShadowInterp = 0x2,
94 * Defines additional transformation that should be applied by the model view matrix, beyond that of
95 * the currentTransform()
99 * Used when the model view should simply translate geometry passed to the shader. The resulting
100 * matrix will be a simple translation.
102 kModelViewMode_Translate = 0,
105 * Used when the model view should translate and scale geometry. The resulting matrix will be a
106 * translation + scale. This is frequently used together with VBO 0, the (0,0,1,1) rect.
108 kModelViewMode_TranslateAndScale = 1,
111 ///////////////////////////////////////////////////////////////////////////////
113 ///////////////////////////////////////////////////////////////////////////////
115 * OpenGL Renderer implementation.
117 class OpenGLRenderer : public CanvasStateClient {
119 OpenGLRenderer(RenderState& renderState);
120 virtual ~OpenGLRenderer();
122 void initProperties();
123 void initLight(float lightRadius, uint8_t ambientShadowAlpha,
124 uint8_t spotShadowAlpha);
125 void setLightCenter(const Vector3& lightCenter);
128 * Prepares the renderer to draw a frame. This method must be invoked
129 * at the beginning of each frame. Only the specified rectangle of the
130 * frame is assumed to be dirty. A clip will automatically be set to
131 * the specified rectangle.
133 * @param opaque If true, the target surface is considered opaque
134 * and will not be cleared. If false, the target surface
137 virtual void prepareDirty(int viewportWidth, int viewportHeight,
138 float left, float top, float right, float bottom, bool opaque);
141 * Indicates the end of a frame. This method must be invoked whenever
142 * the caller is done rendering a frame.
143 * Returns true if any drawing was done during the frame (the output
144 * has changed / is "dirty" and should be displayed to the user).
146 virtual bool finish();
148 void callDrawGLFunction(Functor* functor, Rect& dirty);
150 void pushLayerUpdate(Layer* layer);
151 void cancelLayerUpdate(Layer* layer);
152 void flushLayerUpdates();
153 void markLayersAsBuildLayers();
155 virtual int saveLayer(float left, float top, float right, float bottom,
156 const SkPaint* paint, int flags) {
157 return saveLayer(left, top, right, bottom, paint, flags, nullptr);
160 // Specialized saveLayer implementation, which will pass the convexMask to an FBO layer, if
161 // created, which will in turn clip to that mask when drawn back/restored.
162 int saveLayer(float left, float top, float right, float bottom,
163 const SkPaint* paint, int flags, const SkPath* convexMask);
165 int saveLayerDeferred(float left, float top, float right, float bottom,
166 const SkPaint* paint, int flags);
168 void drawRenderNode(RenderNode* displayList, Rect& dirty, int32_t replayFlags = 1);
169 void drawLayer(Layer* layer);
170 void drawBitmap(const SkBitmap* bitmap, const SkPaint* paint);
171 void drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, int bitmapCount,
172 TextureVertex* vertices, bool pureTranslate, const Rect& bounds, const SkPaint* paint);
173 void drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst,
174 const SkPaint* paint);
175 void drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
176 const float* vertices, const int* colors, const SkPaint* paint);
177 void drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
178 TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint);
179 void drawPatch(const SkBitmap* bitmap, const Patch* mesh, AssetAtlas::Entry* entry,
180 float left, float top, float right, float bottom, const SkPaint* paint);
181 void drawColor(int color, SkXfermode::Mode mode);
182 void drawRect(float left, float top, float right, float bottom,
183 const SkPaint* paint);
184 void drawRoundRect(float left, float top, float right, float bottom,
185 float rx, float ry, const SkPaint* paint);
186 void drawCircle(float x, float y, float radius, const SkPaint* paint);
187 void drawOval(float left, float top, float right, float bottom,
188 const SkPaint* paint);
189 void drawArc(float left, float top, float right, float bottom,
190 float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint);
191 void drawPath(const SkPath* path, const SkPaint* paint);
192 void drawLines(const float* points, int count, const SkPaint* paint);
193 void drawPoints(const float* points, int count, const SkPaint* paint);
194 void drawTextOnPath(const glyph_t* glyphs, int bytesCount, int count, const SkPath* path,
195 float hOffset, float vOffset, const SkPaint* paint);
196 void drawText(const glyph_t* glyphs, int bytesCount, int count, float x, float y,
197 const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
198 DrawOpMode drawOpMode = DrawOpMode::kImmediate);
199 void drawRects(const float* rects, int count, const SkPaint* paint);
201 void drawShadow(float casterAlpha,
202 const VertexBuffer* ambientShadowVertexBuffer,
203 const VertexBuffer* spotShadowVertexBuffer);
205 void setDrawFilter(SkDrawFilter* filter);
208 * Store the current display state (most importantly, the current clip and transform), and
209 * additionally map the state's bounds from local to window coordinates.
211 * Returns true if quick-rejected
213 bool storeDisplayState(DeferredDisplayState& state, int stateDeferFlags);
214 void restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore = false);
215 void setupMergedMultiDraw(const Rect* clipRect);
217 bool isCurrentTransformSimple() {
218 return currentTransform()->isSimple();
221 Caches& getCaches() {
225 RenderState& renderState() {
229 int getViewportWidth() { return mState.getViewportWidth(); }
230 int getViewportHeight() { return mState.getViewportHeight(); }
233 * Scales the alpha on the current snapshot. This alpha value will be modulated
234 * with other alpha values when drawing primitives.
236 void scaleAlpha(float alpha) { mState.scaleAlpha(alpha); }
239 * Inserts a named event marker in the stream of GL commands.
241 void eventMark(const char* name) const;
244 * Inserts a formatted event marker in the stream of GL commands.
246 void eventMarkDEBUG(const char *fmt, ...) const;
249 * Inserts a named group marker in the stream of GL commands. This marker
250 * can be used by tools to group commands into logical groups. A call to
251 * this method must always be followed later on by a call to endMark().
253 void startMark(const char* name) const;
256 * Closes the last group marker opened by startMark().
258 void endMark() const;
261 * Build the best transform to use to rasterize text given a full
262 * transform matrix, and whether filteration is needed.
264 * Returns whether filtration is needed
266 bool findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const;
268 #if DEBUG_MERGE_BEHAVIOR
269 void drawScreenSpaceColorRect(float left, float top, float right, float bottom, int color) {
270 mCaches.setScissorEnabled(false);
272 // should only be called outside of other draw ops, so stencil can only be in test state
273 bool stencilWasEnabled = mCaches.stencil.isTestEnabled();
274 mCaches.stencil.disable();
276 drawColorRect(left, top, right, bottom, color, SkXfermode::kSrcOver_Mode, true);
278 if (stencilWasEnabled) mCaches.stencil.enableTest();
283 const Vector3& getLightCenter() const { return mState.currentLightCenter(); }
284 float getLightRadius() const { return mLightRadius; }
285 uint8_t getAmbientShadowAlpha() const { return mAmbientShadowAlpha; }
286 uint8_t getSpotShadowAlpha() const { return mSpotShadowAlpha; }
288 ///////////////////////////////////////////////////////////////////
289 /// State manipulation
291 int getSaveCount() const;
294 void restoreToCount(int saveCount);
296 void setGlobalMatrix(const Matrix4& matrix) {
297 mState.setMatrix(matrix);
299 void setLocalMatrix(const Matrix4& matrix);
300 void setLocalMatrix(const SkMatrix& matrix);
301 void concatMatrix(const SkMatrix& matrix) { mState.concatMatrix(matrix); }
303 void translate(float dx, float dy, float dz = 0.0f);
304 void rotate(float degrees);
305 void scale(float sx, float sy);
306 void skew(float sx, float sy);
308 void setMatrix(const Matrix4& matrix); // internal only convenience method
309 void concatMatrix(const Matrix4& matrix); // internal only convenience method
311 const Rect& getLocalClipBounds() const { return mState.getLocalClipBounds(); }
312 const Rect& getRenderTargetClipBounds() const { return mState.getRenderTargetClipBounds(); }
313 bool quickRejectConservative(float left, float top,
314 float right, float bottom) const {
315 return mState.quickRejectConservative(left, top, right, bottom);
318 bool clipRect(float left, float top,
319 float right, float bottom, SkRegion::Op op);
320 bool clipPath(const SkPath* path, SkRegion::Op op);
321 bool clipRegion(const SkRegion* region, SkRegion::Op op);
324 * Does not support different clipping Ops (that is, every call to setClippingOutline is
325 * effectively using SkRegion::kReplaceOp)
327 * The clipping outline is independent from the regular clip.
329 void setClippingOutline(LinearAllocator& allocator, const Outline* outline);
330 void setClippingRoundRect(LinearAllocator& allocator,
331 const Rect& rect, float radius, bool highPriority = true);
332 void setProjectionPathMask(LinearAllocator& allocator, const SkPath* path);
334 inline bool hasRectToRectTransform() const { return mState.hasRectToRectTransform(); }
335 inline const mat4* currentTransform() const { return mState.currentTransform(); }
337 ///////////////////////////////////////////////////////////////////
338 /// CanvasStateClient interface
340 virtual void onViewportInitialized() override;
341 virtual void onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) override;
342 virtual GLuint getTargetFbo() const override { return 0; }
344 SkPath* allocPathForFrame() {
345 std::unique_ptr<SkPath> path(new SkPath());
346 SkPath* returnPath = path.get();
347 mTempPaths.push_back(std::move(path));
351 void setBaseTransform(const Matrix4& matrix) { mBaseTransform = matrix; }
355 * Perform the setup specific to a frame. This method does not
356 * issue any OpenGL commands.
358 void setupFrameState(int viewportWidth, int viewportHeight,
359 float left, float top, float right, float bottom, bool opaque);
362 * Indicates the start of rendering. This method will setup the
363 * initial OpenGL state (viewport, clearing the buffer, etc.)
368 * Clears the underlying surface if needed.
370 virtual void clear(float left, float top, float right, float bottom, bool opaque);
373 * Call this method after updating a layer during a drawing pass.
375 void resumeAfterLayer();
378 * This method is called whenever a stencil buffer is required. Subclasses
379 * should override this method and call attachStencilBufferToLayer() on the
380 * appropriate layer(s).
382 virtual void ensureStencilBuffer();
385 * Obtains a stencil render buffer (allocating it if necessary) and
386 * attaches it to the specified layer.
388 void attachStencilBufferToLayer(Layer* layer);
391 * Draw a rectangle list. Currently only used for the the stencil buffer so that the stencil
392 * will have a value of 'n' in every unclipped pixel, where 'n' is the number of rectangles
395 void drawRectangleList(const RectangleList& rectangleList);
397 bool quickRejectSetupScissor(float left, float top, float right, float bottom,
398 const SkPaint* paint = nullptr);
399 bool quickRejectSetupScissor(const Rect& bounds, const SkPaint* paint = nullptr) {
400 return quickRejectSetupScissor(bounds.left, bounds.top,
401 bounds.right, bounds.bottom, paint);
405 * Compose the layer defined in the current snapshot with the layer
406 * defined by the previous snapshot.
408 * The current snapshot *must* be a layer (flag kFlagIsLayer set.)
410 * @param curent The current snapshot containing the layer to compose
411 * @param previous The previous snapshot to compose the current layer with
413 virtual void composeLayer(const Snapshot& current, const Snapshot& previous);
416 * Marks the specified region as dirty at the specified bounds.
418 void dirtyLayerUnchecked(Rect& bounds, Region* region);
421 * Returns the region of the current layer.
423 virtual Region* getRegion() const {
424 return mState.currentRegion();
428 * Indicates whether rendering is currently targeted at a layer.
430 virtual bool hasLayer() const {
431 return (mState.currentFlags() & Snapshot::kFlagFboTarget) && mState.currentRegion();
435 * Renders the specified layer as a textured quad.
437 * @param layer The layer to render
438 * @param rect The bounds of the layer
440 void drawTextureLayer(Layer* layer, const Rect& rect);
443 * Gets the alpha from a layer, accounting for snapshot alpha
445 * @param layer The layer from which the alpha is extracted
447 inline float getLayerAlpha(const Layer* layer) const;
450 * Set to true to suppress error checks at the end of a frame.
452 virtual bool suppressErrorChecks() const {
458 RenderState& mRenderState;
461 enum class GlopRenderType {
467 void renderGlop(const Glop& glop, GlopRenderType type = GlopRenderType::Standard);
470 * Discards the content of the framebuffer if supported by the driver.
471 * This method should be called at the beginning of a frame to optimize
472 * rendering on some tiler architectures.
474 void discardFramebuffer(float left, float top, float right, float bottom);
477 * Sets the clipping rectangle using glScissor. The clip is defined by
478 * the current snapshot's clipRect member.
480 void setScissorFromClip();
483 * Sets the clipping region using the stencil buffer. The clip region
484 * is defined by the current snapshot's clipRegion member.
486 void setStencilFromClip();
489 * Given the local bounds of the layer, calculates ...
491 void calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer);
494 * Given the local bounds + clip of the layer, updates current snapshot's empty/invisible
496 void updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
497 bool fboLayer, int alpha);
500 * Creates a new layer stored in the specified snapshot.
502 * @param snapshot The snapshot associated with the new layer
503 * @param left The left coordinate of the layer
504 * @param top The top coordinate of the layer
505 * @param right The right coordinate of the layer
506 * @param bottom The bottom coordinate of the layer
507 * @param alpha The translucency of the layer
508 * @param mode The blending mode of the layer
509 * @param flags The layer save flags
510 * @param mask A mask to use when drawing the layer back, may be empty
512 * @return True if the layer was successfully created, false otherwise
514 bool createLayer(float left, float top, float right, float bottom,
515 const SkPaint* paint, int flags, const SkPath* convexMask);
518 * Creates a new layer stored in the specified snapshot as an FBO.
520 * @param layer The layer to store as an FBO
521 * @param snapshot The snapshot associated with the new layer
522 * @param bounds The bounds of the layer
524 bool createFboLayer(Layer* layer, Rect& bounds, Rect& clip);
527 * Compose the specified layer as a region.
529 * @param layer The layer to compose
530 * @param rect The layer's bounds
532 void composeLayerRegion(Layer* layer, const Rect& rect);
535 * Restores the content in layer to the screen, swapping the blend mode,
536 * specifically used in the restore() of a saveLayerAlpha().
538 * This allows e.g. a layer that would have been drawn on top of existing content (with SrcOver)
539 * to be drawn underneath.
541 * This will always ignore the canvas transform.
543 void composeLayerRectSwapped(Layer* layer, const Rect& rect);
546 * Draws the content in layer to the screen.
548 void composeLayerRect(Layer* layer, const Rect& rect);
551 * Clears all the regions corresponding to the current list of layers.
552 * This method MUST be invoked before any drawing operation.
554 void clearLayerRegions();
557 * Mark the layer as dirty at the specified coordinates. The coordinates
558 * are transformed with the supplied matrix.
560 void dirtyLayer(const float left, const float top,
561 const float right, const float bottom, const Matrix4& transform);
564 * Mark the layer as dirty at the specified coordinates.
566 void dirtyLayer(const float left, const float top,
567 const float right, const float bottom);
570 * Draws a colored rectangle with the specified color. The specified coordinates
571 * are transformed by the current snapshot's transform matrix unless specified
574 * @param left The left coordinate of the rectangle
575 * @param top The top coordinate of the rectangle
576 * @param right The right coordinate of the rectangle
577 * @param bottom The bottom coordinate of the rectangle
578 * @param paint The paint containing the color, blending mode, etc.
579 * @param ignoreTransform True if the current transform should be ignored
581 void drawColorRect(float left, float top, float right, float bottom,
582 const SkPaint* paint, bool ignoreTransform = false);
585 * Draws a series of colored rectangles with the specified color. The specified
586 * coordinates are transformed by the current snapshot's transform matrix unless
587 * specified otherwise.
589 * @param rects A list of rectangles, 4 floats (left, top, right, bottom)
591 * @param paint The paint containing the color, blending mode, etc.
592 * @param ignoreTransform True if the current transform should be ignored
593 * @param dirty True if calling this method should dirty the current layer
594 * @param clip True if the rects should be clipped, false otherwise
596 void drawColorRects(const float* rects, int count, const SkPaint* paint,
597 bool ignoreTransform = false, bool dirty = true, bool clip = true);
600 * Draws the shape represented by the specified path texture.
601 * This method invokes drawPathTexture() but takes into account
602 * the extra left/top offset and the texture offset to correctly
603 * position the final shape.
605 * @param left The left coordinate of the shape to render
606 * @param top The top coordinate of the shape to render
607 * @param texture The texture reprsenting the shape
608 * @param paint The paint to draw the shape with
610 void drawShape(float left, float top, PathTexture* texture, const SkPaint* paint);
613 * Renders a strip of polygons with the specified paint, used for tessellated geometry.
615 * @param vertexBuffer The VertexBuffer to be drawn
616 * @param paint The paint to render with
617 * @param flags flags with which to draw
619 void drawVertexBuffer(float translateX, float translateY, const VertexBuffer& vertexBuffer,
620 const SkPaint* paint, int flags = 0);
623 * Convenience for translating method
625 void drawVertexBuffer(const VertexBuffer& vertexBuffer,
626 const SkPaint* paint, int flags = 0) {
627 drawVertexBuffer(0.0f, 0.0f, vertexBuffer, paint, flags);
631 * Renders the convex hull defined by the specified path as a strip of polygons.
633 * @param path The hull of the path to draw
634 * @param paint The paint to render with
636 void drawConvexPath(const SkPath& path, const SkPaint* paint);
639 * Draws shadow layer on text (with optional positions).
641 * @param paint The paint to draw the shadow with
642 * @param text The text to draw
643 * @param count The number of glyphs in the text
644 * @param positions The x, y positions of individual glyphs (or NULL)
645 * @param fontRenderer The font renderer object
646 * @param alpha The alpha value for drawing the shadow
647 * @param x The x coordinate where the shadow will be drawn
648 * @param y The y coordinate where the shadow will be drawn
650 void drawTextShadow(const SkPaint* paint, const glyph_t* glyphs, int count,
651 const float* positions, FontRenderer& fontRenderer, int alpha,
655 * Draws a path texture. Path textures are alpha8 bitmaps that need special
656 * compositing to apply colors/filters/etc.
658 * @param texture The texture to render
659 * @param x The x coordinate where the texture will be drawn
660 * @param y The y coordinate where the texture will be drawn
661 * @param paint The paint to draw the texture with
663 void drawPathTexture(PathTexture* texture, float x, float y, const SkPaint* paint);
666 * Resets the texture coordinates stored in mMeshVertices. Setting the values
667 * back to default is achieved by calling:
669 * resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
671 * @param u1 The left coordinate of the texture
672 * @param v1 The bottom coordinate of the texture
673 * @param u2 The right coordinate of the texture
674 * @param v2 The top coordinate of the texture
676 void resetDrawTextureTexCoords(float u1, float v1, float u2, float v2);
679 * Returns true if the specified paint will draw invisible text.
681 bool canSkipText(const SkPaint* paint) const;
683 bool updateLayer(Layer* layer, bool inFrame);
687 #if DEBUG_LAYERS_AS_REGIONS
689 * Renders the specified region as a series of rectangles. This method
690 * is used for debugging only.
692 void drawRegionRectsDebug(const Region& region);
696 * Renders the specified region as a series of rectangles. The region
697 * must be in screen-space coordinates.
699 void drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty = false);
702 * Draws the current clip region if any. Only when DEBUG_CLIP_REGIONS
707 void debugOverdraw(bool enable, bool clear);
708 void renderOverdraw();
709 void countOverdraw();
712 * Should be invoked every time the glScissor is modified.
714 inline void dirtyClip() { mState.setDirtyClip(true); }
716 inline const UvMapper& getMapper(const Texture* texture) {
717 return texture && texture->uvMapper ? *texture->uvMapper : mUvMapper;
721 * Returns a texture object for the specified bitmap. The texture can
722 * come from the texture cache or an atlas. If this method returns
723 * NULL, the texture could not be found and/or allocated.
725 Texture* getTexture(const SkBitmap* bitmap);
727 bool reportAndClearDirty() { bool ret = mDirty; mDirty = false; return ret; }
728 inline Snapshot* writableSnapshot() { return mState.writableSnapshot(); }
729 inline const Snapshot* currentSnapshot() const { return mState.currentSnapshot(); }
731 // State used to define the clipping region
733 // Is the target render surface opaque
735 // Is a frame currently being rendered
739 const UvMapper mUvMapper;
741 // List of rectangles to clear after saveLayer() is invoked
742 std::vector<Rect> mLayers;
743 // List of layers to update at the beginning of a frame
744 std::vector< sp<Layer> > mLayerUpdates;
746 // See PROPERTY_DISABLE_SCISSOR_OPTIMIZATION in
748 bool mScissorOptimizationDisabled;
750 bool mSkipOutlineClip;
752 // True if anything has been drawn since the last call to
753 // reportAndClearDirty()
756 // Lighting + shadows
757 Vector3 mLightCenter;
759 uint8_t mAmbientShadowAlpha;
760 uint8_t mSpotShadowAlpha;
762 // Paths kept alive for the duration of the frame
763 std::vector<std::unique_ptr<SkPath>> mTempPaths;
766 * Initial transform for a rendering pass; transform from global device
767 * coordinates to the current RenderNode's drawing content coordinates,
768 * with the RenderNode's RenderProperty transforms already applied.
769 * Calling setMatrix(mBaseTransform) will result in drawing at the origin
770 * of the DisplayList's recorded surface prior to any Canvas
773 Matrix4 mBaseTransform;
776 friend class TextDrawFunctor;
777 friend class DrawBitmapOp;
778 friend class DrawPatchOp;
780 }; // class OpenGLRenderer
782 }; // namespace uirenderer
783 }; // namespace android
785 #endif // ANDROID_HWUI_OPENGL_RENDERER_H