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