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