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 #include "OpenGLRenderer.h"
19 #include "DeferredDisplayList.h"
20 #include "GammaFontRenderer.h"
22 #include "GlopBuilder.h"
24 #include "PathTessellator.h"
25 #include "Properties.h"
26 #include "RenderNode.h"
27 #include "renderstate/MeshState.h"
28 #include "renderstate/RenderState.h"
29 #include "ShadowTessellator.h"
30 #include "SkiaShader.h"
32 #include "VertexBuffer.h"
33 #include "utils/GLUtils.h"
34 #include "utils/PaintUtils.h"
35 #include "utils/TraceUtils.h"
39 #include <sys/types.h>
43 #include <SkPathOps.h>
45 #include <SkTypeface.h>
47 #include <utils/Log.h>
48 #include <utils/StopWatch.h>
50 #include <private/hwui/DrawGlInfo.h>
54 #if DEBUG_DETAILED_EVENTS
55 #define EVENT_LOGD(...) eventMarkDEBUG(__VA_ARGS__)
57 #define EVENT_LOGD(...)
61 namespace uirenderer {
63 ///////////////////////////////////////////////////////////////////////////////
64 // Constructors/destructor
65 ///////////////////////////////////////////////////////////////////////////////
67 OpenGLRenderer::OpenGLRenderer(RenderState& renderState)
69 , mCaches(Caches::getInstance())
70 , mRenderState(renderState)
71 , mFrameStarted(false)
72 , mScissorOptimizationDisabled(false)
73 , mSuppressTiling(false)
74 , mFirstFrameAfterResize(true)
76 , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN})
77 , mLightRadius(FLT_MIN)
78 , mAmbientShadowAlpha(0)
79 , mSpotShadowAlpha(0) {
82 OpenGLRenderer::~OpenGLRenderer() {
83 // The context has already been destroyed at this point, do not call
84 // GL APIs. All GL state should be kept in Caches.h
87 void OpenGLRenderer::initProperties() {
88 char property[PROPERTY_VALUE_MAX];
89 if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
90 mScissorOptimizationDisabled = !strcasecmp(property, "true");
91 INIT_LOGD(" Scissor optimization %s",
92 mScissorOptimizationDisabled ? "disabled" : "enabled");
94 INIT_LOGD(" Scissor optimization enabled");
98 void OpenGLRenderer::initLight(float lightRadius, uint8_t ambientShadowAlpha,
99 uint8_t spotShadowAlpha) {
100 mLightRadius = lightRadius;
101 mAmbientShadowAlpha = ambientShadowAlpha;
102 mSpotShadowAlpha = spotShadowAlpha;
105 void OpenGLRenderer::setLightCenter(const Vector3& lightCenter) {
106 mLightCenter = lightCenter;
109 ///////////////////////////////////////////////////////////////////////////////
111 ///////////////////////////////////////////////////////////////////////////////
113 void OpenGLRenderer::onViewportInitialized() {
114 glDisable(GL_DITHER);
115 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
116 mFirstFrameAfterResize = true;
119 void OpenGLRenderer::setupFrameState(float left, float top,
120 float right, float bottom, bool opaque) {
121 mCaches.clearGarbage();
122 mState.initializeSaveStack(left, top, right, bottom, mLightCenter);
124 mTilingClip.set(left, top, right, bottom);
127 void OpenGLRenderer::startFrame() {
128 if (mFrameStarted) return;
129 mFrameStarted = true;
131 mState.setDirtyClip(true);
133 discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom);
135 mRenderState.setViewport(mState.getWidth(), mState.getHeight());
137 // Functors break the tiling extension in pretty spectacular ways
138 // This ensures we don't use tiling when a functor is going to be
139 // invoked during the frame
140 mSuppressTiling = mCaches.hasRegisteredFunctors()
141 || mFirstFrameAfterResize;
142 mFirstFrameAfterResize = false;
144 startTilingCurrentClip(true);
146 debugOverdraw(true, true);
148 clear(mTilingClip.left, mTilingClip.top,
149 mTilingClip.right, mTilingClip.bottom, mOpaque);
152 void OpenGLRenderer::prepareDirty(float left, float top,
153 float right, float bottom, bool opaque) {
155 setupFrameState(left, top, right, bottom, opaque);
157 // Layer renderers will start the frame immediately
158 // The framebuffer renderer will first defer the display list
159 // for each layer and wait until the first drawing command
160 // to start the frame
161 if (currentSnapshot()->fbo == 0) {
162 mRenderState.blend().syncEnabled();
169 void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) {
170 // If we know that we are going to redraw the entire framebuffer,
171 // perform a discard to let the driver know we don't need to preserve
172 // the back buffer for this frame.
173 if (mCaches.extensions().hasDiscardFramebuffer() &&
174 left <= 0.0f && top <= 0.0f && right >= mState.getWidth() && bottom >= mState.getHeight()) {
175 const bool isFbo = getTargetFbo() == 0;
176 const GLenum attachments[] = {
177 isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0,
178 isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT };
179 glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
183 void OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
185 mRenderState.scissor().setEnabled(true);
186 mRenderState.scissor().set(left, getViewportHeight() - bottom, right - left, bottom - top);
187 glClear(GL_COLOR_BUFFER_BIT);
192 mRenderState.scissor().reset();
195 void OpenGLRenderer::startTilingCurrentClip(bool opaque, bool expand) {
196 if (!mSuppressTiling) {
197 const Snapshot* snapshot = currentSnapshot();
199 const Rect* clip = &mTilingClip;
200 if (snapshot->flags & Snapshot::kFlagFboTarget) {
201 clip = &(snapshot->layer->clipRect);
204 startTiling(*clip, getViewportHeight(), opaque, expand);
208 void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque, bool expand) {
209 if (!mSuppressTiling) {
211 // Expand the startTiling region by 1
212 int leftNotZero = (clip.left > 0) ? 1 : 0;
213 int topNotZero = (windowHeight - clip.bottom > 0) ? 1 : 0;
216 clip.left - leftNotZero,
217 windowHeight - clip.bottom - topNotZero,
218 clip.right - clip.left + leftNotZero + 1,
219 clip.bottom - clip.top + topNotZero + 1,
222 mCaches.startTiling(clip.left, windowHeight - clip.bottom,
223 clip.right - clip.left, clip.bottom - clip.top, opaque);
228 void OpenGLRenderer::endTiling() {
229 if (!mSuppressTiling) mCaches.endTiling();
232 bool OpenGLRenderer::finish() {
237 // When finish() is invoked on FBO 0 we've reached the end
238 // of the current frame
239 if (getTargetFbo() == 0) {
240 mCaches.pathCache.trim();
241 mCaches.tessellationCache.trim();
244 if (!suppressErrorChecks()) {
246 GLUtils::dumpGLErrors();
249 #if DEBUG_MEMORY_USAGE
250 mCaches.dumpMemoryUsage();
252 if (Properties::debugLevel & kDebugMemory) {
253 mCaches.dumpMemoryUsage();
258 mFrameStarted = false;
260 return reportAndClearDirty();
263 void OpenGLRenderer::resumeAfterLayer() {
264 mRenderState.setViewport(getViewportWidth(), getViewportHeight());
265 mRenderState.bindFramebuffer(currentSnapshot()->fbo);
266 debugOverdraw(true, false);
268 mRenderState.scissor().reset();
272 void OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
273 if (mState.currentlyIgnored()) return;
275 Rect clip(mState.currentClipRect());
276 clip.snapToPixelBoundaries();
278 // Since we don't know what the functor will draw, let's dirty
279 // the entire clip region
281 dirtyLayerUnchecked(clip, getRegion());
285 info.clipLeft = clip.left;
286 info.clipTop = clip.top;
287 info.clipRight = clip.right;
288 info.clipBottom = clip.bottom;
289 info.isLayer = hasLayer();
290 info.width = getViewportWidth();
291 info.height = getViewportHeight();
292 currentTransform()->copyTo(&info.transform[0]);
294 bool prevDirtyClip = mState.getDirtyClip();
295 // setup GL state for functor
296 if (mState.getDirtyClip()) {
297 setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt()
299 if (mRenderState.scissor().setEnabled(true) || prevDirtyClip) {
300 setScissorFromClip();
303 mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info);
304 // Scissor may have been modified, reset dirty clip
310 ///////////////////////////////////////////////////////////////////////////////
312 ///////////////////////////////////////////////////////////////////////////////
314 void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const {
315 #if DEBUG_DETAILED_EVENTS
316 const int BUFFER_SIZE = 256;
318 char buf[BUFFER_SIZE];
321 vsnprintf(buf, BUFFER_SIZE, fmt, ap);
329 void OpenGLRenderer::eventMark(const char* name) const {
330 mCaches.eventMark(0, name);
333 void OpenGLRenderer::startMark(const char* name) const {
334 mCaches.startMark(0, name);
337 void OpenGLRenderer::endMark() const {
341 void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
342 mRenderState.debugOverdraw(enable, clear);
345 void OpenGLRenderer::renderOverdraw() {
346 if (Properties::debugOverdraw && getTargetFbo() == 0) {
347 const Rect* clip = &mTilingClip;
349 mRenderState.scissor().setEnabled(true);
350 mRenderState.scissor().set(clip->left,
351 mState.firstSnapshot()->getViewportHeight() - clip->bottom,
352 clip->right - clip->left,
353 clip->bottom - clip->top);
356 mRenderState.stencil().enableDebugTest(2);
357 drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode);
360 mRenderState.stencil().enableDebugTest(3);
361 drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode);
364 mRenderState.stencil().enableDebugTest(4);
365 drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode);
367 // 4x overdraw and higher
368 mRenderState.stencil().enableDebugTest(4, true);
369 drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode);
371 mRenderState.stencil().disable();
375 ///////////////////////////////////////////////////////////////////////////////
377 ///////////////////////////////////////////////////////////////////////////////
379 bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
380 if (layer->deferredUpdateScheduled && layer->renderer
381 && layer->renderNode.get() && layer->renderNode->isRenderable()) {
385 debugOverdraw(false, false);
388 if (CC_UNLIKELY(inFrame || Properties::drawDeferDisabled)) {
389 layer->render(*this);
396 startTilingCurrentClip();
399 layer->debugDrawUpdate = Properties::debugLayersUpdates;
400 layer->hasDrawnSinceUpdate = false;
408 void OpenGLRenderer::updateLayers() {
409 // If draw deferring is enabled this method will simply defer
410 // the display list of each individual layer. The layers remain
411 // in the layer updates list which will be cleared by flushLayers().
412 int count = mLayerUpdates.size();
414 if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
415 startMark("Layer Updates");
417 startMark("Defer Layer Updates");
420 // Note: it is very important to update the layers in order
421 for (int i = 0; i < count; i++) {
422 Layer* layer = mLayerUpdates.itemAt(i).get();
423 updateLayer(layer, false);
426 if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
427 mLayerUpdates.clear();
428 mRenderState.bindFramebuffer(getTargetFbo());
434 void OpenGLRenderer::flushLayers() {
435 int count = mLayerUpdates.size();
437 startMark("Apply Layer Updates");
439 // Note: it is very important to update the layers in order
440 for (int i = 0; i < count; i++) {
441 mLayerUpdates.itemAt(i)->flush();
444 mLayerUpdates.clear();
445 mRenderState.bindFramebuffer(getTargetFbo());
451 void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
453 // Make sure we don't introduce duplicates.
454 // SortedVector would do this automatically but we need to respect
455 // the insertion order. The linear search is not an issue since
456 // this list is usually very short (typically one item, at most a few)
457 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
458 if (mLayerUpdates.itemAt(i) == layer) {
462 mLayerUpdates.push_back(layer);
466 void OpenGLRenderer::cancelLayerUpdate(Layer* layer) {
468 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
469 if (mLayerUpdates.itemAt(i) == layer) {
470 mLayerUpdates.removeAt(i);
477 void OpenGLRenderer::flushLayerUpdates() {
478 ATRACE_NAME("Update HW Layers");
479 mRenderState.blend().syncEnabled();
482 // Wait for all the layer updates to be executed
486 void OpenGLRenderer::markLayersAsBuildLayers() {
487 for (size_t i = 0; i < mLayerUpdates.size(); i++) {
488 mLayerUpdates[i]->wasBuildLayered = true;
492 ///////////////////////////////////////////////////////////////////////////////
494 ///////////////////////////////////////////////////////////////////////////////
496 void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {
497 bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer;
498 bool restoreClip = removed.flags & Snapshot::kFlagClipSet;
499 bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer;
501 if (restoreViewport) {
502 mRenderState.setViewport(getViewportWidth(), getViewportHeight());
510 endMark(); // Savelayer
511 ATRACE_END(); // SaveLayer
512 startMark("ComposeLayer");
513 composeLayer(removed, restored);
518 ///////////////////////////////////////////////////////////////////////////////
520 ///////////////////////////////////////////////////////////////////////////////
522 int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
523 const SkPaint* paint, int flags, const SkPath* convexMask) {
524 // force matrix/clip isolation for layer
525 flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag;
527 const int count = mState.saveSnapshot(flags);
529 if (!mState.currentlyIgnored()) {
530 createLayer(left, top, right, bottom, paint, flags, convexMask);
536 void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) {
537 const Rect untransformedBounds(bounds);
539 currentTransform()->mapRect(bounds);
541 // Layers only make sense if they are in the framebuffer's bounds
542 if (bounds.intersect(mState.currentClipRect())) {
543 // We cannot work with sub-pixels in this case
544 bounds.snapToPixelBoundaries();
546 // When the layer is not an FBO, we may use glCopyTexImage so we
547 // need to make sure the layer does not extend outside the bounds
548 // of the framebuffer
549 const Snapshot& previous = *(currentSnapshot()->previous);
550 Rect previousViewport(0, 0, previous.getViewportWidth(), previous.getViewportHeight());
551 if (!bounds.intersect(previousViewport)) {
553 } else if (fboLayer) {
556 inverse.loadInverse(*currentTransform());
557 inverse.mapRect(clip);
558 clip.snapToPixelBoundaries();
559 if (clip.intersect(untransformedBounds)) {
560 clip.translate(-untransformedBounds.left, -untransformedBounds.top);
561 bounds.set(untransformedBounds);
571 void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
572 bool fboLayer, int alpha) {
573 if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
574 bounds.getHeight() > mCaches.maxTextureSize ||
575 (fboLayer && clip.isEmpty())) {
576 writableSnapshot()->empty = fboLayer;
578 writableSnapshot()->invisible = writableSnapshot()->invisible || (alpha <= 0 && fboLayer);
582 int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom,
583 const SkPaint* paint, int flags) {
584 const int count = mState.saveSnapshot(flags);
586 if (!mState.currentlyIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) {
587 // initialize the snapshot as though it almost represents an FBO layer so deferred draw
588 // operations will be able to store and restore the current clip and transform info, and
589 // quick rejection will be correct (for display lists)
591 Rect bounds(left, top, right, bottom);
593 calculateLayerBoundsAndClip(bounds, clip, true);
594 updateSnapshotIgnoreForLayer(bounds, clip, true, getAlphaDirect(paint));
596 if (!mState.currentlyIgnored()) {
597 writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
598 writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
599 writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
600 writableSnapshot()->roundRectClipState = nullptr;
608 * Layers are viewed by Skia are slightly different than layers in image editing
609 * programs (for instance.) When a layer is created, previously created layers
610 * and the frame buffer still receive every drawing command. For instance, if a
611 * layer is created and a shape intersecting the bounds of the layers and the
612 * framebuffer is draw, the shape will be drawn on both (unless the layer was
613 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
615 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
616 * texture. Unfortunately, this is inefficient as it requires every primitive to
617 * be drawn n + 1 times, where n is the number of active layers. In practice this
618 * means, for every primitive:
619 * - Switch active frame buffer
620 * - Change viewport, clip and projection matrix
621 * - Issue the drawing
623 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
624 * To avoid this, layers are implemented in a different way here, at least in the
625 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
626 * is set. When this flag is set we can redirect all drawing operations into a
629 * This implementation relies on the frame buffer being at least RGBA 8888. When
630 * a layer is created, only a texture is created, not an FBO. The content of the
631 * frame buffer contained within the layer's bounds is copied into this texture
632 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
633 * buffer and drawing continues as normal. This technique therefore treats the
634 * frame buffer as a scratch buffer for the layers.
636 * To compose the layers back onto the frame buffer, each layer texture
637 * (containing the original frame buffer data) is drawn as a simple quad over
638 * the frame buffer. The trick is that the quad is set as the composition
639 * destination in the blending equation, and the frame buffer becomes the source
640 * of the composition.
642 * Drawing layers with an alpha value requires an extra step before composition.
643 * An empty quad is drawn over the layer's region in the frame buffer. This quad
644 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
645 * quad is used to multiply the colors in the frame buffer. This is achieved by
646 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
647 * GL_ZERO, GL_SRC_ALPHA.
649 * Because glCopyTexImage2D() can be slow, an alternative implementation might
650 * be use to draw a single clipped layer. The implementation described above
651 * is correct in every case.
653 * (1) The frame buffer is actually not cleared right away. To allow the GPU
654 * to potentially optimize series of calls to glCopyTexImage2D, the frame
655 * buffer is left untouched until the first drawing operation. Only when
656 * something actually gets drawn are the layers regions cleared.
658 bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
659 const SkPaint* paint, int flags, const SkPath* convexMask) {
660 LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
661 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
663 const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
665 // Window coordinates of the layer
667 Rect bounds(left, top, right, bottom);
668 calculateLayerBoundsAndClip(bounds, clip, fboLayer);
669 updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, getAlphaDirect(paint));
671 // Bail out if we won't draw in this snapshot
672 if (mState.currentlyIgnored()) {
676 mCaches.textureState().activateTexture(0);
677 Layer* layer = mCaches.layerCache.get(mRenderState, bounds.getWidth(), bounds.getHeight());
682 layer->setPaint(paint);
683 layer->layer.set(bounds);
684 layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
685 bounds.getWidth() / float(layer->getWidth()), 0.0f);
687 layer->setBlend(true);
688 layer->setDirty(false);
689 layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache
691 // Save the layer in the snapshot
692 writableSnapshot()->flags |= Snapshot::kFlagIsLayer;
693 writableSnapshot()->layer = layer;
695 ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u",
696 fboLayer ? "" : "unclipped ",
697 layer->getWidth(), layer->getHeight());
698 startMark("SaveLayer");
700 return createFboLayer(layer, bounds, clip);
702 // Copy the framebuffer into the layer
703 layer->bindTexture();
704 if (!bounds.isEmpty()) {
705 if (layer->isEmpty()) {
706 // Workaround for some GL drivers. When reading pixels lying outside
707 // of the window we should get undefined values for those pixels.
708 // Unfortunately some drivers will turn the entire target texture black
709 // when reading outside of the window.
710 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(),
711 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
712 layer->setEmpty(false);
715 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
716 bounds.left, getViewportHeight() - bounds.bottom,
717 bounds.getWidth(), bounds.getHeight());
719 // Enqueue the buffer coordinates to clear the corresponding region later
720 mLayers.push_back(Rect(bounds));
727 bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) {
728 layer->clipRect.set(clip);
729 layer->setFbo(mCaches.fboCache.get());
731 writableSnapshot()->region = &writableSnapshot()->layer->region;
732 writableSnapshot()->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer;
733 writableSnapshot()->fbo = layer->getFbo();
734 writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f);
735 writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom);
736 writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight());
737 writableSnapshot()->roundRectClipState = nullptr;
740 debugOverdraw(false, false);
741 // Bind texture to FBO
742 mRenderState.bindFramebuffer(layer->getFbo());
743 layer->bindTexture();
745 // Initialize the texture if needed
746 if (layer->isEmpty()) {
747 layer->allocateTexture();
748 layer->setEmpty(false);
751 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
752 layer->getTextureId(), 0);
754 // Expand the startTiling region by 1
755 startTilingCurrentClip(true, true);
757 // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
758 mRenderState.scissor().setEnabled(true);
759 mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
760 clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
761 glClear(GL_COLOR_BUFFER_BIT);
765 // Change the ortho projection
766 mRenderState.setViewport(bounds.getWidth(), bounds.getHeight());
771 * Read the documentation of createLayer() before doing anything in this method.
773 void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) {
774 if (!removed.layer) {
775 ALOGE("Attempting to compose a layer that does not exist");
779 Layer* layer = removed.layer;
780 const Rect& rect = layer->layer;
781 const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer;
783 bool clipRequired = false;
784 mState.calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom,
785 &clipRequired, nullptr, false); // safely ignore return, should never be rejected
786 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
791 // Detach the texture from the FBO
792 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
794 layer->removeFbo(false);
796 // Unbind current FBO and restore previous one
797 mRenderState.bindFramebuffer(restored.fbo);
798 debugOverdraw(true, false);
800 startTilingCurrentClip();
803 if (!fboLayer && layer->getAlpha() < 255) {
805 layerPaint.setAlpha(layer->getAlpha());
806 layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode);
807 layerPaint.setColorFilter(layer->getColorFilter());
809 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true);
810 // Required below, composeLayerRect() will divide by 255
811 layer->setAlpha(255);
814 mRenderState.meshState().unbindMeshBuffer();
816 mCaches.textureState().activateTexture(0);
818 // When the layer is stored in an FBO, we can save a bit of fillrate by
819 // drawing only the dirty region
821 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform);
822 composeLayerRegion(layer, rect);
823 } else if (!rect.isEmpty()) {
824 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
827 // the layer contains screen buffer content that shouldn't be alpha modulated
828 // (and any necessary alpha modulation was handled drawing into the layer)
829 writableSnapshot()->alpha = 1.0f;
830 composeLayerRectSwapped(layer, rect);
836 // Failing to add the layer to the cache should happen only if the layer is too large
837 layer->setConvexMask(nullptr);
838 if (!mCaches.layerCache.put(layer)) {
839 LAYER_LOGD("Deleting layer");
840 layer->decStrong(nullptr);
844 void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
845 const bool tryToSnap = !layer->getForceFilter()
846 && layer->getWidth() == (uint32_t) rect.getWidth()
847 && layer->getHeight() == (uint32_t) rect.getHeight();
849 GlopBuilder(mRenderState, mCaches, &glop)
850 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
851 .setMeshTexturedUvQuad(nullptr, Rect(0, 1, 1, 0)) // TODO: simplify with VBO
852 .setFillTextureLayer(*layer, getLayerAlpha(layer))
853 .setTransform(*currentSnapshot(), TransformFlags::None)
854 .setModelViewMapUnitToRectOptionalSnap(tryToSnap, rect)
859 void OpenGLRenderer::composeLayerRectSwapped(Layer* layer, const Rect& rect) {
861 GlopBuilder(mRenderState, mCaches, &glop)
862 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
863 .setMeshTexturedUvQuad(nullptr, layer->texCoords)
864 .setFillLayer(layer->getTexture(), layer->getColorFilter(),
865 getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::Swap)
866 .setTransform(*currentSnapshot(), TransformFlags::MeshIgnoresCanvasTransform)
867 .setModelViewMapUnitToRect(rect)
872 void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect) {
873 if (layer->isTextureLayer()) {
874 EVENT_LOGD("composeTextureLayerRect");
875 drawTextureLayer(layer, rect);
877 EVENT_LOGD("composeHardwareLayerRect");
879 const bool tryToSnap = layer->getWidth() == static_cast<uint32_t>(rect.getWidth())
880 && layer->getHeight() == static_cast<uint32_t>(rect.getHeight());
882 GlopBuilder(mRenderState, mCaches, &glop)
883 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
884 .setMeshTexturedUvQuad(nullptr, layer->texCoords)
885 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap)
886 .setTransform(*currentSnapshot(), TransformFlags::None)
887 .setModelViewMapUnitToRectOptionalSnap(tryToSnap, rect)
894 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
895 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
896 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
897 * by saveLayer's restore
899 #define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \
901 if (CC_UNLIKELY(Properties::debugOverdraw && getTargetFbo() == 0 && COND)) { \
902 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \
904 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \
908 #define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
910 // This class is purely for inspection. It inherits from SkShader, but Skia does not know how to
911 // use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque.
912 class LayerShader : public SkShader {
914 LayerShader(Layer* layer, const SkMatrix* localMatrix)
915 : INHERITED(localMatrix)
919 virtual bool asACustomShader(void** data) const override {
921 *data = static_cast<void*>(mLayer);
926 virtual bool isOpaque() const override {
927 return !mLayer->isBlend();
931 virtual void shadeSpan(int x, int y, SkPMColor[], int count) {
932 LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend.");
935 virtual void flatten(SkWriteBuffer&) const override {
936 LOG_ALWAYS_FATAL("LayerShader should never be flattened.");
939 virtual Factory getFactory() const override {
940 LOG_ALWAYS_FATAL("LayerShader should never be created from a stream.");
946 typedef SkShader INHERITED;
949 void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
950 if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw
952 if (layer->getConvexMask()) {
953 save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
955 // clip to the area of the layer the mask can be larger
956 clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op);
959 paint.setAntiAlias(true);
960 paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0));
962 // create LayerShader to map SaveLayer content into subsequent draw
963 SkMatrix shaderMatrix;
964 shaderMatrix.setTranslate(rect.left, rect.bottom);
965 shaderMatrix.preScale(1, -1);
966 LayerShader layerShader(layer, &shaderMatrix);
967 paint.setShader(&layerShader);
969 // Since the drawing primitive is defined in local drawing space,
970 // we don't need to modify the draw matrix
971 const SkPath* maskPath = layer->getConvexMask();
972 DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint));
974 paint.setShader(nullptr);
980 if (layer->region.isRect()) {
981 layer->setRegionAsRect();
983 DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
985 layer->region.clear();
989 EVENT_LOGD("composeLayerRegion");
990 // standard Region based draw
992 const android::Rect* rects;
994 if (CC_LIKELY(hasRectToRectTransform())) {
995 rects = layer->region.getArray(&count);
997 safeRegion = Region::createTJunctionFreeRegion(layer->region);
998 rects = safeRegion.getArray(&count);
1001 const float texX = 1.0f / float(layer->getWidth());
1002 const float texY = 1.0f / float(layer->getHeight());
1003 const float height = rect.getHeight();
1005 TextureVertex quadVertices[count * 4];
1006 TextureVertex* mesh = &quadVertices[0];
1007 for (size_t i = 0; i < count; i++) {
1008 const android::Rect* r = &rects[i];
1010 const float u1 = r->left * texX;
1011 const float v1 = (height - r->top) * texY;
1012 const float u2 = r->right * texX;
1013 const float v2 = (height - r->bottom) * texY;
1015 // TODO: Reject quads outside of the clip
1016 TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1017 TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1018 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1019 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1021 Rect modelRect = Rect(rect.getWidth(), rect.getHeight());
1023 GlopBuilder(mRenderState, mCaches, &glop)
1024 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1025 .setMeshTexturedIndexedQuads(&quadVertices[0], count * 6)
1026 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap)
1027 .setTransform(*currentSnapshot(), TransformFlags::None)
1028 .setModelViewOffsetRectSnap(rect.left, rect.top, modelRect)
1030 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop));
1032 #if DEBUG_LAYERS_AS_REGIONS
1033 drawRegionRectsDebug(layer->region);
1036 layer->region.clear();
1039 #if DEBUG_LAYERS_AS_REGIONS
1040 void OpenGLRenderer::drawRegionRectsDebug(const Region& region) {
1042 const android::Rect* rects = region.getArray(&count);
1044 uint32_t colors[] = {
1045 0x7fff0000, 0x7f00ff00,
1046 0x7f0000ff, 0x7fff00ff,
1050 int32_t top = rects[0].top;
1052 for (size_t i = 0; i < count; i++) {
1053 if (top != rects[i].top) {
1059 paint.setColor(colors[offset + (i & 0x1)]);
1060 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1061 drawColorRect(r.left, r.top, r.right, r.bottom, paint);
1066 void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) {
1067 Vector<float> rects;
1069 SkRegion::Iterator it(region);
1070 while (!it.done()) {
1071 const SkIRect& r = it.rect();
1072 rects.push(r.fLeft);
1074 rects.push(r.fRight);
1075 rects.push(r.fBottom);
1079 drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false);
1082 void OpenGLRenderer::dirtyLayer(const float left, const float top,
1083 const float right, const float bottom, const Matrix4& transform) {
1085 Rect bounds(left, top, right, bottom);
1086 transform.mapRect(bounds);
1087 dirtyLayerUnchecked(bounds, getRegion());
1091 void OpenGLRenderer::dirtyLayer(const float left, const float top,
1092 const float right, const float bottom) {
1094 Rect bounds(left, top, right, bottom);
1095 dirtyLayerUnchecked(bounds, getRegion());
1099 void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1100 if (CC_LIKELY(!bounds.isEmpty() && bounds.intersect(mState.currentClipRect()))) {
1101 bounds.snapToPixelBoundaries();
1102 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1103 if (!dirty.isEmpty()) {
1104 region->orSelf(dirty);
1109 void OpenGLRenderer::clearLayerRegions() {
1110 const size_t quadCount = mLayers.size();
1111 if (quadCount == 0) return;
1113 if (!mState.currentlyIgnored()) {
1114 EVENT_LOGD("clearLayerRegions");
1115 // Doing several glScissor/glClear here can negatively impact
1116 // GPUs with a tiler architecture, instead we draw quads with
1117 // the Clear blending mode
1119 // The list contains bounds that have already been clipped
1120 // against their initial clip rect, and the current clip
1121 // is likely different so we need to disable clipping here
1122 bool scissorChanged = mRenderState.scissor().setEnabled(false);
1124 Vertex mesh[quadCount * 4];
1125 Vertex* vertex = mesh;
1127 for (uint32_t i = 0; i < quadCount; i++) {
1128 const Rect& bounds = mLayers[i];
1130 Vertex::set(vertex++, bounds.left, bounds.top);
1131 Vertex::set(vertex++, bounds.right, bounds.top);
1132 Vertex::set(vertex++, bounds.left, bounds.bottom);
1133 Vertex::set(vertex++, bounds.right, bounds.bottom);
1135 // We must clear the list of dirty rects before we
1136 // call clearLayerRegions() in renderGlop to prevent
1137 // stencil setup from doing the same thing again
1140 const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform;
1142 GlopBuilder(mRenderState, mCaches, &glop)
1143 .setRoundRectClipState(nullptr) // clear ignores clip state
1144 .setMeshIndexedQuads(&mesh[0], quadCount)
1146 .setTransform(*currentSnapshot(), transformFlags)
1147 .setModelViewOffsetRect(0, 0, Rect(currentSnapshot()->getClipRect()))
1149 renderGlop(glop, GlopRenderType::LayerClear);
1151 if (scissorChanged) mRenderState.scissor().setEnabled(true);
1157 ///////////////////////////////////////////////////////////////////////////////
1159 ///////////////////////////////////////////////////////////////////////////////
1161 bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1162 const Rect& currentClip = mState.currentClipRect();
1163 const mat4* currentMatrix = currentTransform();
1165 if (stateDeferFlags & kStateDeferFlag_Draw) {
1166 // state has bounds initialized in local coordinates
1167 if (!state.mBounds.isEmpty()) {
1168 currentMatrix->mapRect(state.mBounds);
1169 Rect clippedBounds(state.mBounds);
1170 // NOTE: if we ever want to use this clipping info to drive whether the scissor
1171 // is used, it should more closely duplicate the quickReject logic (in how it uses
1172 // snapToPixelBoundaries)
1174 if (!clippedBounds.intersect(currentClip)) {
1179 state.mClipSideFlags = kClipSide_None;
1180 if (!currentClip.contains(state.mBounds)) {
1181 int& flags = state.mClipSideFlags;
1182 // op partially clipped, so record which sides are clipped for clip-aware merging
1183 if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left;
1184 if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top;
1185 if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right;
1186 if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom;
1188 state.mBounds.set(clippedBounds);
1190 // Empty bounds implies size unknown. Label op as conservatively clipped to disable
1191 // overdraw avoidance (since we don't know what it overlaps)
1192 state.mClipSideFlags = kClipSide_ConservativeFull;
1193 state.mBounds.set(currentClip);
1197 state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1198 if (state.mClipValid) {
1199 state.mClip.set(currentClip);
1202 // Transform and alpha always deferred, since they are used by state operations
1203 // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1204 state.mMatrix.load(*currentMatrix);
1205 state.mAlpha = currentSnapshot()->alpha;
1207 // always store/restore, since these are just pointers
1208 state.mRoundRectClipState = currentSnapshot()->roundRectClipState;
1209 state.mProjectionPathMask = currentSnapshot()->projectionPathMask;
1213 void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1214 setMatrix(state.mMatrix);
1215 writableSnapshot()->alpha = state.mAlpha;
1216 writableSnapshot()->roundRectClipState = state.mRoundRectClipState;
1217 writableSnapshot()->projectionPathMask = state.mProjectionPathMask;
1219 if (state.mClipValid && !skipClipRestore) {
1220 writableSnapshot()->setClip(state.mClip.left, state.mClip.top,
1221 state.mClip.right, state.mClip.bottom);
1227 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done
1228 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at
1229 * least one op is clipped), or disabled entirely (because no merged op is clipped)
1231 * This method should be called when restoreDisplayState() won't be restoring the clip
1233 void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) {
1234 if (clipRect != nullptr) {
1235 writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom);
1237 writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight());
1240 bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled;
1241 mRenderState.scissor().setEnabled(enableScissor);
1244 ///////////////////////////////////////////////////////////////////////////////
1246 ///////////////////////////////////////////////////////////////////////////////
1248 void OpenGLRenderer::setScissorFromClip() {
1249 Rect clip(mState.currentClipRect());
1250 clip.snapToPixelBoundaries();
1252 if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom,
1253 clip.getWidth(), clip.getHeight())) {
1254 mState.setDirtyClip(false);
1258 void OpenGLRenderer::ensureStencilBuffer() {
1259 // Thanks to the mismatch between EGL and OpenGL ES FBO we
1260 // cannot attach a stencil buffer to fbo0 dynamically. Let's
1261 // just hope we have one when hasLayer() returns false.
1263 attachStencilBufferToLayer(currentSnapshot()->layer);
1267 void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1268 // The layer's FBO is already bound when we reach this stage
1269 if (!layer->getStencilRenderBuffer()) {
1270 // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1271 // is attached after we initiated tiling. We must turn it off,
1272 // attach the new render buffer then turn tiling back on
1275 RenderBuffer* buffer = mCaches.renderBufferCache.get(
1276 Stencil::getLayerStencilFormat(),
1277 layer->getWidth(), layer->getHeight());
1278 layer->setStencilRenderBuffer(buffer);
1280 startTiling(layer->clipRect, layer->layer.getHeight());
1284 static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform,
1289 transform.mapPoint(v.x, v.y);
1290 rectangleVertices.push_back(v);
1293 static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) {
1297 rectangleVertices.push_back(v);
1300 void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) {
1301 int quadCount = rectangleList.getTransformedRectanglesCount();
1302 std::vector<Vertex> rectangleVertices(quadCount * 4);
1303 Rect scissorBox = rectangleList.calculateBounds();
1304 scissorBox.snapToPixelBoundaries();
1305 for (int i = 0; i < quadCount; ++i) {
1306 const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i));
1307 const Matrix4& transform = tr.getTransform();
1308 Rect bounds = tr.getBounds();
1309 if (transform.rectToRect()) {
1310 transform.mapRect(bounds);
1311 if (!bounds.intersect(scissorBox)) {
1314 handlePointNoTransform(rectangleVertices, bounds.left, bounds.top);
1315 handlePointNoTransform(rectangleVertices, bounds.right, bounds.top);
1316 handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom);
1317 handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom);
1320 handlePoint(rectangleVertices, transform, bounds.left, bounds.top);
1321 handlePoint(rectangleVertices, transform, bounds.right, bounds.top);
1322 handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom);
1323 handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom);
1327 mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom,
1328 scissorBox.getWidth(), scissorBox.getHeight());
1329 const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform;
1331 Vertex* vertices = &rectangleVertices[0];
1332 GlopBuilder(mRenderState, mCaches, &glop)
1333 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1334 .setMeshIndexedQuads(vertices, rectangleVertices.size() / 4)
1336 .setTransform(*currentSnapshot(), transformFlags)
1337 .setModelViewOffsetRect(0, 0, scissorBox)
1342 void OpenGLRenderer::setStencilFromClip() {
1343 if (!Properties::debugOverdraw) {
1344 if (!currentSnapshot()->clipIsSimple()) {
1345 int incrementThreshold;
1346 EVENT_LOGD("setStencilFromClip - enabling");
1348 // NOTE: The order here is important, we must set dirtyClip to false
1349 // before any draw call to avoid calling back into this method
1350 mState.setDirtyClip(false);
1352 ensureStencilBuffer();
1354 const ClipArea& clipArea = currentSnapshot()->getClipArea();
1356 bool isRectangleList = clipArea.isRectangleList();
1357 if (isRectangleList) {
1358 incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount();
1360 incrementThreshold = 0;
1363 mRenderState.stencil().enableWrite(incrementThreshold);
1365 // Clean and update the stencil, but first make sure we restrict drawing
1366 // to the region's bounds
1367 bool resetScissor = mRenderState.scissor().setEnabled(true);
1369 // The scissor was not set so we now need to update it
1370 setScissorFromClip();
1373 mRenderState.stencil().clear();
1375 // stash and disable the outline clip state, since stencil doesn't account for outline
1376 bool storedSkipOutlineClip = mSkipOutlineClip;
1377 mSkipOutlineClip = true;
1380 paint.setColor(SK_ColorBLACK);
1381 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1383 if (isRectangleList) {
1384 drawRectangleList(clipArea.getRectangleList());
1386 // NOTE: We could use the region contour path to generate a smaller mesh
1387 // Since we are using the stencil we could use the red book path
1388 // drawing technique. It might increase bandwidth usage though.
1390 // The last parameter is important: we are not drawing in the color buffer
1391 // so we don't want to dirty the current layer, if any
1392 drawRegionRects(clipArea.getClipRegion(), paint, false);
1394 if (resetScissor) mRenderState.scissor().setEnabled(false);
1395 mSkipOutlineClip = storedSkipOutlineClip;
1397 mRenderState.stencil().enableTest(incrementThreshold);
1399 // Draw the region used to generate the stencil if the appropriate debug
1401 // TODO: Implement for rectangle list clip areas
1402 if (Properties::debugStencilClip == StencilClipDebug::ShowRegion
1403 && !clipArea.isRectangleList()) {
1404 paint.setColor(0x7f0000ff);
1405 paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
1406 drawRegionRects(currentSnapshot()->getClipRegion(), paint);
1409 EVENT_LOGD("setStencilFromClip - disabling");
1410 mRenderState.stencil().disable();
1416 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out.
1418 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint
1419 * style, and tessellated AA ramp
1421 bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom,
1422 const SkPaint* paint) {
1423 bool snapOut = paint && paint->isAntiAlias();
1425 if (paint && paint->getStyle() != SkPaint::kFill_Style) {
1426 float outset = paint->getStrokeWidth() * 0.5f;
1433 bool clipRequired = false;
1434 bool roundRectClipRequired = false;
1435 if (mState.calculateQuickRejectForScissor(left, top, right, bottom,
1436 &clipRequired, &roundRectClipRequired, snapOut)) {
1440 // not quick rejected, so enable the scissor if clipRequired
1441 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
1442 mSkipOutlineClip = !roundRectClipRequired;
1446 void OpenGLRenderer::debugClip() {
1447 #if DEBUG_CLIP_REGIONS
1448 if (!currentSnapshot()->clipRegion->isEmpty()) {
1450 paint.setColor(0x7f00ff00);
1451 drawRegionRects(*(currentSnapshot()->clipRegion, paint);
1457 void OpenGLRenderer::renderGlop(const Glop& glop, GlopRenderType type) {
1458 // TODO: It would be best if we could do this before quickRejectSetupScissor()
1459 // changes the scissor test state
1460 if (type != GlopRenderType::LayerClear) {
1461 // Regular draws need to clear the dirty area on the layer before they start drawing on top
1462 // of it. If this draw *is* a layer clear, it skips the clear step (since it would
1463 // infinitely recurse)
1464 clearLayerRegions();
1467 if (mState.getDirtyClip()) {
1468 if (mRenderState.scissor().isEnabled()) {
1469 setScissorFromClip();
1472 setStencilFromClip();
1474 mRenderState.render(glop);
1475 if (type == GlopRenderType::Standard && !mRenderState.stencil().isWriteEnabled()) {
1476 // TODO: specify more clearly when a draw should dirty the layer.
1477 // is writing to the stencil the only time we should ignore this?
1478 dirtyLayer(glop.bounds.left, glop.bounds.top, glop.bounds.right, glop.bounds.bottom);
1483 ///////////////////////////////////////////////////////////////////////////////
1485 ///////////////////////////////////////////////////////////////////////////////
1487 void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) {
1488 // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1489 // will be performed by the display list itself
1490 if (renderNode && renderNode->isRenderable()) {
1491 // compute 3d ordering
1492 renderNode->computeOrdering();
1493 if (CC_UNLIKELY(Properties::drawDeferDisabled)) {
1495 ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1496 renderNode->replay(replayStruct, 0);
1500 // Don't avoid overdraw when visualizing, since that makes it harder to
1501 // debug where it's coming from, and when the problem occurs.
1502 bool avoidOverdraw = !Properties::debugOverdraw;
1503 DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw);
1504 DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1505 renderNode->defer(deferStruct, 0);
1510 deferredList.flush(*this, dirty);
1512 // Even if there is no drawing command(Ex: invisible),
1513 // it still needs startFrame to clear buffer and start tiling.
1519 * Important note: this method is intended to draw batches of bitmaps and
1520 * will not set the scissor enable or dirty the current layer, if any.
1521 * The caller is responsible for properly dirtying the current layer.
1523 void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
1524 int bitmapCount, TextureVertex* vertices, bool pureTranslate,
1525 const Rect& bounds, const SkPaint* paint) {
1526 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1527 if (!texture) return;
1529 const AutoTexture autoCleanup(texture);
1531 // TODO: remove layer dirty in multi-draw callers
1532 // TODO: snap doesn't need to touch transform, only texture filter.
1533 bool snap = pureTranslate;
1534 const float x = floorf(bounds.left + 0.5f);
1535 const float y = floorf(bounds.top + 0.5f);
1537 const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType)
1538 ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
1539 const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform;
1541 GlopBuilder(mRenderState, mCaches, &glop)
1542 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1543 .setMeshTexturedMesh(vertices, bitmapCount * 6)
1544 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1545 .setTransform(*currentSnapshot(), transformFlags)
1546 .setModelViewOffsetRectOptionalSnap(snap, x, y, Rect(0, 0, bounds.getWidth(), bounds.getHeight()))
1548 renderGlop(glop, GlopRenderType::Multi);
1551 void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
1552 if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) {
1556 mCaches.textureState().activateTexture(0);
1557 Texture* texture = getTexture(bitmap);
1558 if (!texture) return;
1559 const AutoTexture autoCleanup(texture);
1561 const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType)
1562 ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
1564 GlopBuilder(mRenderState, mCaches, &glop)
1565 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1566 .setMeshTexturedUnitQuad(texture->uvMapper)
1567 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1568 .setTransform(*currentSnapshot(), TransformFlags::None)
1569 .setModelViewMapUnitToRectSnap(Rect(0, 0, texture->width, texture->height))
1574 void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight,
1575 const float* vertices, const int* colors, const SkPaint* paint) {
1576 if (!vertices || mState.currentlyIgnored()) {
1580 float left = FLT_MAX;
1581 float top = FLT_MAX;
1582 float right = FLT_MIN;
1583 float bottom = FLT_MIN;
1585 const uint32_t elementCount = meshWidth * meshHeight * 6;
1587 std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[elementCount]);
1588 ColorTextureVertex* vertex = &mesh[0];
1590 std::unique_ptr<int[]> tempColors;
1592 uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
1593 tempColors.reset(new int[colorsCount]);
1594 memset(tempColors.get(), 0xff, colorsCount * sizeof(int));
1595 colors = tempColors.get();
1598 Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
1599 const UvMapper& mapper(getMapper(texture));
1601 for (int32_t y = 0; y < meshHeight; y++) {
1602 for (int32_t x = 0; x < meshWidth; x++) {
1603 uint32_t i = (y * (meshWidth + 1) + x) * 2;
1605 float u1 = float(x) / meshWidth;
1606 float u2 = float(x + 1) / meshWidth;
1607 float v1 = float(y) / meshHeight;
1608 float v2 = float(y + 1) / meshHeight;
1610 mapper.map(u1, v1, u2, v2);
1612 int ax = i + (meshWidth + 1) * 2;
1618 int dx = i + (meshWidth + 1) * 2 + 2;
1621 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
1622 ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
1623 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
1625 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
1626 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
1627 ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
1629 left = std::min(left, std::min(vertices[ax], std::min(vertices[bx], vertices[cx])));
1630 top = std::min(top, std::min(vertices[ay], std::min(vertices[by], vertices[cy])));
1631 right = std::max(right, std::max(vertices[ax], std::max(vertices[bx], vertices[cx])));
1632 bottom = std::max(bottom, std::max(vertices[ay], std::max(vertices[by], vertices[cy])));
1636 if (quickRejectSetupScissor(left, top, right, bottom)) {
1641 texture = mCaches.textureCache.get(bitmap);
1646 const AutoTexture autoCleanup(texture);
1649 * TODO: handle alpha_8 textures correctly by applying paint color, but *not*
1650 * shader in that case to mimic the behavior in SkiaCanvas::drawBitmapMesh.
1652 const int textureFillFlags = TextureFillFlags::None;
1654 GlopBuilder(mRenderState, mCaches, &glop)
1655 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1656 .setMeshColoredTexturedMesh(mesh.get(), elementCount)
1657 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1658 .setTransform(*currentSnapshot(), TransformFlags::None)
1659 .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom))
1664 void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst, const SkPaint* paint) {
1665 if (quickRejectSetupScissor(dst)) {
1669 Texture* texture = getTexture(bitmap);
1670 if (!texture) return;
1671 const AutoTexture autoCleanup(texture);
1673 Rect uv(std::max(0.0f, src.left / texture->width),
1674 std::max(0.0f, src.top / texture->height),
1675 std::min(1.0f, src.right / texture->width),
1676 std::min(1.0f, src.bottom / texture->height));
1678 const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType)
1679 ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None;
1680 const bool tryToSnap = MathUtils::areEqual(src.getWidth(), dst.getWidth())
1681 && MathUtils::areEqual(src.getHeight(), dst.getHeight());
1683 GlopBuilder(mRenderState, mCaches, &glop)
1684 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1685 .setMeshTexturedUvQuad(texture->uvMapper, uv)
1686 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1687 .setTransform(*currentSnapshot(), TransformFlags::None)
1688 .setModelViewMapUnitToRectOptionalSnap(tryToSnap, dst)
1693 void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh,
1694 AssetAtlas::Entry* entry, float left, float top, float right, float bottom,
1695 const SkPaint* paint) {
1696 if (!mesh || !mesh->verticesCount || quickRejectSetupScissor(left, top, right, bottom)) {
1700 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1701 if (!texture) return;
1703 // 9 patches are built for stretching - always filter
1704 int textureFillFlags = TextureFillFlags::ForceFilter;
1705 if (bitmap->colorType() == kAlpha_8_SkColorType) {
1706 textureFillFlags |= TextureFillFlags::IsAlphaMaskTexture;
1709 GlopBuilder(mRenderState, mCaches, &glop)
1710 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1711 .setMeshPatchQuads(*mesh)
1712 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1713 .setTransform(*currentSnapshot(), TransformFlags::None)
1714 .setModelViewOffsetRectSnap(left, top, Rect(0, 0, right - left, bottom - top)) // TODO: get minimal bounds from patch
1720 * Important note: this method is intended to draw batches of 9-patch objects and
1721 * will not set the scissor enable or dirty the current layer, if any.
1722 * The caller is responsible for properly dirtying the current layer.
1724 void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry,
1725 TextureVertex* vertices, uint32_t elementCount, const SkPaint* paint) {
1726 mCaches.textureState().activateTexture(0);
1727 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap);
1728 if (!texture) return;
1729 const AutoTexture autoCleanup(texture);
1731 // TODO: get correct bounds from caller
1732 const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform;
1733 // 9 patches are built for stretching - always filter
1734 int textureFillFlags = TextureFillFlags::ForceFilter;
1735 if (bitmap->colorType() == kAlpha_8_SkColorType) {
1736 textureFillFlags |= TextureFillFlags::IsAlphaMaskTexture;
1739 GlopBuilder(mRenderState, mCaches, &glop)
1740 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1741 .setMeshTexturedIndexedQuads(vertices, elementCount)
1742 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha)
1743 .setTransform(*currentSnapshot(), transformFlags)
1744 .setModelViewOffsetRect(0, 0, Rect(0, 0, 0, 0))
1746 renderGlop(glop, GlopRenderType::Multi);
1749 void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY,
1750 const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) {
1751 // not missing call to quickReject/dirtyLayer, always done at a higher level
1752 if (!vertexBuffer.getVertexCount()) {
1753 // no vertices to draw
1757 bool shadowInterp = displayFlags & kVertexBuffer_ShadowInterp;
1758 const int transformFlags = TransformFlags::OffsetByFudgeFactor;
1760 GlopBuilder(mRenderState, mCaches, &glop)
1761 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
1762 .setMeshVertexBuffer(vertexBuffer, shadowInterp)
1763 .setFillPaint(*paint, currentSnapshot()->alpha)
1764 .setTransform(*currentSnapshot(), transformFlags)
1765 .setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds())
1771 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
1772 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in
1773 * screen space in all directions. However, instead of using a fragment shader to compute the
1774 * translucency of the color from its position, we simply use a varying parameter to define how far
1775 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
1777 * Doesn't yet support joins, caps, or path effects.
1779 void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) {
1780 VertexBuffer vertexBuffer;
1781 // TODO: try clipping large paths to viewport
1783 PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer);
1784 drawVertexBuffer(vertexBuffer, paint);
1788 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
1789 * and additional geometry for defining an alpha slope perimeter.
1791 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
1792 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
1793 * in-shader alpha region, but found it to be taxing on some GPUs.
1795 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
1796 * memory transfer by removing need for degenerate vertices.
1798 void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) {
1799 if (mState.currentlyIgnored() || count < 4) return;
1801 count &= ~0x3; // round down to nearest four
1803 VertexBuffer buffer;
1804 PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer);
1805 const Rect& bounds = buffer.getBounds();
1807 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
1811 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
1812 drawVertexBuffer(buffer, paint, displayFlags);
1815 void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) {
1816 if (mState.currentlyIgnored() || count < 2) return;
1818 count &= ~0x1; // round down to nearest two
1820 VertexBuffer buffer;
1821 PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer);
1823 const Rect& bounds = buffer.getBounds();
1824 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) {
1828 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset;
1829 drawVertexBuffer(buffer, paint, displayFlags);
1834 void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
1835 // No need to check against the clip, we fill the clip region
1836 if (mState.currentlyIgnored()) return;
1838 Rect clip(mState.currentClipRect());
1839 clip.snapToPixelBoundaries();
1842 paint.setColor(color);
1843 paint.setXfermodeMode(mode);
1845 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true);
1850 void OpenGLRenderer::drawShape(float left, float top, PathTexture* texture,
1851 const SkPaint* paint) {
1852 if (!texture) return;
1853 const AutoTexture autoCleanup(texture);
1855 const float x = left + texture->left - texture->offset;
1856 const float y = top + texture->top - texture->offset;
1858 drawPathTexture(texture, x, y, paint);
1863 void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
1864 float rx, float ry, const SkPaint* p) {
1865 if (mState.currentlyIgnored()
1866 || quickRejectSetupScissor(left, top, right, bottom, p)
1867 || PaintUtils::paintWillNotDraw(*p)) {
1871 if (p->getPathEffect() != nullptr) {
1872 mCaches.textureState().activateTexture(0);
1873 PathTexture* texture = mCaches.pathCache.getRoundRect(
1874 right - left, bottom - top, rx, ry, p);
1875 drawShape(left, top, texture, p);
1877 const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect(
1878 *currentTransform(), *p, right - left, bottom - top, rx, ry);
1879 drawVertexBuffer(left, top, *vertexBuffer, p);
1883 void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) {
1884 if (mState.currentlyIgnored()
1885 || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p)
1886 || PaintUtils::paintWillNotDraw(*p)) {
1890 if (p->getPathEffect() != nullptr) {
1891 mCaches.textureState().activateTexture(0);
1892 PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
1893 drawShape(x - radius, y - radius, texture, p);
1898 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1899 path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
1901 path.addCircle(x, y, radius);
1904 if (CC_UNLIKELY(currentSnapshot()->projectionPathMask != nullptr)) {
1905 // mask ripples with projection mask
1906 SkPath maskPath = *(currentSnapshot()->projectionPathMask->projectionMask);
1908 Matrix4 screenSpaceTransform;
1909 currentSnapshot()->buildScreenSpaceTransform(&screenSpaceTransform);
1911 Matrix4 totalTransform;
1912 totalTransform.loadInverse(screenSpaceTransform);
1913 totalTransform.multiply(currentSnapshot()->projectionPathMask->projectionMaskTransform);
1915 SkMatrix skTotalTransform;
1916 totalTransform.copyTo(skTotalTransform);
1917 maskPath.transform(skTotalTransform);
1919 // Mask the ripple path by the projection mask, now that it's
1920 // in local space. Note that this can create CCW paths.
1921 Op(path, maskPath, kIntersect_PathOp, &path);
1923 drawConvexPath(path, p);
1926 void OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
1928 if (mState.currentlyIgnored()
1929 || quickRejectSetupScissor(left, top, right, bottom, p)
1930 || PaintUtils::paintWillNotDraw(*p)) {
1934 if (p->getPathEffect() != nullptr) {
1935 mCaches.textureState().activateTexture(0);
1936 PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
1937 drawShape(left, top, texture, p);
1940 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
1941 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1942 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
1945 drawConvexPath(path, p);
1949 void OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
1950 float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) {
1951 if (mState.currentlyIgnored()
1952 || quickRejectSetupScissor(left, top, right, bottom, p)
1953 || PaintUtils::paintWillNotDraw(*p)) {
1957 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
1958 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) {
1959 mCaches.textureState().activateTexture(0);
1960 PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
1961 startAngle, sweepAngle, useCenter, p);
1962 drawShape(left, top, texture, p);
1965 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
1966 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
1967 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
1972 path.moveTo(rect.centerX(), rect.centerY());
1974 path.arcTo(rect, startAngle, sweepAngle, !useCenter);
1978 drawConvexPath(path, p);
1981 // See SkPaintDefaults.h
1982 #define SkPaintDefaults_MiterLimit SkIntToScalar(4)
1984 void OpenGLRenderer::drawRect(float left, float top, float right, float bottom,
1986 if (mState.currentlyIgnored()
1987 || quickRejectSetupScissor(left, top, right, bottom, p)
1988 || PaintUtils::paintWillNotDraw(*p)) {
1992 if (p->getStyle() != SkPaint::kFill_Style) {
1993 // only fill style is supported by drawConvexPath, since others have to handle joins
1994 if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join ||
1995 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
1996 mCaches.textureState().activateTexture(0);
1997 PathTexture* texture =
1998 mCaches.pathCache.getRect(right - left, bottom - top, p);
1999 drawShape(left, top, texture, p);
2002 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2003 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2004 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2007 drawConvexPath(path, p);
2010 if (p->isAntiAlias() && !currentTransform()->isSimple()) {
2012 path.addRect(left, top, right, bottom);
2013 drawConvexPath(path, p);
2015 drawColorRect(left, top, right, bottom, p);
2022 void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text,
2023 int bytesCount, int count, const float* positions,
2024 FontRenderer& fontRenderer, int alpha, float x, float y) {
2025 mCaches.textureState().activateTexture(0);
2027 TextShadow textShadow;
2028 if (!getTextShadow(paint, &textShadow)) {
2029 LOG_ALWAYS_FATAL("failed to query shadow attributes");
2032 // NOTE: The drop shadow will not perform gamma correction
2033 // if shader-based correction is enabled
2034 mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2035 ShadowTexture* texture = mCaches.dropShadowCache.get(
2036 paint, text, bytesCount, count, textShadow.radius, positions);
2037 // If the drop shadow exceeds the max texture size or couldn't be
2038 // allocated, skip drawing
2039 if (!texture) return;
2040 const AutoTexture autoCleanup(texture);
2042 const float sx = x - texture->left + textShadow.dx;
2043 const float sy = y - texture->top + textShadow.dy;
2046 GlopBuilder(mRenderState, mCaches, &glop)
2047 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2048 .setMeshTexturedUnitQuad(nullptr)
2049 .setFillShadowTexturePaint(*texture, textShadow.color, *paint, currentSnapshot()->alpha)
2050 .setTransform(*currentSnapshot(), TransformFlags::None)
2051 .setModelViewMapUnitToRect(Rect(sx, sy, sx + texture->width, sy + texture->height))
2056 bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2057 float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha;
2058 return MathUtils::isZero(alpha)
2059 && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2062 void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2063 const float* positions, const SkPaint* paint) {
2064 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2068 // NOTE: Skia does not support perspective transform on drawPosText yet
2069 if (!currentTransform()->isSimple()) {
2073 mRenderState.scissor().setEnabled(true);
2077 const bool pureTranslate = currentTransform()->isPureTranslate();
2078 if (pureTranslate) {
2079 x = floorf(x + currentTransform()->getTranslateX() + 0.5f);
2080 y = floorf(y + currentTransform()->getTranslateY() + 0.5f);
2083 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2084 fontRenderer.setFont(paint, SkMatrix::I());
2087 SkXfermode::Mode mode;
2088 getAlphaAndMode(paint, &alpha, &mode);
2090 if (CC_UNLIKELY(hasTextShadow(paint))) {
2091 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2095 // Pick the appropriate texture filtering
2096 bool linearFilter = currentTransform()->changesBounds();
2097 if (pureTranslate && !linearFilter) {
2098 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2100 fontRenderer.setTextureFiltering(linearFilter);
2102 const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip());
2103 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2105 TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2106 if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y,
2107 positions, hasLayer() ? &bounds : nullptr, &functor)) {
2108 dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2114 bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const {
2115 if (CC_LIKELY(transform.isPureTranslate())) {
2116 outMatrix->setIdentity();
2118 } else if (CC_UNLIKELY(transform.isPerspective())) {
2119 outMatrix->setIdentity();
2124 * Input is a non-perspective, scaling transform. Generate a scale-only transform,
2125 * with values rounded to the nearest int.
2128 transform.decomposeScale(sx, sy);
2129 outMatrix->setScale(
2130 roundf(std::max(1.0f, sx)),
2131 roundf(std::max(1.0f, sy)));
2135 int OpenGLRenderer::getSaveCount() const {
2136 return mState.getSaveCount();
2139 int OpenGLRenderer::save(int flags) {
2140 return mState.save(flags);
2143 void OpenGLRenderer::restore() {
2147 void OpenGLRenderer::restoreToCount(int saveCount) {
2148 mState.restoreToCount(saveCount);
2151 void OpenGLRenderer::translate(float dx, float dy, float dz) {
2152 mState.translate(dx, dy, dz);
2155 void OpenGLRenderer::rotate(float degrees) {
2156 mState.rotate(degrees);
2159 void OpenGLRenderer::scale(float sx, float sy) {
2160 mState.scale(sx, sy);
2163 void OpenGLRenderer::skew(float sx, float sy) {
2164 mState.skew(sx, sy);
2167 void OpenGLRenderer::setMatrix(const Matrix4& matrix) {
2168 mState.setMatrix(matrix);
2171 void OpenGLRenderer::concatMatrix(const Matrix4& matrix) {
2172 mState.concatMatrix(matrix);
2175 bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
2176 return mState.clipRect(left, top, right, bottom, op);
2179 bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) {
2180 return mState.clipPath(path, op);
2183 bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) {
2184 return mState.clipRegion(region, op);
2187 void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) {
2188 mState.setClippingOutline(allocator, outline);
2191 void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator,
2192 const Rect& rect, float radius, bool highPriority) {
2193 mState.setClippingRoundRect(allocator, rect, radius, highPriority);
2196 void OpenGLRenderer::setProjectionPathMask(LinearAllocator& allocator, const SkPath* path) {
2197 mState.setProjectionPathMask(allocator, path);
2200 void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y,
2201 const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds,
2202 DrawOpMode drawOpMode) {
2204 if (drawOpMode == DrawOpMode::kImmediate) {
2205 // The checks for corner-case ignorable text and quick rejection is only done for immediate
2206 // drawing as ops from DeferredDisplayList are already filtered for these
2207 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) ||
2208 quickRejectSetupScissor(bounds)) {
2213 const float oldX = x;
2214 const float oldY = y;
2216 const mat4& transform = *currentTransform();
2217 const bool pureTranslate = transform.isPureTranslate();
2219 if (CC_LIKELY(pureTranslate)) {
2220 x = floorf(x + transform.getTranslateX() + 0.5f);
2221 y = floorf(y + transform.getTranslateY() + 0.5f);
2225 SkXfermode::Mode mode;
2226 getAlphaAndMode(paint, &alpha, &mode);
2228 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2230 if (CC_UNLIKELY(hasTextShadow(paint))) {
2231 fontRenderer.setFont(paint, SkMatrix::I());
2232 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2236 const bool hasActiveLayer = hasLayer();
2238 // We only pass a partial transform to the font renderer. That partial
2239 // matrix defines how glyphs are rasterized. Typically we want glyphs
2240 // to be rasterized at their final size on screen, which means the partial
2241 // matrix needs to take the scale factor into account.
2242 // When a partial matrix is used to transform glyphs during rasterization,
2243 // the mesh is generated with the inverse transform (in the case of scale,
2244 // the mesh is generated at 1.0 / scale for instance.) This allows us to
2245 // apply the full transform matrix at draw time in the vertex shader.
2246 // Applying the full matrix in the shader is the easiest way to handle
2247 // rotation and perspective and allows us to always generated quads in the
2248 // font renderer which greatly simplifies the code, clipping in particular.
2249 SkMatrix fontTransform;
2250 bool linearFilter = findBestFontTransform(transform, &fontTransform)
2251 || fabs(y - (int) y) > 0.0f
2252 || fabs(x - (int) x) > 0.0f;
2253 fontRenderer.setFont(paint, fontTransform);
2254 fontRenderer.setTextureFiltering(linearFilter);
2256 // TODO: Implement better clipping for scaled/rotated text
2257 const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect();
2258 Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2261 TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint);
2263 // don't call issuedrawcommand, do it at end of batch
2264 bool forceFinish = (drawOpMode != DrawOpMode::kDefer);
2265 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2266 SkPaint paintCopy(*paint);
2267 paintCopy.setTextAlign(SkPaint::kLeft_Align);
2268 status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2269 positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2271 status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2272 positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish);
2275 if ((status || drawOpMode != DrawOpMode::kImmediate) && hasActiveLayer) {
2276 if (!pureTranslate) {
2277 transform.mapRect(layerBounds);
2279 dirtyLayerUnchecked(layerBounds, getRegion());
2282 drawTextDecorations(totalAdvance, oldX, oldY, paint);
2287 void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count,
2288 const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) {
2289 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) {
2293 // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics
2294 mRenderState.scissor().setEnabled(true);
2296 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2297 fontRenderer.setFont(paint, SkMatrix::I());
2298 fontRenderer.setTextureFiltering(true);
2301 SkXfermode::Mode mode;
2302 getAlphaAndMode(paint, &alpha, &mode);
2303 TextDrawFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint);
2305 const Rect* clip = &writableSnapshot()->getLocalClip();
2306 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2308 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
2309 hOffset, vOffset, hasLayer() ? &bounds : nullptr, &functor)) {
2310 dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform());
2315 void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) {
2316 if (mState.currentlyIgnored()) return;
2318 mCaches.textureState().activateTexture(0);
2320 PathTexture* texture = mCaches.pathCache.get(path, paint);
2321 if (!texture) return;
2322 const AutoTexture autoCleanup(texture);
2324 const float x = texture->left - texture->offset;
2325 const float y = texture->top - texture->offset;
2327 drawPathTexture(texture, x, y, paint);
2331 void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
2336 mat4* transform = nullptr;
2337 if (layer->isTextureLayer()) {
2338 transform = &layer->getTransform();
2339 if (!transform->isIdentity()) {
2340 save(SkCanvas::kMatrix_SaveFlag);
2341 concatMatrix(*transform);
2345 bool clipRequired = false;
2346 const bool rejected = mState.calculateQuickRejectForScissor(
2347 x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
2348 &clipRequired, nullptr, false);
2351 if (transform && !transform->isIdentity()) {
2357 EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y,
2358 x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired);
2360 updateLayer(layer, true);
2362 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired);
2363 mCaches.textureState().activateTexture(0);
2365 if (CC_LIKELY(!layer->region.isEmpty())) {
2366 if (layer->region.isRect()) {
2367 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
2368 composeLayerRect(layer, layer->regionRect));
2369 } else if (layer->mesh) {
2371 GlopBuilder(mRenderState, mCaches, &glop)
2372 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2373 .setMeshTexturedIndexedQuads(layer->mesh, layer->meshElementCount)
2374 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap)
2375 .setTransform(*currentSnapshot(), TransformFlags::None)
2376 .setModelViewOffsetRectSnap(x, y, Rect(0, 0, layer->layer.getWidth(), layer->layer.getHeight()))
2378 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop));
2379 #if DEBUG_LAYERS_AS_REGIONS
2380 drawRegionRectsDebug(layer->region);
2384 if (layer->debugDrawUpdate) {
2385 layer->debugDrawUpdate = false;
2388 paint.setColor(0x7f00ff00);
2389 drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint);
2392 layer->hasDrawnSinceUpdate = true;
2394 if (transform && !transform->isIdentity()) {
2401 ///////////////////////////////////////////////////////////////////////////////
2403 ///////////////////////////////////////////////////////////////////////////////
2404 void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) {
2405 // We should never get here since we apply the draw filter when stashing
2406 // the paints in the DisplayList.
2407 LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters");
2410 ///////////////////////////////////////////////////////////////////////////////
2411 // Drawing implementation
2412 ///////////////////////////////////////////////////////////////////////////////
2414 Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) {
2415 Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap);
2417 return mCaches.textureCache.get(bitmap);
2422 void OpenGLRenderer::drawPathTexture(PathTexture* texture, float x, float y,
2423 const SkPaint* paint) {
2424 if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) {
2429 GlopBuilder(mRenderState, mCaches, &glop)
2430 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2431 .setMeshTexturedUnitQuad(nullptr)
2432 .setFillPathTexturePaint(*texture, *paint, currentSnapshot()->alpha)
2433 .setTransform(*currentSnapshot(), TransformFlags::None)
2434 .setModelViewMapUnitToRect(Rect(x, y, x + texture->width, y + texture->height))
2439 // Same values used by Skia
2440 #define kStdStrikeThru_Offset (-6.0f / 21.0f)
2441 #define kStdUnderline_Offset (1.0f / 9.0f)
2442 #define kStdUnderline_Thickness (1.0f / 18.0f)
2444 void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y,
2445 const SkPaint* paint) {
2446 // Handle underline and strike-through
2447 uint32_t flags = paint->getFlags();
2448 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
2449 SkPaint paintCopy(*paint);
2451 if (CC_LIKELY(underlineWidth > 0.0f)) {
2452 const float textSize = paintCopy.getTextSize();
2453 const float strokeWidth = std::max(textSize * kStdUnderline_Thickness, 1.0f);
2455 const float left = x;
2459 if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
2460 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
2462 const int pointsCount = 4 * linesCount;
2463 float points[pointsCount];
2464 int currentPoint = 0;
2466 if (flags & SkPaint::kUnderlineText_Flag) {
2467 top = y + textSize * kStdUnderline_Offset;
2468 points[currentPoint++] = left;
2469 points[currentPoint++] = top;
2470 points[currentPoint++] = left + underlineWidth;
2471 points[currentPoint++] = top;
2474 if (flags & SkPaint::kStrikeThruText_Flag) {
2475 top = y + textSize * kStdStrikeThru_Offset;
2476 points[currentPoint++] = left;
2477 points[currentPoint++] = top;
2478 points[currentPoint++] = left + underlineWidth;
2479 points[currentPoint++] = top;
2482 paintCopy.setStrokeWidth(strokeWidth);
2484 drawLines(&points[0], pointsCount, &paintCopy);
2489 void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) {
2490 if (mState.currentlyIgnored()) {
2494 drawColorRects(rects, count, paint, false, true, true);
2497 void OpenGLRenderer::drawShadow(float casterAlpha,
2498 const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) {
2499 if (mState.currentlyIgnored()) return;
2501 // TODO: use quickRejectWithScissor. For now, always force enable scissor.
2502 mRenderState.scissor().setEnabled(true);
2505 paint.setAntiAlias(true); // want to use AlphaVertex
2507 // The caller has made sure casterAlpha > 0.
2508 float ambientShadowAlpha = mAmbientShadowAlpha;
2509 if (CC_UNLIKELY(Properties::overrideAmbientShadowStrength >= 0)) {
2510 ambientShadowAlpha = Properties::overrideAmbientShadowStrength;
2512 if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) {
2513 paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0);
2514 drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
2517 float spotShadowAlpha = mSpotShadowAlpha;
2518 if (CC_UNLIKELY(Properties::overrideSpotShadowStrength >= 0)) {
2519 spotShadowAlpha = Properties::overrideSpotShadowStrength;
2521 if (spotShadowVertexBuffer && spotShadowAlpha > 0) {
2522 paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0);
2523 drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp);
2529 void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint,
2530 bool ignoreTransform, bool dirty, bool clip) {
2535 float left = FLT_MAX;
2536 float top = FLT_MAX;
2537 float right = FLT_MIN;
2538 float bottom = FLT_MIN;
2541 Vertex* vertex = mesh;
2543 for (int index = 0; index < count; index += 4) {
2544 float l = rects[index + 0];
2545 float t = rects[index + 1];
2546 float r = rects[index + 2];
2547 float b = rects[index + 3];
2549 Vertex::set(vertex++, l, t);
2550 Vertex::set(vertex++, r, t);
2551 Vertex::set(vertex++, l, b);
2552 Vertex::set(vertex++, r, b);
2554 left = std::min(left, l);
2555 top = std::min(top, t);
2556 right = std::max(right, r);
2557 bottom = std::max(bottom, b);
2560 if (clip && quickRejectSetupScissor(left, top, right, bottom)) {
2564 const int transformFlags = ignoreTransform
2565 ? TransformFlags::MeshIgnoresCanvasTransform : TransformFlags::None;
2567 GlopBuilder(mRenderState, mCaches, &glop)
2568 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2569 .setMeshIndexedQuads(&mesh[0], count / 4)
2570 .setFillPaint(*paint, currentSnapshot()->alpha)
2571 .setTransform(*currentSnapshot(), transformFlags)
2572 .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom))
2577 void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
2578 const SkPaint* paint, bool ignoreTransform) {
2579 const int transformFlags = ignoreTransform
2580 ? TransformFlags::MeshIgnoresCanvasTransform : TransformFlags::None;
2582 GlopBuilder(mRenderState, mCaches, &glop)
2583 .setRoundRectClipState(currentSnapshot()->roundRectClipState)
2585 .setFillPaint(*paint, currentSnapshot()->alpha)
2586 .setTransform(*currentSnapshot(), transformFlags)
2587 .setModelViewMapUnitToRect(Rect(left, top, right, bottom))
2592 void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha,
2593 SkXfermode::Mode* mode) const {
2594 getAlphaAndModeDirect(paint, alpha, mode);
2595 *alpha *= currentSnapshot()->alpha;
2598 float OpenGLRenderer::getLayerAlpha(const Layer* layer) const {
2599 return (layer->getAlpha() / 255.0f) * currentSnapshot()->alpha;
2602 }; // namespace uirenderer
2603 }; // namespace android