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