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