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