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