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