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