OpenGLRenderer.cpp revision 922d3a7f6f8c1c05a996ee3e91e8cbadfff560c9
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include "OpenGLRenderer.h" 18 19#include "DeferredDisplayList.h" 20#include "DisplayListRenderer.h" 21#include "GammaFontRenderer.h" 22#include "Glop.h" 23#include "GlopBuilder.h" 24#include "Patch.h" 25#include "PathTessellator.h" 26#include "Properties.h" 27#include "RenderNode.h" 28#include "renderstate/MeshState.h" 29#include "renderstate/RenderState.h" 30#include "ShadowTessellator.h" 31#include "SkiaShader.h" 32#include "Vector.h" 33#include "VertexBuffer.h" 34#include "utils/GLUtils.h" 35#include "utils/PaintUtils.h" 36#include "utils/TraceUtils.h" 37 38#include <stdlib.h> 39#include <stdint.h> 40#include <sys/types.h> 41 42#include <SkCanvas.h> 43#include <SkColor.h> 44#include <SkShader.h> 45#include <SkTypeface.h> 46 47#include <utils/Log.h> 48#include <utils/StopWatch.h> 49 50#include <private/hwui/DrawGlInfo.h> 51 52#include <ui/Rect.h> 53 54#if DEBUG_DETAILED_EVENTS 55 #define EVENT_LOGD(...) eventMarkDEBUG(__VA_ARGS__) 56#else 57 #define EVENT_LOGD(...) 58#endif 59 60#define USE_GLOPS true 61 62namespace android { 63namespace uirenderer { 64 65/////////////////////////////////////////////////////////////////////////////// 66// Constructors/destructor 67/////////////////////////////////////////////////////////////////////////////// 68 69OpenGLRenderer::OpenGLRenderer(RenderState& renderState) 70 : mState(*this) 71 , mCaches(Caches::getInstance()) 72 , mRenderState(renderState) 73 , mFrameStarted(false) 74 , mScissorOptimizationDisabled(false) 75 , mSuppressTiling(false) 76 , mFirstFrameAfterResize(true) 77 , mDirty(false) 78 , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN}) 79 , mLightRadius(FLT_MIN) 80 , mAmbientShadowAlpha(0) 81 , mSpotShadowAlpha(0) { 82 // *set* draw modifiers to be 0 83 memset(&mDrawModifiers, 0, sizeof(mDrawModifiers)); 84 mDrawModifiers.mOverrideLayerAlpha = 1.0f; 85 86 memcpy(mMeshVertices, kUnitQuadVertices, sizeof(kUnitQuadVertices)); 87} 88 89OpenGLRenderer::~OpenGLRenderer() { 90 // The context has already been destroyed at this point, do not call 91 // GL APIs. All GL state should be kept in Caches.h 92} 93 94void OpenGLRenderer::initProperties() { 95 char property[PROPERTY_VALUE_MAX]; 96 if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) { 97 mScissorOptimizationDisabled = !strcasecmp(property, "true"); 98 INIT_LOGD(" Scissor optimization %s", 99 mScissorOptimizationDisabled ? "disabled" : "enabled"); 100 } else { 101 INIT_LOGD(" Scissor optimization enabled"); 102 } 103} 104 105void OpenGLRenderer::initLight(const Vector3& lightCenter, float lightRadius, 106 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) { 107 mLightCenter = lightCenter; 108 mLightRadius = lightRadius; 109 mAmbientShadowAlpha = ambientShadowAlpha; 110 mSpotShadowAlpha = spotShadowAlpha; 111} 112 113/////////////////////////////////////////////////////////////////////////////// 114// Setup 115/////////////////////////////////////////////////////////////////////////////// 116 117void OpenGLRenderer::onViewportInitialized() { 118 glDisable(GL_DITHER); 119 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 120 mFirstFrameAfterResize = true; 121} 122 123void OpenGLRenderer::setupFrameState(float left, float top, 124 float right, float bottom, bool opaque) { 125 mCaches.clearGarbage(); 126 mState.initializeSaveStack(left, top, right, bottom, mLightCenter); 127 mOpaque = opaque; 128 mTilingClip.set(left, top, right, bottom); 129} 130 131void OpenGLRenderer::startFrame() { 132 if (mFrameStarted) return; 133 mFrameStarted = true; 134 135 mState.setDirtyClip(true); 136 137 discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom); 138 139 mRenderState.setViewport(mState.getWidth(), mState.getHeight()); 140 141 // Functors break the tiling extension in pretty spectacular ways 142 // This ensures we don't use tiling when a functor is going to be 143 // invoked during the frame 144 mSuppressTiling = mCaches.hasRegisteredFunctors() 145 || mFirstFrameAfterResize; 146 mFirstFrameAfterResize = false; 147 148 startTilingCurrentClip(true); 149 150 debugOverdraw(true, true); 151 152 clear(mTilingClip.left, mTilingClip.top, 153 mTilingClip.right, mTilingClip.bottom, mOpaque); 154} 155 156void OpenGLRenderer::prepareDirty(float left, float top, 157 float right, float bottom, bool opaque) { 158 159 setupFrameState(left, top, right, bottom, opaque); 160 161 // Layer renderers will start the frame immediately 162 // The framebuffer renderer will first defer the display list 163 // for each layer and wait until the first drawing command 164 // to start the frame 165 if (currentSnapshot()->fbo == 0) { 166 mRenderState.blend().syncEnabled(); 167 updateLayers(); 168 } else { 169 startFrame(); 170 } 171} 172 173void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) { 174 // If we know that we are going to redraw the entire framebuffer, 175 // perform a discard to let the driver know we don't need to preserve 176 // the back buffer for this frame. 177 if (mCaches.extensions().hasDiscardFramebuffer() && 178 left <= 0.0f && top <= 0.0f && right >= mState.getWidth() && bottom >= mState.getHeight()) { 179 const bool isFbo = onGetTargetFbo() == 0; 180 const GLenum attachments[] = { 181 isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0, 182 isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT }; 183 glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); 184 } 185} 186 187void OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) { 188 if (!opaque) { 189 mRenderState.scissor().setEnabled(true); 190 mRenderState.scissor().set(left, getViewportHeight() - bottom, right - left, bottom - top); 191 glClear(GL_COLOR_BUFFER_BIT); 192 mDirty = true; 193 return; 194 } 195 196 mRenderState.scissor().reset(); 197} 198 199void OpenGLRenderer::startTilingCurrentClip(bool opaque, bool expand) { 200 if (!mSuppressTiling) { 201 const Snapshot* snapshot = currentSnapshot(); 202 203 const Rect* clip = &mTilingClip; 204 if (snapshot->flags & Snapshot::kFlagFboTarget) { 205 clip = &(snapshot->layer->clipRect); 206 } 207 208 startTiling(*clip, getViewportHeight(), opaque, expand); 209 } 210} 211 212void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque, bool expand) { 213 if (!mSuppressTiling) { 214 if(expand) { 215 // Expand the startTiling region by 1 216 int leftNotZero = (clip.left > 0) ? 1 : 0; 217 int topNotZero = (windowHeight - clip.bottom > 0) ? 1 : 0; 218 219 mCaches.startTiling( 220 clip.left - leftNotZero, 221 windowHeight - clip.bottom - topNotZero, 222 clip.right - clip.left + leftNotZero + 1, 223 clip.bottom - clip.top + topNotZero + 1, 224 opaque); 225 } else { 226 mCaches.startTiling(clip.left, windowHeight - clip.bottom, 227 clip.right - clip.left, clip.bottom - clip.top, opaque); 228 } 229 } 230} 231 232void OpenGLRenderer::endTiling() { 233 if (!mSuppressTiling) mCaches.endTiling(); 234} 235 236bool OpenGLRenderer::finish() { 237 renderOverdraw(); 238 endTiling(); 239 mTempPaths.clear(); 240 241 // When finish() is invoked on FBO 0 we've reached the end 242 // of the current frame 243 if (onGetTargetFbo() == 0) { 244 mCaches.pathCache.trim(); 245 mCaches.tessellationCache.trim(); 246 } 247 248 if (!suppressErrorChecks()) { 249#if DEBUG_OPENGL 250 GLUtils::dumpGLErrors(); 251#endif 252 253#if DEBUG_MEMORY_USAGE 254 mCaches.dumpMemoryUsage(); 255#else 256 if (mCaches.getDebugLevel() & kDebugMemory) { 257 mCaches.dumpMemoryUsage(); 258 } 259#endif 260 } 261 262 mFrameStarted = false; 263 264 return reportAndClearDirty(); 265} 266 267void OpenGLRenderer::resumeAfterLayer() { 268 mRenderState.setViewport(getViewportWidth(), getViewportHeight()); 269 mRenderState.bindFramebuffer(currentSnapshot()->fbo); 270 debugOverdraw(true, false); 271 272 mRenderState.scissor().reset(); 273 dirtyClip(); 274} 275 276void OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) { 277 if (mState.currentlyIgnored()) return; 278 279 Rect clip(mState.currentClipRect()); 280 clip.snapToPixelBoundaries(); 281 282 // Since we don't know what the functor will draw, let's dirty 283 // the entire clip region 284 if (hasLayer()) { 285 dirtyLayerUnchecked(clip, getRegion()); 286 } 287 288 DrawGlInfo info; 289 info.clipLeft = clip.left; 290 info.clipTop = clip.top; 291 info.clipRight = clip.right; 292 info.clipBottom = clip.bottom; 293 info.isLayer = hasLayer(); 294 info.width = getViewportWidth(); 295 info.height = getViewportHeight(); 296 currentTransform()->copyTo(&info.transform[0]); 297 298 bool prevDirtyClip = mState.getDirtyClip(); 299 // setup GL state for functor 300 if (mState.getDirtyClip()) { 301 setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt() 302 } 303 if (mRenderState.scissor().setEnabled(true) || prevDirtyClip) { 304 setScissorFromClip(); 305 } 306 307 mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info); 308 // Scissor may have been modified, reset dirty clip 309 dirtyClip(); 310 311 mDirty = true; 312} 313 314/////////////////////////////////////////////////////////////////////////////// 315// Debug 316/////////////////////////////////////////////////////////////////////////////// 317 318void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const { 319#if DEBUG_DETAILED_EVENTS 320 const int BUFFER_SIZE = 256; 321 va_list ap; 322 char buf[BUFFER_SIZE]; 323 324 va_start(ap, fmt); 325 vsnprintf(buf, BUFFER_SIZE, fmt, ap); 326 va_end(ap); 327 328 eventMark(buf); 329#endif 330} 331 332 333void OpenGLRenderer::eventMark(const char* name) const { 334 mCaches.eventMark(0, name); 335} 336 337void OpenGLRenderer::startMark(const char* name) const { 338 mCaches.startMark(0, name); 339} 340 341void OpenGLRenderer::endMark() const { 342 mCaches.endMark(); 343} 344 345void OpenGLRenderer::debugOverdraw(bool enable, bool clear) { 346 mRenderState.debugOverdraw(enable, clear); 347} 348 349void OpenGLRenderer::renderOverdraw() { 350 if (mCaches.debugOverdraw && onGetTargetFbo() == 0) { 351 const Rect* clip = &mTilingClip; 352 353 mRenderState.scissor().setEnabled(true); 354 mRenderState.scissor().set(clip->left, 355 mState.firstSnapshot()->getViewportHeight() - clip->bottom, 356 clip->right - clip->left, 357 clip->bottom - clip->top); 358 359 // 1x overdraw 360 mRenderState.stencil().enableDebugTest(2); 361 drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode); 362 363 // 2x overdraw 364 mRenderState.stencil().enableDebugTest(3); 365 drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode); 366 367 // 3x overdraw 368 mRenderState.stencil().enableDebugTest(4); 369 drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode); 370 371 // 4x overdraw and higher 372 mRenderState.stencil().enableDebugTest(4, true); 373 drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode); 374 375 mRenderState.stencil().disable(); 376 } 377} 378 379/////////////////////////////////////////////////////////////////////////////// 380// Layers 381/////////////////////////////////////////////////////////////////////////////// 382 383bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) { 384 if (layer->deferredUpdateScheduled && layer->renderer 385 && layer->renderNode.get() && layer->renderNode->isRenderable()) { 386 387 if (inFrame) { 388 endTiling(); 389 debugOverdraw(false, false); 390 } 391 392 if (CC_UNLIKELY(inFrame || mCaches.drawDeferDisabled)) { 393 layer->render(*this); 394 } else { 395 layer->defer(*this); 396 } 397 398 if (inFrame) { 399 resumeAfterLayer(); 400 startTilingCurrentClip(); 401 } 402 403 layer->debugDrawUpdate = mCaches.debugLayersUpdates; 404 layer->hasDrawnSinceUpdate = false; 405 406 return true; 407 } 408 409 return false; 410} 411 412void OpenGLRenderer::updateLayers() { 413 // If draw deferring is enabled this method will simply defer 414 // the display list of each individual layer. The layers remain 415 // in the layer updates list which will be cleared by flushLayers(). 416 int count = mLayerUpdates.size(); 417 if (count > 0) { 418 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 419 startMark("Layer Updates"); 420 } else { 421 startMark("Defer Layer Updates"); 422 } 423 424 // Note: it is very important to update the layers in order 425 for (int i = 0; i < count; i++) { 426 Layer* layer = mLayerUpdates.itemAt(i).get(); 427 updateLayer(layer, false); 428 } 429 430 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 431 mLayerUpdates.clear(); 432 mRenderState.bindFramebuffer(onGetTargetFbo()); 433 } 434 endMark(); 435 } 436} 437 438void OpenGLRenderer::flushLayers() { 439 int count = mLayerUpdates.size(); 440 if (count > 0) { 441 startMark("Apply Layer Updates"); 442 443 // Note: it is very important to update the layers in order 444 for (int i = 0; i < count; i++) { 445 mLayerUpdates.itemAt(i)->flush(); 446 } 447 448 mLayerUpdates.clear(); 449 mRenderState.bindFramebuffer(onGetTargetFbo()); 450 451 endMark(); 452 } 453} 454 455void OpenGLRenderer::pushLayerUpdate(Layer* layer) { 456 if (layer) { 457 // Make sure we don't introduce duplicates. 458 // SortedVector would do this automatically but we need to respect 459 // the insertion order. The linear search is not an issue since 460 // this list is usually very short (typically one item, at most a few) 461 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 462 if (mLayerUpdates.itemAt(i) == layer) { 463 return; 464 } 465 } 466 mLayerUpdates.push_back(layer); 467 } 468} 469 470void OpenGLRenderer::cancelLayerUpdate(Layer* layer) { 471 if (layer) { 472 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 473 if (mLayerUpdates.itemAt(i) == layer) { 474 mLayerUpdates.removeAt(i); 475 break; 476 } 477 } 478 } 479} 480 481void OpenGLRenderer::flushLayerUpdates() { 482 ATRACE_NAME("Update HW Layers"); 483 mRenderState.blend().syncEnabled(); 484 updateLayers(); 485 flushLayers(); 486 // Wait for all the layer updates to be executed 487 glFinish(); 488} 489 490void OpenGLRenderer::markLayersAsBuildLayers() { 491 for (size_t i = 0; i < mLayerUpdates.size(); i++) { 492 mLayerUpdates[i]->wasBuildLayered = true; 493 } 494} 495 496/////////////////////////////////////////////////////////////////////////////// 497// State management 498/////////////////////////////////////////////////////////////////////////////// 499 500void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) { 501 bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer; 502 bool restoreClip = removed.flags & Snapshot::kFlagClipSet; 503 bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer; 504 505 if (restoreViewport) { 506 mRenderState.setViewport(getViewportWidth(), getViewportHeight()); 507 } 508 509 if (restoreClip) { 510 dirtyClip(); 511 } 512 513 if (restoreLayer) { 514 endMark(); // Savelayer 515 ATRACE_END(); // SaveLayer 516 startMark("ComposeLayer"); 517 composeLayer(removed, restored); 518 endMark(); 519 } 520} 521 522/////////////////////////////////////////////////////////////////////////////// 523// Layers 524/////////////////////////////////////////////////////////////////////////////// 525 526int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 527 const SkPaint* paint, int flags, const SkPath* convexMask) { 528 // force matrix/clip isolation for layer 529 flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag; 530 531 const int count = mState.saveSnapshot(flags); 532 533 if (!mState.currentlyIgnored()) { 534 createLayer(left, top, right, bottom, paint, flags, convexMask); 535 } 536 537 return count; 538} 539 540void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) { 541 const Rect untransformedBounds(bounds); 542 543 currentTransform()->mapRect(bounds); 544 545 // Layers only make sense if they are in the framebuffer's bounds 546 if (bounds.intersect(mState.currentClipRect())) { 547 // We cannot work with sub-pixels in this case 548 bounds.snapToPixelBoundaries(); 549 550 // When the layer is not an FBO, we may use glCopyTexImage so we 551 // need to make sure the layer does not extend outside the bounds 552 // of the framebuffer 553 const Snapshot& previous = *(currentSnapshot()->previous); 554 Rect previousViewport(0, 0, previous.getViewportWidth(), previous.getViewportHeight()); 555 if (!bounds.intersect(previousViewport)) { 556 bounds.setEmpty(); 557 } else if (fboLayer) { 558 clip.set(bounds); 559 mat4 inverse; 560 inverse.loadInverse(*currentTransform()); 561 inverse.mapRect(clip); 562 clip.snapToPixelBoundaries(); 563 if (clip.intersect(untransformedBounds)) { 564 clip.translate(-untransformedBounds.left, -untransformedBounds.top); 565 bounds.set(untransformedBounds); 566 } else { 567 clip.setEmpty(); 568 } 569 } 570 } else { 571 bounds.setEmpty(); 572 } 573} 574 575void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip, 576 bool fboLayer, int alpha) { 577 if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize || 578 bounds.getHeight() > mCaches.maxTextureSize || 579 (fboLayer && clip.isEmpty())) { 580 writableSnapshot()->empty = fboLayer; 581 } else { 582 writableSnapshot()->invisible = writableSnapshot()->invisible || (alpha <= 0 && fboLayer); 583 } 584} 585 586int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom, 587 const SkPaint* paint, int flags) { 588 const int count = mState.saveSnapshot(flags); 589 590 if (!mState.currentlyIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) { 591 // initialize the snapshot as though it almost represents an FBO layer so deferred draw 592 // operations will be able to store and restore the current clip and transform info, and 593 // quick rejection will be correct (for display lists) 594 595 Rect bounds(left, top, right, bottom); 596 Rect clip; 597 calculateLayerBoundsAndClip(bounds, clip, true); 598 updateSnapshotIgnoreForLayer(bounds, clip, true, getAlphaDirect(paint)); 599 600 if (!mState.currentlyIgnored()) { 601 writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f); 602 writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom); 603 writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight()); 604 writableSnapshot()->roundRectClipState = nullptr; 605 } 606 } 607 608 return count; 609} 610 611/** 612 * Layers are viewed by Skia are slightly different than layers in image editing 613 * programs (for instance.) When a layer is created, previously created layers 614 * and the frame buffer still receive every drawing command. For instance, if a 615 * layer is created and a shape intersecting the bounds of the layers and the 616 * framebuffer is draw, the shape will be drawn on both (unless the layer was 617 * created with the SkCanvas::kClipToLayer_SaveFlag flag.) 618 * 619 * A way to implement layers is to create an FBO for each layer, backed by an RGBA 620 * texture. Unfortunately, this is inefficient as it requires every primitive to 621 * be drawn n + 1 times, where n is the number of active layers. In practice this 622 * means, for every primitive: 623 * - Switch active frame buffer 624 * - Change viewport, clip and projection matrix 625 * - Issue the drawing 626 * 627 * Switching rendering target n + 1 times per drawn primitive is extremely costly. 628 * To avoid this, layers are implemented in a different way here, at least in the 629 * general case. FBOs are used, as an optimization, when the "clip to layer" flag 630 * is set. When this flag is set we can redirect all drawing operations into a 631 * single FBO. 632 * 633 * This implementation relies on the frame buffer being at least RGBA 8888. When 634 * a layer is created, only a texture is created, not an FBO. The content of the 635 * frame buffer contained within the layer's bounds is copied into this texture 636 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame 637 * buffer and drawing continues as normal. This technique therefore treats the 638 * frame buffer as a scratch buffer for the layers. 639 * 640 * To compose the layers back onto the frame buffer, each layer texture 641 * (containing the original frame buffer data) is drawn as a simple quad over 642 * the frame buffer. The trick is that the quad is set as the composition 643 * destination in the blending equation, and the frame buffer becomes the source 644 * of the composition. 645 * 646 * Drawing layers with an alpha value requires an extra step before composition. 647 * An empty quad is drawn over the layer's region in the frame buffer. This quad 648 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the 649 * quad is used to multiply the colors in the frame buffer. This is achieved by 650 * changing the GL blend functions for the GL_FUNC_ADD blend equation to 651 * GL_ZERO, GL_SRC_ALPHA. 652 * 653 * Because glCopyTexImage2D() can be slow, an alternative implementation might 654 * be use to draw a single clipped layer. The implementation described above 655 * is correct in every case. 656 * 657 * (1) The frame buffer is actually not cleared right away. To allow the GPU 658 * to potentially optimize series of calls to glCopyTexImage2D, the frame 659 * buffer is left untouched until the first drawing operation. Only when 660 * something actually gets drawn are the layers regions cleared. 661 */ 662bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom, 663 const SkPaint* paint, int flags, const SkPath* convexMask) { 664 LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top); 665 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize()); 666 667 const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag; 668 669 // Window coordinates of the layer 670 Rect clip; 671 Rect bounds(left, top, right, bottom); 672 calculateLayerBoundsAndClip(bounds, clip, fboLayer); 673 updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, getAlphaDirect(paint)); 674 675 // Bail out if we won't draw in this snapshot 676 if (mState.currentlyIgnored()) { 677 return false; 678 } 679 680 mCaches.textureState().activateTexture(0); 681 Layer* layer = mCaches.layerCache.get(mRenderState, bounds.getWidth(), bounds.getHeight()); 682 if (!layer) { 683 return false; 684 } 685 686 layer->setPaint(paint); 687 layer->layer.set(bounds); 688 layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()), 689 bounds.getWidth() / float(layer->getWidth()), 0.0f); 690 691 layer->setBlend(true); 692 layer->setDirty(false); 693 layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache 694 695 // Save the layer in the snapshot 696 writableSnapshot()->flags |= Snapshot::kFlagIsLayer; 697 writableSnapshot()->layer = layer; 698 699 ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u", 700 fboLayer ? "" : "unclipped ", 701 layer->getWidth(), layer->getHeight()); 702 startMark("SaveLayer"); 703 if (fboLayer) { 704 return createFboLayer(layer, bounds, clip); 705 } else { 706 // Copy the framebuffer into the layer 707 layer->bindTexture(); 708 if (!bounds.isEmpty()) { 709 if (layer->isEmpty()) { 710 // Workaround for some GL drivers. When reading pixels lying outside 711 // of the window we should get undefined values for those pixels. 712 // Unfortunately some drivers will turn the entire target texture black 713 // when reading outside of the window. 714 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(), 715 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); 716 layer->setEmpty(false); 717 } 718 719 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 720 bounds.left, getViewportHeight() - bounds.bottom, 721 bounds.getWidth(), bounds.getHeight()); 722 723 // Enqueue the buffer coordinates to clear the corresponding region later 724 mLayers.push_back(Rect(bounds)); 725 } 726 } 727 728 return true; 729} 730 731bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) { 732 layer->clipRect.set(clip); 733 layer->setFbo(mCaches.fboCache.get()); 734 735 writableSnapshot()->region = &writableSnapshot()->layer->region; 736 writableSnapshot()->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer; 737 writableSnapshot()->fbo = layer->getFbo(); 738 writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f); 739 writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom); 740 writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight()); 741 writableSnapshot()->roundRectClipState = nullptr; 742 743 endTiling(); 744 debugOverdraw(false, false); 745 // Bind texture to FBO 746 mRenderState.bindFramebuffer(layer->getFbo()); 747 layer->bindTexture(); 748 749 // Initialize the texture if needed 750 if (layer->isEmpty()) { 751 layer->allocateTexture(); 752 layer->setEmpty(false); 753 } 754 755 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 756 layer->getTexture(), 0); 757 758 // Expand the startTiling region by 1 759 startTilingCurrentClip(true, true); 760 761 // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering 762 mRenderState.scissor().setEnabled(true); 763 mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f, 764 clip.getWidth() + 2.0f, clip.getHeight() + 2.0f); 765 glClear(GL_COLOR_BUFFER_BIT); 766 767 dirtyClip(); 768 769 // Change the ortho projection 770 mRenderState.setViewport(bounds.getWidth(), bounds.getHeight()); 771 return true; 772} 773 774/** 775 * Read the documentation of createLayer() before doing anything in this method. 776 */ 777void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) { 778 if (!removed.layer) { 779 ALOGE("Attempting to compose a layer that does not exist"); 780 return; 781 } 782 783 Layer* layer = removed.layer; 784 const Rect& rect = layer->layer; 785 const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer; 786 787 bool clipRequired = false; 788 mState.calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom, 789 &clipRequired, nullptr, false); // safely ignore return, should never be rejected 790 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 791 792 if (fboLayer) { 793 endTiling(); 794 795 // Detach the texture from the FBO 796 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); 797 798 layer->removeFbo(false); 799 800 // Unbind current FBO and restore previous one 801 mRenderState.bindFramebuffer(restored.fbo); 802 debugOverdraw(true, false); 803 804 startTilingCurrentClip(); 805 } 806 807 if (!fboLayer && layer->getAlpha() < 255) { 808 SkPaint layerPaint; 809 layerPaint.setAlpha(layer->getAlpha()); 810 layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode); 811 layerPaint.setColorFilter(layer->getColorFilter()); 812 813 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true); 814 // Required below, composeLayerRect() will divide by 255 815 layer->setAlpha(255); 816 } 817 818 mRenderState.meshState().unbindMeshBuffer(); 819 820 mCaches.textureState().activateTexture(0); 821 822 // When the layer is stored in an FBO, we can save a bit of fillrate by 823 // drawing only the dirty region 824 if (fboLayer) { 825 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform); 826 composeLayerRegion(layer, rect); 827 } else if (!rect.isEmpty()) { 828 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom); 829 830 save(0); 831 // the layer contains screen buffer content that shouldn't be alpha modulated 832 // (and any necessary alpha modulation was handled drawing into the layer) 833 writableSnapshot()->alpha = 1.0f; 834 composeLayerRect(layer, rect, true); 835 restore(); 836 } 837 838 dirtyClip(); 839 840 // Failing to add the layer to the cache should happen only if the layer is too large 841 layer->setConvexMask(nullptr); 842 if (!mCaches.layerCache.put(layer)) { 843 LAYER_LOGD("Deleting layer"); 844 layer->decStrong(nullptr); 845 } 846} 847 848void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) { 849 float alpha = getLayerAlpha(layer); 850 851 setupDraw(); 852 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 853 setupDrawWithTexture(); 854 } else { 855 setupDrawWithExternalTexture(); 856 } 857 setupDrawTextureTransform(); 858 setupDrawColor(alpha, alpha, alpha, alpha); 859 setupDrawColorFilter(layer->getColorFilter()); 860 setupDrawBlending(layer); 861 setupDrawProgram(); 862 setupDrawPureColorUniforms(); 863 setupDrawColorFilterUniforms(layer->getColorFilter()); 864 if (layer->getRenderTarget() == GL_TEXTURE_2D) { 865 setupDrawTexture(layer->getTexture()); 866 } else { 867 setupDrawExternalTexture(layer->getTexture()); 868 } 869 if (currentTransform()->isPureTranslate() && 870 !layer->getForceFilter() && 871 layer->getWidth() == (uint32_t) rect.getWidth() && 872 layer->getHeight() == (uint32_t) rect.getHeight()) { 873 const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 874 const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 875 876 layer->setFilter(GL_NEAREST); 877 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 878 x, y, x + rect.getWidth(), y + rect.getHeight(), true); 879 } else { 880 layer->setFilter(GL_LINEAR); 881 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 882 rect.left, rect.top, rect.right, rect.bottom); 883 } 884 setupDrawTextureTransformUniforms(layer->getTexTransform()); 885 setupDrawMesh(&mMeshVertices[0].x, &mMeshVertices[0].u); 886 887 glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount); 888} 889 890void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) { 891 if (layer->isTextureLayer()) { 892 EVENT_LOGD("composeTextureLayerRect"); 893 resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f); 894 drawTextureLayer(layer, rect); 895 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 896 } else { 897 EVENT_LOGD("composeHardwareLayerRect"); 898 const Rect& texCoords = layer->texCoords; 899 resetDrawTextureTexCoords(texCoords.left, texCoords.top, 900 texCoords.right, texCoords.bottom); 901 902 float x = rect.left; 903 float y = rect.top; 904 bool simpleTransform = currentTransform()->isPureTranslate() && 905 layer->getWidth() == (uint32_t) rect.getWidth() && 906 layer->getHeight() == (uint32_t) rect.getHeight(); 907 908 if (simpleTransform) { 909 // When we're swapping, the layer is already in screen coordinates 910 if (!swap) { 911 x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 912 y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 913 } 914 915 layer->setFilter(GL_NEAREST, true); 916 } else { 917 layer->setFilter(GL_LINEAR, true); 918 } 919 920 SkPaint layerPaint; 921 layerPaint.setAlpha(getLayerAlpha(layer) * 255); 922 layerPaint.setXfermodeMode(layer->getMode()); 923 layerPaint.setColorFilter(layer->getColorFilter()); 924 925 bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f; 926 drawTextureMesh(x, y, x + rect.getWidth(), y + rect.getHeight(), 927 layer->getTexture(), &layerPaint, blend, 928 &mMeshVertices[0].x, &mMeshVertices[0].u, 929 GL_TRIANGLE_STRIP, kUnitQuadCount, swap, swap || simpleTransform); 930 931 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 932 } 933} 934 935/** 936 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated 937 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw 938 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used 939 * by saveLayer's restore 940 */ 941#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \ 942 DRAW_COMMAND; \ 943 if (CC_UNLIKELY(mCaches.debugOverdraw && onGetTargetFbo() == 0 && COND)) { \ 944 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \ 945 DRAW_COMMAND; \ 946 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \ 947 } \ 948 } 949 950#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND) 951 952// This class is purely for inspection. It inherits from SkShader, but Skia does not know how to 953// use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque. 954class LayerShader : public SkShader { 955public: 956 LayerShader(Layer* layer, const SkMatrix* localMatrix) 957 : INHERITED(localMatrix) 958 , mLayer(layer) { 959 } 960 961 virtual bool asACustomShader(void** data) const override { 962 if (data) { 963 *data = static_cast<void*>(mLayer); 964 } 965 return true; 966 } 967 968 virtual bool isOpaque() const override { 969 return !mLayer->isBlend(); 970 } 971 972protected: 973 virtual void shadeSpan(int x, int y, SkPMColor[], int count) { 974 LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend."); 975 } 976 977 virtual void flatten(SkWriteBuffer&) const override { 978 LOG_ALWAYS_FATAL("LayerShader should never be flattened."); 979 } 980 981 virtual Factory getFactory() const override { 982 LOG_ALWAYS_FATAL("LayerShader should never be created from a stream."); 983 return nullptr; 984 } 985private: 986 // Unowned. 987 Layer* mLayer; 988 typedef SkShader INHERITED; 989}; 990 991void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) { 992 if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw 993 994 if (layer->getConvexMask()) { 995 save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag); 996 997 // clip to the area of the layer the mask can be larger 998 clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op); 999 1000 SkPaint paint; 1001 paint.setAntiAlias(true); 1002 paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0)); 1003 1004 // create LayerShader to map SaveLayer content into subsequent draw 1005 SkMatrix shaderMatrix; 1006 shaderMatrix.setTranslate(rect.left, rect.bottom); 1007 shaderMatrix.preScale(1, -1); 1008 LayerShader layerShader(layer, &shaderMatrix); 1009 paint.setShader(&layerShader); 1010 1011 // Since the drawing primitive is defined in local drawing space, 1012 // we don't need to modify the draw matrix 1013 const SkPath* maskPath = layer->getConvexMask(); 1014 DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint)); 1015 1016 paint.setShader(nullptr); 1017 restore(); 1018 1019 return; 1020 } 1021 1022 if (layer->region.isRect()) { 1023 layer->setRegionAsRect(); 1024 1025 DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect)); 1026 1027 layer->region.clear(); 1028 return; 1029 } 1030 1031 EVENT_LOGD("composeLayerRegion"); 1032 // standard Region based draw 1033 size_t count; 1034 const android::Rect* rects; 1035 Region safeRegion; 1036 if (CC_LIKELY(hasRectToRectTransform())) { 1037 rects = layer->region.getArray(&count); 1038 } else { 1039 safeRegion = Region::createTJunctionFreeRegion(layer->region); 1040 rects = safeRegion.getArray(&count); 1041 } 1042 1043 const float alpha = getLayerAlpha(layer); 1044 const float texX = 1.0f / float(layer->getWidth()); 1045 const float texY = 1.0f / float(layer->getHeight()); 1046 const float height = rect.getHeight(); 1047 1048 setupDraw(); 1049 1050 // We must get (and therefore bind) the region mesh buffer 1051 // after we setup drawing in case we need to mess with the 1052 // stencil buffer in setupDraw() 1053 TextureVertex* mesh = mCaches.getRegionMesh(); 1054 uint32_t numQuads = 0; 1055 1056 setupDrawWithTexture(); 1057 setupDrawColor(alpha, alpha, alpha, alpha); 1058 setupDrawColorFilter(layer->getColorFilter()); 1059 setupDrawBlending(layer); 1060 setupDrawProgram(); 1061 setupDrawDirtyRegionsDisabled(); 1062 setupDrawPureColorUniforms(); 1063 setupDrawColorFilterUniforms(layer->getColorFilter()); 1064 setupDrawTexture(layer->getTexture()); 1065 if (currentTransform()->isPureTranslate()) { 1066 const float x = (int) floorf(rect.left + currentTransform()->getTranslateX() + 0.5f); 1067 const float y = (int) floorf(rect.top + currentTransform()->getTranslateY() + 0.5f); 1068 1069 layer->setFilter(GL_NEAREST); 1070 setupDrawModelView(kModelViewMode_Translate, false, 1071 x, y, x + rect.getWidth(), y + rect.getHeight(), true); 1072 } else { 1073 layer->setFilter(GL_LINEAR); 1074 setupDrawModelView(kModelViewMode_Translate, false, 1075 rect.left, rect.top, rect.right, rect.bottom); 1076 } 1077 setupDrawMeshIndices(&mesh[0].x, &mesh[0].u); 1078 1079 for (size_t i = 0; i < count; i++) { 1080 const android::Rect* r = &rects[i]; 1081 1082 const float u1 = r->left * texX; 1083 const float v1 = (height - r->top) * texY; 1084 const float u2 = r->right * texX; 1085 const float v2 = (height - r->bottom) * texY; 1086 1087 // TODO: Reject quads outside of the clip 1088 TextureVertex::set(mesh++, r->left, r->top, u1, v1); 1089 TextureVertex::set(mesh++, r->right, r->top, u2, v1); 1090 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2); 1091 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2); 1092 1093 numQuads++; 1094 1095 if (numQuads >= kMaxNumberOfQuads) { 1096 DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6, 1097 GL_UNSIGNED_SHORT, nullptr)); 1098 numQuads = 0; 1099 mesh = mCaches.getRegionMesh(); 1100 } 1101 } 1102 1103 if (numQuads > 0) { 1104 DRAW_DOUBLE_STENCIL(glDrawElements(GL_TRIANGLES, numQuads * 6, 1105 GL_UNSIGNED_SHORT, nullptr)); 1106 } 1107 1108#if DEBUG_LAYERS_AS_REGIONS 1109 drawRegionRectsDebug(layer->region); 1110#endif 1111 1112 layer->region.clear(); 1113} 1114 1115#if DEBUG_LAYERS_AS_REGIONS 1116void OpenGLRenderer::drawRegionRectsDebug(const Region& region) { 1117 size_t count; 1118 const android::Rect* rects = region.getArray(&count); 1119 1120 uint32_t colors[] = { 1121 0x7fff0000, 0x7f00ff00, 1122 0x7f0000ff, 0x7fff00ff, 1123 }; 1124 1125 int offset = 0; 1126 int32_t top = rects[0].top; 1127 1128 for (size_t i = 0; i < count; i++) { 1129 if (top != rects[i].top) { 1130 offset ^= 0x2; 1131 top = rects[i].top; 1132 } 1133 1134 SkPaint paint; 1135 paint.setColor(colors[offset + (i & 0x1)]); 1136 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom); 1137 drawColorRect(r.left, r.top, r.right, r.bottom, paint); 1138 } 1139} 1140#endif 1141 1142void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) { 1143 Vector<float> rects; 1144 1145 SkRegion::Iterator it(region); 1146 while (!it.done()) { 1147 const SkIRect& r = it.rect(); 1148 rects.push(r.fLeft); 1149 rects.push(r.fTop); 1150 rects.push(r.fRight); 1151 rects.push(r.fBottom); 1152 it.next(); 1153 } 1154 1155 drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false); 1156} 1157 1158void OpenGLRenderer::dirtyLayer(const float left, const float top, 1159 const float right, const float bottom, const mat4 transform) { 1160 if (hasLayer()) { 1161 Rect bounds(left, top, right, bottom); 1162 transform.mapRect(bounds); 1163 dirtyLayerUnchecked(bounds, getRegion()); 1164 } 1165} 1166 1167void OpenGLRenderer::dirtyLayer(const float left, const float top, 1168 const float right, const float bottom) { 1169 if (hasLayer()) { 1170 Rect bounds(left, top, right, bottom); 1171 dirtyLayerUnchecked(bounds, getRegion()); 1172 } 1173} 1174 1175void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) { 1176 if (bounds.intersect(mState.currentClipRect())) { 1177 bounds.snapToPixelBoundaries(); 1178 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 1179 if (!dirty.isEmpty()) { 1180 region->orSelf(dirty); 1181 } 1182 } 1183} 1184 1185void OpenGLRenderer::issueIndexedQuadDraw(Vertex* mesh, GLsizei quadsCount) { 1186 GLsizei elementsCount = quadsCount * 6; 1187 while (elementsCount > 0) { 1188 GLsizei drawCount = MathUtils::min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6); 1189 1190 setupDrawIndexedVertices(&mesh[0].x); 1191 glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr); 1192 1193 elementsCount -= drawCount; 1194 // Though there are 4 vertices in a quad, we use 6 indices per 1195 // quad to draw with GL_TRIANGLES 1196 mesh += (drawCount / 6) * 4; 1197 } 1198} 1199 1200void OpenGLRenderer::clearLayerRegions() { 1201 const size_t count = mLayers.size(); 1202 if (count == 0) return; 1203 1204 if (!mState.currentlyIgnored()) { 1205 EVENT_LOGD("clearLayerRegions"); 1206 // Doing several glScissor/glClear here can negatively impact 1207 // GPUs with a tiler architecture, instead we draw quads with 1208 // the Clear blending mode 1209 1210 // The list contains bounds that have already been clipped 1211 // against their initial clip rect, and the current clip 1212 // is likely different so we need to disable clipping here 1213 bool scissorChanged = mRenderState.scissor().setEnabled(false); 1214 1215 Vertex mesh[count * 4]; 1216 Vertex* vertex = mesh; 1217 1218 for (uint32_t i = 0; i < count; i++) { 1219 const Rect& bounds = mLayers[i]; 1220 1221 Vertex::set(vertex++, bounds.left, bounds.top); 1222 Vertex::set(vertex++, bounds.right, bounds.top); 1223 Vertex::set(vertex++, bounds.left, bounds.bottom); 1224 Vertex::set(vertex++, bounds.right, bounds.bottom); 1225 } 1226 // We must clear the list of dirty rects before we 1227 // call setupDraw() to prevent stencil setup to do 1228 // the same thing again 1229 mLayers.clear(); 1230 1231 SkPaint clearPaint; 1232 clearPaint.setXfermodeMode(SkXfermode::kClear_Mode); 1233 1234 setupDraw(false); 1235 setupDrawColor(0.0f, 0.0f, 0.0f, 1.0f); 1236 setupDrawBlending(&clearPaint, true); 1237 setupDrawProgram(); 1238 setupDrawPureColorUniforms(); 1239 setupDrawModelView(kModelViewMode_Translate, false, 1240 0.0f, 0.0f, 0.0f, 0.0f, true); 1241 1242 issueIndexedQuadDraw(&mesh[0], count); 1243 1244 if (scissorChanged) mRenderState.scissor().setEnabled(true); 1245 } else { 1246 mLayers.clear(); 1247 } 1248} 1249 1250/////////////////////////////////////////////////////////////////////////////// 1251// State Deferral 1252/////////////////////////////////////////////////////////////////////////////// 1253 1254bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) { 1255 const Rect& currentClip = mState.currentClipRect(); 1256 const mat4* currentMatrix = currentTransform(); 1257 1258 if (stateDeferFlags & kStateDeferFlag_Draw) { 1259 // state has bounds initialized in local coordinates 1260 if (!state.mBounds.isEmpty()) { 1261 currentMatrix->mapRect(state.mBounds); 1262 Rect clippedBounds(state.mBounds); 1263 // NOTE: if we ever want to use this clipping info to drive whether the scissor 1264 // is used, it should more closely duplicate the quickReject logic (in how it uses 1265 // snapToPixelBoundaries) 1266 1267 if (!clippedBounds.intersect(currentClip)) { 1268 // quick rejected 1269 return true; 1270 } 1271 1272 state.mClipSideFlags = kClipSide_None; 1273 if (!currentClip.contains(state.mBounds)) { 1274 int& flags = state.mClipSideFlags; 1275 // op partially clipped, so record which sides are clipped for clip-aware merging 1276 if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left; 1277 if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top; 1278 if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right; 1279 if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom; 1280 } 1281 state.mBounds.set(clippedBounds); 1282 } else { 1283 // Empty bounds implies size unknown. Label op as conservatively clipped to disable 1284 // overdraw avoidance (since we don't know what it overlaps) 1285 state.mClipSideFlags = kClipSide_ConservativeFull; 1286 state.mBounds.set(currentClip); 1287 } 1288 } 1289 1290 state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip); 1291 if (state.mClipValid) { 1292 state.mClip.set(currentClip); 1293 } 1294 1295 // Transform, drawModifiers, and alpha always deferred, since they are used by state operations 1296 // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything) 1297 state.mMatrix.load(*currentMatrix); 1298 state.mDrawModifiers = mDrawModifiers; 1299 state.mAlpha = currentSnapshot()->alpha; 1300 1301 // always store/restore, since it's just a pointer 1302 state.mRoundRectClipState = currentSnapshot()->roundRectClipState; 1303 return false; 1304} 1305 1306void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) { 1307 setMatrix(state.mMatrix); 1308 writableSnapshot()->alpha = state.mAlpha; 1309 mDrawModifiers = state.mDrawModifiers; 1310 writableSnapshot()->roundRectClipState = state.mRoundRectClipState; 1311 1312 if (state.mClipValid && !skipClipRestore) { 1313 writableSnapshot()->setClip(state.mClip.left, state.mClip.top, 1314 state.mClip.right, state.mClip.bottom); 1315 dirtyClip(); 1316 } 1317} 1318 1319/** 1320 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done 1321 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at 1322 * least one op is clipped), or disabled entirely (because no merged op is clipped) 1323 * 1324 * This method should be called when restoreDisplayState() won't be restoring the clip 1325 */ 1326void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) { 1327 if (clipRect != nullptr) { 1328 writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom); 1329 } else { 1330 writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight()); 1331 } 1332 dirtyClip(); 1333 bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled; 1334 mRenderState.scissor().setEnabled(enableScissor); 1335} 1336 1337/////////////////////////////////////////////////////////////////////////////// 1338// Clipping 1339/////////////////////////////////////////////////////////////////////////////// 1340 1341void OpenGLRenderer::setScissorFromClip() { 1342 Rect clip(mState.currentClipRect()); 1343 clip.snapToPixelBoundaries(); 1344 1345 if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom, 1346 clip.getWidth(), clip.getHeight())) { 1347 mState.setDirtyClip(false); 1348 } 1349} 1350 1351void OpenGLRenderer::ensureStencilBuffer() { 1352 // Thanks to the mismatch between EGL and OpenGL ES FBO we 1353 // cannot attach a stencil buffer to fbo0 dynamically. Let's 1354 // just hope we have one when hasLayer() returns false. 1355 if (hasLayer()) { 1356 attachStencilBufferToLayer(currentSnapshot()->layer); 1357 } 1358} 1359 1360void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) { 1361 // The layer's FBO is already bound when we reach this stage 1362 if (!layer->getStencilRenderBuffer()) { 1363 // GL_QCOM_tiled_rendering doesn't like it if a renderbuffer 1364 // is attached after we initiated tiling. We must turn it off, 1365 // attach the new render buffer then turn tiling back on 1366 endTiling(); 1367 1368 RenderBuffer* buffer = mCaches.renderBufferCache.get( 1369 Stencil::getSmallestStencilFormat(), 1370 layer->getWidth(), layer->getHeight()); 1371 layer->setStencilRenderBuffer(buffer); 1372 1373 startTiling(layer->clipRect, layer->layer.getHeight()); 1374 } 1375} 1376 1377static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform, 1378 float x, float y) { 1379 Vertex v; 1380 v.x = x; 1381 v.y = y; 1382 transform.mapPoint(v.x, v.y); 1383 rectangleVertices.push_back(v); 1384} 1385 1386static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) { 1387 Vertex v; 1388 v.x = x; 1389 v.y = y; 1390 rectangleVertices.push_back(v); 1391} 1392 1393void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) { 1394 int count = rectangleList.getTransformedRectanglesCount(); 1395 std::vector<Vertex> rectangleVertices(count * 4); 1396 Rect scissorBox = rectangleList.calculateBounds(); 1397 scissorBox.snapToPixelBoundaries(); 1398 for (int i = 0; i < count; ++i) { 1399 const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i)); 1400 const Matrix4& transform = tr.getTransform(); 1401 Rect bounds = tr.getBounds(); 1402 if (transform.rectToRect()) { 1403 transform.mapRect(bounds); 1404 if (!bounds.intersect(scissorBox)) { 1405 bounds.setEmpty(); 1406 } else { 1407 handlePointNoTransform(rectangleVertices, bounds.left, bounds.top); 1408 handlePointNoTransform(rectangleVertices, bounds.right, bounds.top); 1409 handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom); 1410 handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom); 1411 } 1412 } else { 1413 handlePoint(rectangleVertices, transform, bounds.left, bounds.top); 1414 handlePoint(rectangleVertices, transform, bounds.right, bounds.top); 1415 handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom); 1416 handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom); 1417 } 1418 } 1419 1420 mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom, 1421 scissorBox.getWidth(), scissorBox.getHeight()); 1422 1423 const SkPaint* paint = nullptr; 1424 setupDraw(); 1425 setupDrawNoTexture(); 1426 setupDrawColor(0, 0xff * currentSnapshot()->alpha); 1427 setupDrawShader(getShader(paint)); 1428 setupDrawColorFilter(getColorFilter(paint)); 1429 setupDrawBlending(paint); 1430 setupDrawProgram(); 1431 setupDrawDirtyRegionsDisabled(); 1432 setupDrawModelView(kModelViewMode_Translate, false, 1433 0.0f, 0.0f, 0.0f, 0.0f, true); 1434 setupDrawColorUniforms(getShader(paint)); 1435 setupDrawShaderUniforms(getShader(paint)); 1436 setupDrawColorFilterUniforms(getColorFilter(paint)); 1437 1438 issueIndexedQuadDraw(&rectangleVertices[0], rectangleVertices.size() / 4); 1439} 1440 1441void OpenGLRenderer::setStencilFromClip() { 1442 if (!mCaches.debugOverdraw) { 1443 if (!currentSnapshot()->clipIsSimple()) { 1444 int incrementThreshold; 1445 EVENT_LOGD("setStencilFromClip - enabling"); 1446 1447 // NOTE: The order here is important, we must set dirtyClip to false 1448 // before any draw call to avoid calling back into this method 1449 mState.setDirtyClip(false); 1450 1451 ensureStencilBuffer(); 1452 1453 const ClipArea& clipArea = currentSnapshot()->getClipArea(); 1454 1455 bool isRectangleList = clipArea.isRectangleList(); 1456 if (isRectangleList) { 1457 incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount(); 1458 } else { 1459 incrementThreshold = 0; 1460 } 1461 1462 mRenderState.stencil().enableWrite(incrementThreshold); 1463 1464 // Clean and update the stencil, but first make sure we restrict drawing 1465 // to the region's bounds 1466 bool resetScissor = mRenderState.scissor().setEnabled(true); 1467 if (resetScissor) { 1468 // The scissor was not set so we now need to update it 1469 setScissorFromClip(); 1470 } 1471 1472 mRenderState.stencil().clear(); 1473 1474 // stash and disable the outline clip state, since stencil doesn't account for outline 1475 bool storedSkipOutlineClip = mSkipOutlineClip; 1476 mSkipOutlineClip = true; 1477 1478 SkPaint paint; 1479 paint.setColor(SK_ColorBLACK); 1480 paint.setXfermodeMode(SkXfermode::kSrc_Mode); 1481 1482 if (isRectangleList) { 1483 drawRectangleList(clipArea.getRectangleList()); 1484 } else { 1485 // NOTE: We could use the region contour path to generate a smaller mesh 1486 // Since we are using the stencil we could use the red book path 1487 // drawing technique. It might increase bandwidth usage though. 1488 1489 // The last parameter is important: we are not drawing in the color buffer 1490 // so we don't want to dirty the current layer, if any 1491 drawRegionRects(clipArea.getClipRegion(), paint, false); 1492 } 1493 if (resetScissor) mRenderState.scissor().setEnabled(false); 1494 mSkipOutlineClip = storedSkipOutlineClip; 1495 1496 mRenderState.stencil().enableTest(incrementThreshold); 1497 1498 // Draw the region used to generate the stencil if the appropriate debug 1499 // mode is enabled 1500 // TODO: Implement for rectangle list clip areas 1501 if (mCaches.debugStencilClip == Caches::kStencilShowRegion && 1502 !clipArea.isRectangleList()) { 1503 paint.setColor(0x7f0000ff); 1504 paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); 1505 drawRegionRects(currentSnapshot()->getClipRegion(), paint); 1506 } 1507 } else { 1508 EVENT_LOGD("setStencilFromClip - disabling"); 1509 mRenderState.stencil().disable(); 1510 } 1511 } 1512} 1513 1514/** 1515 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out. 1516 * 1517 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint 1518 * style, and tessellated AA ramp 1519 */ 1520bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom, 1521 const SkPaint* paint) { 1522 bool snapOut = paint && paint->isAntiAlias(); 1523 1524 if (paint && paint->getStyle() != SkPaint::kFill_Style) { 1525 float outset = paint->getStrokeWidth() * 0.5f; 1526 left -= outset; 1527 top -= outset; 1528 right += outset; 1529 bottom += outset; 1530 } 1531 1532 bool clipRequired = false; 1533 bool roundRectClipRequired = false; 1534 if (mState.calculateQuickRejectForScissor(left, top, right, bottom, 1535 &clipRequired, &roundRectClipRequired, snapOut)) { 1536 return true; 1537 } 1538 1539 // not quick rejected, so enable the scissor if clipRequired 1540 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 1541 mSkipOutlineClip = !roundRectClipRequired; 1542 return false; 1543} 1544 1545void OpenGLRenderer::debugClip() { 1546#if DEBUG_CLIP_REGIONS 1547 if (!currentSnapshot()->clipRegion->isEmpty()) { 1548 SkPaint paint; 1549 paint.setColor(0x7f00ff00); 1550 drawRegionRects(*(currentSnapshot()->clipRegion, paint); 1551 1552 } 1553#endif 1554} 1555 1556void OpenGLRenderer::renderGlop(const Glop& glop) { 1557 if (mState.getDirtyClip()) { 1558 if (mRenderState.scissor().isEnabled()) { 1559 setScissorFromClip(); 1560 } 1561 1562 setStencilFromClip(); 1563 } 1564 mRenderState.render(glop); 1565 1566 if (!mRenderState.stencil().isWriteEnabled()) { 1567 // TODO: specify more clearly when a draw should dirty the layer. 1568 // is writing to the stencil the only time we should ignore this? 1569 dirtyLayer(glop.bounds.left, glop.bounds.top, glop.bounds.right, glop.bounds.bottom); 1570 mDirty = true; 1571 } 1572} 1573 1574/////////////////////////////////////////////////////////////////////////////// 1575// Drawing commands 1576/////////////////////////////////////////////////////////////////////////////// 1577 1578void OpenGLRenderer::setupDraw(bool clearLayer) { 1579 // TODO: It would be best if we could do this before quickRejectSetupScissor() 1580 // changes the scissor test state 1581 if (clearLayer) clearLayerRegions(); 1582 // Make sure setScissor & setStencil happen at the beginning of 1583 // this method 1584 if (mState.getDirtyClip()) { 1585 if (mRenderState.scissor().isEnabled()) { 1586 setScissorFromClip(); 1587 } 1588 1589 setStencilFromClip(); 1590 } 1591 1592 mDescription.reset(); 1593 1594 mSetShaderColor = false; 1595 mColorSet = false; 1596 mColor.a = mColor.r = mColor.g = mColor.b = 0.0f; 1597 mTextureUnit = 0; 1598 mTrackDirtyRegions = true; 1599 1600 // Enable debug highlight when what we're about to draw is tested against 1601 // the stencil buffer and if stencil highlight debugging is on 1602 mDescription.hasDebugHighlight = !mCaches.debugOverdraw 1603 && mCaches.debugStencilClip == Caches::kStencilShowHighlight 1604 && mRenderState.stencil().isTestEnabled(); 1605} 1606 1607void OpenGLRenderer::setupDrawWithTexture(bool isAlpha8) { 1608 mDescription.hasTexture = true; 1609 mDescription.hasAlpha8Texture = isAlpha8; 1610} 1611 1612void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) { 1613 mDescription.hasTexture = true; 1614 mDescription.hasColors = true; 1615 mDescription.hasAlpha8Texture = isAlpha8; 1616} 1617 1618void OpenGLRenderer::setupDrawWithExternalTexture() { 1619 mDescription.hasExternalTexture = true; 1620} 1621 1622void OpenGLRenderer::setupDrawNoTexture() { 1623 mRenderState.meshState().disableTexCoordsVertexArray(); 1624} 1625 1626void OpenGLRenderer::setupDrawVertexAlpha(bool useShadowAlphaInterp) { 1627 mDescription.hasVertexAlpha = true; 1628 mDescription.useShadowAlphaInterp = useShadowAlphaInterp; 1629} 1630 1631void OpenGLRenderer::setupDrawColor(int color, int alpha) { 1632 mColor.a = alpha / 255.0f; 1633 mColor.r = mColor.a * ((color >> 16) & 0xFF) / 255.0f; 1634 mColor.g = mColor.a * ((color >> 8) & 0xFF) / 255.0f; 1635 mColor.b = mColor.a * ((color ) & 0xFF) / 255.0f; 1636 mColorSet = true; 1637 mSetShaderColor = mDescription.setColorModulate(mColor.a); 1638} 1639 1640void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) { 1641 mColor.a = alpha / 255.0f; 1642 mColor.r = mColor.a * ((color >> 16) & 0xFF) / 255.0f; 1643 mColor.g = mColor.a * ((color >> 8) & 0xFF) / 255.0f; 1644 mColor.b = mColor.a * ((color ) & 0xFF) / 255.0f; 1645 mColorSet = true; 1646 mSetShaderColor = mDescription.setAlpha8ColorModulate(mColor.r, mColor.g, mColor.b, mColor.a); 1647} 1648 1649void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) { 1650 mCaches.fontRenderer->describe(mDescription, paint); 1651} 1652 1653void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) { 1654 mColor.a = a; 1655 mColor.r = r; 1656 mColor.g = g; 1657 mColor.b = b; 1658 mColorSet = true; 1659 mSetShaderColor = mDescription.setColorModulate(a); 1660} 1661 1662void OpenGLRenderer::setupDrawShader(const SkShader* shader) { 1663 if (shader != nullptr) { 1664 SkiaShader::describe(&mCaches, mDescription, mCaches.extensions(), *shader); 1665 } 1666} 1667 1668void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) { 1669 if (filter == nullptr) { 1670 return; 1671 } 1672 1673 SkXfermode::Mode mode; 1674 if (filter->asColorMode(nullptr, &mode)) { 1675 mDescription.colorOp = ProgramDescription::kColorBlend; 1676 mDescription.colorMode = mode; 1677 } else if (filter->asColorMatrix(nullptr)) { 1678 mDescription.colorOp = ProgramDescription::kColorMatrix; 1679 } 1680} 1681 1682void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) { 1683 if (mColorSet && mode == SkXfermode::kClear_Mode) { 1684 mColor.a = 1.0f; 1685 mColor.r = mColor.g = mColor.b = 0.0f; 1686 mSetShaderColor = mDescription.modulate = true; 1687 } 1688} 1689 1690void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) { 1691 SkXfermode::Mode mode = layer->getMode(); 1692 // When the blending mode is kClear_Mode, we need to use a modulate color 1693 // argb=1,0,0,0 1694 accountForClear(mode); 1695 // TODO: check shader blending, once we have shader drawing support for layers. 1696 bool blend = layer->isBlend() 1697 || getLayerAlpha(layer) < 1.0f 1698 || (mColorSet && mColor.a < 1.0f) 1699 || PaintUtils::isBlendedColorFilter(layer->getColorFilter()); 1700 chooseBlending(blend, mode, mDescription, swapSrcDst); 1701} 1702 1703void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) { 1704 SkXfermode::Mode mode = getXfermodeDirect(paint); 1705 // When the blending mode is kClear_Mode, we need to use a modulate color 1706 // argb=1,0,0,0 1707 accountForClear(mode); 1708 blend |= (mColorSet && mColor.a < 1.0f) 1709 || (getShader(paint) && !getShader(paint)->isOpaque()) 1710 || PaintUtils::isBlendedColorFilter(getColorFilter(paint)); 1711 chooseBlending(blend, mode, mDescription, swapSrcDst); 1712} 1713 1714void OpenGLRenderer::setupDrawProgram() { 1715 mCaches.setProgram(mDescription); 1716 if (mDescription.hasRoundRectClip) { 1717 // TODO: avoid doing this repeatedly, stashing state pointer in program 1718 const RoundRectClipState* state = writableSnapshot()->roundRectClipState; 1719 const Rect& innerRect = state->innerRect; 1720 glUniform4f(mCaches.program().getUniform("roundRectInnerRectLTRB"), 1721 innerRect.left, innerRect.top, 1722 innerRect.right, innerRect.bottom); 1723 glUniformMatrix4fv(mCaches.program().getUniform("roundRectInvTransform"), 1724 1, GL_FALSE, &state->matrix.data[0]); 1725 1726 // add half pixel to round out integer rect space to cover pixel centers 1727 float roundedOutRadius = state->radius + 0.5f; 1728 glUniform1f(mCaches.program().getUniform("roundRectRadius"), 1729 roundedOutRadius); 1730 } 1731} 1732 1733void OpenGLRenderer::setupDrawDirtyRegionsDisabled() { 1734 mTrackDirtyRegions = false; 1735} 1736 1737void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset, 1738 float left, float top, float right, float bottom, bool ignoreTransform) { 1739 mModelViewMatrix.loadTranslate(left, top, 0.0f); 1740 if (mode == kModelViewMode_TranslateAndScale) { 1741 mModelViewMatrix.scale(right - left, bottom - top, 1.0f); 1742 } 1743 1744 bool dirty = right - left > 0.0f && bottom - top > 0.0f; 1745 const Matrix4& transformMatrix = ignoreTransform ? Matrix4::identity() : *currentTransform(); 1746 1747 mCaches.program().set(currentSnapshot()->getOrthoMatrix(), 1748 mModelViewMatrix, transformMatrix, offset); 1749 if (dirty && mTrackDirtyRegions) { 1750 if (!ignoreTransform) { 1751 dirtyLayer(left, top, right, bottom, *currentTransform()); 1752 } else { 1753 dirtyLayer(left, top, right, bottom); 1754 } 1755 } 1756} 1757 1758void OpenGLRenderer::setupDrawColorUniforms(bool hasShader) { 1759 if ((mColorSet && !hasShader) || (hasShader && mSetShaderColor)) { 1760 mCaches.program().setColor(mColor); 1761 } 1762} 1763 1764void OpenGLRenderer::setupDrawPureColorUniforms() { 1765 if (mSetShaderColor) { 1766 mCaches.program().setColor(mColor); 1767 } 1768} 1769 1770void OpenGLRenderer::setupDrawShaderUniforms(const SkShader* shader, bool ignoreTransform) { 1771 if (shader == nullptr) { 1772 return; 1773 } 1774 1775 if (ignoreTransform) { 1776 // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform() 1777 // because it was built into modelView / the geometry, and the description needs to 1778 // compensate. 1779 mat4 modelViewWithoutTransform; 1780 modelViewWithoutTransform.loadInverse(*currentTransform()); 1781 modelViewWithoutTransform.multiply(mModelViewMatrix); 1782 mModelViewMatrix.load(modelViewWithoutTransform); 1783 } 1784 1785 SkiaShader::setupProgram(&mCaches, mModelViewMatrix, &mTextureUnit, 1786 mCaches.extensions(), *shader); 1787} 1788 1789void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) { 1790 if (nullptr == filter) { 1791 return; 1792 } 1793 1794 SkColor color; 1795 SkXfermode::Mode mode; 1796 if (filter->asColorMode(&color, &mode)) { 1797 const int alpha = SkColorGetA(color); 1798 const GLfloat a = alpha / 255.0f; 1799 const GLfloat r = a * SkColorGetR(color) / 255.0f; 1800 const GLfloat g = a * SkColorGetG(color) / 255.0f; 1801 const GLfloat b = a * SkColorGetB(color) / 255.0f; 1802 glUniform4f(mCaches.program().getUniform("colorBlend"), r, g, b, a); 1803 return; 1804 } 1805 1806 SkScalar srcColorMatrix[20]; 1807 if (filter->asColorMatrix(srcColorMatrix)) { 1808 1809 float colorMatrix[16]; 1810 memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float)); 1811 memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float)); 1812 memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float)); 1813 memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float)); 1814 1815 // Skia uses the range [0..255] for the addition vector, but we need 1816 // the [0..1] range to apply the vector in GLSL 1817 float colorVector[4]; 1818 colorVector[0] = srcColorMatrix[4] / 255.0f; 1819 colorVector[1] = srcColorMatrix[9] / 255.0f; 1820 colorVector[2] = srcColorMatrix[14] / 255.0f; 1821 colorVector[3] = srcColorMatrix[19] / 255.0f; 1822 1823 glUniformMatrix4fv(mCaches.program().getUniform("colorMatrix"), 1, 1824 GL_FALSE, colorMatrix); 1825 glUniform4fv(mCaches.program().getUniform("colorMatrixVector"), 1, colorVector); 1826 return; 1827 } 1828 1829 // it is an error if we ever get here 1830} 1831 1832void OpenGLRenderer::setupDrawTextGammaUniforms() { 1833 mCaches.fontRenderer->setupProgram(mDescription, mCaches.program()); 1834} 1835 1836void OpenGLRenderer::setupDrawSimpleMesh() { 1837 bool force = mRenderState.meshState().bindMeshBuffer(); 1838 mRenderState.meshState().bindPositionVertexPointer(force, nullptr); 1839 mRenderState.meshState().unbindIndicesBuffer(); 1840} 1841 1842void OpenGLRenderer::setupDrawTexture(GLuint texture) { 1843 if (texture) mCaches.textureState().bindTexture(texture); 1844 mTextureUnit++; 1845 mRenderState.meshState().enableTexCoordsVertexArray(); 1846} 1847 1848void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) { 1849 mCaches.textureState().bindTexture(GL_TEXTURE_EXTERNAL_OES, texture); 1850 mTextureUnit++; 1851 mRenderState.meshState().enableTexCoordsVertexArray(); 1852} 1853 1854void OpenGLRenderer::setupDrawTextureTransform() { 1855 mDescription.hasTextureTransform = true; 1856} 1857 1858void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) { 1859 glUniformMatrix4fv(mCaches.program().getUniform("mainTextureTransform"), 1, 1860 GL_FALSE, &transform.data[0]); 1861} 1862 1863void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices, 1864 const GLvoid* texCoords, GLuint vbo) { 1865 bool force = false; 1866 if (!vertices || vbo) { 1867 force = mRenderState.meshState().bindMeshBuffer(vbo); 1868 } else { 1869 force = mRenderState.meshState().unbindMeshBuffer(); 1870 } 1871 1872 mRenderState.meshState().bindPositionVertexPointer(force, vertices); 1873 if (mCaches.program().texCoords >= 0) { 1874 mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords); 1875 } 1876 1877 mRenderState.meshState().unbindIndicesBuffer(); 1878} 1879 1880void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices, 1881 const GLvoid* texCoords, const GLvoid* colors) { 1882 bool force = mRenderState.meshState().unbindMeshBuffer(); 1883 GLsizei stride = sizeof(ColorTextureVertex); 1884 1885 mRenderState.meshState().bindPositionVertexPointer(force, vertices, stride); 1886 if (mCaches.program().texCoords >= 0) { 1887 mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords, stride); 1888 } 1889 int slot = mCaches.program().getAttrib("colors"); 1890 if (slot >= 0) { 1891 glEnableVertexAttribArray(slot); 1892 glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors); 1893 } 1894 1895 mRenderState.meshState().unbindIndicesBuffer(); 1896} 1897 1898void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices, 1899 const GLvoid* texCoords, GLuint vbo) { 1900 bool force = false; 1901 // If vbo is != 0 we want to treat the vertices parameter as an offset inside 1902 // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to 1903 // use the default VBO found in RenderState 1904 if (!vertices || vbo) { 1905 force = mRenderState.meshState().bindMeshBuffer(vbo); 1906 } else { 1907 force = mRenderState.meshState().unbindMeshBuffer(); 1908 } 1909 mRenderState.meshState().bindQuadIndicesBuffer(); 1910 1911 mRenderState.meshState().bindPositionVertexPointer(force, vertices); 1912 if (mCaches.program().texCoords >= 0) { 1913 mRenderState.meshState().bindTexCoordsVertexPointer(force, texCoords); 1914 } 1915} 1916 1917void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) { 1918 bool force = mRenderState.meshState().unbindMeshBuffer(); 1919 mRenderState.meshState().bindQuadIndicesBuffer(); 1920 mRenderState.meshState().bindPositionVertexPointer(force, vertices, kVertexStride); 1921} 1922 1923/////////////////////////////////////////////////////////////////////////////// 1924// Drawing 1925/////////////////////////////////////////////////////////////////////////////// 1926 1927void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) { 1928 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1929 // will be performed by the display list itself 1930 if (renderNode && renderNode->isRenderable()) { 1931 // compute 3d ordering 1932 renderNode->computeOrdering(); 1933 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 1934 startFrame(); 1935 ReplayStateStruct replayStruct(*this, dirty, replayFlags); 1936 renderNode->replay(replayStruct, 0); 1937 return; 1938 } 1939 1940 // Don't avoid overdraw when visualizing, since that makes it harder to 1941 // debug where it's coming from, and when the problem occurs. 1942 bool avoidOverdraw = !mCaches.debugOverdraw; 1943 DeferredDisplayList deferredList(mState.currentClipRect(), avoidOverdraw); 1944 DeferStateStruct deferStruct(deferredList, *this, replayFlags); 1945 renderNode->defer(deferStruct, 0); 1946 1947 flushLayers(); 1948 startFrame(); 1949 1950 deferredList.flush(*this, dirty); 1951 } else { 1952 // Even if there is no drawing command(Ex: invisible), 1953 // it still needs startFrame to clear buffer and start tiling. 1954 startFrame(); 1955 } 1956} 1957 1958void OpenGLRenderer::drawAlphaBitmap(Texture* texture, const SkPaint* paint) { 1959 if (USE_GLOPS) { 1960 Glop glop; 1961 GlopBuilder aBuilder(mRenderState, mCaches, &glop); 1962 aBuilder.setMeshTexturedUnitQuad(texture->uvMapper, true) 1963 .setFillTexturePaint(*texture, true, paint, currentSnapshot()->alpha) 1964 .setTransformClip(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 1965 .setModelViewMapUnitToRectSnap(Rect(0, 0, texture->width, texture->height)) 1966 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1967 .build(); 1968 renderGlop(glop); 1969 return; 1970 } 1971 1972 float x = 0; 1973 float y = 0; 1974 1975 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1976 1977 bool ignoreTransform = false; 1978 if (currentTransform()->isPureTranslate()) { 1979 x = (int) floorf(currentTransform()->getTranslateX() + 0.5f); 1980 y = (int) floorf(currentTransform()->getTranslateY() + 0.5f); 1981 ignoreTransform = true; 1982 1983 texture->setFilter(GL_NEAREST, true); 1984 } else { 1985 texture->setFilter(PaintUtils::getFilter(paint), true); 1986 } 1987 1988 // No need to check for a UV mapper on the texture object, only ARGB_8888 1989 // bitmaps get packed in the atlas 1990 drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 1991 paint, (GLvoid*) nullptr, (GLvoid*) kMeshTextureOffset, 1992 GL_TRIANGLE_STRIP, kUnitQuadCount, ignoreTransform); 1993} 1994 1995/** 1996 * Important note: this method is intended to draw batches of bitmaps and 1997 * will not set the scissor enable or dirty the current layer, if any. 1998 * The caller is responsible for properly dirtying the current layer. 1999 */ 2000void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 2001 int bitmapCount, TextureVertex* vertices, bool pureTranslate, 2002 const Rect& bounds, const SkPaint* paint) { 2003 mCaches.textureState().activateTexture(0); 2004 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2005 if (!texture) return; 2006 2007 const AutoTexture autoCleanup(texture); 2008 2009 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2010 texture->setFilter(pureTranslate ? GL_NEAREST : PaintUtils::getFilter(paint), true); 2011 2012 const float x = (int) floorf(bounds.left + 0.5f); 2013 const float y = (int) floorf(bounds.top + 0.5f); 2014 if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) { 2015 drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(), 2016 texture->id, paint, &vertices[0].x, &vertices[0].u, 2017 GL_TRIANGLES, bitmapCount * 6, true, 2018 kModelViewMode_Translate, false); 2019 } else { 2020 drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(), 2021 texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u, 2022 GL_TRIANGLES, bitmapCount * 6, false, true, 0, 2023 kModelViewMode_Translate, false); 2024 } 2025 2026 mDirty = true; 2027} 2028 2029void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) { 2030 if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) { 2031 return; 2032 } 2033 2034 mCaches.textureState().activateTexture(0); 2035 Texture* texture = getTexture(bitmap); 2036 if (!texture) return; 2037 const AutoTexture autoCleanup(texture); 2038 2039 if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) { 2040 drawAlphaBitmap(texture, paint); 2041 } else { 2042 drawTextureRect(texture, paint); 2043 } 2044 2045 mDirty = true; 2046} 2047 2048void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight, 2049 const float* vertices, const int* colors, const SkPaint* paint) { 2050 if (!vertices || mState.currentlyIgnored()) { 2051 return; 2052 } 2053 2054 // TODO: use quickReject on bounds from vertices 2055 mRenderState.scissor().setEnabled(true); 2056 2057 float left = FLT_MAX; 2058 float top = FLT_MAX; 2059 float right = FLT_MIN; 2060 float bottom = FLT_MIN; 2061 2062 const uint32_t count = meshWidth * meshHeight * 6; 2063 2064 std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[count]); 2065 ColorTextureVertex* vertex = &mesh[0]; 2066 2067 std::unique_ptr<int[]> tempColors; 2068 if (!colors) { 2069 uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1); 2070 tempColors.reset(new int[colorsCount]); 2071 memset(tempColors.get(), 0xff, colorsCount * sizeof(int)); 2072 colors = tempColors.get(); 2073 } 2074 2075 mCaches.textureState().activateTexture(0); 2076 Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap); 2077 const UvMapper& mapper(getMapper(texture)); 2078 2079 for (int32_t y = 0; y < meshHeight; y++) { 2080 for (int32_t x = 0; x < meshWidth; x++) { 2081 uint32_t i = (y * (meshWidth + 1) + x) * 2; 2082 2083 float u1 = float(x) / meshWidth; 2084 float u2 = float(x + 1) / meshWidth; 2085 float v1 = float(y) / meshHeight; 2086 float v2 = float(y + 1) / meshHeight; 2087 2088 mapper.map(u1, v1, u2, v2); 2089 2090 int ax = i + (meshWidth + 1) * 2; 2091 int ay = ax + 1; 2092 int bx = i; 2093 int by = bx + 1; 2094 int cx = i + 2; 2095 int cy = cx + 1; 2096 int dx = i + (meshWidth + 1) * 2 + 2; 2097 int dy = dx + 1; 2098 2099 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 2100 ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]); 2101 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 2102 2103 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 2104 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 2105 ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]); 2106 2107 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx]))); 2108 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy]))); 2109 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx]))); 2110 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy]))); 2111 } 2112 } 2113 2114 if (quickRejectSetupScissor(left, top, right, bottom)) { 2115 return; 2116 } 2117 2118 if (!texture) { 2119 texture = mCaches.textureCache.get(bitmap); 2120 if (!texture) { 2121 return; 2122 } 2123 } 2124 const AutoTexture autoCleanup(texture); 2125 2126 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2127 texture->setFilter(PaintUtils::getFilter(paint), true); 2128 2129 int alpha; 2130 SkXfermode::Mode mode; 2131 getAlphaAndMode(paint, &alpha, &mode); 2132 2133 float a = alpha / 255.0f; 2134 2135 if (hasLayer()) { 2136 dirtyLayer(left, top, right, bottom, *currentTransform()); 2137 } 2138 2139 setupDraw(); 2140 setupDrawWithTextureAndColor(); 2141 setupDrawColor(a, a, a, a); 2142 setupDrawColorFilter(getColorFilter(paint)); 2143 setupDrawBlending(paint, true); 2144 setupDrawProgram(); 2145 setupDrawDirtyRegionsDisabled(); 2146 setupDrawModelView(kModelViewMode_Translate, false, 0, 0, 0, 0); 2147 setupDrawTexture(texture->id); 2148 setupDrawPureColorUniforms(); 2149 setupDrawColorFilterUniforms(getColorFilter(paint)); 2150 setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r); 2151 2152 glDrawArrays(GL_TRIANGLES, 0, count); 2153 2154 int slot = mCaches.program().getAttrib("colors"); 2155 if (slot >= 0) { 2156 glDisableVertexAttribArray(slot); 2157 } 2158 2159 mDirty = true; 2160} 2161 2162void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, 2163 float srcLeft, float srcTop, float srcRight, float srcBottom, 2164 float dstLeft, float dstTop, float dstRight, float dstBottom, 2165 const SkPaint* paint) { 2166 if (quickRejectSetupScissor(dstLeft, dstTop, dstRight, dstBottom)) { 2167 return; 2168 } 2169 2170 mCaches.textureState().activateTexture(0); 2171 Texture* texture = getTexture(bitmap); 2172 if (!texture) return; 2173 const AutoTexture autoCleanup(texture); 2174 2175 const float width = texture->width; 2176 const float height = texture->height; 2177 2178 float u1 = fmax(0.0f, srcLeft / width); 2179 float v1 = fmax(0.0f, srcTop / height); 2180 float u2 = fmin(1.0f, srcRight / width); 2181 float v2 = fmin(1.0f, srcBottom / height); 2182 2183 getMapper(texture).map(u1, v1, u2, v2); 2184 2185 mRenderState.meshState().unbindMeshBuffer(); 2186 resetDrawTextureTexCoords(u1, v1, u2, v2); 2187 2188 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2189 2190 float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft); 2191 float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop); 2192 2193 bool scaled = scaleX != 1.0f || scaleY != 1.0f; 2194 // Apply a scale transform on the canvas only when a shader is in use 2195 // Skia handles the ratio between the dst and src rects as a scale factor 2196 // when a shader is set 2197 bool useScaleTransform = getShader(paint) && scaled; 2198 bool ignoreTransform = false; 2199 2200 if (CC_LIKELY(currentTransform()->isPureTranslate() && !useScaleTransform)) { 2201 float x = (int) floorf(dstLeft + currentTransform()->getTranslateX() + 0.5f); 2202 float y = (int) floorf(dstTop + currentTransform()->getTranslateY() + 0.5f); 2203 2204 dstRight = x + (dstRight - dstLeft); 2205 dstBottom = y + (dstBottom - dstTop); 2206 2207 dstLeft = x; 2208 dstTop = y; 2209 2210 texture->setFilter(scaled ? PaintUtils::getFilter(paint) : GL_NEAREST, true); 2211 ignoreTransform = true; 2212 } else { 2213 texture->setFilter(PaintUtils::getFilter(paint), true); 2214 } 2215 2216 if (CC_UNLIKELY(useScaleTransform)) { 2217 save(SkCanvas::kMatrix_SaveFlag); 2218 translate(dstLeft, dstTop); 2219 scale(scaleX, scaleY); 2220 2221 dstLeft = 0.0f; 2222 dstTop = 0.0f; 2223 2224 dstRight = srcRight - srcLeft; 2225 dstBottom = srcBottom - srcTop; 2226 } 2227 2228 if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) { 2229 drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom, 2230 texture->id, paint, 2231 &mMeshVertices[0].x, &mMeshVertices[0].u, 2232 GL_TRIANGLE_STRIP, kUnitQuadCount, ignoreTransform); 2233 } else { 2234 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, 2235 texture->id, paint, texture->blend, 2236 &mMeshVertices[0].x, &mMeshVertices[0].u, 2237 GL_TRIANGLE_STRIP, kUnitQuadCount, false, ignoreTransform); 2238 } 2239 2240 if (CC_UNLIKELY(useScaleTransform)) { 2241 restore(); 2242 } 2243 2244 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 2245 2246 mDirty = true; 2247} 2248 2249void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch, 2250 float left, float top, float right, float bottom, const SkPaint* paint) { 2251 if (quickRejectSetupScissor(left, top, right, bottom)) { 2252 return; 2253 } 2254 2255 AssetAtlas::Entry* entry = mRenderState.assetAtlas().getEntry(bitmap); 2256 const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(), 2257 right - left, bottom - top, patch); 2258 2259 drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint); 2260} 2261 2262void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh, 2263 AssetAtlas::Entry* entry, float left, float top, float right, float bottom, 2264 const SkPaint* paint) { 2265 if (quickRejectSetupScissor(left, top, right, bottom)) { 2266 return; 2267 } 2268 2269 if (CC_LIKELY(mesh && mesh->verticesCount > 0)) { 2270 mCaches.textureState().activateTexture(0); 2271 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2272 if (!texture) return; 2273 const AutoTexture autoCleanup(texture); 2274 2275 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2276 texture->setFilter(GL_LINEAR, true); 2277 2278 const bool pureTranslate = currentTransform()->isPureTranslate(); 2279 // Mark the current layer dirty where we are going to draw the patch 2280 if (hasLayer() && mesh->hasEmptyQuads) { 2281 const float offsetX = left + currentTransform()->getTranslateX(); 2282 const float offsetY = top + currentTransform()->getTranslateY(); 2283 const size_t count = mesh->quads.size(); 2284 for (size_t i = 0; i < count; i++) { 2285 const Rect& bounds = mesh->quads.itemAt(i); 2286 if (CC_LIKELY(pureTranslate)) { 2287 const float x = (int) floorf(bounds.left + offsetX + 0.5f); 2288 const float y = (int) floorf(bounds.top + offsetY + 0.5f); 2289 dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight()); 2290 } else { 2291 dirtyLayer(left + bounds.left, top + bounds.top, 2292 left + bounds.right, top + bounds.bottom, *currentTransform()); 2293 } 2294 } 2295 } 2296 2297 bool ignoreTransform = false; 2298 if (CC_LIKELY(pureTranslate)) { 2299 const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 2300 const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 2301 2302 right = x + right - left; 2303 bottom = y + bottom - top; 2304 left = x; 2305 top = y; 2306 ignoreTransform = true; 2307 } 2308 drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint, 2309 texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset, 2310 GL_TRIANGLES, mesh->indexCount, false, ignoreTransform, 2311 mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads); 2312 } 2313 2314 mDirty = true; 2315} 2316 2317/** 2318 * Important note: this method is intended to draw batches of 9-patch objects and 2319 * will not set the scissor enable or dirty the current layer, if any. 2320 * The caller is responsible for properly dirtying the current layer. 2321 */ 2322void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 2323 TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) { 2324 mCaches.textureState().activateTexture(0); 2325 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2326 if (!texture) return; 2327 const AutoTexture autoCleanup(texture); 2328 2329 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2330 texture->setFilter(GL_LINEAR, true); 2331 2332 drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint, 2333 texture->blend, &vertices[0].x, &vertices[0].u, 2334 GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false); 2335 2336 mDirty = true; 2337} 2338 2339void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY, 2340 const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) { 2341 // not missing call to quickReject/dirtyLayer, always done at a higher level 2342 if (!vertexBuffer.getVertexCount()) { 2343 // no vertices to draw 2344 return; 2345 } 2346 2347 if (USE_GLOPS) { 2348 Glop glop; 2349 GlopBuilder aBuilder(mRenderState, mCaches, &glop); 2350 bool fudgeOffset = displayFlags & kVertexBuffer_Offset; 2351 bool shadowInterp = displayFlags & kVertexBuffer_ShadowInterp; 2352 aBuilder.setMeshVertexBuffer(vertexBuffer, shadowInterp) 2353 .setFillPaint(*paint, currentSnapshot()->alpha) 2354 .setTransformClip(currentSnapshot()->getOrthoMatrix(), *currentTransform(), fudgeOffset) 2355 .setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds()) 2356 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2357 .build(); 2358 renderGlop(glop); 2359 return; 2360 } 2361 2362 const VertexBuffer::MeshFeatureFlags meshFeatureFlags = vertexBuffer.getMeshFeatureFlags(); 2363 Rect bounds(vertexBuffer.getBounds()); 2364 bounds.translate(translateX, translateY); 2365 dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform()); 2366 2367 int color = paint->getColor(); 2368 bool isAA = meshFeatureFlags & VertexBuffer::kAlpha; 2369 2370 setupDraw(); 2371 setupDrawNoTexture(); 2372 if (isAA) setupDrawVertexAlpha((displayFlags & kVertexBuffer_ShadowInterp)); 2373 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 2374 setupDrawColorFilter(getColorFilter(paint)); 2375 setupDrawShader(getShader(paint)); 2376 setupDrawBlending(paint, isAA); 2377 setupDrawProgram(); 2378 setupDrawModelView(kModelViewMode_Translate, (displayFlags & kVertexBuffer_Offset), 2379 translateX, translateY, 0, 0); 2380 setupDrawColorUniforms(getShader(paint)); 2381 setupDrawColorFilterUniforms(getColorFilter(paint)); 2382 setupDrawShaderUniforms(getShader(paint)); 2383 2384 const void* vertices = vertexBuffer.getBuffer(); 2385 mRenderState.meshState().unbindMeshBuffer(); 2386 mRenderState.meshState().bindPositionVertexPointer(true, vertices, 2387 isAA ? kAlphaVertexStride : kVertexStride); 2388 mRenderState.meshState().resetTexCoordsVertexPointer(); 2389 2390 int alphaSlot = -1; 2391 if (isAA) { 2392 void* alphaCoords = ((GLbyte*) vertices) + kVertexAlphaOffset; 2393 alphaSlot = mCaches.program().getAttrib("vtxAlpha"); 2394 // TODO: avoid enable/disable in back to back uses of the alpha attribute 2395 glEnableVertexAttribArray(alphaSlot); 2396 glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, kAlphaVertexStride, alphaCoords); 2397 } 2398 2399 if (meshFeatureFlags & VertexBuffer::kIndices) { 2400 mRenderState.meshState().unbindIndicesBuffer(); 2401 glDrawElements(GL_TRIANGLE_STRIP, vertexBuffer.getIndexCount(), 2402 GL_UNSIGNED_SHORT, vertexBuffer.getIndices()); 2403 } else { 2404 mRenderState.meshState().unbindIndicesBuffer(); 2405 glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount()); 2406 } 2407 2408 if (isAA) { 2409 glDisableVertexAttribArray(alphaSlot); 2410 } 2411 2412 mDirty = true; 2413} 2414 2415/** 2416 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to 2417 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in 2418 * screen space in all directions. However, instead of using a fragment shader to compute the 2419 * translucency of the color from its position, we simply use a varying parameter to define how far 2420 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used. 2421 * 2422 * Doesn't yet support joins, caps, or path effects. 2423 */ 2424void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) { 2425 VertexBuffer vertexBuffer; 2426 // TODO: try clipping large paths to viewport 2427 PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer); 2428 drawVertexBuffer(vertexBuffer, paint); 2429} 2430 2431/** 2432 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha 2433 * and additional geometry for defining an alpha slope perimeter. 2434 * 2435 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some 2436 * unexpected results, and may vary between hardware devices. Previously we used a varying-base 2437 * in-shader alpha region, but found it to be taxing on some GPUs. 2438 * 2439 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce 2440 * memory transfer by removing need for degenerate vertices. 2441 */ 2442void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) { 2443 if (mState.currentlyIgnored() || count < 4) return; 2444 2445 count &= ~0x3; // round down to nearest four 2446 2447 VertexBuffer buffer; 2448 PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer); 2449 const Rect& bounds = buffer.getBounds(); 2450 2451 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) { 2452 return; 2453 } 2454 2455 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset; 2456 drawVertexBuffer(buffer, paint, displayFlags); 2457} 2458 2459void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) { 2460 if (mState.currentlyIgnored() || count < 2) return; 2461 2462 count &= ~0x1; // round down to nearest two 2463 2464 VertexBuffer buffer; 2465 PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer); 2466 2467 const Rect& bounds = buffer.getBounds(); 2468 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) { 2469 return; 2470 } 2471 2472 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset; 2473 drawVertexBuffer(buffer, paint, displayFlags); 2474 2475 mDirty = true; 2476} 2477 2478void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 2479 // No need to check against the clip, we fill the clip region 2480 if (mState.currentlyIgnored()) return; 2481 2482 Rect clip(mState.currentClipRect()); 2483 clip.snapToPixelBoundaries(); 2484 2485 SkPaint paint; 2486 paint.setColor(color); 2487 paint.setXfermodeMode(mode); 2488 2489 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true); 2490 2491 mDirty = true; 2492} 2493 2494void OpenGLRenderer::drawShape(float left, float top, PathTexture* texture, 2495 const SkPaint* paint) { 2496 if (!texture) return; 2497 const AutoTexture autoCleanup(texture); 2498 2499 const float x = left + texture->left - texture->offset; 2500 const float y = top + texture->top - texture->offset; 2501 2502 drawPathTexture(texture, x, y, paint); 2503 2504 mDirty = true; 2505} 2506 2507void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 2508 float rx, float ry, const SkPaint* p) { 2509 if (mState.currentlyIgnored() 2510 || quickRejectSetupScissor(left, top, right, bottom, p) 2511 || PaintUtils::paintWillNotDraw(*p)) { 2512 return; 2513 } 2514 2515 if (p->getPathEffect() != nullptr) { 2516 mCaches.textureState().activateTexture(0); 2517 PathTexture* texture = mCaches.pathCache.getRoundRect( 2518 right - left, bottom - top, rx, ry, p); 2519 drawShape(left, top, texture, p); 2520 } else { 2521 const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect( 2522 *currentTransform(), *p, right - left, bottom - top, rx, ry); 2523 drawVertexBuffer(left, top, *vertexBuffer, p); 2524 } 2525} 2526 2527void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) { 2528 if (mState.currentlyIgnored() 2529 || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p) 2530 || PaintUtils::paintWillNotDraw(*p)) { 2531 return; 2532 } 2533 if (p->getPathEffect() != nullptr) { 2534 mCaches.textureState().activateTexture(0); 2535 PathTexture* texture = mCaches.pathCache.getCircle(radius, p); 2536 drawShape(x - radius, y - radius, texture, p); 2537 } else { 2538 SkPath path; 2539 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2540 path.addCircle(x, y, radius + p->getStrokeWidth() / 2); 2541 } else { 2542 path.addCircle(x, y, radius); 2543 } 2544 drawConvexPath(path, p); 2545 } 2546} 2547 2548void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, 2549 const SkPaint* p) { 2550 if (mState.currentlyIgnored() 2551 || quickRejectSetupScissor(left, top, right, bottom, p) 2552 || PaintUtils::paintWillNotDraw(*p)) { 2553 return; 2554 } 2555 2556 if (p->getPathEffect() != nullptr) { 2557 mCaches.textureState().activateTexture(0); 2558 PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p); 2559 drawShape(left, top, texture, p); 2560 } else { 2561 SkPath path; 2562 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2563 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2564 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2565 } 2566 path.addOval(rect); 2567 drawConvexPath(path, p); 2568 } 2569} 2570 2571void OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 2572 float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) { 2573 if (mState.currentlyIgnored() 2574 || quickRejectSetupScissor(left, top, right, bottom, p) 2575 || PaintUtils::paintWillNotDraw(*p)) { 2576 return; 2577 } 2578 2579 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180) 2580 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) { 2581 mCaches.textureState().activateTexture(0); 2582 PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top, 2583 startAngle, sweepAngle, useCenter, p); 2584 drawShape(left, top, texture, p); 2585 return; 2586 } 2587 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2588 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2589 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2590 } 2591 2592 SkPath path; 2593 if (useCenter) { 2594 path.moveTo(rect.centerX(), rect.centerY()); 2595 } 2596 path.arcTo(rect, startAngle, sweepAngle, !useCenter); 2597 if (useCenter) { 2598 path.close(); 2599 } 2600 drawConvexPath(path, p); 2601} 2602 2603// See SkPaintDefaults.h 2604#define SkPaintDefaults_MiterLimit SkIntToScalar(4) 2605 2606void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, 2607 const SkPaint* p) { 2608 if (mState.currentlyIgnored() 2609 || quickRejectSetupScissor(left, top, right, bottom, p) 2610 || PaintUtils::paintWillNotDraw(*p)) { 2611 return; 2612 } 2613 2614 if (p->getStyle() != SkPaint::kFill_Style) { 2615 // only fill style is supported by drawConvexPath, since others have to handle joins 2616 if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join || 2617 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) { 2618 mCaches.textureState().activateTexture(0); 2619 PathTexture* texture = 2620 mCaches.pathCache.getRect(right - left, bottom - top, p); 2621 drawShape(left, top, texture, p); 2622 } else { 2623 SkPath path; 2624 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2625 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2626 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2627 } 2628 path.addRect(rect); 2629 drawConvexPath(path, p); 2630 } 2631 } else { 2632 if (p->isAntiAlias() && !currentTransform()->isSimple()) { 2633 SkPath path; 2634 path.addRect(left, top, right, bottom); 2635 drawConvexPath(path, p); 2636 } else { 2637 drawColorRect(left, top, right, bottom, p); 2638 2639 mDirty = true; 2640 } 2641 } 2642} 2643 2644void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text, 2645 int bytesCount, int count, const float* positions, 2646 FontRenderer& fontRenderer, int alpha, float x, float y) { 2647 mCaches.textureState().activateTexture(0); 2648 2649 TextShadow textShadow; 2650 if (!getTextShadow(paint, &textShadow)) { 2651 LOG_ALWAYS_FATAL("failed to query shadow attributes"); 2652 } 2653 2654 // NOTE: The drop shadow will not perform gamma correction 2655 // if shader-based correction is enabled 2656 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 2657 const ShadowTexture* shadow = mCaches.dropShadowCache.get( 2658 paint, text, bytesCount, count, textShadow.radius, positions); 2659 // If the drop shadow exceeds the max texture size or couldn't be 2660 // allocated, skip drawing 2661 if (!shadow) return; 2662 const AutoTexture autoCleanup(shadow); 2663 2664 const float sx = x - shadow->left + textShadow.dx; 2665 const float sy = y - shadow->top + textShadow.dy; 2666 2667 const int shadowAlpha = ((textShadow.color >> 24) & 0xFF) * writableSnapshot()->alpha; 2668 if (getShader(paint)) { 2669 textShadow.color = SK_ColorWHITE; 2670 } 2671 2672 setupDraw(); 2673 setupDrawWithTexture(true); 2674 setupDrawAlpha8Color(textShadow.color, shadowAlpha < 255 ? shadowAlpha : alpha); 2675 setupDrawColorFilter(getColorFilter(paint)); 2676 setupDrawShader(getShader(paint)); 2677 setupDrawBlending(paint, true); 2678 setupDrawProgram(); 2679 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 2680 sx, sy, sx + shadow->width, sy + shadow->height); 2681 setupDrawTexture(shadow->id); 2682 setupDrawPureColorUniforms(); 2683 setupDrawColorFilterUniforms(getColorFilter(paint)); 2684 setupDrawShaderUniforms(getShader(paint)); 2685 setupDrawMesh(nullptr, (GLvoid*) kMeshTextureOffset); 2686 2687 glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount); 2688} 2689 2690bool OpenGLRenderer::canSkipText(const SkPaint* paint) const { 2691 float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha; 2692 return MathUtils::isZero(alpha) 2693 && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode; 2694} 2695 2696void OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count, 2697 const float* positions, const SkPaint* paint) { 2698 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) { 2699 return; 2700 } 2701 2702 // NOTE: Skia does not support perspective transform on drawPosText yet 2703 if (!currentTransform()->isSimple()) { 2704 return; 2705 } 2706 2707 mRenderState.scissor().setEnabled(true); 2708 2709 float x = 0.0f; 2710 float y = 0.0f; 2711 const bool pureTranslate = currentTransform()->isPureTranslate(); 2712 if (pureTranslate) { 2713 x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f); 2714 y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f); 2715 } 2716 2717 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2718 fontRenderer.setFont(paint, SkMatrix::I()); 2719 2720 int alpha; 2721 SkXfermode::Mode mode; 2722 getAlphaAndMode(paint, &alpha, &mode); 2723 2724 if (CC_UNLIKELY(hasTextShadow(paint))) { 2725 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2726 alpha, 0.0f, 0.0f); 2727 } 2728 2729 // Pick the appropriate texture filtering 2730 bool linearFilter = currentTransform()->changesBounds(); 2731 if (pureTranslate && !linearFilter) { 2732 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2733 } 2734 fontRenderer.setTextureFiltering(linearFilter); 2735 2736 const Rect& clip(pureTranslate ? writableSnapshot()->getClipRect() : writableSnapshot()->getLocalClip()); 2737 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2738 2739 const bool hasActiveLayer = hasLayer(); 2740 2741 TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2742 if (fontRenderer.renderPosText(paint, &clip, text, 0, bytesCount, count, x, y, 2743 positions, hasActiveLayer ? &bounds : nullptr, &functor)) { 2744 if (hasActiveLayer) { 2745 if (!pureTranslate) { 2746 currentTransform()->mapRect(bounds); 2747 } 2748 dirtyLayerUnchecked(bounds, getRegion()); 2749 } 2750 } 2751 2752 mDirty = true; 2753} 2754 2755bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const { 2756 if (CC_LIKELY(transform.isPureTranslate())) { 2757 outMatrix->setIdentity(); 2758 return false; 2759 } else if (CC_UNLIKELY(transform.isPerspective())) { 2760 outMatrix->setIdentity(); 2761 return true; 2762 } 2763 2764 /** 2765 * Input is a non-perspective, scaling transform. Generate a scale-only transform, 2766 * with values rounded to the nearest int. 2767 */ 2768 float sx, sy; 2769 transform.decomposeScale(sx, sy); 2770 outMatrix->setScale( 2771 roundf(fmaxf(1.0f, sx)), 2772 roundf(fmaxf(1.0f, sy))); 2773 return true; 2774} 2775 2776int OpenGLRenderer::getSaveCount() const { 2777 return mState.getSaveCount(); 2778} 2779 2780int OpenGLRenderer::save(int flags) { 2781 return mState.save(flags); 2782} 2783 2784void OpenGLRenderer::restore() { 2785 return mState.restore(); 2786} 2787 2788void OpenGLRenderer::restoreToCount(int saveCount) { 2789 return mState.restoreToCount(saveCount); 2790} 2791 2792void OpenGLRenderer::translate(float dx, float dy, float dz) { 2793 return mState.translate(dx, dy, dz); 2794} 2795 2796void OpenGLRenderer::rotate(float degrees) { 2797 return mState.rotate(degrees); 2798} 2799 2800void OpenGLRenderer::scale(float sx, float sy) { 2801 return mState.scale(sx, sy); 2802} 2803 2804void OpenGLRenderer::skew(float sx, float sy) { 2805 return mState.skew(sx, sy); 2806} 2807 2808void OpenGLRenderer::setMatrix(const Matrix4& matrix) { 2809 mState.setMatrix(matrix); 2810} 2811 2812void OpenGLRenderer::concatMatrix(const Matrix4& matrix) { 2813 mState.concatMatrix(matrix); 2814} 2815 2816bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 2817 return mState.clipRect(left, top, right, bottom, op); 2818} 2819 2820bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) { 2821 return mState.clipPath(path, op); 2822} 2823 2824bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) { 2825 return mState.clipRegion(region, op); 2826} 2827 2828void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) { 2829 mState.setClippingOutline(allocator, outline); 2830} 2831 2832void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator, 2833 const Rect& rect, float radius, bool highPriority) { 2834 mState.setClippingRoundRect(allocator, rect, radius, highPriority); 2835} 2836 2837void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y, 2838 const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds, 2839 DrawOpMode drawOpMode) { 2840 2841 if (drawOpMode == kDrawOpMode_Immediate) { 2842 // The checks for corner-case ignorable text and quick rejection is only done for immediate 2843 // drawing as ops from DeferredDisplayList are already filtered for these 2844 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) || 2845 quickRejectSetupScissor(bounds)) { 2846 return; 2847 } 2848 } 2849 2850 const float oldX = x; 2851 const float oldY = y; 2852 2853 const mat4& transform = *currentTransform(); 2854 const bool pureTranslate = transform.isPureTranslate(); 2855 2856 if (CC_LIKELY(pureTranslate)) { 2857 x = (int) floorf(x + transform.getTranslateX() + 0.5f); 2858 y = (int) floorf(y + transform.getTranslateY() + 0.5f); 2859 } 2860 2861 int alpha; 2862 SkXfermode::Mode mode; 2863 getAlphaAndMode(paint, &alpha, &mode); 2864 2865 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2866 2867 if (CC_UNLIKELY(hasTextShadow(paint))) { 2868 fontRenderer.setFont(paint, SkMatrix::I()); 2869 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2870 alpha, oldX, oldY); 2871 } 2872 2873 const bool hasActiveLayer = hasLayer(); 2874 2875 // We only pass a partial transform to the font renderer. That partial 2876 // matrix defines how glyphs are rasterized. Typically we want glyphs 2877 // to be rasterized at their final size on screen, which means the partial 2878 // matrix needs to take the scale factor into account. 2879 // When a partial matrix is used to transform glyphs during rasterization, 2880 // the mesh is generated with the inverse transform (in the case of scale, 2881 // the mesh is generated at 1.0 / scale for instance.) This allows us to 2882 // apply the full transform matrix at draw time in the vertex shader. 2883 // Applying the full matrix in the shader is the easiest way to handle 2884 // rotation and perspective and allows us to always generated quads in the 2885 // font renderer which greatly simplifies the code, clipping in particular. 2886 SkMatrix fontTransform; 2887 bool linearFilter = findBestFontTransform(transform, &fontTransform) 2888 || fabs(y - (int) y) > 0.0f 2889 || fabs(x - (int) x) > 0.0f; 2890 fontRenderer.setFont(paint, fontTransform); 2891 fontRenderer.setTextureFiltering(linearFilter); 2892 2893 // TODO: Implement better clipping for scaled/rotated text 2894 const Rect* clip = !pureTranslate ? nullptr : &mState.currentClipRect(); 2895 Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2896 2897 bool status; 2898 TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2899 2900 // don't call issuedrawcommand, do it at end of batch 2901 bool forceFinish = (drawOpMode != kDrawOpMode_Defer); 2902 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) { 2903 SkPaint paintCopy(*paint); 2904 paintCopy.setTextAlign(SkPaint::kLeft_Align); 2905 status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y, 2906 positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish); 2907 } else { 2908 status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2909 positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish); 2910 } 2911 2912 if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) { 2913 if (!pureTranslate) { 2914 transform.mapRect(layerBounds); 2915 } 2916 dirtyLayerUnchecked(layerBounds, getRegion()); 2917 } 2918 2919 drawTextDecorations(totalAdvance, oldX, oldY, paint); 2920 2921 mDirty = true; 2922} 2923 2924void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, 2925 const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) { 2926 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) { 2927 return; 2928 } 2929 2930 // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics 2931 mRenderState.scissor().setEnabled(true); 2932 2933 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2934 fontRenderer.setFont(paint, SkMatrix::I()); 2935 fontRenderer.setTextureFiltering(true); 2936 2937 int alpha; 2938 SkXfermode::Mode mode; 2939 getAlphaAndMode(paint, &alpha, &mode); 2940 TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint); 2941 2942 const Rect* clip = &writableSnapshot()->getLocalClip(); 2943 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2944 2945 const bool hasActiveLayer = hasLayer(); 2946 2947 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path, 2948 hOffset, vOffset, hasActiveLayer ? &bounds : nullptr, &functor)) { 2949 if (hasActiveLayer) { 2950 currentTransform()->mapRect(bounds); 2951 dirtyLayerUnchecked(bounds, getRegion()); 2952 } 2953 } 2954 2955 mDirty = true; 2956} 2957 2958void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) { 2959 if (mState.currentlyIgnored()) return; 2960 2961 mCaches.textureState().activateTexture(0); 2962 2963 PathTexture* texture = mCaches.pathCache.get(path, paint); 2964 if (!texture) return; 2965 const AutoTexture autoCleanup(texture); 2966 2967 const float x = texture->left - texture->offset; 2968 const float y = texture->top - texture->offset; 2969 2970 drawPathTexture(texture, x, y, paint); 2971 mDirty = true; 2972} 2973 2974void OpenGLRenderer::drawLayer(Layer* layer, float x, float y) { 2975 if (!layer) { 2976 return; 2977 } 2978 2979 mat4* transform = nullptr; 2980 if (layer->isTextureLayer()) { 2981 transform = &layer->getTransform(); 2982 if (!transform->isIdentity()) { 2983 save(SkCanvas::kMatrix_SaveFlag); 2984 concatMatrix(*transform); 2985 } 2986 } 2987 2988 bool clipRequired = false; 2989 const bool rejected = mState.calculateQuickRejectForScissor( 2990 x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), 2991 &clipRequired, nullptr, false); 2992 2993 if (rejected) { 2994 if (transform && !transform->isIdentity()) { 2995 restore(); 2996 } 2997 return; 2998 } 2999 3000 EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y, 3001 x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired); 3002 3003 updateLayer(layer, true); 3004 3005 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 3006 mCaches.textureState().activateTexture(0); 3007 3008 if (CC_LIKELY(!layer->region.isEmpty())) { 3009 if (layer->region.isRect()) { 3010 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 3011 composeLayerRect(layer, layer->regionRect)); 3012 } else if (layer->mesh) { 3013 3014 const float a = getLayerAlpha(layer); 3015 setupDraw(); 3016 setupDrawWithTexture(); 3017 setupDrawColor(a, a, a, a); 3018 setupDrawColorFilter(layer->getColorFilter()); 3019 setupDrawBlending(layer); 3020 setupDrawProgram(); 3021 setupDrawPureColorUniforms(); 3022 setupDrawColorFilterUniforms(layer->getColorFilter()); 3023 setupDrawTexture(layer->getTexture()); 3024 if (CC_LIKELY(currentTransform()->isPureTranslate())) { 3025 int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f); 3026 int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f); 3027 3028 layer->setFilter(GL_NEAREST); 3029 setupDrawModelView(kModelViewMode_Translate, false, tx, ty, 3030 tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true); 3031 } else { 3032 layer->setFilter(GL_LINEAR); 3033 setupDrawModelView(kModelViewMode_Translate, false, x, y, 3034 x + layer->layer.getWidth(), y + layer->layer.getHeight()); 3035 } 3036 3037 TextureVertex* mesh = &layer->mesh[0]; 3038 GLsizei elementsCount = layer->meshElementCount; 3039 3040 while (elementsCount > 0) { 3041 GLsizei drawCount = MathUtils::min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6); 3042 3043 setupDrawMeshIndices(&mesh[0].x, &mesh[0].u); 3044 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 3045 glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, nullptr)); 3046 3047 elementsCount -= drawCount; 3048 // Though there are 4 vertices in a quad, we use 6 indices per 3049 // quad to draw with GL_TRIANGLES 3050 mesh += (drawCount / 6) * 4; 3051 } 3052 3053#if DEBUG_LAYERS_AS_REGIONS 3054 drawRegionRectsDebug(layer->region); 3055#endif 3056 } 3057 3058 if (layer->debugDrawUpdate) { 3059 layer->debugDrawUpdate = false; 3060 3061 SkPaint paint; 3062 paint.setColor(0x7f00ff00); 3063 drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint); 3064 } 3065 } 3066 layer->hasDrawnSinceUpdate = true; 3067 3068 if (transform && !transform->isIdentity()) { 3069 restore(); 3070 } 3071 3072 mDirty = true; 3073} 3074 3075/////////////////////////////////////////////////////////////////////////////// 3076// Draw filters 3077/////////////////////////////////////////////////////////////////////////////// 3078void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) { 3079 // We should never get here since we apply the draw filter when stashing 3080 // the paints in the DisplayList. 3081 LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters"); 3082} 3083 3084/////////////////////////////////////////////////////////////////////////////// 3085// Drawing implementation 3086/////////////////////////////////////////////////////////////////////////////// 3087 3088Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) { 3089 Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap); 3090 if (!texture) { 3091 return mCaches.textureCache.get(bitmap); 3092 } 3093 return texture; 3094} 3095 3096void OpenGLRenderer::drawPathTexture(PathTexture* texture, 3097 float x, float y, const SkPaint* paint) { 3098 if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) { 3099 return; 3100 } 3101 3102 if (USE_GLOPS) { 3103 Glop glop; 3104 GlopBuilder aBuilder(mRenderState, mCaches, &glop); 3105 aBuilder.setMeshTexturedUnitQuad(nullptr, true) 3106 .setFillPathTexturePaint(*texture, *paint, currentSnapshot()->alpha) 3107 .setTransformClip(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 3108 .setModelViewMapUnitToRect(Rect(x, y, x + texture->width, y + texture->height)) 3109 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 3110 .build(); 3111 renderGlop(glop); 3112 return; 3113 } 3114 3115 3116 int alpha; 3117 SkXfermode::Mode mode; 3118 getAlphaAndMode(paint, &alpha, &mode); 3119 3120 setupDraw(); 3121 setupDrawWithTexture(true); 3122 setupDrawAlpha8Color(paint->getColor(), alpha); 3123 setupDrawColorFilter(getColorFilter(paint)); 3124 setupDrawShader(getShader(paint)); 3125 setupDrawBlending(paint, true); 3126 setupDrawProgram(); 3127 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 3128 x, y, x + texture->width, y + texture->height); 3129 setupDrawTexture(texture->id); 3130 setupDrawPureColorUniforms(); 3131 setupDrawColorFilterUniforms(getColorFilter(paint)); 3132 setupDrawShaderUniforms(getShader(paint)); 3133 setupDrawMesh(nullptr, (GLvoid*) kMeshTextureOffset); 3134 3135 glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount); 3136} 3137 3138// Same values used by Skia 3139#define kStdStrikeThru_Offset (-6.0f / 21.0f) 3140#define kStdUnderline_Offset (1.0f / 9.0f) 3141#define kStdUnderline_Thickness (1.0f / 18.0f) 3142 3143void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y, 3144 const SkPaint* paint) { 3145 // Handle underline and strike-through 3146 uint32_t flags = paint->getFlags(); 3147 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 3148 SkPaint paintCopy(*paint); 3149 3150 if (CC_LIKELY(underlineWidth > 0.0f)) { 3151 const float textSize = paintCopy.getTextSize(); 3152 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f); 3153 3154 const float left = x; 3155 float top = 0.0f; 3156 3157 int linesCount = 0; 3158 if (flags & SkPaint::kUnderlineText_Flag) linesCount++; 3159 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++; 3160 3161 const int pointsCount = 4 * linesCount; 3162 float points[pointsCount]; 3163 int currentPoint = 0; 3164 3165 if (flags & SkPaint::kUnderlineText_Flag) { 3166 top = y + textSize * kStdUnderline_Offset; 3167 points[currentPoint++] = left; 3168 points[currentPoint++] = top; 3169 points[currentPoint++] = left + underlineWidth; 3170 points[currentPoint++] = top; 3171 } 3172 3173 if (flags & SkPaint::kStrikeThruText_Flag) { 3174 top = y + textSize * kStdStrikeThru_Offset; 3175 points[currentPoint++] = left; 3176 points[currentPoint++] = top; 3177 points[currentPoint++] = left + underlineWidth; 3178 points[currentPoint++] = top; 3179 } 3180 3181 paintCopy.setStrokeWidth(strokeWidth); 3182 3183 drawLines(&points[0], pointsCount, &paintCopy); 3184 } 3185 } 3186} 3187 3188void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) { 3189 if (mState.currentlyIgnored()) { 3190 return; 3191 } 3192 3193 drawColorRects(rects, count, paint, false, true, true); 3194} 3195 3196void OpenGLRenderer::drawShadow(float casterAlpha, 3197 const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) { 3198 if (mState.currentlyIgnored()) return; 3199 3200 // TODO: use quickRejectWithScissor. For now, always force enable scissor. 3201 mRenderState.scissor().setEnabled(true); 3202 3203 SkPaint paint; 3204 paint.setAntiAlias(true); // want to use AlphaVertex 3205 3206 // The caller has made sure casterAlpha > 0. 3207 float ambientShadowAlpha = mAmbientShadowAlpha; 3208 if (CC_UNLIKELY(mCaches.propertyAmbientShadowStrength >= 0)) { 3209 ambientShadowAlpha = mCaches.propertyAmbientShadowStrength; 3210 } 3211 if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) { 3212 paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0); 3213 drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp); 3214 } 3215 3216 float spotShadowAlpha = mSpotShadowAlpha; 3217 if (CC_UNLIKELY(mCaches.propertySpotShadowStrength >= 0)) { 3218 spotShadowAlpha = mCaches.propertySpotShadowStrength; 3219 } 3220 if (spotShadowVertexBuffer && spotShadowAlpha > 0) { 3221 paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0); 3222 drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp); 3223 } 3224 3225 mDirty=true; 3226} 3227 3228void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint, 3229 bool ignoreTransform, bool dirty, bool clip) { 3230 if (count == 0) { 3231 return; 3232 } 3233 3234 float left = FLT_MAX; 3235 float top = FLT_MAX; 3236 float right = FLT_MIN; 3237 float bottom = FLT_MIN; 3238 3239 Vertex mesh[count]; 3240 Vertex* vertex = mesh; 3241 3242 for (int index = 0; index < count; index += 4) { 3243 float l = rects[index + 0]; 3244 float t = rects[index + 1]; 3245 float r = rects[index + 2]; 3246 float b = rects[index + 3]; 3247 3248 Vertex::set(vertex++, l, t); 3249 Vertex::set(vertex++, r, t); 3250 Vertex::set(vertex++, l, b); 3251 Vertex::set(vertex++, r, b); 3252 3253 left = fminf(left, l); 3254 top = fminf(top, t); 3255 right = fmaxf(right, r); 3256 bottom = fmaxf(bottom, b); 3257 } 3258 3259 if (clip && quickRejectSetupScissor(left, top, right, bottom)) { 3260 return; 3261 } 3262 3263 if (USE_GLOPS) { 3264 const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform(); 3265 Glop glop; 3266 GlopBuilder aBuilder(mRenderState, mCaches, &glop); 3267 aBuilder.setMeshIndexedQuads(&mesh[0], count / 4) 3268 .setFillPaint(*paint, currentSnapshot()->alpha) 3269 .setTransformClip(currentSnapshot()->getOrthoMatrix(), transform, false) 3270 .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom)) 3271 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 3272 .build(); 3273 renderGlop(glop); 3274 return; 3275 } 3276 3277 int color = paint->getColor(); 3278 // If a shader is set, preserve only the alpha 3279 if (getShader(paint)) { 3280 color |= 0x00ffffff; 3281 } 3282 3283 setupDraw(); 3284 setupDrawNoTexture(); 3285 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 3286 setupDrawShader(getShader(paint)); 3287 setupDrawColorFilter(getColorFilter(paint)); 3288 setupDrawBlending(paint); 3289 setupDrawProgram(); 3290 setupDrawDirtyRegionsDisabled(); 3291 setupDrawModelView(kModelViewMode_Translate, false, 3292 0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform); 3293 setupDrawColorUniforms(getShader(paint)); 3294 setupDrawShaderUniforms(getShader(paint)); 3295 setupDrawColorFilterUniforms(getColorFilter(paint)); 3296 3297 if (dirty && hasLayer()) { 3298 dirtyLayer(left, top, right, bottom, *currentTransform()); 3299 } 3300 3301 issueIndexedQuadDraw(&mesh[0], count / 4); 3302 3303 mDirty = true; 3304} 3305 3306void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 3307 const SkPaint* paint, bool ignoreTransform) { 3308 3309 if (USE_GLOPS) { 3310 const Matrix4& transform = ignoreTransform ? Matrix4::identity() : *currentTransform(); 3311 Glop glop; 3312 GlopBuilder aBuilder(mRenderState, mCaches, &glop); 3313 aBuilder.setMeshUnitQuad() 3314 .setFillPaint(*paint, currentSnapshot()->alpha) 3315 .setTransformClip(currentSnapshot()->getOrthoMatrix(), transform, false) 3316 .setModelViewMapUnitToRect(Rect(left, top, right, bottom)) 3317 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 3318 .build(); 3319 renderGlop(glop); 3320 return; 3321 } 3322 3323 int color = paint->getColor(); 3324 // If a shader is set, preserve only the alpha 3325 if (getShader(paint)) { 3326 color |= 0x00ffffff; 3327 } 3328 3329 setupDraw(); 3330 setupDrawNoTexture(); 3331 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 3332 setupDrawShader(getShader(paint)); 3333 setupDrawColorFilter(getColorFilter(paint)); 3334 setupDrawBlending(paint); 3335 setupDrawProgram(); 3336 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 3337 left, top, right, bottom, ignoreTransform); 3338 setupDrawColorUniforms(getShader(paint)); 3339 setupDrawShaderUniforms(getShader(paint), ignoreTransform); 3340 setupDrawColorFilterUniforms(getColorFilter(paint)); 3341 setupDrawSimpleMesh(); 3342 3343 glDrawArrays(GL_TRIANGLE_STRIP, 0, kUnitQuadCount); 3344} 3345 3346void OpenGLRenderer::drawTextureRect(Texture* texture, const SkPaint* paint) { 3347 if (USE_GLOPS) { 3348 Glop glop; 3349 GlopBuilder aBuilder(mRenderState, mCaches, &glop); 3350 aBuilder.setMeshTexturedUnitQuad(texture->uvMapper, false) 3351 .setFillTexturePaint(*texture, false, paint, currentSnapshot()->alpha) 3352 .setTransformClip(currentSnapshot()->getOrthoMatrix(), *currentTransform(), false) 3353 .setModelViewMapUnitToRectSnap(Rect(0, 0, texture->width, texture->height)) 3354 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 3355 .build(); 3356 renderGlop(glop); 3357 return; 3358 } 3359 3360 texture->setWrap(GL_CLAMP_TO_EDGE, true); 3361 3362 GLvoid* vertices = (GLvoid*) nullptr; 3363 GLvoid* texCoords = (GLvoid*) kMeshTextureOffset; 3364 3365 if (texture->uvMapper) { 3366 vertices = &mMeshVertices[0].x; 3367 texCoords = &mMeshVertices[0].u; 3368 3369 Rect uvs(0.0f, 0.0f, 1.0f, 1.0f); 3370 texture->uvMapper->map(uvs); 3371 3372 resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom); 3373 } 3374 3375 if (CC_LIKELY(currentTransform()->isPureTranslate())) { 3376 const float x = (int) floorf(currentTransform()->getTranslateX() + 0.5f); 3377 const float y = (int) floorf(currentTransform()->getTranslateY() + 0.5f); 3378 3379 texture->setFilter(GL_NEAREST, true); 3380 drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 3381 paint, texture->blend, vertices, texCoords, 3382 GL_TRIANGLE_STRIP, kUnitQuadCount, false, true); 3383 } else { 3384 texture->setFilter(PaintUtils::getFilter(paint), true); 3385 drawTextureMesh(0, 0, texture->width, texture->height, texture->id, paint, 3386 texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, kUnitQuadCount); 3387 } 3388 3389 if (texture->uvMapper) { 3390 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 3391 } 3392} 3393 3394void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 3395 GLuint texture, const SkPaint* paint, bool blend, 3396 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3397 bool swapSrcDst, bool ignoreTransform, GLuint vbo, 3398 ModelViewMode modelViewMode, bool dirty) { 3399 3400 int a; 3401 SkXfermode::Mode mode; 3402 getAlphaAndMode(paint, &a, &mode); 3403 const float alpha = a / 255.0f; 3404 3405 setupDraw(); 3406 setupDrawWithTexture(); 3407 setupDrawColor(alpha, alpha, alpha, alpha); 3408 setupDrawColorFilter(getColorFilter(paint)); 3409 setupDrawBlending(paint, blend, swapSrcDst); 3410 setupDrawProgram(); 3411 if (!dirty) setupDrawDirtyRegionsDisabled(); 3412 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3413 setupDrawTexture(texture); 3414 setupDrawPureColorUniforms(); 3415 setupDrawColorFilterUniforms(getColorFilter(paint)); 3416 setupDrawMesh(vertices, texCoords, vbo); 3417 3418 glDrawArrays(drawMode, 0, elementsCount); 3419} 3420 3421void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom, 3422 GLuint texture, const SkPaint* paint, bool blend, 3423 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3424 bool swapSrcDst, bool ignoreTransform, GLuint vbo, 3425 ModelViewMode modelViewMode, bool dirty) { 3426 3427 int a; 3428 SkXfermode::Mode mode; 3429 getAlphaAndMode(paint, &a, &mode); 3430 const float alpha = a / 255.0f; 3431 3432 setupDraw(); 3433 setupDrawWithTexture(); 3434 setupDrawColor(alpha, alpha, alpha, alpha); 3435 setupDrawColorFilter(getColorFilter(paint)); 3436 setupDrawBlending(paint, blend, swapSrcDst); 3437 setupDrawProgram(); 3438 if (!dirty) setupDrawDirtyRegionsDisabled(); 3439 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3440 setupDrawTexture(texture); 3441 setupDrawPureColorUniforms(); 3442 setupDrawColorFilterUniforms(getColorFilter(paint)); 3443 setupDrawMeshIndices(vertices, texCoords, vbo); 3444 3445 glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, nullptr); 3446} 3447 3448void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom, 3449 GLuint texture, const SkPaint* paint, 3450 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3451 bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) { 3452 3453 int color = paint != nullptr ? paint->getColor() : 0; 3454 int alpha; 3455 SkXfermode::Mode mode; 3456 getAlphaAndMode(paint, &alpha, &mode); 3457 3458 setupDraw(); 3459 setupDrawWithTexture(true); 3460 if (paint != nullptr) { 3461 setupDrawAlpha8Color(color, alpha); 3462 } 3463 setupDrawColorFilter(getColorFilter(paint)); 3464 setupDrawShader(getShader(paint)); 3465 setupDrawBlending(paint, true); 3466 setupDrawProgram(); 3467 if (!dirty) setupDrawDirtyRegionsDisabled(); 3468 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3469 setupDrawTexture(texture); 3470 setupDrawPureColorUniforms(); 3471 setupDrawColorFilterUniforms(getColorFilter(paint)); 3472 setupDrawShaderUniforms(getShader(paint), ignoreTransform); 3473 setupDrawMesh(vertices, texCoords); 3474 3475 glDrawArrays(drawMode, 0, elementsCount); 3476} 3477 3478void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 3479 ProgramDescription& description, bool swapSrcDst) { 3480 3481 if (currentSnapshot()->roundRectClipState != nullptr /*&& !mSkipOutlineClip*/) { 3482 blend = true; 3483 mDescription.hasRoundRectClip = true; 3484 } 3485 mSkipOutlineClip = true; 3486 3487 blend = blend || mode != SkXfermode::kSrcOver_Mode; 3488 3489 if (blend) { 3490 // These blend modes are not supported by OpenGL directly and have 3491 // to be implemented using shaders. Since the shader will perform 3492 // the blending, turn blending off here 3493 // If the blend mode cannot be implemented using shaders, fall 3494 // back to the default SrcOver blend mode instead 3495 if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) { 3496 if (CC_UNLIKELY(mCaches.extensions().hasFramebufferFetch())) { 3497 description.framebufferMode = mode; 3498 description.swapSrcDst = swapSrcDst; 3499 3500 mRenderState.blend().disable(); 3501 return; 3502 } else { 3503 mode = SkXfermode::kSrcOver_Mode; 3504 } 3505 } 3506 mRenderState.blend().enable(mode, swapSrcDst); 3507 } else { 3508 mRenderState.blend().disable(); 3509 } 3510} 3511 3512void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 3513 TextureVertex* v = &mMeshVertices[0]; 3514 TextureVertex::setUV(v++, u1, v1); 3515 TextureVertex::setUV(v++, u2, v1); 3516 TextureVertex::setUV(v++, u1, v2); 3517 TextureVertex::setUV(v++, u2, v2); 3518} 3519 3520void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, 3521 SkXfermode::Mode* mode) const { 3522 getAlphaAndModeDirect(paint, alpha, mode); 3523 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) { 3524 // if drawing a layer, ignore the paint's alpha 3525 *alpha = mDrawModifiers.mOverrideLayerAlpha * 255; 3526 } 3527 *alpha *= currentSnapshot()->alpha; 3528} 3529 3530float OpenGLRenderer::getLayerAlpha(const Layer* layer) const { 3531 float alpha; 3532 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) { 3533 alpha = mDrawModifiers.mOverrideLayerAlpha; 3534 } else { 3535 alpha = layer->getAlpha() / 255.0f; 3536 } 3537 return alpha * currentSnapshot()->alpha; 3538} 3539 3540}; // namespace uirenderer 3541}; // namespace android 3542