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