OpenGLRenderer.cpp revision 4ace7305608442ab35ea9aa65a4220df152c187f
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 57static GLenum getFilter(const SkPaint* paint) { 58 if (!paint || paint->getFilterLevel() != SkPaint::kNone_FilterLevel) { 59 return GL_LINEAR; 60 } 61 return GL_NEAREST; 62} 63 64/////////////////////////////////////////////////////////////////////////////// 65// Globals 66/////////////////////////////////////////////////////////////////////////////// 67 68/** 69 * Structure mapping Skia xfermodes to OpenGL blending factors. 70 */ 71struct Blender { 72 SkXfermode::Mode mode; 73 GLenum src; 74 GLenum dst; 75}; // struct Blender 76 77// In this array, the index of each Blender equals the value of the first 78// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode] 79static const Blender gBlends[] = { 80 { SkXfermode::kClear_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 81 { SkXfermode::kSrc_Mode, GL_ONE, GL_ZERO }, 82 { SkXfermode::kDst_Mode, GL_ZERO, GL_ONE }, 83 { SkXfermode::kSrcOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 84 { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 85 { SkXfermode::kSrcIn_Mode, GL_DST_ALPHA, GL_ZERO }, 86 { SkXfermode::kDstIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 87 { SkXfermode::kSrcOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 88 { SkXfermode::kDstOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 89 { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 90 { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 91 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 92 { SkXfermode::kPlus_Mode, GL_ONE, GL_ONE }, 93 { SkXfermode::kModulate_Mode, GL_ZERO, GL_SRC_COLOR }, 94 { SkXfermode::kScreen_Mode, GL_ONE, GL_ONE_MINUS_SRC_COLOR } 95}; 96 97// This array contains the swapped version of each SkXfermode. For instance 98// this array's SrcOver blending mode is actually DstOver. You can refer to 99// createLayer() for more information on the purpose of this array. 100static const Blender gBlendsSwap[] = { 101 { SkXfermode::kClear_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 102 { SkXfermode::kSrc_Mode, GL_ZERO, GL_ONE }, 103 { SkXfermode::kDst_Mode, GL_ONE, GL_ZERO }, 104 { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 105 { SkXfermode::kDstOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 106 { SkXfermode::kSrcIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 107 { SkXfermode::kDstIn_Mode, GL_DST_ALPHA, GL_ZERO }, 108 { SkXfermode::kSrcOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 109 { SkXfermode::kDstOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 110 { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 111 { SkXfermode::kDstATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 112 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 113 { SkXfermode::kPlus_Mode, GL_ONE, GL_ONE }, 114 { SkXfermode::kModulate_Mode, GL_DST_COLOR, GL_ZERO }, 115 { SkXfermode::kScreen_Mode, GL_ONE_MINUS_DST_COLOR, GL_ONE } 116}; 117 118/////////////////////////////////////////////////////////////////////////////// 119// Functions 120/////////////////////////////////////////////////////////////////////////////// 121 122template<typename T> 123static inline T min(T a, T b) { 124 return a < b ? a : b; 125} 126 127/////////////////////////////////////////////////////////////////////////////// 128// Constructors/destructor 129/////////////////////////////////////////////////////////////////////////////// 130 131OpenGLRenderer::OpenGLRenderer(RenderState& renderState) 132 : mFrameStarted(false) 133 , mCaches(Caches::getInstance()) 134 , mExtensions(Extensions::getInstance()) 135 , mRenderState(renderState) 136 , mScissorOptimizationDisabled(false) 137 , mCountOverdraw(false) 138 , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN}) 139 , mLightRadius(FLT_MIN) 140 , mAmbientShadowAlpha(0) 141 , mSpotShadowAlpha(0) { 142 // *set* draw modifiers to be 0 143 memset(&mDrawModifiers, 0, sizeof(mDrawModifiers)); 144 mDrawModifiers.mOverrideLayerAlpha = 1.0f; 145 146 memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices)); 147} 148 149OpenGLRenderer::~OpenGLRenderer() { 150 // The context has already been destroyed at this point, do not call 151 // GL APIs. All GL state should be kept in Caches.h 152} 153 154void OpenGLRenderer::initProperties() { 155 char property[PROPERTY_VALUE_MAX]; 156 if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) { 157 mScissorOptimizationDisabled = !strcasecmp(property, "true"); 158 INIT_LOGD(" Scissor optimization %s", 159 mScissorOptimizationDisabled ? "disabled" : "enabled"); 160 } else { 161 INIT_LOGD(" Scissor optimization enabled"); 162 } 163} 164 165void OpenGLRenderer::initLight(const Vector3& lightCenter, float lightRadius, 166 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) { 167 mLightCenter = lightCenter; 168 mLightRadius = lightRadius; 169 mAmbientShadowAlpha = ambientShadowAlpha; 170 mSpotShadowAlpha = spotShadowAlpha; 171} 172 173/////////////////////////////////////////////////////////////////////////////// 174// Setup 175/////////////////////////////////////////////////////////////////////////////// 176 177void OpenGLRenderer::onViewportInitialized() { 178 glDisable(GL_DITHER); 179 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 180 181 glEnableVertexAttribArray(Program::kBindingPosition); 182} 183 184void OpenGLRenderer::setupFrameState(float left, float top, 185 float right, float bottom, bool opaque) { 186 mCaches.clearGarbage(); 187 initializeSaveStack(left, top, right, bottom, mLightCenter); 188 mOpaque = opaque; 189 mTilingClip.set(left, top, right, bottom); 190} 191 192status_t OpenGLRenderer::startFrame() { 193 if (mFrameStarted) return DrawGlInfo::kStatusDone; 194 mFrameStarted = true; 195 196 mDirtyClip = true; 197 198 discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom); 199 200 mRenderState.setViewport(getWidth(), getHeight()); 201 202 // Functors break the tiling extension in pretty spectacular ways 203 // This ensures we don't use tiling when a functor is going to be 204 // invoked during the frame 205 mSuppressTiling = mCaches.hasRegisteredFunctors(); 206 207 startTilingCurrentClip(true); 208 209 debugOverdraw(true, true); 210 211 return clear(mTilingClip.left, mTilingClip.top, 212 mTilingClip.right, mTilingClip.bottom, mOpaque); 213} 214 215status_t OpenGLRenderer::prepareDirty(float left, float top, 216 float right, float bottom, bool opaque) { 217 218 setupFrameState(left, top, right, bottom, opaque); 219 220 // Layer renderers will start the frame immediately 221 // The framebuffer renderer will first defer the display list 222 // for each layer and wait until the first drawing command 223 // to start the frame 224 if (currentSnapshot()->fbo == 0) { 225 syncState(); 226 updateLayers(); 227 } else { 228 return startFrame(); 229 } 230 231 return DrawGlInfo::kStatusDone; 232} 233 234void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) { 235 // If we know that we are going to redraw the entire framebuffer, 236 // perform a discard to let the driver know we don't need to preserve 237 // the back buffer for this frame. 238 if (mExtensions.hasDiscardFramebuffer() && 239 left <= 0.0f && top <= 0.0f && right >= getWidth() && bottom >= getHeight()) { 240 const bool isFbo = getTargetFbo() == 0; 241 const GLenum attachments[] = { 242 isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0, 243 isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT }; 244 glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); 245 } 246} 247 248status_t OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) { 249 if (!opaque || mCountOverdraw) { 250 mCaches.enableScissor(); 251 mCaches.setScissor(left, getViewportHeight() - bottom, right - left, bottom - top); 252 glClear(GL_COLOR_BUFFER_BIT); 253 return DrawGlInfo::kStatusDrew; 254 } 255 256 mCaches.resetScissor(); 257 return DrawGlInfo::kStatusDone; 258} 259 260void OpenGLRenderer::syncState() { 261 if (mCaches.blend) { 262 glEnable(GL_BLEND); 263 } else { 264 glDisable(GL_BLEND); 265 } 266} 267 268void OpenGLRenderer::startTilingCurrentClip(bool opaque, bool expand) { 269 if (!mSuppressTiling) { 270 const Snapshot* snapshot = currentSnapshot(); 271 272 const Rect* clip = &mTilingClip; 273 if (snapshot->flags & Snapshot::kFlagFboTarget) { 274 clip = &(snapshot->layer->clipRect); 275 } 276 277 startTiling(*clip, getViewportHeight(), opaque, expand); 278 } 279} 280 281void OpenGLRenderer::startTiling(const Rect& clip, int windowHeight, bool opaque, bool expand) { 282 if (!mSuppressTiling) { 283 if(expand) { 284 // Expand the startTiling region by 1 285 int leftNotZero = (clip.left > 0) ? 1 : 0; 286 int topNotZero = (windowHeight - clip.bottom > 0) ? 1 : 0; 287 288 mCaches.startTiling( 289 clip.left - leftNotZero, 290 windowHeight - clip.bottom - topNotZero, 291 clip.right - clip.left + leftNotZero + 1, 292 clip.bottom - clip.top + topNotZero + 1, 293 opaque); 294 } else { 295 mCaches.startTiling(clip.left, windowHeight - clip.bottom, 296 clip.right - clip.left, clip.bottom - clip.top, opaque); 297 } 298 } 299} 300 301void OpenGLRenderer::endTiling() { 302 if (!mSuppressTiling) mCaches.endTiling(); 303} 304 305void OpenGLRenderer::finish() { 306 renderOverdraw(); 307 endTiling(); 308 309 // When finish() is invoked on FBO 0 we've reached the end 310 // of the current frame 311 if (getTargetFbo() == 0) { 312 mCaches.pathCache.trim(); 313 mCaches.tessellationCache.trim(); 314 } 315 316 if (!suppressErrorChecks()) { 317#if DEBUG_OPENGL 318 GLUtils::dumpGLErrors(); 319#endif 320 321#if DEBUG_MEMORY_USAGE 322 mCaches.dumpMemoryUsage(); 323#else 324 if (mCaches.getDebugLevel() & kDebugMemory) { 325 mCaches.dumpMemoryUsage(); 326 } 327#endif 328 } 329 330 if (mCountOverdraw) { 331 countOverdraw(); 332 } 333 334 mFrameStarted = false; 335} 336 337void OpenGLRenderer::resumeAfterLayer() { 338 mRenderState.setViewport(getViewportWidth(), getViewportHeight()); 339 mRenderState.bindFramebuffer(currentSnapshot()->fbo); 340 debugOverdraw(true, false); 341 342 mCaches.resetScissor(); 343 dirtyClip(); 344} 345 346status_t OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) { 347 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 348 349 Rect clip(*currentClipRect()); 350 clip.snapToPixelBoundaries(); 351 352 // Since we don't know what the functor will draw, let's dirty 353 // the entire clip region 354 if (hasLayer()) { 355 dirtyLayerUnchecked(clip, getRegion()); 356 } 357 358 DrawGlInfo info; 359 info.clipLeft = clip.left; 360 info.clipTop = clip.top; 361 info.clipRight = clip.right; 362 info.clipBottom = clip.bottom; 363 info.isLayer = hasLayer(); 364 info.width = getViewportWidth(); 365 info.height = getViewportHeight(); 366 currentTransform()->copyTo(&info.transform[0]); 367 368 bool prevDirtyClip = mDirtyClip; 369 // setup GL state for functor 370 if (mDirtyClip) { 371 setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt() 372 } 373 if (mCaches.enableScissor() || prevDirtyClip) { 374 setScissorFromClip(); 375 } 376 377 mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info); 378 // Scissor may have been modified, reset dirty clip 379 dirtyClip(); 380 381 return DrawGlInfo::kStatusDrew; 382} 383 384/////////////////////////////////////////////////////////////////////////////// 385// Debug 386/////////////////////////////////////////////////////////////////////////////// 387 388void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const { 389#if DEBUG_DETAILED_EVENTS 390 const int BUFFER_SIZE = 256; 391 va_list ap; 392 char buf[BUFFER_SIZE]; 393 394 va_start(ap, fmt); 395 vsnprintf(buf, BUFFER_SIZE, fmt, ap); 396 va_end(ap); 397 398 eventMark(buf); 399#endif 400} 401 402 403void OpenGLRenderer::eventMark(const char* name) const { 404 mCaches.eventMark(0, name); 405} 406 407void OpenGLRenderer::startMark(const char* name) const { 408 mCaches.startMark(0, name); 409} 410 411void OpenGLRenderer::endMark() const { 412 mCaches.endMark(); 413} 414 415void OpenGLRenderer::debugOverdraw(bool enable, bool clear) { 416 mRenderState.debugOverdraw(enable, clear); 417} 418 419void OpenGLRenderer::renderOverdraw() { 420 if (mCaches.debugOverdraw && getTargetFbo() == 0) { 421 const Rect* clip = &mTilingClip; 422 423 mCaches.enableScissor(); 424 mCaches.setScissor(clip->left, firstSnapshot()->getViewportHeight() - clip->bottom, 425 clip->right - clip->left, clip->bottom - clip->top); 426 427 // 1x overdraw 428 mCaches.stencil.enableDebugTest(2); 429 drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode); 430 431 // 2x overdraw 432 mCaches.stencil.enableDebugTest(3); 433 drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode); 434 435 // 3x overdraw 436 mCaches.stencil.enableDebugTest(4); 437 drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode); 438 439 // 4x overdraw and higher 440 mCaches.stencil.enableDebugTest(4, true); 441 drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode); 442 443 mCaches.stencil.disable(); 444 } 445} 446 447void OpenGLRenderer::countOverdraw() { 448 size_t count = getWidth() * getHeight(); 449 uint32_t* buffer = new uint32_t[count]; 450 glReadPixels(0, 0, getWidth(), getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, &buffer[0]); 451 452 size_t total = 0; 453 for (size_t i = 0; i < count; i++) { 454 total += buffer[i] & 0xff; 455 } 456 457 mOverdraw = total / float(count); 458 459 delete[] buffer; 460} 461 462/////////////////////////////////////////////////////////////////////////////// 463// Layers 464/////////////////////////////////////////////////////////////////////////////// 465 466bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) { 467 if (layer->deferredUpdateScheduled && layer->renderer 468 && layer->renderNode.get() && layer->renderNode->isRenderable()) { 469 ATRACE_CALL(); 470 471 Rect& dirty = layer->dirtyRect; 472 473 if (inFrame) { 474 endTiling(); 475 debugOverdraw(false, false); 476 } 477 478 if (CC_UNLIKELY(inFrame || mCaches.drawDeferDisabled)) { 479 layer->render(*this); 480 } else { 481 layer->defer(*this); 482 } 483 484 if (inFrame) { 485 resumeAfterLayer(); 486 startTilingCurrentClip(); 487 } 488 489 layer->debugDrawUpdate = mCaches.debugLayersUpdates; 490 layer->hasDrawnSinceUpdate = false; 491 492 return true; 493 } 494 495 return false; 496} 497 498void OpenGLRenderer::updateLayers() { 499 // If draw deferring is enabled this method will simply defer 500 // the display list of each individual layer. The layers remain 501 // in the layer updates list which will be cleared by flushLayers(). 502 int count = mLayerUpdates.size(); 503 if (count > 0) { 504 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 505 startMark("Layer Updates"); 506 } else { 507 startMark("Defer Layer Updates"); 508 } 509 510 // Note: it is very important to update the layers in order 511 for (int i = 0; i < count; i++) { 512 Layer* layer = mLayerUpdates.itemAt(i); 513 updateLayer(layer, false); 514 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 515 mCaches.resourceCache.decrementRefcount(layer); 516 } 517 } 518 519 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 520 mLayerUpdates.clear(); 521 mRenderState.bindFramebuffer(getTargetFbo()); 522 } 523 endMark(); 524 } 525} 526 527void OpenGLRenderer::flushLayers() { 528 int count = mLayerUpdates.size(); 529 if (count > 0) { 530 startMark("Apply Layer Updates"); 531 char layerName[12]; 532 533 // Note: it is very important to update the layers in order 534 for (int i = 0; i < count; i++) { 535 sprintf(layerName, "Layer #%d", i); 536 startMark(layerName); 537 538 ATRACE_BEGIN("flushLayer"); 539 Layer* layer = mLayerUpdates.itemAt(i); 540 layer->flush(); 541 ATRACE_END(); 542 543 mCaches.resourceCache.decrementRefcount(layer); 544 545 endMark(); 546 } 547 548 mLayerUpdates.clear(); 549 mRenderState.bindFramebuffer(getTargetFbo()); 550 551 endMark(); 552 } 553} 554 555void OpenGLRenderer::pushLayerUpdate(Layer* layer) { 556 if (layer) { 557 // Make sure we don't introduce duplicates. 558 // SortedVector would do this automatically but we need to respect 559 // the insertion order. The linear search is not an issue since 560 // this list is usually very short (typically one item, at most a few) 561 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 562 if (mLayerUpdates.itemAt(i) == layer) { 563 return; 564 } 565 } 566 mLayerUpdates.push_back(layer); 567 mCaches.resourceCache.incrementRefcount(layer); 568 } 569} 570 571void OpenGLRenderer::cancelLayerUpdate(Layer* layer) { 572 if (layer) { 573 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 574 if (mLayerUpdates.itemAt(i) == layer) { 575 mLayerUpdates.removeAt(i); 576 mCaches.resourceCache.decrementRefcount(layer); 577 break; 578 } 579 } 580 } 581} 582 583void OpenGLRenderer::clearLayerUpdates() { 584 size_t count = mLayerUpdates.size(); 585 if (count > 0) { 586 mCaches.resourceCache.lock(); 587 for (size_t i = 0; i < count; i++) { 588 mCaches.resourceCache.decrementRefcountLocked(mLayerUpdates.itemAt(i)); 589 } 590 mCaches.resourceCache.unlock(); 591 mLayerUpdates.clear(); 592 } 593} 594 595void OpenGLRenderer::flushLayerUpdates() { 596 ATRACE_CALL(); 597 syncState(); 598 updateLayers(); 599 flushLayers(); 600 // Wait for all the layer updates to be executed 601 AutoFence fence; 602} 603 604void OpenGLRenderer::markLayersAsBuildLayers() { 605 for (size_t i = 0; i < mLayerUpdates.size(); i++) { 606 mLayerUpdates[i]->wasBuildLayered = true; 607 } 608} 609 610/////////////////////////////////////////////////////////////////////////////// 611// State management 612/////////////////////////////////////////////////////////////////////////////// 613 614void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) { 615 bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer; 616 bool restoreClip = removed.flags & Snapshot::kFlagClipSet; 617 bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer; 618 619 if (restoreViewport) { 620 mRenderState.setViewport(getViewportWidth(), getViewportHeight()); 621 } 622 623 if (restoreClip) { 624 dirtyClip(); 625 } 626 627 if (restoreLayer) { 628 endMark(); // Savelayer 629 startMark("ComposeLayer"); 630 composeLayer(removed, restored); 631 endMark(); 632 } 633} 634 635/////////////////////////////////////////////////////////////////////////////// 636// Layers 637/////////////////////////////////////////////////////////////////////////////// 638 639int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 640 const SkPaint* paint, int flags, const SkPath* convexMask) { 641 // force matrix/clip isolation for layer 642 flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag; 643 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 <= 0 && 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::setupDrawVertexAlpha(bool useShadowAlphaInterp) { 1649 mDescription.hasVertexAlpha = true; 1650 mDescription.useShadowAlphaInterp = useShadowAlphaInterp; 1651} 1652 1653void OpenGLRenderer::setupDrawColor(int color, int alpha) { 1654 mColorA = alpha / 255.0f; 1655 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f; 1656 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f; 1657 mColorB = mColorA * ((color ) & 0xFF) / 255.0f; 1658 mColorSet = true; 1659 mSetShaderColor = mDescription.setColorModulate(mColorA); 1660} 1661 1662void OpenGLRenderer::setupDrawAlpha8Color(int color, int alpha) { 1663 mColorA = alpha / 255.0f; 1664 mColorR = mColorA * ((color >> 16) & 0xFF) / 255.0f; 1665 mColorG = mColorA * ((color >> 8) & 0xFF) / 255.0f; 1666 mColorB = mColorA * ((color ) & 0xFF) / 255.0f; 1667 mColorSet = true; 1668 mSetShaderColor = mDescription.setAlpha8ColorModulate(mColorR, mColorG, mColorB, mColorA); 1669} 1670 1671void OpenGLRenderer::setupDrawTextGamma(const SkPaint* paint) { 1672 mCaches.fontRenderer->describe(mDescription, paint); 1673} 1674 1675void OpenGLRenderer::setupDrawColor(float r, float g, float b, float a) { 1676 mColorA = a; 1677 mColorR = r; 1678 mColorG = g; 1679 mColorB = b; 1680 mColorSet = true; 1681 mSetShaderColor = mDescription.setColorModulate(a); 1682} 1683 1684void OpenGLRenderer::setupDrawShader(const SkShader* shader) { 1685 if (shader != NULL) { 1686 SkiaShader::describe(&mCaches, mDescription, mExtensions, *shader); 1687 } 1688} 1689 1690void OpenGLRenderer::setupDrawColorFilter(const SkColorFilter* filter) { 1691 if (filter == NULL) { 1692 return; 1693 } 1694 1695 SkXfermode::Mode mode; 1696 if (filter->asColorMode(NULL, &mode)) { 1697 mDescription.colorOp = ProgramDescription::kColorBlend; 1698 mDescription.colorMode = mode; 1699 } else if (filter->asColorMatrix(NULL)) { 1700 mDescription.colorOp = ProgramDescription::kColorMatrix; 1701 } 1702} 1703 1704void OpenGLRenderer::accountForClear(SkXfermode::Mode mode) { 1705 if (mColorSet && mode == SkXfermode::kClear_Mode) { 1706 mColorA = 1.0f; 1707 mColorR = mColorG = mColorB = 0.0f; 1708 mSetShaderColor = mDescription.modulate = true; 1709 } 1710} 1711 1712static bool isBlendedColorFilter(const SkColorFilter* filter) { 1713 if (filter == NULL) { 1714 return false; 1715 } 1716 return (filter->getFlags() & SkColorFilter::kAlphaUnchanged_Flag) == 0; 1717} 1718 1719void OpenGLRenderer::setupDrawBlending(const Layer* layer, bool swapSrcDst) { 1720 SkXfermode::Mode mode = layer->getMode(); 1721 // When the blending mode is kClear_Mode, we need to use a modulate color 1722 // argb=1,0,0,0 1723 accountForClear(mode); 1724 // TODO: check shader blending, once we have shader drawing support for layers. 1725 bool blend = layer->isBlend() || getLayerAlpha(layer) < 1.0f || 1726 (mColorSet && mColorA < 1.0f) || isBlendedColorFilter(layer->getColorFilter()); 1727 chooseBlending(blend, mode, mDescription, swapSrcDst); 1728} 1729 1730void OpenGLRenderer::setupDrawBlending(const SkPaint* paint, bool blend, bool swapSrcDst) { 1731 SkXfermode::Mode mode = getXfermodeDirect(paint); 1732 // When the blending mode is kClear_Mode, we need to use a modulate color 1733 // argb=1,0,0,0 1734 accountForClear(mode); 1735 blend |= (mColorSet && mColorA < 1.0f) || 1736 (getShader(paint) && !getShader(paint)->isOpaque()) || 1737 isBlendedColorFilter(getColorFilter(paint)); 1738 chooseBlending(blend, mode, mDescription, swapSrcDst); 1739} 1740 1741void OpenGLRenderer::setupDrawProgram() { 1742 useProgram(mCaches.programCache.get(mDescription)); 1743 if (mDescription.hasRoundRectClip) { 1744 // TODO: avoid doing this repeatedly, stashing state pointer in program 1745 const RoundRectClipState* state = mSnapshot->roundRectClipState; 1746 const Rect& innerRect = state->innerRect; 1747 glUniform4f(mCaches.currentProgram->getUniform("roundRectInnerRectLTRB"), 1748 innerRect.left, innerRect.top, 1749 innerRect.right, innerRect.bottom); 1750 glUniform1f(mCaches.currentProgram->getUniform("roundRectRadius"), 1751 state->radius); 1752 glUniformMatrix4fv(mCaches.currentProgram->getUniform("roundRectInvTransform"), 1753 1, GL_FALSE, &state->matrix.data[0]); 1754 } 1755} 1756 1757void OpenGLRenderer::setupDrawDirtyRegionsDisabled() { 1758 mTrackDirtyRegions = false; 1759} 1760 1761void OpenGLRenderer::setupDrawModelView(ModelViewMode mode, bool offset, 1762 float left, float top, float right, float bottom, bool ignoreTransform) { 1763 mModelViewMatrix.loadTranslate(left, top, 0.0f); 1764 if (mode == kModelViewMode_TranslateAndScale) { 1765 mModelViewMatrix.scale(right - left, bottom - top, 1.0f); 1766 } 1767 1768 bool dirty = right - left > 0.0f && bottom - top > 0.0f; 1769 const Matrix4& transformMatrix = ignoreTransform ? Matrix4::identity() : *currentTransform(); 1770 mCaches.currentProgram->set(mSnapshot->getOrthoMatrix(), mModelViewMatrix, transformMatrix, offset); 1771 if (dirty && mTrackDirtyRegions) { 1772 if (!ignoreTransform) { 1773 dirtyLayer(left, top, right, bottom, *currentTransform()); 1774 } else { 1775 dirtyLayer(left, top, right, bottom); 1776 } 1777 } 1778} 1779 1780void OpenGLRenderer::setupDrawColorUniforms(bool hasShader) { 1781 if ((mColorSet && !hasShader) || (hasShader && mSetShaderColor)) { 1782 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1783 } 1784} 1785 1786void OpenGLRenderer::setupDrawPureColorUniforms() { 1787 if (mSetShaderColor) { 1788 mCaches.currentProgram->setColor(mColorR, mColorG, mColorB, mColorA); 1789 } 1790} 1791 1792void OpenGLRenderer::setupDrawShaderUniforms(const SkShader* shader, bool ignoreTransform) { 1793 if (shader == NULL) { 1794 return; 1795 } 1796 1797 if (ignoreTransform) { 1798 // if ignoreTransform=true was passed to setupDrawModelView, undo currentTransform() 1799 // because it was built into modelView / the geometry, and the description needs to 1800 // compensate. 1801 mat4 modelViewWithoutTransform; 1802 modelViewWithoutTransform.loadInverse(*currentTransform()); 1803 modelViewWithoutTransform.multiply(mModelViewMatrix); 1804 mModelViewMatrix.load(modelViewWithoutTransform); 1805 } 1806 1807 SkiaShader::setupProgram(&mCaches, mModelViewMatrix, &mTextureUnit, mExtensions, *shader); 1808} 1809 1810void OpenGLRenderer::setupDrawColorFilterUniforms(const SkColorFilter* filter) { 1811 if (NULL == filter) { 1812 return; 1813 } 1814 1815 SkColor color; 1816 SkXfermode::Mode mode; 1817 if (filter->asColorMode(&color, &mode)) { 1818 const int alpha = SkColorGetA(color); 1819 const GLfloat a = alpha / 255.0f; 1820 const GLfloat r = a * SkColorGetR(color) / 255.0f; 1821 const GLfloat g = a * SkColorGetG(color) / 255.0f; 1822 const GLfloat b = a * SkColorGetB(color) / 255.0f; 1823 glUniform4f(mCaches.currentProgram->getUniform("colorBlend"), r, g, b, a); 1824 return; 1825 } 1826 1827 SkScalar srcColorMatrix[20]; 1828 if (filter->asColorMatrix(srcColorMatrix)) { 1829 1830 float colorMatrix[16]; 1831 memcpy(colorMatrix, srcColorMatrix, 4 * sizeof(float)); 1832 memcpy(&colorMatrix[4], &srcColorMatrix[5], 4 * sizeof(float)); 1833 memcpy(&colorMatrix[8], &srcColorMatrix[10], 4 * sizeof(float)); 1834 memcpy(&colorMatrix[12], &srcColorMatrix[15], 4 * sizeof(float)); 1835 1836 // Skia uses the range [0..255] for the addition vector, but we need 1837 // the [0..1] range to apply the vector in GLSL 1838 float colorVector[4]; 1839 colorVector[0] = srcColorMatrix[4] / 255.0f; 1840 colorVector[1] = srcColorMatrix[9] / 255.0f; 1841 colorVector[2] = srcColorMatrix[14] / 255.0f; 1842 colorVector[3] = srcColorMatrix[19] / 255.0f; 1843 1844 glUniformMatrix4fv(mCaches.currentProgram->getUniform("colorMatrix"), 1, 1845 GL_FALSE, colorMatrix); 1846 glUniform4fv(mCaches.currentProgram->getUniform("colorMatrixVector"), 1, colorVector); 1847 return; 1848 } 1849 1850 // it is an error if we ever get here 1851} 1852 1853void OpenGLRenderer::setupDrawTextGammaUniforms() { 1854 mCaches.fontRenderer->setupProgram(mDescription, mCaches.currentProgram); 1855} 1856 1857void OpenGLRenderer::setupDrawSimpleMesh() { 1858 bool force = mCaches.bindMeshBuffer(); 1859 mCaches.bindPositionVertexPointer(force, 0); 1860 mCaches.unbindIndicesBuffer(); 1861} 1862 1863void OpenGLRenderer::setupDrawTexture(GLuint texture) { 1864 if (texture) bindTexture(texture); 1865 mTextureUnit++; 1866 mCaches.enableTexCoordsVertexArray(); 1867} 1868 1869void OpenGLRenderer::setupDrawExternalTexture(GLuint texture) { 1870 bindExternalTexture(texture); 1871 mTextureUnit++; 1872 mCaches.enableTexCoordsVertexArray(); 1873} 1874 1875void OpenGLRenderer::setupDrawTextureTransform() { 1876 mDescription.hasTextureTransform = true; 1877} 1878 1879void OpenGLRenderer::setupDrawTextureTransformUniforms(mat4& transform) { 1880 glUniformMatrix4fv(mCaches.currentProgram->getUniform("mainTextureTransform"), 1, 1881 GL_FALSE, &transform.data[0]); 1882} 1883 1884void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices, 1885 const GLvoid* texCoords, GLuint vbo) { 1886 bool force = false; 1887 if (!vertices || vbo) { 1888 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1889 } else { 1890 force = mCaches.unbindMeshBuffer(); 1891 } 1892 1893 mCaches.bindPositionVertexPointer(force, vertices); 1894 if (mCaches.currentProgram->texCoords >= 0) { 1895 mCaches.bindTexCoordsVertexPointer(force, texCoords); 1896 } 1897 1898 mCaches.unbindIndicesBuffer(); 1899} 1900 1901void OpenGLRenderer::setupDrawMesh(const GLvoid* vertices, 1902 const GLvoid* texCoords, const GLvoid* colors) { 1903 bool force = mCaches.unbindMeshBuffer(); 1904 GLsizei stride = sizeof(ColorTextureVertex); 1905 1906 mCaches.bindPositionVertexPointer(force, vertices, stride); 1907 if (mCaches.currentProgram->texCoords >= 0) { 1908 mCaches.bindTexCoordsVertexPointer(force, texCoords, stride); 1909 } 1910 int slot = mCaches.currentProgram->getAttrib("colors"); 1911 if (slot >= 0) { 1912 glEnableVertexAttribArray(slot); 1913 glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors); 1914 } 1915 1916 mCaches.unbindIndicesBuffer(); 1917} 1918 1919void OpenGLRenderer::setupDrawMeshIndices(const GLvoid* vertices, 1920 const GLvoid* texCoords, GLuint vbo) { 1921 bool force = false; 1922 // If vbo is != 0 we want to treat the vertices parameter as an offset inside 1923 // a VBO. However, if vertices is set to NULL and vbo == 0 then we want to 1924 // use the default VBO found in Caches 1925 if (!vertices || vbo) { 1926 force = mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1927 } else { 1928 force = mCaches.unbindMeshBuffer(); 1929 } 1930 mCaches.bindQuadIndicesBuffer(); 1931 1932 mCaches.bindPositionVertexPointer(force, vertices); 1933 if (mCaches.currentProgram->texCoords >= 0) { 1934 mCaches.bindTexCoordsVertexPointer(force, texCoords); 1935 } 1936} 1937 1938void OpenGLRenderer::setupDrawIndexedVertices(GLvoid* vertices) { 1939 bool force = mCaches.unbindMeshBuffer(); 1940 mCaches.bindQuadIndicesBuffer(); 1941 mCaches.bindPositionVertexPointer(force, vertices, gVertexStride); 1942} 1943 1944/////////////////////////////////////////////////////////////////////////////// 1945// Drawing 1946/////////////////////////////////////////////////////////////////////////////// 1947 1948status_t OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) { 1949 status_t status; 1950 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1951 // will be performed by the display list itself 1952 if (renderNode && renderNode->isRenderable()) { 1953 // compute 3d ordering 1954 renderNode->computeOrdering(); 1955 if (CC_UNLIKELY(mCaches.drawDeferDisabled)) { 1956 status = startFrame(); 1957 ReplayStateStruct replayStruct(*this, dirty, replayFlags); 1958 renderNode->replay(replayStruct, 0); 1959 return status | replayStruct.mDrawGlStatus; 1960 } 1961 1962 bool avoidOverdraw = !mCaches.debugOverdraw && !mCountOverdraw; // shh, don't tell devs! 1963 DeferredDisplayList deferredList(*currentClipRect(), avoidOverdraw); 1964 DeferStateStruct deferStruct(deferredList, *this, replayFlags); 1965 renderNode->defer(deferStruct, 0); 1966 1967 flushLayers(); 1968 status = startFrame(); 1969 1970 return deferredList.flush(*this, dirty) | status; 1971 } 1972 1973 // Even if there is no drawing command(Ex: invisible), 1974 // it still needs startFrame to clear buffer and start tiling. 1975 return startFrame(); 1976} 1977 1978void OpenGLRenderer::drawAlphaBitmap(Texture* texture, float left, float top, const SkPaint* paint) { 1979 int color = paint != NULL ? paint->getColor() : 0; 1980 1981 float x = left; 1982 float y = top; 1983 1984 texture->setWrap(GL_CLAMP_TO_EDGE, true); 1985 1986 bool ignoreTransform = false; 1987 if (currentTransform()->isPureTranslate()) { 1988 x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 1989 y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 1990 ignoreTransform = true; 1991 1992 texture->setFilter(GL_NEAREST, true); 1993 } else { 1994 texture->setFilter(getFilter(paint), true); 1995 } 1996 1997 // No need to check for a UV mapper on the texture object, only ARGB_8888 1998 // bitmaps get packed in the atlas 1999 drawAlpha8TextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 2000 paint, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, 2001 GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform); 2002} 2003 2004/** 2005 * Important note: this method is intended to draw batches of bitmaps and 2006 * will not set the scissor enable or dirty the current layer, if any. 2007 * The caller is responsible for properly dirtying the current layer. 2008 */ 2009status_t OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 2010 int bitmapCount, TextureVertex* vertices, bool pureTranslate, 2011 const Rect& bounds, const SkPaint* paint) { 2012 mCaches.activeTexture(0); 2013 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2014 if (!texture) return DrawGlInfo::kStatusDone; 2015 2016 const AutoTexture autoCleanup(texture); 2017 2018 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2019 texture->setFilter(pureTranslate ? GL_NEAREST : getFilter(paint), true); 2020 2021 const float x = (int) floorf(bounds.left + 0.5f); 2022 const float y = (int) floorf(bounds.top + 0.5f); 2023 if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) { 2024 drawAlpha8TextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(), 2025 texture->id, paint, &vertices[0].x, &vertices[0].u, 2026 GL_TRIANGLES, bitmapCount * 6, true, 2027 kModelViewMode_Translate, false); 2028 } else { 2029 drawTextureMesh(x, y, x + bounds.getWidth(), y + bounds.getHeight(), 2030 texture->id, paint, texture->blend, &vertices[0].x, &vertices[0].u, 2031 GL_TRIANGLES, bitmapCount * 6, false, true, 0, 2032 kModelViewMode_Translate, false); 2033 } 2034 2035 return DrawGlInfo::kStatusDrew; 2036} 2037 2038status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) { 2039 if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) { 2040 return DrawGlInfo::kStatusDone; 2041 } 2042 2043 mCaches.activeTexture(0); 2044 Texture* texture = getTexture(bitmap); 2045 if (!texture) return DrawGlInfo::kStatusDone; 2046 const AutoTexture autoCleanup(texture); 2047 2048 if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) { 2049 drawAlphaBitmap(texture, 0, 0, paint); 2050 } else { 2051 drawTextureRect(0, 0, bitmap->width(), bitmap->height(), texture, paint); 2052 } 2053 2054 return DrawGlInfo::kStatusDrew; 2055} 2056 2057status_t OpenGLRenderer::drawBitmapData(const SkBitmap* bitmap, const SkPaint* paint) { 2058 if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) { 2059 return DrawGlInfo::kStatusDone; 2060 } 2061 2062 mCaches.activeTexture(0); 2063 Texture* texture = mCaches.textureCache.getTransient(bitmap); 2064 const AutoTexture autoCleanup(texture); 2065 2066 if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) { 2067 drawAlphaBitmap(texture, 0, 0, paint); 2068 } else { 2069 drawTextureRect(0, 0, bitmap->width(), bitmap->height(), texture, paint); 2070 } 2071 2072 return DrawGlInfo::kStatusDrew; 2073} 2074 2075status_t OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight, 2076 const float* vertices, const int* colors, const SkPaint* paint) { 2077 if (!vertices || currentSnapshot()->isIgnored()) { 2078 return DrawGlInfo::kStatusDone; 2079 } 2080 2081 // TODO: use quickReject on bounds from vertices 2082 mCaches.enableScissor(); 2083 2084 float left = FLT_MAX; 2085 float top = FLT_MAX; 2086 float right = FLT_MIN; 2087 float bottom = FLT_MIN; 2088 2089 const uint32_t count = meshWidth * meshHeight * 6; 2090 2091 Vector<ColorTextureVertex> mesh; // TODO: use C++11 unique_ptr 2092 mesh.setCapacity(count); 2093 ColorTextureVertex* vertex = mesh.editArray(); 2094 2095 bool cleanupColors = false; 2096 if (!colors) { 2097 uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1); 2098 int* newColors = new int[colorsCount]; 2099 memset(newColors, 0xff, colorsCount * sizeof(int)); 2100 colors = newColors; 2101 cleanupColors = true; 2102 } 2103 2104 mCaches.activeTexture(0); 2105 Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap); 2106 const UvMapper& mapper(getMapper(texture)); 2107 2108 for (int32_t y = 0; y < meshHeight; y++) { 2109 for (int32_t x = 0; x < meshWidth; x++) { 2110 uint32_t i = (y * (meshWidth + 1) + x) * 2; 2111 2112 float u1 = float(x) / meshWidth; 2113 float u2 = float(x + 1) / meshWidth; 2114 float v1 = float(y) / meshHeight; 2115 float v2 = float(y + 1) / meshHeight; 2116 2117 mapper.map(u1, v1, u2, v2); 2118 2119 int ax = i + (meshWidth + 1) * 2; 2120 int ay = ax + 1; 2121 int bx = i; 2122 int by = bx + 1; 2123 int cx = i + 2; 2124 int cy = cx + 1; 2125 int dx = i + (meshWidth + 1) * 2 + 2; 2126 int dy = dx + 1; 2127 2128 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 2129 ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]); 2130 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 2131 2132 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 2133 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 2134 ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]); 2135 2136 left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx]))); 2137 top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy]))); 2138 right = fmaxf(right, fmaxf(vertices[ax], fmaxf(vertices[bx], vertices[cx]))); 2139 bottom = fmaxf(bottom, fmaxf(vertices[ay], fmaxf(vertices[by], vertices[cy]))); 2140 } 2141 } 2142 2143 if (quickRejectSetupScissor(left, top, right, bottom)) { 2144 if (cleanupColors) delete[] colors; 2145 return DrawGlInfo::kStatusDone; 2146 } 2147 2148 if (!texture) { 2149 texture = mCaches.textureCache.get(bitmap); 2150 if (!texture) { 2151 if (cleanupColors) delete[] colors; 2152 return DrawGlInfo::kStatusDone; 2153 } 2154 } 2155 const AutoTexture autoCleanup(texture); 2156 2157 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2158 texture->setFilter(getFilter(paint), true); 2159 2160 int alpha; 2161 SkXfermode::Mode mode; 2162 getAlphaAndMode(paint, &alpha, &mode); 2163 2164 float a = alpha / 255.0f; 2165 2166 if (hasLayer()) { 2167 dirtyLayer(left, top, right, bottom, *currentTransform()); 2168 } 2169 2170 setupDraw(); 2171 setupDrawWithTextureAndColor(); 2172 setupDrawColor(a, a, a, a); 2173 setupDrawColorFilter(getColorFilter(paint)); 2174 setupDrawBlending(paint, true); 2175 setupDrawProgram(); 2176 setupDrawDirtyRegionsDisabled(); 2177 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 0.0f, 0.0f, 1.0f, 1.0f); 2178 setupDrawTexture(texture->id); 2179 setupDrawPureColorUniforms(); 2180 setupDrawColorFilterUniforms(getColorFilter(paint)); 2181 setupDrawMesh(&mesh[0].x, &mesh[0].u, &mesh[0].r); 2182 2183 glDrawArrays(GL_TRIANGLES, 0, count); 2184 2185 int slot = mCaches.currentProgram->getAttrib("colors"); 2186 if (slot >= 0) { 2187 glDisableVertexAttribArray(slot); 2188 } 2189 2190 if (cleanupColors) delete[] colors; 2191 2192 return DrawGlInfo::kStatusDrew; 2193} 2194 2195status_t OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, 2196 float srcLeft, float srcTop, float srcRight, float srcBottom, 2197 float dstLeft, float dstTop, float dstRight, float dstBottom, 2198 const SkPaint* paint) { 2199 if (quickRejectSetupScissor(dstLeft, dstTop, dstRight, dstBottom)) { 2200 return DrawGlInfo::kStatusDone; 2201 } 2202 2203 mCaches.activeTexture(0); 2204 Texture* texture = getTexture(bitmap); 2205 if (!texture) return DrawGlInfo::kStatusDone; 2206 const AutoTexture autoCleanup(texture); 2207 2208 const float width = texture->width; 2209 const float height = texture->height; 2210 2211 float u1 = fmax(0.0f, srcLeft / width); 2212 float v1 = fmax(0.0f, srcTop / height); 2213 float u2 = fmin(1.0f, srcRight / width); 2214 float v2 = fmin(1.0f, srcBottom / height); 2215 2216 getMapper(texture).map(u1, v1, u2, v2); 2217 2218 mCaches.unbindMeshBuffer(); 2219 resetDrawTextureTexCoords(u1, v1, u2, v2); 2220 2221 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2222 2223 float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft); 2224 float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop); 2225 2226 bool scaled = scaleX != 1.0f || scaleY != 1.0f; 2227 // Apply a scale transform on the canvas only when a shader is in use 2228 // Skia handles the ratio between the dst and src rects as a scale factor 2229 // when a shader is set 2230 bool useScaleTransform = getShader(paint) && scaled; 2231 bool ignoreTransform = false; 2232 2233 if (CC_LIKELY(currentTransform()->isPureTranslate() && !useScaleTransform)) { 2234 float x = (int) floorf(dstLeft + currentTransform()->getTranslateX() + 0.5f); 2235 float y = (int) floorf(dstTop + currentTransform()->getTranslateY() + 0.5f); 2236 2237 dstRight = x + (dstRight - dstLeft); 2238 dstBottom = y + (dstBottom - dstTop); 2239 2240 dstLeft = x; 2241 dstTop = y; 2242 2243 texture->setFilter(scaled ? getFilter(paint) : GL_NEAREST, true); 2244 ignoreTransform = true; 2245 } else { 2246 texture->setFilter(getFilter(paint), true); 2247 } 2248 2249 if (CC_UNLIKELY(useScaleTransform)) { 2250 save(SkCanvas::kMatrix_SaveFlag); 2251 translate(dstLeft, dstTop); 2252 scale(scaleX, scaleY); 2253 2254 dstLeft = 0.0f; 2255 dstTop = 0.0f; 2256 2257 dstRight = srcRight - srcLeft; 2258 dstBottom = srcBottom - srcTop; 2259 } 2260 2261 if (CC_UNLIKELY(bitmap->colorType() == kAlpha_8_SkColorType)) { 2262 drawAlpha8TextureMesh(dstLeft, dstTop, dstRight, dstBottom, 2263 texture->id, paint, 2264 &mMeshVertices[0].x, &mMeshVertices[0].u, 2265 GL_TRIANGLE_STRIP, gMeshCount, ignoreTransform); 2266 } else { 2267 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, 2268 texture->id, paint, texture->blend, 2269 &mMeshVertices[0].x, &mMeshVertices[0].u, 2270 GL_TRIANGLE_STRIP, gMeshCount, false, ignoreTransform); 2271 } 2272 2273 if (CC_UNLIKELY(useScaleTransform)) { 2274 restore(); 2275 } 2276 2277 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 2278 2279 return DrawGlInfo::kStatusDrew; 2280} 2281 2282status_t OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Res_png_9patch* patch, 2283 float left, float top, float right, float bottom, const SkPaint* paint) { 2284 if (quickRejectSetupScissor(left, top, right, bottom)) { 2285 return DrawGlInfo::kStatusDone; 2286 } 2287 2288 AssetAtlas::Entry* entry = mCaches.assetAtlas.getEntry(bitmap); 2289 const Patch* mesh = mCaches.patchCache.get(entry, bitmap->width(), bitmap->height(), 2290 right - left, bottom - top, patch); 2291 2292 return drawPatch(bitmap, mesh, entry, left, top, right, bottom, paint); 2293} 2294 2295status_t OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh, 2296 AssetAtlas::Entry* entry, float left, float top, float right, float bottom, 2297 const SkPaint* paint) { 2298 if (quickRejectSetupScissor(left, top, right, bottom)) { 2299 return DrawGlInfo::kStatusDone; 2300 } 2301 2302 if (CC_LIKELY(mesh && mesh->verticesCount > 0)) { 2303 mCaches.activeTexture(0); 2304 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2305 if (!texture) return DrawGlInfo::kStatusDone; 2306 const AutoTexture autoCleanup(texture); 2307 2308 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2309 texture->setFilter(GL_LINEAR, true); 2310 2311 const bool pureTranslate = currentTransform()->isPureTranslate(); 2312 // Mark the current layer dirty where we are going to draw the patch 2313 if (hasLayer() && mesh->hasEmptyQuads) { 2314 const float offsetX = left + currentTransform()->getTranslateX(); 2315 const float offsetY = top + currentTransform()->getTranslateY(); 2316 const size_t count = mesh->quads.size(); 2317 for (size_t i = 0; i < count; i++) { 2318 const Rect& bounds = mesh->quads.itemAt(i); 2319 if (CC_LIKELY(pureTranslate)) { 2320 const float x = (int) floorf(bounds.left + offsetX + 0.5f); 2321 const float y = (int) floorf(bounds.top + offsetY + 0.5f); 2322 dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight()); 2323 } else { 2324 dirtyLayer(left + bounds.left, top + bounds.top, 2325 left + bounds.right, top + bounds.bottom, *currentTransform()); 2326 } 2327 } 2328 } 2329 2330 bool ignoreTransform = false; 2331 if (CC_LIKELY(pureTranslate)) { 2332 const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 2333 const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 2334 2335 right = x + right - left; 2336 bottom = y + bottom - top; 2337 left = x; 2338 top = y; 2339 ignoreTransform = true; 2340 } 2341 drawIndexedTextureMesh(left, top, right, bottom, texture->id, paint, 2342 texture->blend, (GLvoid*) mesh->offset, (GLvoid*) mesh->textureOffset, 2343 GL_TRIANGLES, mesh->indexCount, false, ignoreTransform, 2344 mCaches.patchCache.getMeshBuffer(), kModelViewMode_Translate, !mesh->hasEmptyQuads); 2345 } 2346 2347 return DrawGlInfo::kStatusDrew; 2348} 2349 2350/** 2351 * Important note: this method is intended to draw batches of 9-patch objects and 2352 * will not set the scissor enable or dirty the current layer, if any. 2353 * The caller is responsible for properly dirtying the current layer. 2354 */ 2355status_t OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 2356 TextureVertex* vertices, uint32_t indexCount, const SkPaint* paint) { 2357 mCaches.activeTexture(0); 2358 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 2359 if (!texture) return DrawGlInfo::kStatusDone; 2360 const AutoTexture autoCleanup(texture); 2361 2362 texture->setWrap(GL_CLAMP_TO_EDGE, true); 2363 texture->setFilter(GL_LINEAR, true); 2364 2365 drawIndexedTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, paint, 2366 texture->blend, &vertices[0].x, &vertices[0].u, 2367 GL_TRIANGLES, indexCount, false, true, 0, kModelViewMode_Translate, false); 2368 2369 return DrawGlInfo::kStatusDrew; 2370} 2371 2372status_t OpenGLRenderer::drawVertexBuffer(float translateX, float translateY, 2373 const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) { 2374 // not missing call to quickReject/dirtyLayer, always done at a higher level 2375 if (!vertexBuffer.getVertexCount()) { 2376 // no vertices to draw 2377 return DrawGlInfo::kStatusDone; 2378 } 2379 2380 Rect bounds(vertexBuffer.getBounds()); 2381 bounds.translate(translateX, translateY); 2382 dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform()); 2383 2384 int color = paint->getColor(); 2385 bool isAA = paint->isAntiAlias(); 2386 2387 setupDraw(); 2388 setupDrawNoTexture(); 2389 if (isAA) setupDrawVertexAlpha((displayFlags & kVertexBuffer_ShadowInterp)); 2390 setupDrawColor(color, ((color >> 24) & 0xFF) * mSnapshot->alpha); 2391 setupDrawColorFilter(getColorFilter(paint)); 2392 setupDrawShader(getShader(paint)); 2393 setupDrawBlending(paint, isAA); 2394 setupDrawProgram(); 2395 setupDrawModelView(kModelViewMode_Translate, (displayFlags & kVertexBuffer_Offset), 2396 translateX, translateY, 0, 0); 2397 setupDrawColorUniforms(getShader(paint)); 2398 setupDrawColorFilterUniforms(getColorFilter(paint)); 2399 setupDrawShaderUniforms(getShader(paint)); 2400 2401 const void* vertices = vertexBuffer.getBuffer(); 2402 bool force = mCaches.unbindMeshBuffer(); 2403 mCaches.bindPositionVertexPointer(true, vertices, isAA ? gAlphaVertexStride : gVertexStride); 2404 mCaches.resetTexCoordsVertexPointer(); 2405 2406 int alphaSlot = -1; 2407 if (isAA) { 2408 void* alphaCoords = ((GLbyte*) vertices) + gVertexAlphaOffset; 2409 alphaSlot = mCaches.currentProgram->getAttrib("vtxAlpha"); 2410 // TODO: avoid enable/disable in back to back uses of the alpha attribute 2411 glEnableVertexAttribArray(alphaSlot); 2412 glVertexAttribPointer(alphaSlot, 1, GL_FLOAT, GL_FALSE, gAlphaVertexStride, alphaCoords); 2413 } 2414 2415 const VertexBuffer::Mode mode = vertexBuffer.getMode(); 2416 if (mode == VertexBuffer::kStandard) { 2417 mCaches.unbindIndicesBuffer(); 2418 glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexBuffer.getVertexCount()); 2419 } else if (mode == VertexBuffer::kOnePolyRingShadow) { 2420 mCaches.bindShadowIndicesBuffer(); 2421 glDrawElements(GL_TRIANGLE_STRIP, ONE_POLY_RING_SHADOW_INDEX_COUNT, GL_UNSIGNED_SHORT, 0); 2422 } else if (mode == VertexBuffer::kTwoPolyRingShadow) { 2423 mCaches.bindShadowIndicesBuffer(); 2424 glDrawElements(GL_TRIANGLE_STRIP, TWO_POLY_RING_SHADOW_INDEX_COUNT, GL_UNSIGNED_SHORT, 0); 2425 } else if (mode == VertexBuffer::kIndices) { 2426 mCaches.unbindIndicesBuffer(); 2427 glDrawElements(GL_TRIANGLE_STRIP, vertexBuffer.getIndexCount(), GL_UNSIGNED_SHORT, 2428 vertexBuffer.getIndices()); 2429 } 2430 2431 if (isAA) { 2432 glDisableVertexAttribArray(alphaSlot); 2433 } 2434 2435 return DrawGlInfo::kStatusDrew; 2436} 2437 2438/** 2439 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to 2440 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in 2441 * screen space in all directions. However, instead of using a fragment shader to compute the 2442 * translucency of the color from its position, we simply use a varying parameter to define how far 2443 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used. 2444 * 2445 * Doesn't yet support joins, caps, or path effects. 2446 */ 2447status_t OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) { 2448 VertexBuffer vertexBuffer; 2449 // TODO: try clipping large paths to viewport 2450 PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer); 2451 return drawVertexBuffer(vertexBuffer, paint); 2452} 2453 2454/** 2455 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha 2456 * and additional geometry for defining an alpha slope perimeter. 2457 * 2458 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some 2459 * unexpected results, and may vary between hardware devices. Previously we used a varying-base 2460 * in-shader alpha region, but found it to be taxing on some GPUs. 2461 * 2462 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce 2463 * memory transfer by removing need for degenerate vertices. 2464 */ 2465status_t OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) { 2466 if (currentSnapshot()->isIgnored() || count < 4) return DrawGlInfo::kStatusDone; 2467 2468 count &= ~0x3; // round down to nearest four 2469 2470 VertexBuffer buffer; 2471 PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer); 2472 const Rect& bounds = buffer.getBounds(); 2473 2474 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) { 2475 return DrawGlInfo::kStatusDone; 2476 } 2477 2478 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset; 2479 return drawVertexBuffer(buffer, paint, displayFlags); 2480} 2481 2482status_t OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) { 2483 if (currentSnapshot()->isIgnored() || count < 2) return DrawGlInfo::kStatusDone; 2484 2485 count &= ~0x1; // round down to nearest two 2486 2487 VertexBuffer buffer; 2488 PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer); 2489 2490 const Rect& bounds = buffer.getBounds(); 2491 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) { 2492 return DrawGlInfo::kStatusDone; 2493 } 2494 2495 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset; 2496 return drawVertexBuffer(buffer, paint, displayFlags); 2497} 2498 2499status_t OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 2500 // No need to check against the clip, we fill the clip region 2501 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 2502 2503 Rect clip(*currentClipRect()); 2504 clip.snapToPixelBoundaries(); 2505 2506 SkPaint paint; 2507 paint.setColor(color); 2508 paint.setXfermodeMode(mode); 2509 2510 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true); 2511 2512 return DrawGlInfo::kStatusDrew; 2513} 2514 2515status_t OpenGLRenderer::drawShape(float left, float top, const PathTexture* texture, 2516 const SkPaint* paint) { 2517 if (!texture) return DrawGlInfo::kStatusDone; 2518 const AutoTexture autoCleanup(texture); 2519 2520 const float x = left + texture->left - texture->offset; 2521 const float y = top + texture->top - texture->offset; 2522 2523 drawPathTexture(texture, x, y, paint); 2524 2525 return DrawGlInfo::kStatusDrew; 2526} 2527 2528status_t OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 2529 float rx, float ry, const SkPaint* p) { 2530 if (currentSnapshot()->isIgnored() 2531 || quickRejectSetupScissor(left, top, right, bottom, p) 2532 || paintWillNotDraw(*p)) { 2533 return DrawGlInfo::kStatusDone; 2534 } 2535 2536 if (p->getPathEffect() != 0) { 2537 mCaches.activeTexture(0); 2538 const PathTexture* texture = mCaches.pathCache.getRoundRect( 2539 right - left, bottom - top, rx, ry, p); 2540 return drawShape(left, top, texture, p); 2541 } 2542 2543 const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect( 2544 *currentTransform(), *p, right - left, bottom - top, rx, ry); 2545 return drawVertexBuffer(left, top, *vertexBuffer, p); 2546} 2547 2548status_t OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) { 2549 if (currentSnapshot()->isIgnored() 2550 || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p) 2551 || paintWillNotDraw(*p)) { 2552 return DrawGlInfo::kStatusDone; 2553 } 2554 if (p->getPathEffect() != 0) { 2555 mCaches.activeTexture(0); 2556 const PathTexture* texture = mCaches.pathCache.getCircle(radius, p); 2557 return drawShape(x - radius, y - radius, texture, p); 2558 } 2559 2560 SkPath path; 2561 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2562 path.addCircle(x, y, radius + p->getStrokeWidth() / 2); 2563 } else { 2564 path.addCircle(x, y, radius); 2565 } 2566 return drawConvexPath(path, p); 2567} 2568 2569status_t OpenGLRenderer::drawOval(float left, float top, float right, float bottom, 2570 const SkPaint* p) { 2571 if (currentSnapshot()->isIgnored() 2572 || quickRejectSetupScissor(left, top, right, bottom, p) 2573 || paintWillNotDraw(*p)) { 2574 return DrawGlInfo::kStatusDone; 2575 } 2576 2577 if (p->getPathEffect() != 0) { 2578 mCaches.activeTexture(0); 2579 const PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p); 2580 return drawShape(left, top, texture, p); 2581 } 2582 2583 SkPath path; 2584 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2585 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2586 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2587 } 2588 path.addOval(rect); 2589 return drawConvexPath(path, p); 2590} 2591 2592status_t OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 2593 float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) { 2594 if (currentSnapshot()->isIgnored() 2595 || quickRejectSetupScissor(left, top, right, bottom, p) 2596 || paintWillNotDraw(*p)) { 2597 return DrawGlInfo::kStatusDone; 2598 } 2599 2600 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180) 2601 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != 0 || useCenter) { 2602 mCaches.activeTexture(0); 2603 const PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top, 2604 startAngle, sweepAngle, useCenter, p); 2605 return drawShape(left, top, texture, p); 2606 } 2607 2608 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2609 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2610 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2611 } 2612 2613 SkPath path; 2614 if (useCenter) { 2615 path.moveTo(rect.centerX(), rect.centerY()); 2616 } 2617 path.arcTo(rect, startAngle, sweepAngle, !useCenter); 2618 if (useCenter) { 2619 path.close(); 2620 } 2621 return drawConvexPath(path, p); 2622} 2623 2624// See SkPaintDefaults.h 2625#define SkPaintDefaults_MiterLimit SkIntToScalar(4) 2626 2627status_t OpenGLRenderer::drawRect(float left, float top, float right, float bottom, 2628 const SkPaint* p) { 2629 if (currentSnapshot()->isIgnored() 2630 || quickRejectSetupScissor(left, top, right, bottom, p) 2631 || paintWillNotDraw(*p)) { 2632 return DrawGlInfo::kStatusDone; 2633 } 2634 2635 if (p->getStyle() != SkPaint::kFill_Style) { 2636 // only fill style is supported by drawConvexPath, since others have to handle joins 2637 if (p->getPathEffect() != 0 || p->getStrokeJoin() != SkPaint::kMiter_Join || 2638 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) { 2639 mCaches.activeTexture(0); 2640 const PathTexture* texture = 2641 mCaches.pathCache.getRect(right - left, bottom - top, p); 2642 return drawShape(left, top, texture, p); 2643 } 2644 2645 SkPath path; 2646 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 2647 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 2648 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 2649 } 2650 path.addRect(rect); 2651 return drawConvexPath(path, p); 2652 } 2653 2654 if (p->isAntiAlias() && !currentTransform()->isSimple()) { 2655 SkPath path; 2656 path.addRect(left, top, right, bottom); 2657 return drawConvexPath(path, p); 2658 } else { 2659 drawColorRect(left, top, right, bottom, p); 2660 return DrawGlInfo::kStatusDrew; 2661 } 2662} 2663 2664void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text, 2665 int bytesCount, int count, const float* positions, 2666 FontRenderer& fontRenderer, int alpha, float x, float y) { 2667 mCaches.activeTexture(0); 2668 2669 TextShadow textShadow; 2670 if (!getTextShadow(paint, &textShadow)) { 2671 LOG_ALWAYS_FATAL("failed to query shadow attributes"); 2672 } 2673 2674 // NOTE: The drop shadow will not perform gamma correction 2675 // if shader-based correction is enabled 2676 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 2677 const ShadowTexture* shadow = mCaches.dropShadowCache.get( 2678 paint, text, bytesCount, count, textShadow.radius, positions); 2679 // If the drop shadow exceeds the max texture size or couldn't be 2680 // allocated, skip drawing 2681 if (!shadow) return; 2682 const AutoTexture autoCleanup(shadow); 2683 2684 const float sx = x - shadow->left + textShadow.dx; 2685 const float sy = y - shadow->top + textShadow.dy; 2686 2687 const int shadowAlpha = ((textShadow.color >> 24) & 0xFF) * mSnapshot->alpha; 2688 if (getShader(paint)) { 2689 textShadow.color = SK_ColorWHITE; 2690 } 2691 2692 setupDraw(); 2693 setupDrawWithTexture(true); 2694 setupDrawAlpha8Color(textShadow.color, shadowAlpha < 255 ? shadowAlpha : alpha); 2695 setupDrawColorFilter(getColorFilter(paint)); 2696 setupDrawShader(getShader(paint)); 2697 setupDrawBlending(paint, true); 2698 setupDrawProgram(); 2699 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 2700 sx, sy, sx + shadow->width, sy + shadow->height); 2701 setupDrawTexture(shadow->id); 2702 setupDrawPureColorUniforms(); 2703 setupDrawColorFilterUniforms(getColorFilter(paint)); 2704 setupDrawShaderUniforms(getShader(paint)); 2705 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 2706 2707 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 2708} 2709 2710bool OpenGLRenderer::canSkipText(const SkPaint* paint) const { 2711 float alpha = (hasTextShadow(paint) ? 1.0f : paint->getAlpha()) * mSnapshot->alpha; 2712 return alpha == 0.0f && getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode; 2713} 2714 2715status_t OpenGLRenderer::drawPosText(const char* text, int bytesCount, int count, 2716 const float* positions, const SkPaint* paint) { 2717 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint)) { 2718 return DrawGlInfo::kStatusDone; 2719 } 2720 2721 // NOTE: Skia does not support perspective transform on drawPosText yet 2722 if (!currentTransform()->isSimple()) { 2723 return DrawGlInfo::kStatusDone; 2724 } 2725 2726 mCaches.enableScissor(); 2727 2728 float x = 0.0f; 2729 float y = 0.0f; 2730 const bool pureTranslate = currentTransform()->isPureTranslate(); 2731 if (pureTranslate) { 2732 x = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f); 2733 y = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f); 2734 } 2735 2736 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2737 fontRenderer.setFont(paint, SkMatrix::I()); 2738 2739 int alpha; 2740 SkXfermode::Mode mode; 2741 getAlphaAndMode(paint, &alpha, &mode); 2742 2743 if (CC_UNLIKELY(hasTextShadow(paint))) { 2744 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2745 alpha, 0.0f, 0.0f); 2746 } 2747 2748 // Pick the appropriate texture filtering 2749 bool linearFilter = currentTransform()->changesBounds(); 2750 if (pureTranslate && !linearFilter) { 2751 linearFilter = fabs(y - (int) y) > 0.0f || fabs(x - (int) x) > 0.0f; 2752 } 2753 fontRenderer.setTextureFiltering(linearFilter); 2754 2755 const Rect* clip = pureTranslate ? mSnapshot->clipRect : &mSnapshot->getLocalClip(); 2756 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2757 2758 const bool hasActiveLayer = hasLayer(); 2759 2760 TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2761 if (fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2762 positions, hasActiveLayer ? &bounds : NULL, &functor)) { 2763 if (hasActiveLayer) { 2764 if (!pureTranslate) { 2765 currentTransform()->mapRect(bounds); 2766 } 2767 dirtyLayerUnchecked(bounds, getRegion()); 2768 } 2769 } 2770 2771 return DrawGlInfo::kStatusDrew; 2772} 2773 2774bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const { 2775 if (CC_LIKELY(transform.isPureTranslate())) { 2776 outMatrix->setIdentity(); 2777 return false; 2778 } else if (CC_UNLIKELY(transform.isPerspective())) { 2779 outMatrix->setIdentity(); 2780 return true; 2781 } 2782 2783 /** 2784 * Input is a non-perspective, scaling transform. Generate a scale-only transform, 2785 * with values rounded to the nearest int. 2786 */ 2787 float sx, sy; 2788 transform.decomposeScale(sx, sy); 2789 outMatrix->setScale( 2790 roundf(fmaxf(1.0f, sx)), 2791 roundf(fmaxf(1.0f, sy))); 2792 return true; 2793} 2794 2795status_t OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y, 2796 const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds, 2797 DrawOpMode drawOpMode) { 2798 2799 if (drawOpMode == kDrawOpMode_Immediate) { 2800 // The checks for corner-case ignorable text and quick rejection is only done for immediate 2801 // drawing as ops from DeferredDisplayList are already filtered for these 2802 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint) || 2803 quickRejectSetupScissor(bounds)) { 2804 return DrawGlInfo::kStatusDone; 2805 } 2806 } 2807 2808 const float oldX = x; 2809 const float oldY = y; 2810 2811 const mat4& transform = *currentTransform(); 2812 const bool pureTranslate = transform.isPureTranslate(); 2813 2814 if (CC_LIKELY(pureTranslate)) { 2815 x = (int) floorf(x + transform.getTranslateX() + 0.5f); 2816 y = (int) floorf(y + transform.getTranslateY() + 0.5f); 2817 } 2818 2819 int alpha; 2820 SkXfermode::Mode mode; 2821 getAlphaAndMode(paint, &alpha, &mode); 2822 2823 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2824 2825 if (CC_UNLIKELY(hasTextShadow(paint))) { 2826 fontRenderer.setFont(paint, SkMatrix::I()); 2827 drawTextShadow(paint, text, bytesCount, count, positions, fontRenderer, 2828 alpha, oldX, oldY); 2829 } 2830 2831 const bool hasActiveLayer = hasLayer(); 2832 2833 // We only pass a partial transform to the font renderer. That partial 2834 // matrix defines how glyphs are rasterized. Typically we want glyphs 2835 // to be rasterized at their final size on screen, which means the partial 2836 // matrix needs to take the scale factor into account. 2837 // When a partial matrix is used to transform glyphs during rasterization, 2838 // the mesh is generated with the inverse transform (in the case of scale, 2839 // the mesh is generated at 1.0 / scale for instance.) This allows us to 2840 // apply the full transform matrix at draw time in the vertex shader. 2841 // Applying the full matrix in the shader is the easiest way to handle 2842 // rotation and perspective and allows us to always generated quads in the 2843 // font renderer which greatly simplifies the code, clipping in particular. 2844 SkMatrix fontTransform; 2845 bool linearFilter = findBestFontTransform(transform, &fontTransform) 2846 || fabs(y - (int) y) > 0.0f 2847 || fabs(x - (int) x) > 0.0f; 2848 fontRenderer.setFont(paint, fontTransform); 2849 fontRenderer.setTextureFiltering(linearFilter); 2850 2851 // TODO: Implement better clipping for scaled/rotated text 2852 const Rect* clip = !pureTranslate ? NULL : currentClipRect(); 2853 Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2854 2855 bool status; 2856 TextSetupFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2857 2858 // don't call issuedrawcommand, do it at end of batch 2859 bool forceFinish = (drawOpMode != kDrawOpMode_Defer); 2860 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) { 2861 SkPaint paintCopy(*paint); 2862 paintCopy.setTextAlign(SkPaint::kLeft_Align); 2863 status = fontRenderer.renderPosText(&paintCopy, clip, text, 0, bytesCount, count, x, y, 2864 positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish); 2865 } else { 2866 status = fontRenderer.renderPosText(paint, clip, text, 0, bytesCount, count, x, y, 2867 positions, hasActiveLayer ? &layerBounds : NULL, &functor, forceFinish); 2868 } 2869 2870 if ((status || drawOpMode != kDrawOpMode_Immediate) && hasActiveLayer) { 2871 if (!pureTranslate) { 2872 transform.mapRect(layerBounds); 2873 } 2874 dirtyLayerUnchecked(layerBounds, getRegion()); 2875 } 2876 2877 drawTextDecorations(totalAdvance, oldX, oldY, paint); 2878 2879 return DrawGlInfo::kStatusDrew; 2880} 2881 2882status_t OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, 2883 const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) { 2884 if (text == NULL || count == 0 || currentSnapshot()->isIgnored() || canSkipText(paint)) { 2885 return DrawGlInfo::kStatusDone; 2886 } 2887 2888 // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics 2889 mCaches.enableScissor(); 2890 2891 FontRenderer& fontRenderer = mCaches.fontRenderer->getFontRenderer(paint); 2892 fontRenderer.setFont(paint, SkMatrix::I()); 2893 fontRenderer.setTextureFiltering(true); 2894 2895 int alpha; 2896 SkXfermode::Mode mode; 2897 getAlphaAndMode(paint, &alpha, &mode); 2898 TextSetupFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint); 2899 2900 const Rect* clip = &mSnapshot->getLocalClip(); 2901 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2902 2903 const bool hasActiveLayer = hasLayer(); 2904 2905 if (fontRenderer.renderTextOnPath(paint, clip, text, 0, bytesCount, count, path, 2906 hOffset, vOffset, hasActiveLayer ? &bounds : NULL, &functor)) { 2907 if (hasActiveLayer) { 2908 currentTransform()->mapRect(bounds); 2909 dirtyLayerUnchecked(bounds, getRegion()); 2910 } 2911 } 2912 2913 return DrawGlInfo::kStatusDrew; 2914} 2915 2916status_t OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) { 2917 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 2918 2919 mCaches.activeTexture(0); 2920 2921 const PathTexture* texture = mCaches.pathCache.get(path, paint); 2922 if (!texture) return DrawGlInfo::kStatusDone; 2923 const AutoTexture autoCleanup(texture); 2924 2925 const float x = texture->left - texture->offset; 2926 const float y = texture->top - texture->offset; 2927 2928 drawPathTexture(texture, x, y, paint); 2929 2930 return DrawGlInfo::kStatusDrew; 2931} 2932 2933status_t OpenGLRenderer::drawLayer(Layer* layer, float x, float y) { 2934 if (!layer) { 2935 return DrawGlInfo::kStatusDone; 2936 } 2937 2938 mat4* transform = NULL; 2939 if (layer->isTextureLayer()) { 2940 transform = &layer->getTransform(); 2941 if (!transform->isIdentity()) { 2942 save(SkCanvas::kMatrix_SaveFlag); 2943 concatMatrix(*transform); 2944 } 2945 } 2946 2947 bool clipRequired = false; 2948 const bool rejected = calculateQuickRejectForScissor(x, y, 2949 x + layer->layer.getWidth(), y + layer->layer.getHeight(), &clipRequired, NULL, false); 2950 2951 if (rejected) { 2952 if (transform && !transform->isIdentity()) { 2953 restore(); 2954 } 2955 return DrawGlInfo::kStatusDone; 2956 } 2957 2958 EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y, 2959 x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired); 2960 2961 updateLayer(layer, true); 2962 2963 mCaches.setScissorEnabled(mScissorOptimizationDisabled || clipRequired); 2964 mCaches.activeTexture(0); 2965 2966 if (CC_LIKELY(!layer->region.isEmpty())) { 2967 if (layer->region.isRect()) { 2968 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 2969 composeLayerRect(layer, layer->regionRect)); 2970 } else if (layer->mesh) { 2971 2972 const float a = getLayerAlpha(layer); 2973 setupDraw(); 2974 setupDrawWithTexture(); 2975 setupDrawColor(a, a, a, a); 2976 setupDrawColorFilter(layer->getColorFilter()); 2977 setupDrawBlending(layer); 2978 setupDrawProgram(); 2979 setupDrawPureColorUniforms(); 2980 setupDrawColorFilterUniforms(layer->getColorFilter()); 2981 setupDrawTexture(layer->getTexture()); 2982 if (CC_LIKELY(currentTransform()->isPureTranslate())) { 2983 int tx = (int) floorf(x + currentTransform()->getTranslateX() + 0.5f); 2984 int ty = (int) floorf(y + currentTransform()->getTranslateY() + 0.5f); 2985 2986 layer->setFilter(GL_NEAREST); 2987 setupDrawModelView(kModelViewMode_Translate, false, tx, ty, 2988 tx + layer->layer.getWidth(), ty + layer->layer.getHeight(), true); 2989 } else { 2990 layer->setFilter(GL_LINEAR); 2991 setupDrawModelView(kModelViewMode_Translate, false, x, y, 2992 x + layer->layer.getWidth(), y + layer->layer.getHeight()); 2993 } 2994 2995 TextureVertex* mesh = &layer->mesh[0]; 2996 GLsizei elementsCount = layer->meshElementCount; 2997 2998 while (elementsCount > 0) { 2999 GLsizei drawCount = min(elementsCount, (GLsizei) gMaxNumberOfQuads * 6); 3000 3001 setupDrawMeshIndices(&mesh[0].x, &mesh[0].u); 3002 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 3003 glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_SHORT, NULL)); 3004 3005 elementsCount -= drawCount; 3006 // Though there are 4 vertices in a quad, we use 6 indices per 3007 // quad to draw with GL_TRIANGLES 3008 mesh += (drawCount / 6) * 4; 3009 } 3010 3011#if DEBUG_LAYERS_AS_REGIONS 3012 drawRegionRectsDebug(layer->region); 3013#endif 3014 } 3015 3016 if (layer->debugDrawUpdate) { 3017 layer->debugDrawUpdate = false; 3018 3019 SkPaint paint; 3020 paint.setColor(0x7f00ff00); 3021 drawColorRect(x, y, x + layer->layer.getWidth(), y + layer->layer.getHeight(), &paint); 3022 } 3023 } 3024 layer->hasDrawnSinceUpdate = true; 3025 3026 if (transform && !transform->isIdentity()) { 3027 restore(); 3028 } 3029 3030 return DrawGlInfo::kStatusDrew; 3031} 3032 3033/////////////////////////////////////////////////////////////////////////////// 3034// Draw filters 3035/////////////////////////////////////////////////////////////////////////////// 3036 3037void OpenGLRenderer::resetPaintFilter() { 3038 // when clearing the PaintFilter, the masks should also be cleared for simple DrawModifier 3039 // comparison, see MergingDrawBatch::canMergeWith 3040 mDrawModifiers.mHasDrawFilter = false; 3041 mDrawModifiers.mPaintFilterClearBits = 0; 3042 mDrawModifiers.mPaintFilterSetBits = 0; 3043} 3044 3045void OpenGLRenderer::setupPaintFilter(int clearBits, int setBits) { 3046 // TODO: don't bother with boolean, it's redundant with clear/set bits 3047 mDrawModifiers.mHasDrawFilter = true; 3048 mDrawModifiers.mPaintFilterClearBits = clearBits & SkPaint::kAllFlags; 3049 mDrawModifiers.mPaintFilterSetBits = setBits & SkPaint::kAllFlags; 3050} 3051 3052const SkPaint* OpenGLRenderer::filterPaint(const SkPaint* paint) { 3053 // TODO: use CompatFlagsDrawFilter here, and combine logic with android/graphics/DrawFilter.cpp 3054 // to avoid clobbering 0x02 paint flag 3055 3056 // Equivalent to the Java Paint's FILTER_BITMAP_FLAG. 3057 static const uint32_t sFilterBitmapFlag = 0x02; 3058 3059 if (CC_LIKELY(!mDrawModifiers.mHasDrawFilter || !paint)) { 3060 return paint; 3061 } 3062 3063 const uint32_t clearBits = mDrawModifiers.mPaintFilterClearBits; 3064 const uint32_t setBits = mDrawModifiers.mPaintFilterSetBits; 3065 3066 const uint32_t flags = (paint->getFlags() & ~clearBits) | setBits; 3067 mFilteredPaint = *paint; 3068 mFilteredPaint.setFlags(flags); 3069 3070 // check if paint filter trying to override bitmap filter 3071 if ((clearBits | setBits) & sFilterBitmapFlag) { 3072 mFilteredPaint.setFilterLevel(flags & sFilterBitmapFlag 3073 ? SkPaint::kLow_FilterLevel : SkPaint::kNone_FilterLevel); 3074 } 3075 3076 return &mFilteredPaint; 3077} 3078 3079/////////////////////////////////////////////////////////////////////////////// 3080// Drawing implementation 3081/////////////////////////////////////////////////////////////////////////////// 3082 3083Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) { 3084 Texture* texture = mCaches.assetAtlas.getEntryTexture(bitmap); 3085 if (!texture) { 3086 return mCaches.textureCache.get(bitmap); 3087 } 3088 return texture; 3089} 3090 3091void OpenGLRenderer::drawPathTexture(const PathTexture* texture, 3092 float x, float y, const SkPaint* paint) { 3093 if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) { 3094 return; 3095 } 3096 3097 int alpha; 3098 SkXfermode::Mode mode; 3099 getAlphaAndMode(paint, &alpha, &mode); 3100 3101 setupDraw(); 3102 setupDrawWithTexture(true); 3103 setupDrawAlpha8Color(paint->getColor(), alpha); 3104 setupDrawColorFilter(getColorFilter(paint)); 3105 setupDrawShader(getShader(paint)); 3106 setupDrawBlending(paint, true); 3107 setupDrawProgram(); 3108 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 3109 x, y, x + texture->width, y + texture->height); 3110 setupDrawTexture(texture->id); 3111 setupDrawPureColorUniforms(); 3112 setupDrawColorFilterUniforms(getColorFilter(paint)); 3113 setupDrawShaderUniforms(getShader(paint)); 3114 setupDrawMesh(NULL, (GLvoid*) gMeshTextureOffset); 3115 3116 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 3117} 3118 3119// Same values used by Skia 3120#define kStdStrikeThru_Offset (-6.0f / 21.0f) 3121#define kStdUnderline_Offset (1.0f / 9.0f) 3122#define kStdUnderline_Thickness (1.0f / 18.0f) 3123 3124void OpenGLRenderer::drawTextDecorations(float underlineWidth, float x, float y, 3125 const SkPaint* paint) { 3126 // Handle underline and strike-through 3127 uint32_t flags = paint->getFlags(); 3128 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 3129 SkPaint paintCopy(*paint); 3130 3131 if (CC_LIKELY(underlineWidth > 0.0f)) { 3132 const float textSize = paintCopy.getTextSize(); 3133 const float strokeWidth = fmax(textSize * kStdUnderline_Thickness, 1.0f); 3134 3135 const float left = x; 3136 float top = 0.0f; 3137 3138 int linesCount = 0; 3139 if (flags & SkPaint::kUnderlineText_Flag) linesCount++; 3140 if (flags & SkPaint::kStrikeThruText_Flag) linesCount++; 3141 3142 const int pointsCount = 4 * linesCount; 3143 float points[pointsCount]; 3144 int currentPoint = 0; 3145 3146 if (flags & SkPaint::kUnderlineText_Flag) { 3147 top = y + textSize * kStdUnderline_Offset; 3148 points[currentPoint++] = left; 3149 points[currentPoint++] = top; 3150 points[currentPoint++] = left + underlineWidth; 3151 points[currentPoint++] = top; 3152 } 3153 3154 if (flags & SkPaint::kStrikeThruText_Flag) { 3155 top = y + textSize * kStdStrikeThru_Offset; 3156 points[currentPoint++] = left; 3157 points[currentPoint++] = top; 3158 points[currentPoint++] = left + underlineWidth; 3159 points[currentPoint++] = top; 3160 } 3161 3162 paintCopy.setStrokeWidth(strokeWidth); 3163 3164 drawLines(&points[0], pointsCount, &paintCopy); 3165 } 3166 } 3167} 3168 3169status_t OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) { 3170 if (currentSnapshot()->isIgnored()) { 3171 return DrawGlInfo::kStatusDone; 3172 } 3173 3174 return drawColorRects(rects, count, paint, false, true, true); 3175} 3176 3177static void mapPointFakeZ(Vector3& point, const mat4& transformXY, const mat4& transformZ) { 3178 // map z coordinate with true 3d matrix 3179 point.z = transformZ.mapZ(point); 3180 3181 // map x,y coordinates with draw/Skia matrix 3182 transformXY.mapPoint(point.x, point.y); 3183} 3184 3185status_t OpenGLRenderer::drawShadow(float casterAlpha, 3186 const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) { 3187 if (currentSnapshot()->isIgnored()) return DrawGlInfo::kStatusDone; 3188 3189 // TODO: use quickRejectWithScissor. For now, always force enable scissor. 3190 mCaches.enableScissor(); 3191 3192 SkPaint paint; 3193 paint.setAntiAlias(true); // want to use AlphaVertex 3194 3195 // The caller has made sure casterAlpha > 0. 3196 float ambientShadowAlpha = mAmbientShadowAlpha; 3197 if (CC_UNLIKELY(mCaches.propertyAmbientShadowStrength >= 0)) { 3198 ambientShadowAlpha = mCaches.propertyAmbientShadowStrength; 3199 } 3200 if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) { 3201 paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0); 3202 drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp); 3203 } 3204 3205 float spotShadowAlpha = mSpotShadowAlpha; 3206 if (CC_UNLIKELY(mCaches.propertySpotShadowStrength >= 0)) { 3207 spotShadowAlpha = mCaches.propertySpotShadowStrength; 3208 } 3209 if (spotShadowVertexBuffer && spotShadowAlpha > 0) { 3210 paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0); 3211 drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp); 3212 } 3213 3214 return DrawGlInfo::kStatusDrew; 3215} 3216 3217status_t OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint, 3218 bool ignoreTransform, bool dirty, bool clip) { 3219 if (count == 0) { 3220 return DrawGlInfo::kStatusDone; 3221 } 3222 3223 int color = paint->getColor(); 3224 // If a shader is set, preserve only the alpha 3225 if (getShader(paint)) { 3226 color |= 0x00ffffff; 3227 } 3228 3229 float left = FLT_MAX; 3230 float top = FLT_MAX; 3231 float right = FLT_MIN; 3232 float bottom = FLT_MIN; 3233 3234 Vertex mesh[count]; 3235 Vertex* vertex = mesh; 3236 3237 for (int index = 0; index < count; index += 4) { 3238 float l = rects[index + 0]; 3239 float t = rects[index + 1]; 3240 float r = rects[index + 2]; 3241 float b = rects[index + 3]; 3242 3243 Vertex::set(vertex++, l, t); 3244 Vertex::set(vertex++, r, t); 3245 Vertex::set(vertex++, l, b); 3246 Vertex::set(vertex++, r, b); 3247 3248 left = fminf(left, l); 3249 top = fminf(top, t); 3250 right = fmaxf(right, r); 3251 bottom = fmaxf(bottom, b); 3252 } 3253 3254 if (clip && quickRejectSetupScissor(left, top, right, bottom)) { 3255 return DrawGlInfo::kStatusDone; 3256 } 3257 3258 setupDraw(); 3259 setupDrawNoTexture(); 3260 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 3261 setupDrawShader(getShader(paint)); 3262 setupDrawColorFilter(getColorFilter(paint)); 3263 setupDrawBlending(paint); 3264 setupDrawProgram(); 3265 setupDrawDirtyRegionsDisabled(); 3266 setupDrawModelView(kModelViewMode_Translate, false, 3267 0.0f, 0.0f, 0.0f, 0.0f, ignoreTransform); 3268 setupDrawColorUniforms(getShader(paint)); 3269 setupDrawShaderUniforms(getShader(paint)); 3270 setupDrawColorFilterUniforms(getColorFilter(paint)); 3271 3272 if (dirty && hasLayer()) { 3273 dirtyLayer(left, top, right, bottom, *currentTransform()); 3274 } 3275 3276 issueIndexedQuadDraw(&mesh[0], count / 4); 3277 3278 return DrawGlInfo::kStatusDrew; 3279} 3280 3281void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 3282 const SkPaint* paint, bool ignoreTransform) { 3283 int color = paint->getColor(); 3284 // If a shader is set, preserve only the alpha 3285 if (getShader(paint)) { 3286 color |= 0x00ffffff; 3287 } 3288 3289 setupDraw(); 3290 setupDrawNoTexture(); 3291 setupDrawColor(color, ((color >> 24) & 0xFF) * currentSnapshot()->alpha); 3292 setupDrawShader(getShader(paint)); 3293 setupDrawColorFilter(getColorFilter(paint)); 3294 setupDrawBlending(paint); 3295 setupDrawProgram(); 3296 setupDrawModelView(kModelViewMode_TranslateAndScale, false, 3297 left, top, right, bottom, ignoreTransform); 3298 setupDrawColorUniforms(getShader(paint)); 3299 setupDrawShaderUniforms(getShader(paint), ignoreTransform); 3300 setupDrawColorFilterUniforms(getColorFilter(paint)); 3301 setupDrawSimpleMesh(); 3302 3303 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 3304} 3305 3306void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 3307 Texture* texture, const SkPaint* paint) { 3308 texture->setWrap(GL_CLAMP_TO_EDGE, true); 3309 3310 GLvoid* vertices = (GLvoid*) NULL; 3311 GLvoid* texCoords = (GLvoid*) gMeshTextureOffset; 3312 3313 if (texture->uvMapper) { 3314 vertices = &mMeshVertices[0].x; 3315 texCoords = &mMeshVertices[0].u; 3316 3317 Rect uvs(0.0f, 0.0f, 1.0f, 1.0f); 3318 texture->uvMapper->map(uvs); 3319 3320 resetDrawTextureTexCoords(uvs.left, uvs.top, uvs.right, uvs.bottom); 3321 } 3322 3323 if (CC_LIKELY(currentTransform()->isPureTranslate())) { 3324 const float x = (int) floorf(left + currentTransform()->getTranslateX() + 0.5f); 3325 const float y = (int) floorf(top + currentTransform()->getTranslateY() + 0.5f); 3326 3327 texture->setFilter(GL_NEAREST, true); 3328 drawTextureMesh(x, y, x + texture->width, y + texture->height, texture->id, 3329 paint, texture->blend, vertices, texCoords, 3330 GL_TRIANGLE_STRIP, gMeshCount, false, true); 3331 } else { 3332 texture->setFilter(getFilter(paint), true); 3333 drawTextureMesh(left, top, right, bottom, texture->id, paint, 3334 texture->blend, vertices, texCoords, GL_TRIANGLE_STRIP, gMeshCount); 3335 } 3336 3337 if (texture->uvMapper) { 3338 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 3339 } 3340} 3341 3342void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 3343 GLuint texture, const SkPaint* paint, bool blend, 3344 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3345 bool swapSrcDst, bool ignoreTransform, GLuint vbo, 3346 ModelViewMode modelViewMode, bool dirty) { 3347 3348 int a; 3349 SkXfermode::Mode mode; 3350 getAlphaAndMode(paint, &a, &mode); 3351 const float alpha = a / 255.0f; 3352 3353 setupDraw(); 3354 setupDrawWithTexture(); 3355 setupDrawColor(alpha, alpha, alpha, alpha); 3356 setupDrawColorFilter(getColorFilter(paint)); 3357 setupDrawBlending(paint, blend, swapSrcDst); 3358 setupDrawProgram(); 3359 if (!dirty) setupDrawDirtyRegionsDisabled(); 3360 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3361 setupDrawTexture(texture); 3362 setupDrawPureColorUniforms(); 3363 setupDrawColorFilterUniforms(getColorFilter(paint)); 3364 setupDrawMesh(vertices, texCoords, vbo); 3365 3366 glDrawArrays(drawMode, 0, elementsCount); 3367} 3368 3369void OpenGLRenderer::drawIndexedTextureMesh(float left, float top, float right, float bottom, 3370 GLuint texture, const SkPaint* paint, bool blend, 3371 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3372 bool swapSrcDst, bool ignoreTransform, GLuint vbo, 3373 ModelViewMode modelViewMode, bool dirty) { 3374 3375 int a; 3376 SkXfermode::Mode mode; 3377 getAlphaAndMode(paint, &a, &mode); 3378 const float alpha = a / 255.0f; 3379 3380 setupDraw(); 3381 setupDrawWithTexture(); 3382 setupDrawColor(alpha, alpha, alpha, alpha); 3383 setupDrawColorFilter(getColorFilter(paint)); 3384 setupDrawBlending(paint, blend, swapSrcDst); 3385 setupDrawProgram(); 3386 if (!dirty) setupDrawDirtyRegionsDisabled(); 3387 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3388 setupDrawTexture(texture); 3389 setupDrawPureColorUniforms(); 3390 setupDrawColorFilterUniforms(getColorFilter(paint)); 3391 setupDrawMeshIndices(vertices, texCoords, vbo); 3392 3393 glDrawElements(drawMode, elementsCount, GL_UNSIGNED_SHORT, NULL); 3394} 3395 3396void OpenGLRenderer::drawAlpha8TextureMesh(float left, float top, float right, float bottom, 3397 GLuint texture, const SkPaint* paint, 3398 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 3399 bool ignoreTransform, ModelViewMode modelViewMode, bool dirty) { 3400 3401 int color = paint != NULL ? paint->getColor() : 0; 3402 int alpha; 3403 SkXfermode::Mode mode; 3404 getAlphaAndMode(paint, &alpha, &mode); 3405 3406 setupDraw(); 3407 setupDrawWithTexture(true); 3408 if (paint != NULL) { 3409 setupDrawAlpha8Color(color, alpha); 3410 } 3411 setupDrawColorFilter(getColorFilter(paint)); 3412 setupDrawShader(getShader(paint)); 3413 setupDrawBlending(paint, true); 3414 setupDrawProgram(); 3415 if (!dirty) setupDrawDirtyRegionsDisabled(); 3416 setupDrawModelView(modelViewMode, false, left, top, right, bottom, ignoreTransform); 3417 setupDrawTexture(texture); 3418 setupDrawPureColorUniforms(); 3419 setupDrawColorFilterUniforms(getColorFilter(paint)); 3420 setupDrawShaderUniforms(getShader(paint), ignoreTransform); 3421 setupDrawMesh(vertices, texCoords); 3422 3423 glDrawArrays(drawMode, 0, elementsCount); 3424} 3425 3426void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 3427 ProgramDescription& description, bool swapSrcDst) { 3428 3429 if (mSnapshot->roundRectClipState != NULL /*&& !mSkipOutlineClip*/) { 3430 blend = true; 3431 mDescription.hasRoundRectClip = true; 3432 } 3433 mSkipOutlineClip = true; 3434 3435 if (mCountOverdraw) { 3436 if (!mCaches.blend) glEnable(GL_BLEND); 3437 if (mCaches.lastSrcMode != GL_ONE || mCaches.lastDstMode != GL_ONE) { 3438 glBlendFunc(GL_ONE, GL_ONE); 3439 } 3440 3441 mCaches.blend = true; 3442 mCaches.lastSrcMode = GL_ONE; 3443 mCaches.lastDstMode = GL_ONE; 3444 3445 return; 3446 } 3447 3448 blend = blend || mode != SkXfermode::kSrcOver_Mode; 3449 3450 if (blend) { 3451 // These blend modes are not supported by OpenGL directly and have 3452 // to be implemented using shaders. Since the shader will perform 3453 // the blending, turn blending off here 3454 // If the blend mode cannot be implemented using shaders, fall 3455 // back to the default SrcOver blend mode instead 3456 if (CC_UNLIKELY(mode > SkXfermode::kScreen_Mode)) { 3457 if (CC_UNLIKELY(mExtensions.hasFramebufferFetch())) { 3458 description.framebufferMode = mode; 3459 description.swapSrcDst = swapSrcDst; 3460 3461 if (mCaches.blend) { 3462 glDisable(GL_BLEND); 3463 mCaches.blend = false; 3464 } 3465 3466 return; 3467 } else { 3468 mode = SkXfermode::kSrcOver_Mode; 3469 } 3470 } 3471 3472 if (!mCaches.blend) { 3473 glEnable(GL_BLEND); 3474 } 3475 3476 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 3477 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 3478 3479 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 3480 glBlendFunc(sourceMode, destMode); 3481 mCaches.lastSrcMode = sourceMode; 3482 mCaches.lastDstMode = destMode; 3483 } 3484 } else if (mCaches.blend) { 3485 glDisable(GL_BLEND); 3486 } 3487 mCaches.blend = blend; 3488} 3489 3490bool OpenGLRenderer::useProgram(Program* program) { 3491 if (!program->isInUse()) { 3492 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 3493 program->use(); 3494 mCaches.currentProgram = program; 3495 return false; 3496 } 3497 return true; 3498} 3499 3500void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 3501 TextureVertex* v = &mMeshVertices[0]; 3502 TextureVertex::setUV(v++, u1, v1); 3503 TextureVertex::setUV(v++, u2, v1); 3504 TextureVertex::setUV(v++, u1, v2); 3505 TextureVertex::setUV(v++, u2, v2); 3506} 3507 3508void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) const { 3509 getAlphaAndModeDirect(paint, alpha, mode); 3510 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) { 3511 // if drawing a layer, ignore the paint's alpha 3512 *alpha = mDrawModifiers.mOverrideLayerAlpha * 255; 3513 } 3514 *alpha *= currentSnapshot()->alpha; 3515} 3516 3517float OpenGLRenderer::getLayerAlpha(const Layer* layer) const { 3518 float alpha; 3519 if (mDrawModifiers.mOverrideLayerAlpha < 1.0f) { 3520 alpha = mDrawModifiers.mOverrideLayerAlpha; 3521 } else { 3522 alpha = layer->getAlpha() / 255.0f; 3523 } 3524 return alpha * currentSnapshot()->alpha; 3525} 3526 3527}; // namespace uirenderer 3528}; // namespace android 3529