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