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