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