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