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 #define LOG_TAG "OpenGLRenderer"
21 #include <sys/types.h>
24 #include <SkPathMeasure.h>
25 #include <SkTypeface.h>
27 #include <utils/Log.h>
28 #include <utils/StopWatch.h>
30 #include <private/hwui/DrawGlInfo.h>
34 #include "OpenGLRenderer.h"
35 #include "DeferredDisplayList.h"
36 #include "DisplayListRenderer.h"
37 #include "PathTessellator.h"
38 #include "Properties.h"
42 namespace uirenderer {
44 ///////////////////////////////////////////////////////////////////////////////
46 ///////////////////////////////////////////////////////////////////////////////
48 #define RAD_TO_DEG (180.0f / 3.14159265f)
49 #define MIN_ANGLE 0.001f
51 #define ALPHA_THRESHOLD 0
53 #define FILTER(paint) (!paint || paint->isFilterBitmap() ? GL_LINEAR : GL_NEAREST)
55 ///////////////////////////////////////////////////////////////////////////////
57 ///////////////////////////////////////////////////////////////////////////////
60 * Structure mapping Skia xfermodes to OpenGL blending factors.
63 SkXfermode::Mode mode;
68 // In this array, the index of each Blender equals the value of the first
69 // entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
70 static const Blender gBlends[] = {
71 { SkXfermode::kClear_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA },
72 { SkXfermode::kSrc_Mode, GL_ONE, GL_ZERO },
73 { SkXfermode::kDst_Mode, GL_ZERO, GL_ONE },
74 { SkXfermode::kSrcOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA },
75 { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE },
76 { SkXfermode::kSrcIn_Mode, GL_DST_ALPHA, GL_ZERO },
77 { SkXfermode::kDstIn_Mode, GL_ZERO, GL_SRC_ALPHA },
78 { SkXfermode::kSrcOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
79 { SkXfermode::kDstOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA },
80 { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
81 { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
82 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
83 { SkXfermode::kPlus_Mode, GL_ONE, GL_ONE },
84 { SkXfermode::kModulate_Mode, GL_ZERO, GL_SRC_COLOR },
85 { SkXfermode::kScreen_Mode, GL_ONE, GL_ONE_MINUS_SRC_COLOR }
88 // This array contains the swapped version of each SkXfermode. For instance
89 // this array's SrcOver blending mode is actually DstOver. You can refer to
90 // createLayer() for more information on the purpose of this array.
91 static const Blender gBlendsSwap[] = {
92 { SkXfermode::kClear_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
93 { SkXfermode::kSrc_Mode, GL_ZERO, GL_ONE },
94 { SkXfermode::kDst_Mode, GL_ONE, GL_ZERO },
95 { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE },
96 { SkXfermode::kDstOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA },
97 { SkXfermode::kSrcIn_Mode, GL_ZERO, GL_SRC_ALPHA },
98 { SkXfermode::kDstIn_Mode, GL_DST_ALPHA, GL_ZERO },
99 { SkXfermode::kSrcOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA },
100 { SkXfermode::kDstOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO },
101 { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA },
102 { SkXfermode::kDstATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
103 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
104 { SkXfermode::kPlus_Mode, GL_ONE, GL_ONE },
105 { SkXfermode::kModulate_Mode, GL_DST_COLOR, GL_ZERO },
106 { SkXfermode::kScreen_Mode, GL_ONE_MINUS_DST_COLOR, GL_ONE }
109 ///////////////////////////////////////////////////////////////////////////////
110 // Constructors/destructor
111 ///////////////////////////////////////////////////////////////////////////////
113 OpenGLRenderer::OpenGLRenderer():
114 mCaches(Caches::getInstance()), mExtensions(Extensions::getInstance()) {
115 // *set* draw modifiers to be 0
116 memset(&mDrawModifiers, 0, sizeof(mDrawModifiers));
117 mDrawModifiers.mOverrideLayerAlpha = 1.0f;
119 memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
121 mFirstSnapshot = new Snapshot;
122 mFrameStarted = false;
124 mScissorOptimizationDisabled = false;
127 OpenGLRenderer::~OpenGLRenderer() {
128 // The context has already been destroyed at this point, do not call
129 // GL APIs. All GL state should be kept in Caches.h
132 void OpenGLRenderer::initProperties() {
133 char property[PROPERTY_VALUE_MAX];
134 if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) {
135 mScissorOptimizationDisabled = !strcasecmp(property, "true");
136 INIT_LOGD(" Scissor optimization %s",
137 mScissorOptimizationDisabled ? "disabled" : "enabled");
139 INIT_LOGD(" Scissor optimization enabled");
143 ///////////////////////////////////////////////////////////////////////////////
145 ///////////////////////////////////////////////////////////////////////////////
147 void OpenGLRenderer::setName(const char* name) {
155 const char* OpenGLRenderer::getName() const {
156 return mName.string();
159 bool OpenGLRenderer::isDeferred() {
163 void OpenGLRenderer::setViewport(int width, int height) {
164 initViewport(width, height);
166 glDisable(GL_DITHER);
167 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
169 glEnableVertexAttribArray(Program::kBindingPosition);
172 void OpenGLRenderer::initViewport(int width, int height) {
173 mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
178 mFirstSnapshot->height = height;
179 mFirstSnapshot->viewport.set(0, 0, width, height);
182 void OpenGLRenderer::setupFrameState(float left, float top,
183 float right, float bottom, bool opaque) {
184 mCaches.clearGarbage();
187 mSnapshot = new Snapshot(mFirstSnapshot,
188 SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
189 mSnapshot->fbo = getTargetFbo();
192 mSnapshot->setClip(left, top, right, bottom);
193 mTilingClip.set(left, top, right, bottom);
196 status_t OpenGLRenderer::startFrame() {
197 if (mFrameStarted) return DrawGlInfo::kStatusDone;
198 mFrameStarted = true;
202 discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom);
204 glViewport(0, 0, mWidth, mHeight);
206 // Functors break the tiling extension in pretty spectacular ways
207 // This ensures we don't use tiling when a functor is going to be
208 // invoked during the frame
209 mSuppressTiling = mCaches.hasRegisteredFunctors();
211 startTiling(mSnapshot, true);
213 debugOverdraw(true, true);
215 return clear(mTilingClip.left, mTilingClip.top,
216 mTilingClip.right, mTilingClip.bottom, mOpaque);
219 status_t OpenGLRenderer::prepare(bool opaque) {
220 return prepareDirty(0.0f, 0.0f, mWidth, mHeight, opaque);
223 status_t OpenGLRenderer::prepareDirty(float left, float top,
224 float right, float bottom, bool opaque) {
225 setupFrameState(left, top, right, bottom, opaque);
227 // Layer renderers will start the frame immediately
228 // The framebuffer renderer will first defer the display list
229 // for each layer and wait until the first drawing command
230 // to start the frame
231 if (mSnapshot->fbo == 0) {
238 return DrawGlInfo::kStatusDone;
241 void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) {
242 // If we know that we are going to redraw the entire framebuffer,
243 // perform a discard to let the driver know we don't need to preserve
244 // the back buffer for this frame.
245 if (mExtensions.hasDiscardFramebuffer() &&
246 left <= 0.0f && top <= 0.0f && right >= mWidth && bottom >= mHeight) {
247 const bool isFbo = getTargetFbo() == 0;
248 const GLenum attachments[] = {
249 isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0,
250 isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT };
251 glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
255 status_t OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) {
257 mCaches.enableScissor();
258 mCaches.setScissor(left, mSnapshot->height - bottom, right - left, bottom - top);
259 glClear(GL_COLOR_BUFFER_BIT);
260 return DrawGlInfo::kStatusDrew;
263 mCaches.resetScissor();
264 return DrawGlInfo::kStatusDone;
267 void OpenGLRenderer::syncState() {
275 void OpenGLRenderer::startTiling(const sp<Snapshot>& s, bool opaque) {
276 if (!mSuppressTiling) {
277 Rect* clip = &mTilingClip;
278 if (s->flags & Snapshot::kFlagFboTarget) {
279 clip = &(s->layer->clipRect);
282 startTiling(*clip, s->height, opaque);
286 void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque) {
287 if (!mSuppressTiling) {
288 mCaches.startTiling(clip.left, windowHeight - clip.bottom,
289 clip.right - clip.left, clip.bottom - clip.top, opaque);
293 void OpenGLRenderer::endTiling() {
294 if (!mSuppressTiling) mCaches.endTiling();
297 void OpenGLRenderer::finish() {
301 // When finish() is invoked on FBO 0 we've reached the end
302 // of the current frame
303 if (getTargetFbo() == 0) {
304 mCaches.pathCache.trim();
307 if (!suppressErrorChecks()) {
309 GLenum status = GL_NO_ERROR;
310 while ((status = glGetError()) != GL_NO_ERROR) {
311 ALOGD("GL error from OpenGLRenderer: 0x%x", status);
313 case GL_INVALID_ENUM:
314 ALOGE(" GL_INVALID_ENUM");
316 case GL_INVALID_VALUE:
317 ALOGE(" GL_INVALID_VALUE");
319 case GL_INVALID_OPERATION:
320 ALOGE(" GL_INVALID_OPERATION");
322 case GL_OUT_OF_MEMORY:
323 ALOGE(" Out of memory!");
329 #if DEBUG_MEMORY_USAGE
330 mCaches.dumpMemoryUsage();
332 if (mCaches.getDebugLevel() & kDebugMemory) {
333 mCaches.dumpMemoryUsage();
338 mFrameStarted = false;
341 void OpenGLRenderer::interrupt() {
342 if (mCaches.currentProgram) {
343 if (mCaches.currentProgram->isInUse()) {
344 mCaches.currentProgram->remove();
345 mCaches.currentProgram = NULL;
348 mCaches.unbindMeshBuffer();
349 mCaches.unbindIndicesBuffer();
350 mCaches.resetVertexPointers();
351 mCaches.disableTexCoordsVertexArray();
352 debugOverdraw(false, false);
355 void OpenGLRenderer::resume() {
356 sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
357 glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
358 glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
359 debugOverdraw(true, false);
361 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
363 mCaches.scissorEnabled = glIsEnabled(GL_SCISSOR_TEST);
364 mCaches.enableScissor();
365 mCaches.resetScissor();
368 mCaches.activeTexture(0);
370 mCaches.blend = true;
372 glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode);
373 glBlendEquation(GL_FUNC_ADD);
376 void OpenGLRenderer::resumeAfterLayer() {
377 sp<Snapshot> snapshot = (mSnapshot != NULL) ? mSnapshot : mFirstSnapshot;
378 glViewport(0, 0, snapshot->viewport.getWidth(), snapshot->viewport.getHeight());
379 glBindFramebuffer(GL_FRAMEBUFFER, snapshot->fbo);
380 debugOverdraw(true, false);
382 mCaches.resetScissor();
386 void OpenGLRenderer::detachFunctor(Functor* functor) {
387 mFunctors.remove(functor);
390 void OpenGLRenderer::attachFunctor(Functor* functor) {
391 mFunctors.add(functor);
394 status_t OpenGLRenderer::invokeFunctors(Rect& dirty) {
395 status_t result = DrawGlInfo::kStatusDone;
396 size_t count = mFunctors.size();
400 SortedVector<Functor*> functors(mFunctors);
408 info.isLayer = false;
411 memset(info.transform, 0, sizeof(float) * 16);
413 for (size_t i = 0; i < count; i++) {
414 Functor* f = functors.itemAt(i);
415 result |= (*f)(DrawGlInfo::kModeProcess, &info);
417 if (result & DrawGlInfo::kStatusDraw) {
418 Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
419 dirty.unionWith(localDirty);
422 if (result & DrawGlInfo::kStatusInvoke) {
432 status_t OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) {
433 if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
436 detachFunctor(functor);
438 mCaches.enableScissor();
440 setScissorFromClip();
443 Rect clip(*mSnapshot->clipRect);
444 clip.snapToPixelBoundaries();
446 // Since we don't know what the functor will draw, let's dirty
447 // tne entire clip region
449 dirtyLayerUnchecked(clip, getRegion());
453 info.clipLeft = clip.left;
454 info.clipTop = clip.top;
455 info.clipRight = clip.right;
456 info.clipBottom = clip.bottom;
457 info.isLayer = hasLayer();
458 info.width = getSnapshot()->viewport.getWidth();
459 info.height = getSnapshot()->height;
460 getSnapshot()->transform->copyTo(&info.transform[0]);
462 status_t result = (*functor)(DrawGlInfo::kModeDraw, &info) | DrawGlInfo::kStatusDrew;
464 if (result != DrawGlInfo::kStatusDone) {
465 Rect localDirty(info.dirtyLeft, info.dirtyTop, info.dirtyRight, info.dirtyBottom);
466 dirty.unionWith(localDirty);
468 if (result & DrawGlInfo::kStatusInvoke) {
469 mFunctors.add(functor);
477 ///////////////////////////////////////////////////////////////////////////////
479 ///////////////////////////////////////////////////////////////////////////////
481 void OpenGLRenderer::eventMark(const char* name) const {
482 mCaches.eventMark(0, name);
485 void OpenGLRenderer::startMark(const char* name) const {
486 mCaches.startMark(0, name);
489 void OpenGLRenderer::endMark() const {
493 void OpenGLRenderer::debugOverdraw(bool enable, bool clear) {
494 if (mCaches.debugOverdraw && getTargetFbo() == 0) {
496 mCaches.disableScissor();
497 mCaches.stencil.clear();
500 mCaches.stencil.enableDebugWrite();
502 mCaches.stencil.disable();
507 void OpenGLRenderer::renderOverdraw() {
508 if (mCaches.debugOverdraw && getTargetFbo() == 0) {
509 const Rect* clip = &mTilingClip;
511 mCaches.enableScissor();
512 mCaches.setScissor(clip->left, mFirstSnapshot->height - clip->bottom,
513 clip->right - clip->left, clip->bottom - clip->top);
515 mCaches.stencil.enableDebugTest(2);
516 drawColor(0x2f0000ff, SkXfermode::kSrcOver_Mode);
517 mCaches.stencil.enableDebugTest(3);
518 drawColor(0x2f00ff00, SkXfermode::kSrcOver_Mode);
519 mCaches.stencil.enableDebugTest(4);
520 drawColor(0x3fff0000, SkXfermode::kSrcOver_Mode);
521 mCaches.stencil.enableDebugTest(4, true);
522 drawColor(0x7fff0000, SkXfermode::kSrcOver_Mode);
523 mCaches.stencil.disable();
527 ///////////////////////////////////////////////////////////////////////////////
529 ///////////////////////////////////////////////////////////////////////////////
531 bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) {
532 if (layer->deferredUpdateScheduled && layer->renderer &&
533 layer->displayList && layer->displayList->isRenderable()) {
534 Rect& dirty = layer->dirtyRect;
538 debugOverdraw(false, false);
541 if (CC_UNLIKELY(inFrame || mCaches.drawDeferDisabled)) {
549 startTiling(mSnapshot);
552 layer->debugDrawUpdate = mCaches.debugLayersUpdates;
553 layer->hasDrawnSinceUpdate = false;
561 void OpenGLRenderer::updateLayers() {
562 // If draw deferring is enabled this method will simply defer
563 // the display list of each individual layer. The layers remain
564 // in the layer updates list which will be cleared by flushLayers().
565 int count = mLayerUpdates.size();
567 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
568 startMark("Layer Updates");
570 startMark("Defer Layer Updates");
573 // Note: it is very important to update the layers in order
574 for (int i = 0; i < count; i++) {
575 Layer* layer = mLayerUpdates.itemAt(i);
576 updateLayer(layer, false);
577 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
578 mCaches.resourceCache.decrementRefcount(layer);
582 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
583 mLayerUpdates.clear();
584 glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
590 void OpenGLRenderer::flushLayers() {
591 int count = mLayerUpdates.size();
593 startMark("Apply Layer Updates");
596 // Note: it is very important to update the layers in order
597 for (int i = 0; i < count; i++) {
598 sprintf(layerName, "Layer #%d", i);
599 startMark(layerName);
601 Layer* layer = mLayerUpdates.itemAt(i);
603 mCaches.resourceCache.decrementRefcount(layer);
608 mLayerUpdates.clear();
609 glBindFramebuffer(GL_FRAMEBUFFER, getTargetFbo());
615 void OpenGLRenderer::pushLayerUpdate(Layer* layer) {
617 // Make sure we don't introduce duplicates.
618 // SortedVector would do this automatically but we need to respect
619 // the insertion order. The linear search is not an issue since
620 // this list is usually very short (typically one item, at most a few)
621 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) {
622 if (mLayerUpdates.itemAt(i) == layer) {
626 mLayerUpdates.push_back(layer);
627 mCaches.resourceCache.incrementRefcount(layer);
631 void OpenGLRenderer::clearLayerUpdates() {
632 size_t count = mLayerUpdates.size();
634 mCaches.resourceCache.lock();
635 for (size_t i = 0; i < count; i++) {
636 mCaches.resourceCache.decrementRefcountLocked(mLayerUpdates.itemAt(i));
638 mCaches.resourceCache.unlock();
639 mLayerUpdates.clear();
643 ///////////////////////////////////////////////////////////////////////////////
645 ///////////////////////////////////////////////////////////////////////////////
647 int OpenGLRenderer::getSaveCount() const {
651 int OpenGLRenderer::save(int flags) {
652 return saveSnapshot(flags);
655 void OpenGLRenderer::restore() {
656 if (mSaveCount > 1) {
661 void OpenGLRenderer::restoreToCount(int saveCount) {
662 if (saveCount < 1) saveCount = 1;
664 while (mSaveCount > saveCount) {
669 int OpenGLRenderer::saveSnapshot(int flags) {
670 mSnapshot = new Snapshot(mSnapshot, flags);
674 bool OpenGLRenderer::restoreSnapshot() {
675 bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet;
676 bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer;
677 bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho;
679 sp<Snapshot> current = mSnapshot;
680 sp<Snapshot> previous = mSnapshot->previous;
683 Rect& r = previous->viewport;
684 glViewport(r.left, r.top, r.right, r.bottom);
685 mOrthoMatrix.load(current->orthoMatrix);
689 mSnapshot = previous;
696 endMark(); // Savelayer
697 startMark("ComposeLayer");
698 composeLayer(current, previous);
705 ///////////////////////////////////////////////////////////////////////////////
707 ///////////////////////////////////////////////////////////////////////////////
709 int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom,
710 int alpha, SkXfermode::Mode mode, int flags) {
711 const GLuint previousFbo = mSnapshot->fbo;
712 const int count = saveSnapshot(flags);
714 if (!mSnapshot->isIgnored()) {
715 createLayer(left, top, right, bottom, alpha, mode, flags, previousFbo);
721 void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) {
722 const Rect untransformedBounds(bounds);
724 currentTransform().mapRect(bounds);
726 // Layers only make sense if they are in the framebuffer's bounds
727 if (bounds.intersect(*mSnapshot->clipRect)) {
728 // We cannot work with sub-pixels in this case
729 bounds.snapToPixelBoundaries();
731 // When the layer is not an FBO, we may use glCopyTexImage so we
732 // need to make sure the layer does not extend outside the bounds
733 // of the framebuffer
734 if (!bounds.intersect(mSnapshot->previous->viewport)) {
736 } else if (fboLayer) {
739 inverse.loadInverse(currentTransform());
740 inverse.mapRect(clip);
741 clip.snapToPixelBoundaries();
742 if (clip.intersect(untransformedBounds)) {
743 clip.translate(-untransformedBounds.left, -untransformedBounds.top);
744 bounds.set(untransformedBounds);
754 void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip,
755 bool fboLayer, int alpha) {
756 if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize ||
757 bounds.getHeight() > mCaches.maxTextureSize ||
758 (fboLayer && clip.isEmpty())) {
759 mSnapshot->empty = fboLayer;
761 mSnapshot->invisible = mSnapshot->invisible || (alpha <= ALPHA_THRESHOLD && fboLayer);
765 int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom,
766 int alpha, SkXfermode::Mode mode, int flags) {
767 const GLuint previousFbo = mSnapshot->fbo;
768 const int count = saveSnapshot(flags);
770 if (!mSnapshot->isIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) {
771 // initialize the snapshot as though it almost represents an FBO layer so deferred draw
772 // operations will be able to store and restore the current clip and transform info, and
773 // quick rejection will be correct (for display lists)
775 Rect bounds(left, top, right, bottom);
777 calculateLayerBoundsAndClip(bounds, clip, true);
778 updateSnapshotIgnoreForLayer(bounds, clip, true, alpha);
780 if (!mSnapshot->isIgnored()) {
781 mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
782 mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
791 * Layers are viewed by Skia are slightly different than layers in image editing
792 * programs (for instance.) When a layer is created, previously created layers
793 * and the frame buffer still receive every drawing command. For instance, if a
794 * layer is created and a shape intersecting the bounds of the layers and the
795 * framebuffer is draw, the shape will be drawn on both (unless the layer was
796 * created with the SkCanvas::kClipToLayer_SaveFlag flag.)
798 * A way to implement layers is to create an FBO for each layer, backed by an RGBA
799 * texture. Unfortunately, this is inefficient as it requires every primitive to
800 * be drawn n + 1 times, where n is the number of active layers. In practice this
801 * means, for every primitive:
802 * - Switch active frame buffer
803 * - Change viewport, clip and projection matrix
804 * - Issue the drawing
806 * Switching rendering target n + 1 times per drawn primitive is extremely costly.
807 * To avoid this, layers are implemented in a different way here, at least in the
808 * general case. FBOs are used, as an optimization, when the "clip to layer" flag
809 * is set. When this flag is set we can redirect all drawing operations into a
812 * This implementation relies on the frame buffer being at least RGBA 8888. When
813 * a layer is created, only a texture is created, not an FBO. The content of the
814 * frame buffer contained within the layer's bounds is copied into this texture
815 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame
816 * buffer and drawing continues as normal. This technique therefore treats the
817 * frame buffer as a scratch buffer for the layers.
819 * To compose the layers back onto the frame buffer, each layer texture
820 * (containing the original frame buffer data) is drawn as a simple quad over
821 * the frame buffer. The trick is that the quad is set as the composition
822 * destination in the blending equation, and the frame buffer becomes the source
823 * of the composition.
825 * Drawing layers with an alpha value requires an extra step before composition.
826 * An empty quad is drawn over the layer's region in the frame buffer. This quad
827 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the
828 * quad is used to multiply the colors in the frame buffer. This is achieved by
829 * changing the GL blend functions for the GL_FUNC_ADD blend equation to
830 * GL_ZERO, GL_SRC_ALPHA.
832 * Because glCopyTexImage2D() can be slow, an alternative implementation might
833 * be use to draw a single clipped layer. The implementation described above
834 * is correct in every case.
836 * (1) The frame buffer is actually not cleared right away. To allow the GPU
837 * to potentially optimize series of calls to glCopyTexImage2D, the frame
838 * buffer is left untouched until the first drawing operation. Only when
839 * something actually gets drawn are the layers regions cleared.
841 bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom,
842 int alpha, SkXfermode::Mode mode, int flags, GLuint previousFbo) {
843 LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top);
844 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize());
846 const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag;
848 // Window coordinates of the layer
850 Rect bounds(left, top, right, bottom);
851 calculateLayerBoundsAndClip(bounds, clip, fboLayer);
852 updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, alpha);
854 // Bail out if we won't draw in this snapshot
855 if (mSnapshot->isIgnored()) {
859 mCaches.activeTexture(0);
860 Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight());
865 layer->setAlpha(alpha, mode);
866 layer->layer.set(bounds);
867 layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()),
868 bounds.getWidth() / float(layer->getWidth()), 0.0f);
869 layer->setColorFilter(mDrawModifiers.mColorFilter);
870 layer->setBlend(true);
871 layer->setDirty(false);
873 // Save the layer in the snapshot
874 mSnapshot->flags |= Snapshot::kFlagIsLayer;
875 mSnapshot->layer = layer;
877 startMark("SaveLayer");
879 return createFboLayer(layer, bounds, clip, previousFbo);
881 // Copy the framebuffer into the layer
882 layer->bindTexture();
883 if (!bounds.isEmpty()) {
884 if (layer->isEmpty()) {
885 // Workaround for some GL drivers. When reading pixels lying outside
886 // of the window we should get undefined values for those pixels.
887 // Unfortunately some drivers will turn the entire target texture black
888 // when reading outside of the window.
889 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(),
890 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
891 layer->setEmpty(false);
894 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left,
895 mSnapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight());
897 // Enqueue the buffer coordinates to clear the corresponding region later
898 mLayers.push(new Rect(bounds));
905 bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip, GLuint previousFbo) {
906 layer->clipRect.set(clip);
907 layer->setFbo(mCaches.fboCache.get());
909 mSnapshot->region = &mSnapshot->layer->region;
910 mSnapshot->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer |
911 Snapshot::kFlagDirtyOrtho;
912 mSnapshot->fbo = layer->getFbo();
913 mSnapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
914 mSnapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
915 mSnapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
916 mSnapshot->height = bounds.getHeight();
917 mSnapshot->orthoMatrix.load(mOrthoMatrix);
920 debugOverdraw(false, false);
921 // Bind texture to FBO
922 glBindFramebuffer(GL_FRAMEBUFFER, layer->getFbo());
923 layer->bindTexture();
925 // Initialize the texture if needed
926 if (layer->isEmpty()) {
927 layer->allocateTexture();
928 layer->setEmpty(false);
931 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
932 layer->getTexture(), 0);
934 startTiling(mSnapshot, true);
936 // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering
937 mCaches.enableScissor();
938 mCaches.setScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f,
939 clip.getWidth() + 2.0f, clip.getHeight() + 2.0f);
940 glClear(GL_COLOR_BUFFER_BIT);
944 // Change the ortho projection
945 glViewport(0, 0, bounds.getWidth(), bounds.getHeight());
946 mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f);
952 * Read the documentation of createLayer() before doing anything in this method.
954 void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) {
955 if (!current->layer) {
956 ALOGE("Attempting to compose a layer that does not exist");
960 Layer* layer = current->layer;
961 const Rect& rect = layer->layer;
962 const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer;
967 // Detach the texture from the FBO
968 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
970 layer->removeFbo(false);
972 // Unbind current FBO and restore previous one
973 glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo);
974 debugOverdraw(true, false);
976 startTiling(previous);
979 if (!fboLayer && layer->getAlpha() < 255) {
980 drawColorRect(rect.left, rect.top, rect.right, rect.bottom,
981 layer->getAlpha() << 24, SkXfermode::kDstIn_Mode, true);
982 // Required below, composeLayerRect() will divide by 255
983 layer->setAlpha(255);
986 mCaches.unbindMeshBuffer();
988 mCaches.activeTexture(0);
990 // When the layer is stored in an FBO, we can save a bit of fillrate by
991 // drawing only the dirty region
993 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
994 if (layer->getColorFilter()) {
995 setupColorFilter(layer->getColorFilter());
997 composeLayerRegion(layer, rect);
998 if (layer->getColorFilter()) {
1001 } else if (!rect.isEmpty()) {
1002 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
1003 composeLayerRect(layer, rect, true);
1008 // Failing to add the layer to the cache should happen only if the layer is too large
1009 if (!mCaches.layerCache.put(layer)) {
1010 LAYER_LOGD("Deleting layer");
1011 Caches::getInstance().resourceCache.decrementRefcount(layer);
1015 void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) {
1016 float alpha = layer->getAlpha() / 255.0f * mSnapshot->alpha;
1019 if (layer->getRenderTarget() == GL_TEXTURE_2D) {
1020 setupDrawWithTexture();
1022 setupDrawWithExternalTexture();
1024 setupDrawTextureTransform();
1025 setupDrawColor(alpha, alpha, alpha, alpha);
1026 setupDrawColorFilter();
1027 setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode());
1029 setupDrawPureColorUniforms();
1030 setupDrawColorFilterUniforms();
1031 if (layer->getRenderTarget() == GL_TEXTURE_2D) {
1032 setupDrawTexture(layer->getTexture());
1034 setupDrawExternalTexture(layer->getTexture());
1036 if (currentTransform().isPureTranslate() &&
1037 layer->getWidth() == (uint32_t) rect.getWidth() &&
1038 layer->getHeight() == (uint32_t) rect.getHeight()) {
1039 const float x = (int) floorf(rect.left + currentTransform().getTranslateX() + 0.5f);
1040 const float y = (int) floorf(rect.top + currentTransform().getTranslateY() + 0.5f);
1042 layer->setFilter(GL_NEAREST);
1043 setupDrawModelView(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1045 layer->setFilter(GL_LINEAR);
1046 setupDrawModelView(rect.left, rect.top, rect.right, rect.bottom);
1048 setupDrawTextureTransformUniforms(layer->getTexTransform());
1049 setupDrawMesh(&mMeshVertices[0].position[0], &mMeshVertices[0].texture[0]);
1051 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
1053 finishDrawTexture();
1056 void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) {
1057 if (!layer->isTextureLayer()) {
1058 const Rect& texCoords = layer->texCoords;
1059 resetDrawTextureTexCoords(texCoords.left, texCoords.top,
1060 texCoords.right, texCoords.bottom);
1062 float x = rect.left;
1064 bool simpleTransform = currentTransform().isPureTranslate() &&
1065 layer->getWidth() == (uint32_t) rect.getWidth() &&
1066 layer->getHeight() == (uint32_t) rect.getHeight();
1068 if (simpleTransform) {
1069 // When we're swapping, the layer is already in screen coordinates
1071 x = (int) floorf(rect.left + currentTransform().getTranslateX() + 0.5f);
1072 y = (int) floorf(rect.top + currentTransform().getTranslateY() + 0.5f);
1075 layer->setFilter(GL_NEAREST, true);
1077 layer->setFilter(GL_LINEAR, true);
1080 float alpha = getLayerAlpha(layer);
1081 bool blend = layer->isBlend() || alpha < 1.0f;
1082 drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(),
1083 layer->getTexture(), alpha, layer->getMode(), blend,
1084 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
1085 GL_TRIANGLE_STRIP, gMeshCount, swap, swap || simpleTransform);
1087 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1089 resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f);
1090 drawTextureLayer(layer, rect);
1091 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
1096 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated
1097 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw
1098 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used
1099 * by saveLayer's restore
1101 #define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \
1103 if (CC_UNLIKELY(mCaches.debugOverdraw && getTargetFbo() == 0 && COND)) { \
1104 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \
1106 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \
1110 #define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND)
1112 void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) {
1113 if (layer->region.isRect()) {
1114 layer->setRegionAsRect();
1116 DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect));
1118 layer->region.clear();
1122 // TODO: See LayerRenderer.cpp::generateMesh() for important
1123 // information about this implementation
1124 if (CC_LIKELY(!layer->region.isEmpty())) {
1126 const android::Rect* rects;
1128 if (CC_LIKELY(hasRectToRectTransform())) {
1129 rects = layer->region.getArray(&count);
1131 safeRegion = Region::createTJunctionFreeRegion(layer->region);
1132 rects = safeRegion.getArray(&count);
1135 const float alpha = getLayerAlpha(layer);
1136 const float texX = 1.0f / float(layer->getWidth());
1137 const float texY = 1.0f / float(layer->getHeight());
1138 const float height = rect.getHeight();
1142 // We must get (and therefore bind) the region mesh buffer
1143 // after we setup drawing in case we need to mess with the
1144 // stencil buffer in setupDraw()
1145 TextureVertex* mesh = mCaches.getRegionMesh();
1146 GLsizei numQuads = 0;
1148 setupDrawWithTexture();
1149 setupDrawColor(alpha, alpha, alpha, alpha);
1150 setupDrawColorFilter();
1151 setupDrawBlending(layer->isBlend() || alpha < 1.0f, layer->getMode(), false);
1153 setupDrawDirtyRegionsDisabled();
1154 setupDrawPureColorUniforms();
1155 setupDrawColorFilterUniforms();
1156 setupDrawTexture(layer->getTexture());
1157 if (currentTransform().isPureTranslate()) {
1158 const float x = (int) floorf(rect.left + currentTransform().getTranslateX() + 0.5f);
1159 const float y = (int) floorf(rect.top + currentTransform().getTranslateY() + 0.5f);
1161 layer->setFilter(GL_NEAREST);
1162 setupDrawModelViewTranslate(x, y, x + rect.getWidth(), y + rect.getHeight(), true);
1164 layer->setFilter(GL_LINEAR);
1165 setupDrawModelViewTranslate(rect.left, rect.top, rect.right, rect.bottom);
1167 setupDrawMeshIndices(&mesh[0].position[0], &mesh[0].texture[0]);
1169 for (size_t i = 0; i < count; i++) {
1170 const android::Rect* r = &rects[i];
1172 const float u1 = r->left * texX;
1173 const float v1 = (height - r->top) * texY;
1174 const float u2 = r->right * texX;
1175 const float v2 = (height - r->bottom) * texY;
1177 // TODO: Reject quads outside of the clip
1178 TextureVertex::set(mesh++, r->left, r->top, u1, v1);
1179 TextureVertex::set(mesh++, r->right, r->top, u2, v1);
1180 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2);
1181 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2);
1185 if (numQuads >= REGION_MESH_QUAD_COUNT) {
1186 DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1187 GL_UNSIGNED_SHORT, NULL));
1189 mesh = mCaches.getRegionMesh();
1194 DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6,
1195 GL_UNSIGNED_SHORT, NULL));
1198 finishDrawTexture();
1200 #if DEBUG_LAYERS_AS_REGIONS
1201 drawRegionRects(layer->region);
1204 layer->region.clear();
1208 void OpenGLRenderer::drawRegionRects(const Region& region) {
1209 #if DEBUG_LAYERS_AS_REGIONS
1211 const android::Rect* rects = region.getArray(&count);
1213 uint32_t colors[] = {
1214 0x7fff0000, 0x7f00ff00,
1215 0x7f0000ff, 0x7fff00ff,
1219 int32_t top = rects[0].top;
1221 for (size_t i = 0; i < count; i++) {
1222 if (top != rects[i].top) {
1227 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
1228 drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)],
1229 SkXfermode::kSrcOver_Mode);
1234 void OpenGLRenderer::drawRegionRects(const SkRegion& region, int color,
1235 SkXfermode::Mode mode, bool dirty) {
1237 Vector<float> rects;
1239 SkRegion::Iterator it(region);
1240 while (!it.done()) {
1241 const SkIRect& r = it.rect();
1242 rects.push(r.fLeft);
1244 rects.push(r.fRight);
1245 rects.push(r.fBottom);
1250 drawColorRects(rects.array(), count, color, mode, true, dirty, false);
1253 void OpenGLRenderer::dirtyLayer(const float left, const float top,
1254 const float right, const float bottom, const mat4 transform) {
1256 Rect bounds(left, top, right, bottom);
1257 transform.mapRect(bounds);
1258 dirtyLayerUnchecked(bounds, getRegion());
1262 void OpenGLRenderer::dirtyLayer(const float left, const float top,
1263 const float right, const float bottom) {
1265 Rect bounds(left, top, right, bottom);
1266 dirtyLayerUnchecked(bounds, getRegion());
1270 void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) {
1271 if (bounds.intersect(*mSnapshot->clipRect)) {
1272 bounds.snapToPixelBoundaries();
1273 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom);
1274 if (!dirty.isEmpty()) {
1275 region->orSelf(dirty);
1280 void OpenGLRenderer::clearLayerRegions() {
1281 const size_t count = mLayers.size();
1282 if (count == 0) return;
1284 if (!mSnapshot->isIgnored()) {
1285 // Doing several glScissor/glClear here can negatively impact
1286 // GPUs with a tiler architecture, instead we draw quads with
1287 // the Clear blending mode
1289 // The list contains bounds that have already been clipped
1290 // against their initial clip rect, and the current clip
1291 // is likely different so we need to disable clipping here
1292 bool scissorChanged = mCaches.disableScissor();
1294 Vertex mesh[count * 6];
1295 Vertex* vertex = mesh;
1297 for (uint32_t i = 0; i < count; i++) {
1298 Rect* bounds = mLayers.itemAt(i);
1300 Vertex::set(vertex++, bounds->left, bounds->bottom);
1301 Vertex::set(vertex++, bounds->left, bounds->top);
1302 Vertex::set(vertex++, bounds->right, bounds->top);
1303 Vertex::set(vertex++, bounds->left, bounds->bottom);
1304 Vertex::set(vertex++, bounds->right, bounds->top);
1305 Vertex::set(vertex++, bounds->right, bounds->bottom);
1309 // We must clear the list of dirty rects before we
1310 // call setupDraw() to prevent stencil setup to do
1311 // the same thing again
1315 setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f);
1316 setupDrawBlending(true, SkXfermode::kClear_Mode);
1318 setupDrawPureColorUniforms();
1319 setupDrawModelViewTranslate(0.0f, 0.0f, 0.0f, 0.0f, true);
1320 setupDrawVertices(&mesh[0].position[0]);
1322 glDrawArrays(GL_TRIANGLES, 0, count * 6);
1324 if (scissorChanged) mCaches.enableScissor();
1326 for (uint32_t i = 0; i < count; i++) {
1327 delete mLayers.itemAt(i);
1333 ///////////////////////////////////////////////////////////////////////////////
1335 ///////////////////////////////////////////////////////////////////////////////
1337 bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) {
1338 const Rect& currentClip = *(mSnapshot->clipRect);
1339 const mat4& currentMatrix = *(mSnapshot->transform);
1341 if (stateDeferFlags & kStateDeferFlag_Draw) {
1342 // state has bounds initialized in local coordinates
1343 if (!state.mBounds.isEmpty()) {
1344 currentMatrix.mapRect(state.mBounds);
1345 if (!state.mBounds.intersect(currentClip)) {
1350 state.mBounds.set(currentClip);
1354 state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip);
1355 if (state.mClipValid) {
1356 state.mClip.set(currentClip);
1359 // Transform, drawModifiers, and alpha always deferred, since they are used by state operations
1360 // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything)
1361 state.mMatrix.load(currentMatrix);
1362 state.mDrawModifiers = mDrawModifiers;
1363 state.mAlpha = mSnapshot->alpha;
1367 void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) {
1368 currentTransform().load(state.mMatrix);
1369 mDrawModifiers = state.mDrawModifiers;
1370 mSnapshot->alpha = state.mAlpha;
1372 if (state.mClipValid && !skipClipRestore) {
1373 mSnapshot->setClip(state.mClip.left, state.mClip.top, state.mClip.right, state.mClip.bottom);
1378 void OpenGLRenderer::setFullScreenClip() {
1379 mSnapshot->setClip(0, 0, mWidth, mHeight);
1383 ///////////////////////////////////////////////////////////////////////////////
1385 ///////////////////////////////////////////////////////////////////////////////
1387 void OpenGLRenderer::translate(float dx, float dy) {
1388 currentTransform().translate(dx, dy, 0.0f);
1391 void OpenGLRenderer::rotate(float degrees) {
1392 currentTransform().rotate(degrees, 0.0f, 0.0f, 1.0f);
1395 void OpenGLRenderer::scale(float sx, float sy) {
1396 currentTransform().scale(sx, sy, 1.0f);
1399 void OpenGLRenderer::skew(float sx, float sy) {
1400 currentTransform().skew(sx, sy);
1403 void OpenGLRenderer::setMatrix(SkMatrix* matrix) {
1405 currentTransform().load(*matrix);
1407 currentTransform().loadIdentity();
1411 bool OpenGLRenderer::hasRectToRectTransform() {
1412 return CC_LIKELY(currentTransform().rectToRect());
1415 void OpenGLRenderer::getMatrix(SkMatrix* matrix) {
1416 currentTransform().copyTo(*matrix);
1419 void OpenGLRenderer::concatMatrix(SkMatrix* matrix) {
1421 currentTransform().copyTo(transform);
1422 transform.preConcat(*matrix);
1423 currentTransform().load(transform);
1426 ///////////////////////////////////////////////////////////////////////////////
1428 ///////////////////////////////////////////////////////////////////////////////
1430 void OpenGLRenderer::setScissorFromClip() {
1431 Rect clip(*mSnapshot->clipRect);
1432 clip.snapToPixelBoundaries();
1434 if (mCaches.setScissor(clip.left, mSnapshot->height - clip.bottom,
1435 clip.getWidth(), clip.getHeight())) {
1440 void OpenGLRenderer::ensureStencilBuffer() {
1441 // Thanks to the mismatch between EGL and OpenGL ES FBO we
1442 // cannot attach a stencil buffer to fbo0 dynamically. Let's
1443 // just hope we have one when hasLayer() returns false.
1445 attachStencilBufferToLayer(mSnapshot->layer);
1449 void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) {
1450 // The layer's FBO is already bound when we reach this stage
1451 if (!layer->getStencilRenderBuffer()) {
1452 // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer
1453 // is attached after we initiated tiling. We must turn it off,
1454 // attach the new render buffer then turn tiling back on
1457 RenderBuffer* buffer = mCaches.renderBufferCache.get(
1458 Stencil::getSmallestStencilFormat(), layer->getWidth(), layer->getHeight());
1459 layer->setStencilRenderBuffer(buffer);
1461 startTiling(layer->clipRect, layer->layer.getHeight());
1465 void OpenGLRenderer::setStencilFromClip() {
1466 if (!mCaches.debugOverdraw) {
1467 if (!mSnapshot->clipRegion->isEmpty()) {
1468 // NOTE: The order here is important, we must set dirtyClip to false
1469 // before any draw call to avoid calling back into this method
1472 ensureStencilBuffer();
1474 mCaches.stencil.enableWrite();
1476 // Clear the stencil but first make sure we restrict drawing
1477 // to the region's bounds
1478 bool resetScissor = mCaches.enableScissor();
1480 // The scissor was not set so we now need to update it
1481 setScissorFromClip();
1483 mCaches.stencil.clear();
1484 if (resetScissor) mCaches.disableScissor();
1486 // NOTE: We could use the region contour path to generate a smaller mesh
1487 // Since we are using the stencil we could use the red book path
1488 // drawing technique. It might increase bandwidth usage though.
1490 // The last parameter is important: we are not drawing in the color buffer
1491 // so we don't want to dirty the current layer, if any
1492 drawRegionRects(*mSnapshot->clipRegion, 0xff000000, SkXfermode::kSrc_Mode, false);
1494 mCaches.stencil.enableTest();
1496 // Draw the region used to generate the stencil if the appropriate debug
1498 if (mCaches.debugStencilClip == Caches::kStencilShowRegion) {
1499 drawRegionRects(*mSnapshot->clipRegion, 0x7f0000ff, SkXfermode::kSrcOver_Mode);
1502 mCaches.stencil.disable();
1507 const Rect& OpenGLRenderer::getClipBounds() {
1508 return mSnapshot->getLocalClip();
1511 bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom) {
1512 if (mSnapshot->isIgnored()) {
1516 Rect r(left, top, right, bottom);
1517 currentTransform().mapRect(r);
1518 r.snapToPixelBoundaries();
1520 Rect clipRect(*mSnapshot->clipRect);
1521 clipRect.snapToPixelBoundaries();
1523 return !clipRect.intersects(r);
1526 bool OpenGLRenderer::quickRejectNoScissor(float left, float top, float right, float bottom,
1527 Rect& transformed, Rect& clip) {
1528 if (mSnapshot->isIgnored()) {
1532 transformed.set(left, top, right, bottom);
1533 currentTransform().mapRect(transformed);
1534 transformed.snapToPixelBoundaries();
1536 clip.set(*mSnapshot->clipRect);
1537 clip.snapToPixelBoundaries();
1539 return !clip.intersects(transformed);
1542 bool OpenGLRenderer::quickRejectPreStroke(float left, float top, float right, float bottom,
1544 if (paint->getStyle() != SkPaint::kFill_Style) {
1545 float outset = paint->getStrokeWidth() * 0.5f;
1546 return quickReject(left - outset, top - outset, right + outset, bottom + outset);
1548 return quickReject(left, top, right, bottom);
1552 bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) {
1553 if (mSnapshot->isIgnored() || bottom <= top || right <= left) {
1557 Rect r(left, top, right, bottom);
1558 currentTransform().mapRect(r);
1559 r.snapToPixelBoundaries();
1561 Rect clipRect(*mSnapshot->clipRect);
1562 clipRect.snapToPixelBoundaries();
1564 bool rejected = !clipRect.intersects(r);
1565 if (!isDeferred() && !rejected) {
1566 mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clipRect.contains(r));
1572 void OpenGLRenderer::debugClip() {
1573 #if DEBUG_CLIP_REGIONS
1574 if (!isDeferred() && !mSnapshot->clipRegion->isEmpty()) {
1575 drawRegionRects(*mSnapshot->clipRegion, 0x7f00ff00, SkXfermode::kSrcOver_Mode);
1580 bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
1581 if (CC_LIKELY(currentTransform().rectToRect())) {
1582 bool clipped = mSnapshot->clip(left, top, right, bottom, op);
1586 return !mSnapshot->clipRect->isEmpty();
1590 path.addRect(left, top, right, bottom);
1592 return clipPath(&path, op);
1595 bool OpenGLRenderer::clipPath(SkPath* path, SkRegion::Op op) {
1597 currentTransform().copyTo(transform);
1600 path->transform(transform, &transformed);
1603 if (!mSnapshot->clipRegion->isEmpty()) {
1604 clip.setRegion(*mSnapshot->clipRegion);
1606 Rect* bounds = mSnapshot->clipRect;
1607 clip.setRect(bounds->left, bounds->top, bounds->right, bounds->bottom);
1611 region.setPath(transformed, clip);
1613 bool clipped = mSnapshot->clipRegionTransformed(region, op);
1617 return !mSnapshot->clipRect->isEmpty();
1620 bool OpenGLRenderer::clipRegion(SkRegion* region, SkRegion::Op op) {
1621 bool clipped = mSnapshot->clipRegionTransformed(*region, op);
1625 return !mSnapshot->clipRect->isEmpty();
1628 Rect* OpenGLRenderer::getClipRect() {
1629 return mSnapshot->clipRect;
1632 ///////////////////////////////////////////////////////////////////////////////
1634 ///////////////////////////////////////////////////////////////////////////////
1636 void OpenGLRenderer::setupDraw(bool clear) {
1637 // TODO: It would be best if we could do this before quickReject()
1638 // changes the scissor test state
1639 if (clear) clearLayerRegions();
1640 // Make sure setScissor & setStencil happen at the beginning of
1643 if (mCaches.scissorEnabled) {
1644 setScissorFromClip();
1646 setStencilFromClip();
1649 mDescription.reset();
1651 mSetShaderColor = false;
1653 mColorA = mColorR = mColorG = mColorB = 0.0f;
1655 mTrackDirtyRegions = true;
1657 // Enable debug highlight when what we're about to draw is tested against
1658 // the stencil buffer and if stencil highlight debugging is on
1659 mDescription.hasDebugHighlight = !mCaches.debugOverdraw &&
1660 mCaches.debugStencilClip == Caches::kStencilShowHighlight &&
1661 mCaches.stencil.isTestEnabled();
1664 void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) {
1665 mDescription.hasTexture = true;
1666 mDescription.hasAlpha8Texture = isAlpha8;
1669 void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
1670 mDescription.hasTexture = true;
1671 mDescription.hasColors = true;
1672 mDescription.hasAlpha8Texture = isAlpha8;
1675 void OpenGLRenderer::setupDrawWithExternalTexture() {
1676 mDescription.hasExternalTexture = true;
1679 void OpenGLRenderer::setupDrawNoTexture() {
1680 mCaches.disableTexCoordsVertexArray();
1683 void OpenGLRenderer::setupDrawAA() {
1684 mDescription.isAA = true;
1687 void OpenGLRenderer::setupDrawPoint(float pointSize) {
1688 mDescription.isPoint = true;
1689 mDescription.pointSize = pointSize;
1692 void OpenGLRenderer::setupDrawColor(int color, int alpha) {
1693 mColorA = alpha / 255.0f;
1694 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1695 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f;
1696 mColorB = mColorA * ((color ) & 0xFF) / 255.0f;
1698 mSetShaderColor = mDescription.setColor(mColorR, mColorG, mColorB, mColorA);
1701 void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) {
1702 mColorA = alpha / 255.0f;
1703 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f;
1704 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f;
1705 mColorB = mColorA * ((color ) & 0xFF) / 255.0f;
1707 mSetShaderColor = mDescription.setAlpha8Color(mColorR, mColorG, mColorB, mColorA);
1710 void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) {
1711 mCaches.fontRenderer->describe(mDescription, paint);
1714 void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) {
1720 mSetShaderColor = mDescription.setColor(r, g, b, a);
1723 void OpenGLRenderer::setupDrawShader() {
1724 if (mDrawModifiers.mShader) {
1725 mDrawModifiers.mShader->describe(mDescription, mExtensions);
1729 void OpenGLRenderer::setupDrawColorFilter() {
1730 if (mDrawModifiers.mColorFilter) {
1731 mDrawModifiers.mColorFilter->describe(mDescription, mExtensions);
1735 void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) {
1736 if (mColorSet && mode == SkXfermode::kClear_Mode) {
1738 mColorR = mColorG = mColorB = 0.0f;
1739 mSetShaderColor = mDescription.modulate = true;
1743 void OpenGLRenderer::setupDrawBlending(SkXfermode::Mode mode, bool swapSrcDst) {
1744 // When the blending mode is kClear_Mode, we need to use a modulate color
1746 accountForClear(mode);
1747 bool blend = (mColorSet && mColorA < 1.0f) ||
1748 (mDrawModifiers.mShader && mDrawModifiers.mShader->blend());
1749 chooseBlending(blend, mode, mDescription, swapSrcDst);
1752 void OpenGLRenderer::setupDrawBlending(bool blend, SkXfermode::Mode mode, bool swapSrcDst) {
1753 // When the blending mode is kClear_Mode, we need to use a modulate color
1755 accountForClear(mode);
1756 blend |= (mColorSet && mColorA < 1.0f) ||
1757 (mDrawModifiers.mShader && mDrawModifiers.mShader->blend()) ||
1758 (mDrawModifiers.mColorFilter && mDrawModifiers.mColorFilter->blend());
1759 chooseBlending(blend, mode, mDescription, swapSrcDst);
1762 void OpenGLRenderer::setupDrawProgram() {
1763 useProgram(mCaches.programCache.get(mDescription));
1766 void OpenGLRenderer::setupDrawDirtyRegionsDisabled() {
1767 mTrackDirtyRegions = false;
1770 void OpenGLRenderer::setupDrawModelViewTranslate(float left, float top, float right, float bottom,
1771 bool ignoreTransform) {
1772 mModelView.loadTranslate(left, top, 0.0f);
1773 if (!ignoreTransform) {
1774 mCaches.currentProgram->set(mOrthoMatrix, mModelView, currentTransform());
1775 if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom, currentTransform());
1777 mCaches.currentProgram->set(mOrthoMatrix, mModelView, mat4::identity());
1778 if (mTrackDirtyRegions) dirtyLayer(left, top, right, bottom);
1782 void OpenGLRenderer::setupDrawModelViewIdentity(bool offset) {
1783 mCaches.currentProgram->set(mOrthoMatrix, mat4::identity(), currentTransform(), offset);
1786 void OpenGLRenderer::setupDrawModelView(float left, float top, float right, float bottom,
1787 bool ignoreTransform, bool ignoreModelView) {
1788 if (!ignoreModelView) {
1789 mModelView.loadTranslate(left, top, 0.0f);
1790 mModelView.scale(right - left, bottom - top, 1.0f);
1792 mModelView.loadIdentity();
1794 bool dirty = right - left > 0.0f && bottom - top > 0.0f;
1795 if (!ignoreTransform) {
1796 mCaches.currentProgram->set(mOrthoMatrix, mModelView, currentTransform());
1797 if (mTrackDirtyRegions && dirty) {
1798 dirtyLayer(left, top, right, bottom, currentTransform());
1801 mCaches.currentProgram->set(mOrthoMatrix, mModelView, mat4::identity());
1802 if (mTrackDirtyRegions && dirty) dirtyLayer(left, top, right, bottom);
1806 void OpenGLRenderer::setupDrawPointUniforms() {
1807 int slot = mCaches.currentProgram->getUniform("pointSize");
1808 glUniform1f(slot, mDescription.pointSize);
1811 void OpenGLRenderer::setupDrawColorUniforms() {
1812 if ((mColorSet && !mDrawModifiers.mShader) || (mDrawModifiers.mShader && mSetShaderColor)) {
1813 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1817 void OpenGLRenderer::setupDrawPureColorUniforms() {
1818 if (mSetShaderColor) {
1819 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA);
1823 void OpenGLRenderer::setupDrawShaderUniforms(bool ignoreTransform) {
1824 if (mDrawModifiers.mShader) {
1825 if (ignoreTransform) {
1826 mModelView.loadInverse(currentTransform());
1828 mDrawModifiers.mShader->setupProgram(mCaches.currentProgram,
1829 mModelView, *mSnapshot, &mTextureUnit);
1833 void OpenGLRenderer::setupDrawShaderIdentityUniforms() {
1834 if (mDrawModifiers.mShader) {
1835 mDrawModifiers.mShader->setupProgram(mCaches.currentProgram,
1836 mat4::identity(), *mSnapshot, &mTextureUnit);
1840 void OpenGLRenderer::setupDrawColorFilterUniforms() {
1841 if (mDrawModifiers.mColorFilter) {
1842 mDrawModifiers.mColorFilter->setupProgram(mCaches.currentProgram);
1846 void OpenGLRenderer::setupDrawTextGammaUniforms() {
1847 mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram);
1850 void OpenGLRenderer::setupDrawSimpleMesh() {
1851 bool force = mCaches.bindMeshBuffer();
1852 mCaches.bindPositionVertexPointer(force, 0);
1853 mCaches.unbindIndicesBuffer();
1856 void OpenGLRenderer::setupDrawTexture(GLuint texture) {
1857 if (texture) bindTexture(texture);
1859 mCaches.enableTexCoordsVertexArray();
1862 void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) {
1863 bindExternalTexture(texture);
1865 mCaches.enableTexCoordsVertexArray();
1868 void OpenGLRenderer::setupDrawTextureTransform() {
1869 mDescription.hasTextureTransform = true;
1872 void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) {
1873 glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1,
1874 GL_FALSE, &transform.data[0]);
1877 void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLuint vbo) {
1880 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo);
1882 force = mCaches.unbindMeshBuffer();
1885 mCaches.bindPositionVertexPointer(force, vertices);
1886 if (mCaches.currentProgram->texCoords >= 0) {
1887 mCaches.bindTexCoordsVertexPointer(force, texCoords);
1890 mCaches.unbindIndicesBuffer();
1893 void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLvoid* colors) {
1894 bool force = mCaches.unbindMeshBuffer();
1895 GLsizei stride = sizeof(ColorTextureVertex);
1897 mCaches.bindPositionVertexPointer(force, vertices, stride);
1898 if (mCaches.currentProgram->texCoords >= 0) {
1899 mCaches.bindTexCoordsVertexPointer(force, texCoords, stride);
1901 int slot = mCaches.currentProgram->getAttrib("colors");
1903 glEnableVertexAttribArray(slot);
1904 glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
1907 mCaches.unbindIndicesBuffer();
1910 void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) {
1911 bool force = mCaches.unbindMeshBuffer();
1912 mCaches.bindPositionVertexPointer(force, vertices);
1913 if (mCaches.currentProgram->texCoords >= 0) {
1914 mCaches.bindTexCoordsVertexPointer(force, texCoords);
1918 void OpenGLRenderer::setupDrawVertices(GLvoid* vertices) {
1919 bool force = mCaches.unbindMeshBuffer();
1920 mCaches.bindPositionVertexPointer(force, vertices, gVertexStride);
1921 mCaches.unbindIndicesBuffer();
1924 void OpenGLRenderer::finishDrawTexture() {
1927 ///////////////////////////////////////////////////////////////////////////////
1929 ///////////////////////////////////////////////////////////////////////////////
1931 status_t OpenGLRenderer::drawDisplayList(DisplayList* displayList, Rect& dirty,
1932 int32_t replayFlags) {
1934 // All the usual checks and setup operations (quickReject, setupDraw, etc.)
1935 // will be performed by the display list itself
1936 if (displayList && displayList->isRenderable()) {
1937 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) {
1938 status = startFrame();
1939 ReplayStateStruct replayStruct(*this, dirty, replayFlags);
1940 displayList->replay(replayStruct, 0);
1941 return status | replayStruct.mDrawGlStatus;
1944 DeferredDisplayList deferredList;
1945 DeferStateStruct deferStruct(deferredList, *this, replayFlags);
1946 displayList->defer(deferStruct, 0);
1949 status = startFrame();
1951 return status | deferredList.flush(*this, dirty);
1954 return DrawGlInfo::kStatusDone;
1957 void OpenGLRenderer::outputDisplayList(DisplayList* displayList) {
1959 displayList->output(1);
1963 void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, SkPaint* paint) {
1965 SkXfermode::Mode mode;
1966 getAlphaAndMode(paint, &alpha, &mode);
1968 int color = paint != NULL ? paint->getColor() : 0;
1973 texture->setWrap(GL_CLAMP_TO_EDGE, true);
1975 bool ignoreTransform = false;
1976 if (currentTransform().isPureTranslate()) {
1977 x = (int) floorf(left + currentTransform().getTranslateX() + 0.5f);
1978 y = (int) floorf(top + currentTransform().getTranslateY() + 0.5f);
1979 ignoreTransform = true;
1981 texture->setFilter(GL_NEAREST, true);
1983 texture->setFilter(FILTER(paint), true);
1986 drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
1987 paint != NULL, color, alpha, mode, (GLvoid*) NULL,
1988 (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
1991 status_t OpenGLRenderer::drawBitmaps(SkBitmap* bitmap, int bitmapCount, TextureVertex* vertices,
1992 const Rect& bounds, SkPaint* paint) {
1994 // merged draw operations don't need scissor, but clip should still be valid
1995 mCaches.setScissorEnabled(mScissorOptimizationDisabled);
1997 mCaches.activeTexture(0);
1998 Texture* texture = mCaches.textureCache.get(bitmap);
1999 if (!texture) return DrawGlInfo::kStatusDone;
2000 const AutoTexture autoCleanup(texture);
2003 SkXfermode::Mode mode;
2004 getAlphaAndMode(paint, &alpha, &mode);
2006 texture->setWrap(GL_CLAMP_TO_EDGE, true);
2007 texture->setFilter(GL_NEAREST, true); // merged ops are always pure-translation for now
2009 const float x = (int) floorf(bounds.left + 0.5f);
2010 const float y = (int) floorf(bounds.top + 0.5f);
2011 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2012 int color = paint != NULL ? paint->getColor() : 0;
2013 drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2014 texture->id, paint != NULL, color, alpha, mode,
2015 &vertices[0].position[0], &vertices[0].texture[0],
2016 GL_TRIANGLES, bitmapCount * 6, true, true);
2018 drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
2019 texture->id, alpha / 255.0f, mode, texture->blend,
2020 &vertices[0].position[0], &vertices[0].texture[0],
2021 GL_TRIANGLES, bitmapCount * 6, false, true, 0, true);
2024 return DrawGlInfo::kStatusDrew;
2027 status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
2028 const float right = left + bitmap->width();
2029 const float bottom = top + bitmap->height();
2031 if (quickReject(left, top, right, bottom)) {
2032 return DrawGlInfo::kStatusDone;
2035 mCaches.activeTexture(0);
2036 Texture* texture = mCaches.textureCache.get(bitmap);
2037 if (!texture) return DrawGlInfo::kStatusDone;
2038 const AutoTexture autoCleanup(texture);
2040 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2041 drawAlphaBitmap(texture, left, top, paint);
2043 drawTextureRect(left, top, right, bottom, texture, paint);
2046 return DrawGlInfo::kStatusDrew;
2049 status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) {
2050 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height());
2051 const mat4 transform(*matrix);
2052 transform.mapRect(r);
2054 if (quickReject(r.left, r.top, r.right, r.bottom)) {
2055 return DrawGlInfo::kStatusDone;
2058 mCaches.activeTexture(0);
2059 Texture* texture = mCaches.textureCache.get(bitmap);
2060 if (!texture) return DrawGlInfo::kStatusDone;
2061 const AutoTexture autoCleanup(texture);
2063 // This could be done in a cheaper way, all we need is pass the matrix
2064 // to the vertex shader. The save/restore is a bit overkill.
2065 save(SkCanvas::kMatrix_SaveFlag);
2066 concatMatrix(matrix);
2067 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2068 drawAlphaBitmap(texture, 0.0f, 0.0f, paint);
2070 drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint);
2074 return DrawGlInfo::kStatusDrew;
2077 status_t OpenGLRenderer::drawBitmapData(SkBitmap* bitmap, float left, float top, SkPaint* paint) {
2078 const float right = left + bitmap->width();
2079 const float bottom = top + bitmap->height();
2081 if (quickReject(left, top, right, bottom)) {
2082 return DrawGlInfo::kStatusDone;
2085 mCaches.activeTexture(0);
2086 Texture* texture = mCaches.textureCache.getTransient(bitmap);
2087 const AutoTexture autoCleanup(texture);
2089 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2090 drawAlphaBitmap(texture, left, top, paint);
2092 drawTextureRect(left, top, right, bottom, texture, paint);
2095 return DrawGlInfo::kStatusDrew;
2098 status_t OpenGLRenderer::drawBitmapMesh(SkBitmap* bitmap, int meshWidth, int meshHeight,
2099 float* vertices, int* colors, SkPaint* paint) {
2100 if (!vertices || mSnapshot->isIgnored()) {
2101 return DrawGlInfo::kStatusDone;
2104 float left = FLT_MAX;
2105 float top = FLT_MAX;
2106 float right = FLT_MIN;
2107 float bottom = FLT_MIN;
2109 const uint32_t count = meshWidth * meshHeight * 6;
2111 ColorTextureVertex mesh[count];
2112 ColorTextureVertex* vertex = mesh;
2114 bool cleanupColors = false;
2116 uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
2117 colors = new int[colorsCount];
2118 memset(colors, 0xff, colorsCount * sizeof(int));
2119 cleanupColors = true;
2122 for (int32_t y = 0; y < meshHeight; y++) {
2123 for (int32_t x = 0; x < meshWidth; x++) {
2124 uint32_t i = (y * (meshWidth + 1) + x) * 2;
2126 float u1 = float(x) / meshWidth;
2127 float u2 = float(x + 1) / meshWidth;
2128 float v1 = float(y) / meshHeight;
2129 float v2 = float(y + 1) / meshHeight;
2131 int ax = i + (meshWidth + 1) * 2;
2137 int dx = i + (meshWidth + 1) * 2 + 2;
2140 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2141 ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
2142 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2144 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
2145 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
2146 ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
2148 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
2149 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
2150 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx])));
2151 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy])));
2155 if (quickReject(left, top, right, bottom)) {
2156 if (cleanupColors) delete[] colors;
2157 return DrawGlInfo::kStatusDone;
2160 mCaches.activeTexture(0);
2161 Texture* texture = mCaches.textureCache.get(bitmap);
2163 if (cleanupColors) delete[] colors;
2164 return DrawGlInfo::kStatusDone;
2166 const AutoTexture autoCleanup(texture);
2168 texture->setWrap(GL_CLAMP_TO_EDGE, true);
2169 texture->setFilter(FILTER(paint), true);
2172 SkXfermode::Mode mode;
2173 getAlphaAndMode(paint, &alpha, &mode);
2175 float a = alpha / 255.0f;
2178 dirtyLayer(left, top, right, bottom, currentTransform());
2182 setupDrawWithTextureAndColor();
2183 setupDrawColor(a, a, a, a);
2184 setupDrawColorFilter();
2185 setupDrawBlending(true, mode, false);
2187 setupDrawDirtyRegionsDisabled();
2188 setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, false);
2189 setupDrawTexture(texture->id);
2190 setupDrawPureColorUniforms();
2191 setupDrawColorFilterUniforms();
2192 setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0], &mesh[0].color[0]);
2194 glDrawArrays(GL_TRIANGLES, 0, count);
2196 finishDrawTexture();
2198 int slot = mCaches.currentProgram->getAttrib("colors");
2200 glDisableVertexAttribArray(slot);
2203 if (cleanupColors) delete[] colors;
2205 return DrawGlInfo::kStatusDrew;
2208 status_t OpenGLRenderer::drawBitmap(SkBitmap* bitmap,
2209 float srcLeft, float srcTop, float srcRight, float srcBottom,
2210 float dstLeft, float dstTop, float dstRight, float dstBottom,
2212 if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) {
2213 return DrawGlInfo::kStatusDone;
2216 mCaches.activeTexture(0);
2217 Texture* texture = mCaches.textureCache.get(bitmap);
2218 if (!texture) return DrawGlInfo::kStatusDone;
2219 const AutoTexture autoCleanup(texture);
2221 const float width = texture->width;
2222 const float height = texture->height;
2224 const float u1 = fmax(0.0f, srcLeft / width);
2225 const float v1 = fmax(0.0f, srcTop / height);
2226 const float u2 = fmin(1.0f, srcRight / width);
2227 const float v2 = fmin(1.0f, srcBottom / height);
2229 mCaches.unbindMeshBuffer();
2230 resetDrawTextureTexCoords(u1, v1, u2, v2);
2233 SkXfermode::Mode mode;
2234 getAlphaAndMode(paint, &alpha, &mode);
2236 texture->setWrap(GL_CLAMP_TO_EDGE, true);
2238 float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
2239 float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
2241 bool scaled = scaleX != 1.0f || scaleY != 1.0f;
2242 // Apply a scale transform on the canvas only when a shader is in use
2243 // Skia handles the ratio between the dst and src rects as a scale factor
2244 // when a shader is set
2245 bool useScaleTransform = mDrawModifiers.mShader && scaled;
2246 bool ignoreTransform = false;
2248 if (CC_LIKELY(currentTransform().isPureTranslate() && !useScaleTransform)) {
2249 float x = (int) floorf(dstLeft + currentTransform().getTranslateX() + 0.5f);
2250 float y = (int) floorf(dstTop + currentTransform().getTranslateY() + 0.5f);
2252 dstRight = x + (dstRight - dstLeft);
2253 dstBottom = y + (dstBottom - dstTop);
2258 texture->setFilter(scaled ? FILTER(paint) : GL_NEAREST, true);
2259 ignoreTransform = true;
2261 texture->setFilter(FILTER(paint), true);
2264 if (CC_UNLIKELY(useScaleTransform)) {
2265 save(SkCanvas::kMatrix_SaveFlag);
2266 translate(dstLeft, dstTop);
2267 scale(scaleX, scaleY);
2272 dstRight = srcRight - srcLeft;
2273 dstBottom = srcBottom - srcTop;
2276 if (CC_UNLIKELY(bitmap->getConfig() == SkBitmap::kA8_Config)) {
2277 int color = paint ? paint->getColor() : 0;
2278 drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2279 texture->id, paint != NULL, color, alpha, mode,
2280 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
2281 GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform);
2283 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom,
2284 texture->id, alpha / 255.0f, mode, texture->blend,
2285 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0],
2286 GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform);
2289 if (CC_UNLIKELY(useScaleTransform)) {
2293 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
2295 return DrawGlInfo::kStatusDrew;
2298 status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
2299 const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
2300 float left, float top, float right, float bottom, SkPaint* paint) {
2302 SkXfermode::Mode mode;
2303 getAlphaAndMode(paint, &alpha, &mode);
2305 return drawPatch(bitmap, xDivs, yDivs, colors, width, height, numColors,
2306 left, top, right, bottom, alpha, mode);
2309 status_t OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs,
2310 const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors,
2311 float left, float top, float right, float bottom, int alpha, SkXfermode::Mode mode) {
2312 if (quickReject(left, top, right, bottom)) {
2313 return DrawGlInfo::kStatusDone;
2316 alpha *= mSnapshot->alpha;
2318 const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(),
2319 right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors);
2321 if (CC_LIKELY(mesh && mesh->verticesCount > 0)) {
2322 mCaches.activeTexture(0);
2323 Texture* texture = mCaches.textureCache.get(bitmap);
2324 if (!texture) return DrawGlInfo::kStatusDone;
2325 const AutoTexture autoCleanup(texture);
2326 texture->setWrap(GL_CLAMP_TO_EDGE, true);
2327 texture->setFilter(GL_LINEAR, true);
2329 const bool pureTranslate = currentTransform().isPureTranslate();
2330 // Mark the current layer dirty where we are going to draw the patch
2331 if (hasLayer() && mesh->hasEmptyQuads) {
2332 const float offsetX = left + currentTransform().getTranslateX();
2333 const float offsetY = top + currentTransform().getTranslateY();
2334 const size_t count = mesh->quads.size();
2335 for (size_t i = 0; i < count; i++) {
2336 const Rect& bounds = mesh->quads.itemAt(i);
2337 if (CC_LIKELY(pureTranslate)) {
2338 const float x = (int) floorf(bounds.left + offsetX + 0.5f);
2339 const float y = (int) floorf(bounds.top + offsetY + 0.5f);
2340 dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
2342 dirtyLayer(left + bounds.left, top + bounds.top,
2343 left + bounds.right, top + bounds.bottom, currentTransform());
2348 if (CC_LIKELY(pureTranslate)) {
2349 const float x = (int) floorf(left + currentTransform().getTranslateX() + 0.5f);
2350 const float y = (int) floorf(top + currentTransform().getTranslateY() + 0.5f);
2352 drawTextureMesh(x, y, x + right - left, y + bottom - top, texture->id, alpha / 255.0f,
2353 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
2354 GL_TRIANGLES, mesh->verticesCount, false, true, mesh->meshBuffer,
2355 true, !mesh->hasEmptyQuads);
2357 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f,
2358 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset,
2359 GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer,
2360 true, !mesh->hasEmptyQuads);
2364 return DrawGlInfo::kStatusDrew;
2367 status_t OpenGLRenderer::drawVertexBuffer(const VertexBuffer& vertexBuffer, SkPaint* paint,
2369 if (!vertexBuffer.getSize()) {
2370 // no vertices to draw
2371 return DrawGlInfo::kStatusDone;
2374 int color = paint->getColor();
2375 SkXfermode::Mode mode = getXfermode(paint->getXfermode());
2376 bool isAA = paint->isAntiAlias();
2379 setupDrawNoTexture();
2380 if (isAA) setupDrawAA();
2381 setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
2382 setupDrawColorFilter();
2384 setupDrawBlending(isAA, mode);
2386 setupDrawModelViewIdentity(useOffset);
2387 setupDrawColorUniforms();
2388 setupDrawColorFilterUniforms();
2389 setupDrawShaderIdentityUniforms();
2391 void* vertices = vertexBuffer.getBuffer();
2392 bool force = mCaches.unbindMeshBuffer();
2393 mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride);
2394 mCaches.resetTexCoordsVertexPointer();
2395 mCaches.unbindIndicesBuffer();
2399 void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset;
2400 alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha");
2402 // TODO: avoid enable/disable in back to back uses of the alpha attribute
2403 glEnableVertexAttribArray(alphaSlot);
2404 glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords);
2407 glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getSize());
2410 glDisableVertexAttribArray(alphaSlot);
2413 return DrawGlInfo::kStatusDrew;
2417 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to
2418 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in
2419 * screen space in all directions. However, instead of using a fragment shader to compute the
2420 * translucency of the color from its position, we simply use a varying parameter to define how far
2421 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used.
2423 * Doesn't yet support joins, caps, or path effects.
2425 status_t OpenGLRenderer::drawConvexPath(const SkPath& path, SkPaint* paint) {
2426 VertexBuffer vertexBuffer;
2427 // TODO: try clipping large paths to viewport
2428 PathTessellator::tessellatePath(path, paint, mSnapshot->transform, vertexBuffer);
2431 SkRect bounds = path.getBounds();
2432 PathTessellator::expandBoundsForStroke(bounds, paint, false);
2433 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, currentTransform());
2436 return drawVertexBuffer(vertexBuffer, paint);
2440 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha
2441 * and additional geometry for defining an alpha slope perimeter.
2443 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some
2444 * unexpected results, and may vary between hardware devices. Previously we used a varying-base
2445 * in-shader alpha region, but found it to be taxing on some GPUs.
2447 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce
2448 * memory transfer by removing need for degenerate vertices.
2450 status_t OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
2451 if (mSnapshot->isIgnored() || count < 4) return DrawGlInfo::kStatusDone;
2453 count &= ~0x3; // round down to nearest four
2455 VertexBuffer buffer;
2457 PathTessellator::tessellateLines(points, count, paint, mSnapshot->transform, bounds, buffer);
2459 if (quickReject(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom)) {
2460 return DrawGlInfo::kStatusDone;
2463 dirtyLayer(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, currentTransform());
2465 bool useOffset = !paint->isAntiAlias();
2466 return drawVertexBuffer(buffer, paint, useOffset);
2469 status_t OpenGLRenderer::drawPoints(float* points, int count, SkPaint* paint) {
2470 if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2472 // TODO: The paint's cap style defines whether the points are square or circular
2473 // TODO: Handle AA for round points
2475 // A stroke width of 0 has a special meaning in Skia:
2476 // it draws an unscaled 1px point
2477 float strokeWidth = paint->getStrokeWidth();
2478 const bool isHairLine = paint->getStrokeWidth() == 0.0f;
2480 // Now that we know it's hairline, we can set the effective width, to be used later
2483 const float halfWidth = strokeWidth / 2;
2486 SkXfermode::Mode mode;
2487 getAlphaAndMode(paint, &alpha, &mode);
2489 int verticesCount = count >> 1;
2490 int generatedVerticesCount = 0;
2492 TextureVertex pointsData[verticesCount];
2493 TextureVertex* vertex = &pointsData[0];
2495 // TODO: We should optimize this method to not generate vertices for points
2496 // that lie outside of the clip.
2497 mCaches.enableScissor();
2500 setupDrawNoTexture();
2501 setupDrawPoint(strokeWidth);
2502 setupDrawColor(paint->getColor(), alpha);
2503 setupDrawColorFilter();
2505 setupDrawBlending(mode);
2507 setupDrawModelViewIdentity(true);
2508 setupDrawColorUniforms();
2509 setupDrawColorFilterUniforms();
2510 setupDrawPointUniforms();
2511 setupDrawShaderIdentityUniforms();
2512 setupDrawMesh(vertex);
2514 for (int i = 0; i < count; i += 2) {
2515 TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
2516 generatedVerticesCount++;
2518 float left = points[i] - halfWidth;
2519 float right = points[i] + halfWidth;
2520 float top = points[i + 1] - halfWidth;
2521 float bottom = points [i + 1] + halfWidth;
2523 dirtyLayer(left, top, right, bottom, currentTransform());
2526 glDrawArrays(GL_POINTS, 0, generatedVerticesCount);
2528 return DrawGlInfo::kStatusDrew;
2531 status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) {
2532 // No need to check against the clip, we fill the clip region
2533 if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
2535 Rect& clip(*mSnapshot->clipRect);
2536 clip.snapToPixelBoundaries();
2538 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true);
2540 return DrawGlInfo::kStatusDrew;
2543 status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture,
2545 if (!texture) return DrawGlInfo::kStatusDone;
2546 const AutoTexture autoCleanup(texture);
2548 const float x = left + texture->left - texture->offset;
2549 const float y = top + texture->top - texture->offset;
2551 drawPathTexture(texture, x, y, paint);
2553 return DrawGlInfo::kStatusDrew;
2556 status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom,
2557 float rx, float ry, SkPaint* p) {
2558 if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p) ||
2559 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2560 return DrawGlInfo::kStatusDone;
2563 if (p->getPathEffect() != 0) {
2564 mCaches.activeTexture(0);
2565 const PathTexture* texture = mCaches.pathCache.getRoundRect(
2566 right - left, bottom - top, rx, ry, p);
2567 return drawShape(left, top, texture, p);
2571 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2572 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2573 float outset = p->getStrokeWidth() / 2;
2574 rect.outset(outset, outset);
2578 path.addRoundRect(rect, rx, ry);
2579 return drawConvexPath(path, p);
2582 status_t OpenGLRenderer::drawCircle(float x, float y, float radius, SkPaint* p) {
2583 if (mSnapshot->isIgnored() || quickRejectPreStroke(x - radius, y - radius,
2584 x + radius, y + radius, p) ||
2585 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2586 return DrawGlInfo::kStatusDone;
2588 if (p->getPathEffect() != 0) {
2589 mCaches.activeTexture(0);
2590 const PathTexture* texture = mCaches.pathCache.getCircle(radius, p);
2591 return drawShape(x - radius, y - radius, texture, p);
2595 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2596 path.addCircle(x, y, radius + p->getStrokeWidth() / 2);
2598 path.addCircle(x, y, radius);
2600 return drawConvexPath(path, p);
2603 status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom,
2605 if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p) ||
2606 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2607 return DrawGlInfo::kStatusDone;
2610 if (p->getPathEffect() != 0) {
2611 mCaches.activeTexture(0);
2612 const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p);
2613 return drawShape(left, top, texture, p);
2617 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2618 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2619 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2622 return drawConvexPath(path, p);
2625 status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom,
2626 float startAngle, float sweepAngle, bool useCenter, SkPaint* p) {
2627 if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p) ||
2628 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2629 return DrawGlInfo::kStatusDone;
2632 if (fabs(sweepAngle) >= 360.0f) {
2633 return drawOval(left, top, right, bottom, p);
2636 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180)
2637 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) {
2638 mCaches.activeTexture(0);
2639 const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top,
2640 startAngle, sweepAngle, useCenter, p);
2641 return drawShape(left, top, texture, p);
2644 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2645 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2646 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2651 path.moveTo(rect.centerX(), rect.centerY());
2653 path.arcTo(rect, startAngle, sweepAngle, !useCenter);
2657 return drawConvexPath(path, p);
2660 // See SkPaintDefaults.h
2661 #define SkPaintDefaults_MiterLimit SkIntToScalar(4)
2663 status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) {
2664 if (mSnapshot->isIgnored() || quickRejectPreStroke(left, top, right, bottom, p) ||
2665 (p->getAlpha() == 0 && getXfermode(p->getXfermode()) != SkXfermode::kClear_Mode)) {
2666 return DrawGlInfo::kStatusDone;
2669 if (p->getStyle() != SkPaint::kFill_Style) {
2670 // only fill style is supported by drawConvexPath, since others have to handle joins
2671 if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join ||
2672 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) {
2673 mCaches.activeTexture(0);
2674 const PathTexture* texture =
2675 mCaches.pathCache.getRect(right - left, bottom - top, p);
2676 return drawShape(left, top, texture, p);
2680 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
2681 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) {
2682 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2);
2685 return drawConvexPath(path, p);
2688 if (p->isAntiAlias() && !currentTransform().isSimple()) {
2690 path.addRect(left, top, right, bottom);
2691 return drawConvexPath(path, p);
2693 drawColorRect(left, top, right, bottom, p->getColor(), getXfermode(p->getXfermode()));
2694 return DrawGlInfo::kStatusDrew;
2698 void OpenGLRenderer::drawTextShadow(SkPaint* paint, const char* text, int bytesCount, int count,
2699 const float* positions, FontRenderer& fontRenderer, int alpha, SkXfermode::Mode mode,
2701 mCaches.activeTexture(0);
2703 // NOTE: The drop shadow will not perform gamma correction
2704 // if shader-based correction is enabled
2705 mCaches.dropShadowCache.setFontRenderer(fontRenderer);
2706 const ShadowTexture* shadow = mCaches.dropShadowCache.get(
2707 paint, text, bytesCount, count, mDrawModifiers.mShadowRadius, positions);
2708 // If the drop shadow exceeds the max texture size or couldn't be
2709 // allocated, skip drawing
2710 if (!shadow) return;
2711 const AutoTexture autoCleanup(shadow);
2713 const float sx = x - shadow->left + mDrawModifiers.mShadowDx;
2714 const float sy = y - shadow->top + mDrawModifiers.mShadowDy;
2716 const int shadowAlpha = ((mDrawModifiers.mShadowColor >> 24) & 0xFF) * mSnapshot->alpha;
2717 int shadowColor = mDrawModifiers.mShadowColor;
2718 if (mDrawModifiers.mShader) {
2719 shadowColor = 0xffffffff;
2723 setupDrawWithTexture(true);
2724 setupDrawAlpha8Color(shadowColor, shadowAlpha < 255 ? shadowAlpha : alpha);
2725 setupDrawColorFilter();
2727 setupDrawBlending(true, mode);
2729 setupDrawModelView(sx, sy, sx + shadow->width, sy + shadow->height);
2730 setupDrawTexture(shadow->id);
2731 setupDrawPureColorUniforms();
2732 setupDrawColorFilterUniforms();
2733 setupDrawShaderUniforms();
2734 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
2736 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
2739 bool OpenGLRenderer::canSkipText(const SkPaint* paint) const {
2740 float alpha = (mDrawModifiers.mHasShadow ? 1.0f : paint->getAlpha()) * mSnapshot->alpha;
2741 return alpha == 0.0f && getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode;
2744 class TextSetupFunctor: public Functor {
2746 TextSetupFunctor(OpenGLRenderer& renderer, float x, float y, bool pureTranslate,
2747 int alpha, SkXfermode::Mode mode, SkPaint* paint): Functor(),
2748 renderer(renderer), x(x), y(y), pureTranslate(pureTranslate),
2749 alpha(alpha), mode(mode), paint(paint) {
2751 ~TextSetupFunctor() { }
2753 status_t operator ()(int what, void* data) {
2754 renderer.setupDraw();
2755 renderer.setupDrawTextGamma(paint);
2756 renderer.setupDrawDirtyRegionsDisabled();
2757 renderer.setupDrawWithTexture(true);
2758 renderer.setupDrawAlpha8Color(paint->getColor(), alpha);
2759 renderer.setupDrawColorFilter();
2760 renderer.setupDrawShader();
2761 renderer.setupDrawBlending(true, mode);
2762 renderer.setupDrawProgram();
2763 renderer.setupDrawModelView(x, y, x, y, pureTranslate, true);
2764 // Calling setupDrawTexture with the name 0 will enable the
2765 // uv attributes and increase the texture unit count
2766 // texture binding will be performed by the font renderer as
2768 renderer.setupDrawTexture(0);
2769 renderer.setupDrawPureColorUniforms();
2770 renderer.setupDrawColorFilterUniforms();
2771 renderer.setupDrawShaderUniforms(pureTranslate);
2772 renderer.setupDrawTextGammaUniforms();
2777 OpenGLRenderer& renderer;
2782 SkXfermode::Mode mode;
2786 status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count,
2787 const float* positions, SkPaint* paint) {
2788 if (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint)) {
2789 return DrawGlInfo::kStatusDone;
2792 // NOTE: Skia does not support perspective transform on drawPosText yet
2793 if (!currentTransform().isSimple()) {
2794 return DrawGlInfo::kStatusDone;
2799 const bool pureTranslate = currentTransform().isPureTranslate();
2800 if (pureTranslate) {
2801 x = (int) floorf(x + currentTransform().getTranslateX() + 0.5f);
2802 y = (int) floorf(y + currentTransform().getTranslateY() + 0.5f);
2805 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2806 fontRenderer.setFont(paint, mat4::identity());
2809 SkXfermode::Mode mode;
2810 getAlphaAndMode(paint, &alpha, &mode);
2812 if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2813 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2814 alpha, mode, 0.0f, 0.0f);
2817 // Pick the appropriate texture filtering
2818 bool linearFilter = currentTransform().changesBounds();
2819 if (pureTranslate && !linearFilter) {
2820 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2822 fontRenderer.setTextureFiltering(linearFilter);
2824 const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip();
2825 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2827 const bool hasActiveLayer = hasLayer();
2829 TextSetupFunctor functor(*this, x, y, pureTranslate, alpha, mode, paint);
2830 if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2831 positions, hasActiveLayer ? &bounds : NULL, &functor)) {
2832 if (hasActiveLayer) {
2833 if (!pureTranslate) {
2834 currentTransform().mapRect(bounds);
2836 dirtyLayerUnchecked(bounds, getRegion());
2840 return DrawGlInfo::kStatusDrew;
2843 mat4 OpenGLRenderer::findBestFontTransform(const mat4& transform) const {
2845 if (CC_LIKELY(transform.isPureTranslate())) {
2846 fontTransform = mat4::identity();
2848 if (CC_UNLIKELY(transform.isPerspective())) {
2849 fontTransform = mat4::identity();
2852 currentTransform().decomposeScale(sx, sy);
2853 fontTransform.loadScale(sx, sy, 1.0f);
2856 return fontTransform;
2859 status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
2860 float x, float y, const float* positions, SkPaint* paint, float length,
2861 DrawOpMode drawOpMode) {
2863 if (drawOpMode == kDrawOpMode_Immediate &&
2864 (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint))) {
2865 return DrawGlInfo::kStatusDone;
2868 if (length < 0.0f) length = paint->measureText(text, bytesCount);
2869 switch (paint->getTextAlign()) {
2870 case SkPaint::kCenter_Align:
2873 case SkPaint::kRight_Align:
2880 SkPaint::FontMetrics metrics;
2881 paint->getFontMetrics(&metrics, 0.0f);
2882 if (drawOpMode == kDrawOpMode_Immediate) {
2883 if (quickReject(x, y + metrics.fTop, x + length, y + metrics.fBottom)) {
2884 return DrawGlInfo::kStatusDone;
2887 // merged draw operations don't need scissor, but clip should still be valid
2888 mCaches.setScissorEnabled(mScissorOptimizationDisabled);
2891 const float oldX = x;
2892 const float oldY = y;
2894 const mat4& transform = currentTransform();
2895 const bool pureTranslate = transform.isPureTranslate();
2897 if (CC_LIKELY(pureTranslate)) {
2898 x = (int) floorf(x + transform.getTranslateX() + 0.5f);
2899 y = (int) floorf(y + transform.getTranslateY() + 0.5f);
2903 SkXfermode::Mode mode;
2904 getAlphaAndMode(paint, &alpha, &mode);
2906 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2908 if (CC_UNLIKELY(mDrawModifiers.mHasShadow)) {
2909 fontRenderer.setFont(paint, mat4::identity());
2910 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer,
2911 alpha, mode, oldX, oldY);
2914 const bool hasActiveLayer = hasLayer();
2916 // We only pass a partial transform to the font renderer. That partial
2917 // matrix defines how glyphs are rasterized. Typically we want glyphs
2918 // to be rasterized at their final size on screen, which means the partial
2919 // matrix needs to take the scale factor into account.
2920 // When a partial matrix is used to transform glyphs during rasterization,
2921 // the mesh is generated with the inverse transform (in the case of scale,
2922 // the mesh is generated at 1.0 / scale for instance.) This allows us to
2923 // apply the full transform matrix at draw time in the vertex shader.
2924 // Applying the full matrix in the shader is the easiest way to handle
2925 // rotation and perspective and allows us to always generated quads in the
2926 // font renderer which greatly simplifies the code, clipping in particular.
2927 mat4 fontTransform = findBestFontTransform(transform);
2928 fontRenderer.setFont(paint, fontTransform);
2930 // Pick the appropriate texture filtering
2931 bool linearFilter = !pureTranslate || fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f;
2932 fontRenderer.setTextureFiltering(linearFilter);
2934 // TODO: Implement better clipping for scaled/rotated text
2935 const Rect* clip = !pureTranslate ? NULL : mSnapshot->clipRect;
2936 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
2939 TextSetupFunctor functor(*this, x, y, pureTranslate, alpha, mode, paint);
2941 // don't call issuedrawcommand, do it at end of batch
2942 bool forceFinish = (drawOpMode != kDrawOpMode_Defer);
2943 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) {
2944 SkPaint paintCopy(*paint);
2945 paintCopy.setTextAlign(SkPaint::kLeft_Align);
2946 status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y,
2947 positions, hasActiveLayer ? &bounds : NULL, &functor, forceFinish);
2949 status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y,
2950 positions, hasActiveLayer ? &bounds : NULL, &functor, forceFinish);
2953 if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) {
2954 if (!pureTranslate) {
2955 transform.mapRect(bounds);
2957 dirtyLayerUnchecked(bounds, getRegion());
2960 drawTextDecorations(text, bytesCount, length, oldX, oldY, paint);
2962 return DrawGlInfo::kStatusDrew;
2965 status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, SkPath* path,
2966 float hOffset, float vOffset, SkPaint* paint) {
2967 if (text == NULL || count == 0 || mSnapshot->isIgnored() || canSkipText(paint)) {
2968 return DrawGlInfo::kStatusDone;
2971 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint);
2972 fontRenderer.setFont(paint, mat4::identity());
2973 fontRenderer.setTextureFiltering(true);
2976 SkXfermode::Mode mode;
2977 getAlphaAndMode(paint, &alpha, &mode);
2980 setupDrawTextGamma(paint);
2981 setupDrawDirtyRegionsDisabled();
2982 setupDrawWithTexture(true);
2983 setupDrawAlpha8Color(paint->getColor(), alpha);
2984 setupDrawColorFilter();
2986 setupDrawBlending(true, mode);
2988 setupDrawModelView(0.0f, 0.0f, 0.0f, 0.0f, false, true);
2989 // Calling setupDrawTexture with the name 0 will enable the
2990 // uv attributes and increase the texture unit count
2991 // texture binding will be performed by the font renderer as
2993 setupDrawTexture(0);
2994 setupDrawPureColorUniforms();
2995 setupDrawColorFilterUniforms();
2996 setupDrawShaderUniforms(false);
2997 setupDrawTextGammaUniforms();
2999 const Rect* clip = &mSnapshot->getLocalClip();
3000 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f);
3002 const bool hasActiveLayer = hasLayer();
3004 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path,
3005 hOffset, vOffset, hasActiveLayer ? &bounds : NULL)) {
3006 if (hasActiveLayer) {
3007 currentTransform().mapRect(bounds);
3008 dirtyLayerUnchecked(bounds, getRegion());
3012 return DrawGlInfo::kStatusDrew;
3015 status_t OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) {
3016 if (mSnapshot->isIgnored()) return DrawGlInfo::kStatusDone;
3018 mCaches.activeTexture(0);
3020 const PathTexture* texture = mCaches.pathCache.get(path, paint);
3021 if (!texture) return DrawGlInfo::kStatusDone;
3022 const AutoTexture autoCleanup(texture);
3024 const float x = texture->left - texture->offset;
3025 const float y = texture->top - texture->offset;
3027 drawPathTexture(texture, x, y, paint);
3029 return DrawGlInfo::kStatusDrew;
3032 status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y) {
3034 return DrawGlInfo::kStatusDone;
3037 mat4* transform = NULL;
3038 if (layer->isTextureLayer()) {
3039 transform = &layer->getTransform();
3040 if (!transform->isIdentity()) {
3042 currentTransform().multiply(*transform);
3048 const bool rejected = quickRejectNoScissor(x, y,
3049 x + layer->layer.getWidth(), y + layer->layer.getHeight(), transformed, clip);
3052 if (transform && !transform->isIdentity()) {
3055 return DrawGlInfo::kStatusDone;
3058 updateLayer(layer, true);
3060 mCaches.setScissorEnabled(mScissorOptimizationDisabled || !clip.contains(transformed));
3061 mCaches.activeTexture(0);
3063 if (CC_LIKELY(!layer->region.isEmpty())) {
3064 SkiaColorFilter* oldFilter = mDrawModifiers.mColorFilter;
3065 mDrawModifiers.mColorFilter = layer->getColorFilter();
3067 if (layer->region.isRect()) {
3068 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3069 composeLayerRect(layer, layer->regionRect));
3070 } else if (layer->mesh) {
3071 const float a = getLayerAlpha(layer);
3073 setupDrawWithTexture();
3074 setupDrawColor(a, a, a, a);
3075 setupDrawColorFilter();
3076 setupDrawBlending(layer->isBlend() || a < 1.0f, layer->getMode(), false);
3078 setupDrawPureColorUniforms();
3079 setupDrawColorFilterUniforms();
3080 setupDrawTexture(layer->getTexture());
3081 if (CC_LIKELY(currentTransform().isPureTranslate())) {
3082 int tx = (int) floorf(x + currentTransform().getTranslateX() + 0.5f);
3083 int ty = (int) floorf(y + currentTransform().getTranslateY() + 0.5f);
3085 layer->setFilter(GL_NEAREST);
3086 setupDrawModelViewTranslate(tx, ty,
3087 tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true);
3089 layer->setFilter(GL_LINEAR);
3090 setupDrawModelViewTranslate(x, y,
3091 x + layer->layer.getWidth(), y + layer->layer.getHeight());
3093 setupDrawMesh(&layer->mesh[0].position[0], &layer->mesh[0].texture[0]);
3095 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate,
3096 glDrawElements(GL_TRIANGLES, layer->meshElementCount,
3097 GL_UNSIGNED_SHORT, layer->meshIndices));
3099 finishDrawTexture();
3101 #if DEBUG_LAYERS_AS_REGIONS
3102 drawRegionRects(layer->region);
3106 mDrawModifiers.mColorFilter = oldFilter;
3108 if (layer->debugDrawUpdate) {
3109 layer->debugDrawUpdate = false;
3110 drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(),
3111 0x7f00ff00, SkXfermode::kSrcOver_Mode);
3114 layer->hasDrawnSinceUpdate = true;
3116 if (transform && !transform->isIdentity()) {
3120 return DrawGlInfo::kStatusDrew;
3123 ///////////////////////////////////////////////////////////////////////////////
3125 ///////////////////////////////////////////////////////////////////////////////
3127 void OpenGLRenderer::resetShader() {
3128 mDrawModifiers.mShader = NULL;
3131 void OpenGLRenderer::setupShader(SkiaShader* shader) {
3132 mDrawModifiers.mShader = shader;
3133 if (mDrawModifiers.mShader) {
3134 mDrawModifiers.mShader->set(&mCaches.textureCache, &mCaches.gradientCache);
3138 ///////////////////////////////////////////////////////////////////////////////
3140 ///////////////////////////////////////////////////////////////////////////////
3142 void OpenGLRenderer::resetColorFilter() {
3143 mDrawModifiers.mColorFilter = NULL;
3146 void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) {
3147 mDrawModifiers.mColorFilter = filter;
3150 ///////////////////////////////////////////////////////////////////////////////
3152 ///////////////////////////////////////////////////////////////////////////////
3154 void OpenGLRenderer::resetShadow() {
3155 mDrawModifiers.mHasShadow = false;
3158 void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) {
3159 mDrawModifiers.mHasShadow = true;
3160 mDrawModifiers.mShadowRadius = radius;
3161 mDrawModifiers.mShadowDx = dx;
3162 mDrawModifiers.mShadowDy = dy;
3163 mDrawModifiers.mShadowColor = color;
3166 ///////////////////////////////////////////////////////////////////////////////
3168 ///////////////////////////////////////////////////////////////////////////////
3170 void OpenGLRenderer::resetPaintFilter() {
3171 // when clearing the PaintFilter, the masks should also be cleared for simple DrawModifier
3172 // comparison, see MergingDrawBatch::canMergeWith
3173 mDrawModifiers.mHasDrawFilter = false;
3174 mDrawModifiers.mPaintFilterClearBits = 0;
3175 mDrawModifiers.mPaintFilterSetBits = 0;
3178 void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) {
3179 mDrawModifiers.mHasDrawFilter = true;
3180 mDrawModifiers.mPaintFilterClearBits = clearBits & SkPaint::kAllFlags;
3181 mDrawModifiers.mPaintFilterSetBits = setBits & SkPaint::kAllFlags;
3184 SkPaint* OpenGLRenderer::filterPaint(SkPaint* paint) {
3185 if (CC_LIKELY(!mDrawModifiers.mHasDrawFilter || !paint)) {
3189 uint32_t flags = paint->getFlags();
3191 mFilteredPaint = *paint;
3192 mFilteredPaint.setFlags((flags & ~mDrawModifiers.mPaintFilterClearBits) |
3193 mDrawModifiers.mPaintFilterSetBits);
3195 return &mFilteredPaint;
3198 ///////////////////////////////////////////////////////////////////////////////
3199 // Drawing implementation
3200 ///////////////////////////////////////////////////////////////////////////////
3202 void OpenGLRenderer::drawPathTexture(const PathTexture* texture,
3203 float x, float y, SkPaint* paint) {
3204 if (quickReject(x, y, x + texture->width, y + texture->height)) {
3209 SkXfermode::Mode mode;
3210 getAlphaAndMode(paint, &alpha, &mode);
3213 setupDrawWithTexture(true);
3214 setupDrawAlpha8Color(paint->getColor(), alpha);
3215 setupDrawColorFilter();
3217 setupDrawBlending(true, mode);
3219 setupDrawModelView(x, y, x + texture->width, y + texture->height);
3220 setupDrawTexture(texture->id);
3221 setupDrawPureColorUniforms();
3222 setupDrawColorFilterUniforms();
3223 setupDrawShaderUniforms();
3224 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset);
3226 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3228 finishDrawTexture();
3231 // Same values used by Skia
3232 #define kStdStrikeThru_Offset (-6.0f / 21.0f)
3233 #define kStdUnderline_Offset (1.0f / 9.0f)
3234 #define kStdUnderline_Thickness (1.0f / 18.0f)
3236 void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length,
3237 float x, float y, SkPaint* paint) {
3238 // Handle underline and strike-through
3239 uint32_t flags = paint->getFlags();
3240 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) {
3241 SkPaint paintCopy(*paint);
3242 float underlineWidth = length;
3243 // If length is > 0.0f, we already measured the text for the text alignment
3244 if (length <= 0.0f) {
3245 underlineWidth = paintCopy.measureText(text, bytesCount);
3248 if (CC_LIKELY(underlineWidth > 0.0f)) {
3249 const float textSize = paintCopy.getTextSize();
3250 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f);
3252 const float left = x;
3256 if (flags & SkPaint::kUnderlineText_Flag) linesCount++;
3257 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++;
3259 const int pointsCount = 4 * linesCount;
3260 float points[pointsCount];
3261 int currentPoint = 0;
3263 if (flags & SkPaint::kUnderlineText_Flag) {
3264 top = y + textSize * kStdUnderline_Offset;
3265 points[currentPoint++] = left;
3266 points[currentPoint++] = top;
3267 points[currentPoint++] = left + underlineWidth;
3268 points[currentPoint++] = top;
3271 if (flags & SkPaint::kStrikeThruText_Flag) {
3272 top = y + textSize * kStdStrikeThru_Offset;
3273 points[currentPoint++] = left;
3274 points[currentPoint++] = top;
3275 points[currentPoint++] = left + underlineWidth;
3276 points[currentPoint++] = top;
3279 paintCopy.setStrokeWidth(strokeWidth);
3281 drawLines(&points[0], pointsCount, &paintCopy);
3286 status_t OpenGLRenderer::drawRects(const float* rects, int count, SkPaint* paint) {
3287 if (mSnapshot->isIgnored()) {
3288 return DrawGlInfo::kStatusDone;
3291 int color = paint->getColor();
3292 // If a shader is set, preserve only the alpha
3293 if (mDrawModifiers.mShader) {
3294 color |= 0x00ffffff;
3296 SkXfermode::Mode mode = getXfermode(paint->getXfermode());
3298 return drawColorRects(rects, count, color, mode);
3301 status_t OpenGLRenderer::drawColorRects(const float* rects, int count, int color,
3302 SkXfermode::Mode mode, bool ignoreTransform, bool dirty, bool clip) {
3304 return DrawGlInfo::kStatusDone;
3307 float left = FLT_MAX;
3308 float top = FLT_MAX;
3309 float right = FLT_MIN;
3310 float bottom = FLT_MIN;
3312 int vertexCount = 0;
3313 Vertex mesh[count * 6];
3314 Vertex* vertex = mesh;
3316 for (int index = 0; index < count; index += 4) {
3317 float l = rects[index + 0];
3318 float t = rects[index + 1];
3319 float r = rects[index + 2];
3320 float b = rects[index + 3];
3322 Vertex::set(vertex++, l, b);
3323 Vertex::set(vertex++, l, t);
3324 Vertex::set(vertex++, r, t);
3325 Vertex::set(vertex++, l, b);
3326 Vertex::set(vertex++, r, t);
3327 Vertex::set(vertex++, r, b);
3331 left = fminf(left, l);
3332 top = fminf(top, t);
3333 right = fmaxf(right, r);
3334 bottom = fmaxf(bottom, b);
3337 if (clip && quickReject(left, top, right, bottom)) {
3338 return DrawGlInfo::kStatusDone;
3342 setupDrawNoTexture();
3343 setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3345 setupDrawColorFilter();
3346 setupDrawBlending(mode);
3348 setupDrawDirtyRegionsDisabled();
3349 setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, ignoreTransform, true);
3350 setupDrawColorUniforms();
3351 setupDrawShaderUniforms();
3352 setupDrawColorFilterUniforms();
3353 setupDrawVertices((GLvoid*) &mesh[0].position[0]);
3355 if (dirty && hasLayer()) {
3356 dirtyLayer(left, top, right, bottom, currentTransform());
3359 glDrawArrays(GL_TRIANGLES, 0, vertexCount);
3361 return DrawGlInfo::kStatusDrew;
3364 void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom,
3365 int color, SkXfermode::Mode mode, bool ignoreTransform) {
3366 // If a shader is set, preserve only the alpha
3367 if (mDrawModifiers.mShader) {
3368 color |= 0x00ffffff;
3372 setupDrawNoTexture();
3373 setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha);
3375 setupDrawColorFilter();
3376 setupDrawBlending(mode);
3378 setupDrawModelView(left, top, right, bottom, ignoreTransform);
3379 setupDrawColorUniforms();
3380 setupDrawShaderUniforms(ignoreTransform);
3381 setupDrawColorFilterUniforms();
3382 setupDrawSimpleMesh();
3384 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
3387 void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3388 Texture* texture, SkPaint* paint) {
3390 SkXfermode::Mode mode;
3391 getAlphaAndMode(paint, &alpha, &mode);
3393 texture->setWrap(GL_CLAMP_TO_EDGE, true);
3395 if (CC_LIKELY(currentTransform().isPureTranslate())) {
3396 const float x = (int) floorf(left + currentTransform().getTranslateX() + 0.5f);
3397 const float y = (int) floorf(top + currentTransform().getTranslateY() + 0.5f);
3399 texture->setFilter(GL_NEAREST, true);
3400 drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id,
3401 alpha / 255.0f, mode, texture->blend, (GLvoid*) NULL,
3402 (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount, false, true);
3404 texture->setFilter(FILTER(paint), true);
3405 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode,
3406 texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset,
3407 GL_TRIANGLE_STRIP, gMeshCount);
3411 void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
3412 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
3413 drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
3414 (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount);
3417 void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
3418 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend,
3419 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3420 bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) {
3423 setupDrawWithTexture();
3424 setupDrawColor(alpha, alpha, alpha, alpha);
3425 setupDrawColorFilter();
3426 setupDrawBlending(blend, mode, swapSrcDst);
3428 if (!dirty) setupDrawDirtyRegionsDisabled();
3430 setupDrawModelView(left, top, right, bottom, ignoreTransform);
3432 setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3434 setupDrawTexture(texture);
3435 setupDrawPureColorUniforms();
3436 setupDrawColorFilterUniforms();
3437 setupDrawMesh(vertices, texCoords, vbo);
3439 glDrawArrays(drawMode, 0, elementsCount);
3441 finishDrawTexture();
3444 void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom,
3445 GLuint texture, bool hasColor, int color, int alpha, SkXfermode::Mode mode,
3446 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount,
3447 bool ignoreTransform, bool ignoreScale, bool dirty) {
3450 setupDrawWithTexture(true);
3452 setupDrawAlpha8Color(color, alpha);
3454 setupDrawColorFilter();
3456 setupDrawBlending(true, mode);
3458 if (!dirty) setupDrawDirtyRegionsDisabled();
3460 setupDrawModelView(left, top, right, bottom, ignoreTransform);
3462 setupDrawModelViewTranslate(left, top, right, bottom, ignoreTransform);
3464 setupDrawTexture(texture);
3465 setupDrawPureColorUniforms();
3466 setupDrawColorFilterUniforms();
3467 setupDrawShaderUniforms();
3468 setupDrawMesh(vertices, texCoords);
3470 glDrawArrays(drawMode, 0, elementsCount);
3472 finishDrawTexture();
3475 void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode,
3476 ProgramDescription& description, bool swapSrcDst) {
3477 blend = blend || mode != SkXfermode::kSrcOver_Mode;
3480 // These blend modes are not supported by OpenGL directly and have
3481 // to be implemented using shaders. Since the shader will perform
3482 // the blending, turn blending off here
3483 // If the blend mode cannot be implemented using shaders, fall
3484 // back to the default SrcOver blend mode instead
3485 if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) {
3486 if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) {
3487 description.framebufferMode = mode;
3488 description.swapSrcDst = swapSrcDst;
3490 if (mCaches.blend) {
3491 glDisable(GL_BLEND);
3492 mCaches.blend = false;
3497 mode = SkXfermode::kSrcOver_Mode;
3501 if (!mCaches.blend) {
3505 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src;
3506 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst;
3508 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) {
3509 glBlendFunc(sourceMode, destMode);
3510 mCaches.lastSrcMode = sourceMode;
3511 mCaches.lastDstMode = destMode;
3513 } else if (mCaches.blend) {
3514 glDisable(GL_BLEND);
3516 mCaches.blend = blend;
3519 bool OpenGLRenderer::useProgram(Program* program) {
3520 if (!program->isInUse()) {
3521 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove();
3523 mCaches.currentProgram = program;
3529 void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
3530 TextureVertex* v = &mMeshVertices[0];
3531 TextureVertex::setUV(v++, u1, v1);
3532 TextureVertex::setUV(v++, u2, v1);
3533 TextureVertex::setUV(v++, u1, v2);
3534 TextureVertex::setUV(v++, u2, v2);
3537 void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const {
3538 getAlphaAndModeDirect(paint, alpha, mode);
3539 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3540 // if drawing a layer, ignore the paint's alpha
3541 *alpha = mDrawModifiers.mOverrideLayerAlpha * 255;
3543 *alpha *= mSnapshot->alpha;
3546 float OpenGLRenderer::getLayerAlpha(Layer* layer) const {
3548 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) {
3549 alpha = mDrawModifiers.mOverrideLayerAlpha;
3551 alpha = layer->getAlpha() / 255.0f;
3553 return alpha * mSnapshot->alpha;
3556 }; // namespace uirenderer
3557 }; // namespace android