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