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