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