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