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