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