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