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