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