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