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