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