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