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