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