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