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