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