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