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