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