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