OpenGLRenderer.cpp revision 5ec9924d24495822b589f1a17996655d66273b30
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define LOG_TAG "OpenGLRenderer" 18 19#include <stdlib.h> 20#include <stdint.h> 21#include <sys/types.h> 22 23#include <SkCanvas.h> 24#include <SkTypeface.h> 25 26#include <utils/Log.h> 27#include <utils/StopWatch.h> 28 29#include <ui/Rect.h> 30 31#include "OpenGLRenderer.h" 32 33namespace android { 34namespace uirenderer { 35 36/////////////////////////////////////////////////////////////////////////////// 37// Defines 38/////////////////////////////////////////////////////////////////////////////// 39 40#define RAD_TO_DEG (180.0f / 3.14159265f) 41#define MIN_ANGLE 0.001f 42 43// TODO: This should be set in properties 44#define ALPHA_THRESHOLD (0x7f / PANEL_BIT_DEPTH) 45 46/////////////////////////////////////////////////////////////////////////////// 47// Globals 48/////////////////////////////////////////////////////////////////////////////// 49 50/** 51 * Structure mapping Skia xfermodes to OpenGL blending factors. 52 */ 53struct Blender { 54 SkXfermode::Mode mode; 55 GLenum src; 56 GLenum dst; 57}; // struct Blender 58 59// In this array, the index of each Blender equals the value of the first 60// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode] 61static const Blender gBlends[] = { 62 { SkXfermode::kClear_Mode, GL_ZERO, GL_ZERO }, 63 { SkXfermode::kSrc_Mode, GL_ONE, GL_ZERO }, 64 { SkXfermode::kDst_Mode, GL_ZERO, GL_ONE }, 65 { SkXfermode::kSrcOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 66 { SkXfermode::kDstOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 67 { SkXfermode::kSrcIn_Mode, GL_DST_ALPHA, GL_ZERO }, 68 { SkXfermode::kDstIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 69 { SkXfermode::kSrcOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 70 { SkXfermode::kDstOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 71 { SkXfermode::kSrcATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 72 { SkXfermode::kDstATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 73 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA } 74}; 75 76// This array contains the swapped version of each SkXfermode. For instance 77// this array's SrcOver blending mode is actually DstOver. You can refer to 78// createLayer() for more information on the purpose of this array. 79static const Blender gBlendsSwap[] = { 80 { SkXfermode::kClear_Mode, GL_ZERO, GL_ZERO }, 81 { SkXfermode::kSrc_Mode, GL_ZERO, GL_ONE }, 82 { SkXfermode::kDst_Mode, GL_ONE, GL_ZERO }, 83 { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 84 { SkXfermode::kDstOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 85 { SkXfermode::kSrcIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 86 { SkXfermode::kDstIn_Mode, GL_DST_ALPHA, GL_ZERO }, 87 { SkXfermode::kSrcOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 88 { SkXfermode::kDstOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 89 { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 90 { SkXfermode::kDstATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 91 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA } 92}; 93 94static const GLenum gTextureUnits[] = { 95 GL_TEXTURE0, 96 GL_TEXTURE1, 97 GL_TEXTURE2 98}; 99 100/////////////////////////////////////////////////////////////////////////////// 101// Constructors/destructor 102/////////////////////////////////////////////////////////////////////////////// 103 104OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) { 105 mShader = NULL; 106 mColorFilter = NULL; 107 mHasShadow = false; 108 109 memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices)); 110 111 mFirstSnapshot = new Snapshot; 112} 113 114OpenGLRenderer::~OpenGLRenderer() { 115 // The context has already been destroyed at this point, do not call 116 // GL APIs. All GL state should be kept in Caches.h 117} 118 119/////////////////////////////////////////////////////////////////////////////// 120// Setup 121/////////////////////////////////////////////////////////////////////////////// 122 123void OpenGLRenderer::setViewport(int width, int height) { 124 glViewport(0, 0, width, height); 125 mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1); 126 127 mWidth = width; 128 mHeight = height; 129 130 mFirstSnapshot->height = height; 131 mFirstSnapshot->viewport.set(0, 0, width, height); 132 133 mDirtyClip = false; 134} 135 136void OpenGLRenderer::prepare(bool opaque) { 137 mSnapshot = new Snapshot(mFirstSnapshot, 138 SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag); 139 mSaveCount = 1; 140 141 glViewport(0, 0, mWidth, mHeight); 142 143 glDisable(GL_DITHER); 144 145 if (!opaque) { 146 glDisable(GL_SCISSOR_TEST); 147 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 148 glClear(GL_COLOR_BUFFER_BIT); 149 glEnable(GL_SCISSOR_TEST); 150 } else { 151 glEnable(GL_SCISSOR_TEST); 152 glScissor(0, 0, mWidth, mHeight); 153 dirtyClip(); 154 } 155 156 mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight); 157} 158 159void OpenGLRenderer::finish() { 160#if DEBUG_OPENGL 161 GLenum status = GL_NO_ERROR; 162 while ((status = glGetError()) != GL_NO_ERROR) { 163 LOGD("GL error from OpenGLRenderer: 0x%x", status); 164 } 165#endif 166} 167 168void OpenGLRenderer::acquireContext() { 169 if (mCaches.currentProgram) { 170 if (mCaches.currentProgram->isInUse()) { 171 mCaches.currentProgram->remove(); 172 mCaches.currentProgram = NULL; 173 } 174 } 175 mCaches.unbindMeshBuffer(); 176} 177 178void OpenGLRenderer::releaseContext() { 179 glViewport(0, 0, mSnapshot->viewport.getWidth(), mSnapshot->viewport.getHeight()); 180 181 glEnable(GL_SCISSOR_TEST); 182 dirtyClip(); 183 184 glDisable(GL_DITHER); 185 186 glBindFramebuffer(GL_FRAMEBUFFER, 0); 187 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); 188 189 mCaches.blend = true; 190 glEnable(GL_BLEND); 191 glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode); 192 glBlendEquation(GL_FUNC_ADD); 193} 194 195/////////////////////////////////////////////////////////////////////////////// 196// State management 197/////////////////////////////////////////////////////////////////////////////// 198 199int OpenGLRenderer::getSaveCount() const { 200 return mSaveCount; 201} 202 203int OpenGLRenderer::save(int flags) { 204 return saveSnapshot(flags); 205} 206 207void OpenGLRenderer::restore() { 208 if (mSaveCount > 1) { 209 restoreSnapshot(); 210 } 211} 212 213void OpenGLRenderer::restoreToCount(int saveCount) { 214 if (saveCount < 1) saveCount = 1; 215 216 while (mSaveCount > saveCount) { 217 restoreSnapshot(); 218 } 219} 220 221int OpenGLRenderer::saveSnapshot(int flags) { 222 mSnapshot = new Snapshot(mSnapshot, flags); 223 return mSaveCount++; 224} 225 226bool OpenGLRenderer::restoreSnapshot() { 227 bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet; 228 bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer; 229 bool restoreOrtho = mSnapshot->flags & Snapshot::kFlagDirtyOrtho; 230 231 sp<Snapshot> current = mSnapshot; 232 sp<Snapshot> previous = mSnapshot->previous; 233 234 if (restoreOrtho) { 235 Rect& r = previous->viewport; 236 glViewport(r.left, r.top, r.right, r.bottom); 237 mOrthoMatrix.load(current->orthoMatrix); 238 } 239 240 mSaveCount--; 241 mSnapshot = previous; 242 243 if (restoreClip) { 244 dirtyClip(); 245 } 246 247 if (restoreLayer) { 248 composeLayer(current, previous); 249 } 250 251 return restoreClip; 252} 253 254/////////////////////////////////////////////////////////////////////////////// 255// Layers 256/////////////////////////////////////////////////////////////////////////////// 257 258int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 259 SkPaint* p, int flags) { 260 const GLuint previousFbo = mSnapshot->fbo; 261 const int count = saveSnapshot(flags); 262 263 int alpha = 255; 264 SkXfermode::Mode mode; 265 266 if (p) { 267 alpha = p->getAlpha(); 268 if (!mCaches.extensions.hasFramebufferFetch()) { 269 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 270 if (!isMode) { 271 // Assume SRC_OVER 272 mode = SkXfermode::kSrcOver_Mode; 273 } 274 } else { 275 mode = getXfermode(p->getXfermode()); 276 } 277 } else { 278 mode = SkXfermode::kSrcOver_Mode; 279 } 280 281 if (!mSnapshot->previous->invisible) { 282 createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags, previousFbo); 283 } 284 285 return count; 286} 287 288int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom, 289 int alpha, int flags) { 290 if (alpha >= 255 - ALPHA_THRESHOLD) { 291 return saveLayer(left, top, right, bottom, NULL, flags); 292 } else { 293 SkPaint paint; 294 paint.setAlpha(alpha); 295 return saveLayer(left, top, right, bottom, &paint, flags); 296 } 297} 298 299/** 300 * Layers are viewed by Skia are slightly different than layers in image editing 301 * programs (for instance.) When a layer is created, previously created layers 302 * and the frame buffer still receive every drawing command. For instance, if a 303 * layer is created and a shape intersecting the bounds of the layers and the 304 * framebuffer is draw, the shape will be drawn on both (unless the layer was 305 * created with the SkCanvas::kClipToLayer_SaveFlag flag.) 306 * 307 * A way to implement layers is to create an FBO for each layer, backed by an RGBA 308 * texture. Unfortunately, this is inefficient as it requires every primitive to 309 * be drawn n + 1 times, where n is the number of active layers. In practice this 310 * means, for every primitive: 311 * - Switch active frame buffer 312 * - Change viewport, clip and projection matrix 313 * - Issue the drawing 314 * 315 * Switching rendering target n + 1 times per drawn primitive is extremely costly. 316 * To avoid this, layers are implemented in a different way here, at least in the 317 * general case. FBOs are used, as an optimization, when the "clip to layer" flag 318 * is set. When this flag is set we can redirect all drawing operations into a 319 * single FBO. 320 * 321 * This implementation relies on the frame buffer being at least RGBA 8888. When 322 * a layer is created, only a texture is created, not an FBO. The content of the 323 * frame buffer contained within the layer's bounds is copied into this texture 324 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame 325 * buffer and drawing continues as normal. This technique therefore treats the 326 * frame buffer as a scratch buffer for the layers. 327 * 328 * To compose the layers back onto the frame buffer, each layer texture 329 * (containing the original frame buffer data) is drawn as a simple quad over 330 * the frame buffer. The trick is that the quad is set as the composition 331 * destination in the blending equation, and the frame buffer becomes the source 332 * of the composition. 333 * 334 * Drawing layers with an alpha value requires an extra step before composition. 335 * An empty quad is drawn over the layer's region in the frame buffer. This quad 336 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the 337 * quad is used to multiply the colors in the frame buffer. This is achieved by 338 * changing the GL blend functions for the GL_FUNC_ADD blend equation to 339 * GL_ZERO, GL_SRC_ALPHA. 340 * 341 * Because glCopyTexImage2D() can be slow, an alternative implementation might 342 * be use to draw a single clipped layer. The implementation described above 343 * is correct in every case. 344 * 345 * (1) The frame buffer is actually not cleared right away. To allow the GPU 346 * to potentially optimize series of calls to glCopyTexImage2D, the frame 347 * buffer is left untouched until the first drawing operation. Only when 348 * something actually gets drawn are the layers regions cleared. 349 */ 350bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top, 351 float right, float bottom, int alpha, SkXfermode::Mode mode, 352 int flags, GLuint previousFbo) { 353 LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top); 354 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize()); 355 356 const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag; 357 358 // Window coordinates of the layer 359 Rect bounds(left, top, right, bottom); 360 if (fboLayer) { 361 // Clear the previous layer regions before we change the viewport 362 clearLayerRegions(); 363 } else { 364 mSnapshot->transform->mapRect(bounds); 365 366 // Layers only make sense if they are in the framebuffer's bounds 367 bounds.intersect(*snapshot->clipRect); 368 369 // We cannot work with sub-pixels in this case 370 bounds.snapToPixelBoundaries(); 371 372 // When the layer is not an FBO, we may use glCopyTexImage so we 373 // need to make sure the layer does not extend outside the bounds 374 // of the framebuffer 375 bounds.intersect(snapshot->previous->viewport); 376 } 377 378 if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize || 379 bounds.getHeight() > mCaches.maxTextureSize) { 380 snapshot->invisible = true; 381 } else { 382 snapshot->invisible = snapshot->previous->invisible || 383 (alpha <= ALPHA_THRESHOLD && fboLayer); 384 } 385 386 // Bail out if we won't draw in this snapshot 387 if (snapshot->invisible) { 388 return false; 389 } 390 391 glActiveTexture(gTextureUnits[0]); 392 Layer* layer = mCaches.layerCache.get(bounds.getWidth(), bounds.getHeight()); 393 if (!layer) { 394 return false; 395 } 396 397 layer->mode = mode; 398 layer->alpha = alpha; 399 layer->layer.set(bounds); 400 layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height), 401 bounds.getWidth() / float(layer->width), 0.0f); 402 403 // Save the layer in the snapshot 404 snapshot->flags |= Snapshot::kFlagIsLayer; 405 snapshot->layer = layer; 406 407 if (fboLayer) { 408 return createFboLayer(layer, bounds, snapshot, previousFbo); 409 } else { 410 // Copy the framebuffer into the layer 411 glBindTexture(GL_TEXTURE_2D, layer->texture); 412 413 if (layer->empty) { 414 glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, 415 snapshot->height - bounds.bottom, layer->width, layer->height, 0); 416 layer->empty = false; 417 } else { 418 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.left, 419 snapshot->height - bounds.bottom, bounds.getWidth(), bounds.getHeight()); 420 } 421 422 // Enqueue the buffer coordinates to clear the corresponding region later 423 mLayers.push(new Rect(bounds)); 424 } 425 426 return true; 427} 428 429bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, sp<Snapshot> snapshot, 430 GLuint previousFbo) { 431 layer->fbo = mCaches.fboCache.get(); 432 433#if RENDER_LAYERS_AS_REGIONS 434 snapshot->region = &snapshot->layer->region; 435 snapshot->flags |= Snapshot::kFlagFboTarget; 436#endif 437 438 Rect clip(bounds); 439 snapshot->transform->mapRect(clip); 440 clip.intersect(*snapshot->clipRect); 441 clip.snapToPixelBoundaries(); 442 clip.intersect(snapshot->previous->viewport); 443 444 mat4 inverse; 445 inverse.loadInverse(*mSnapshot->transform); 446 447 inverse.mapRect(clip); 448 clip.snapToPixelBoundaries(); 449 clip.intersect(bounds); 450 clip.translate(-bounds.left, -bounds.top); 451 452 snapshot->flags |= Snapshot::kFlagIsFboLayer; 453 snapshot->fbo = layer->fbo; 454 snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f); 455 //snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight()); 456 snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom); 457 snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight()); 458 snapshot->height = bounds.getHeight(); 459 snapshot->flags |= Snapshot::kFlagDirtyOrtho; 460 snapshot->orthoMatrix.load(mOrthoMatrix); 461 462 // Bind texture to FBO 463 glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo); 464 glBindTexture(GL_TEXTURE_2D, layer->texture); 465 466 // Initialize the texture if needed 467 if (layer->empty) { 468 layer->empty = false; 469 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->width, layer->height, 0, 470 GL_RGBA, GL_UNSIGNED_BYTE, NULL); 471 } 472 473 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 474 layer->texture, 0); 475 476#if DEBUG_LAYERS_AS_REGIONS 477 GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); 478 if (status != GL_FRAMEBUFFER_COMPLETE) { 479 LOGE("Framebuffer incomplete (GL error code 0x%x)", status); 480 481 glBindFramebuffer(GL_FRAMEBUFFER, previousFbo); 482 glDeleteTextures(1, &layer->texture); 483 mCaches.fboCache.put(layer->fbo); 484 485 delete layer; 486 487 return false; 488 } 489#endif 490 491 // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering 492 glScissor(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f, 493 clip.getWidth() + 2.0f, clip.getHeight() + 2.0f); 494 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 495 glClear(GL_COLOR_BUFFER_BIT); 496 497 dirtyClip(); 498 499 // Change the ortho projection 500 glViewport(0, 0, bounds.getWidth(), bounds.getHeight()); 501 mOrthoMatrix.loadOrtho(0.0f, bounds.getWidth(), bounds.getHeight(), 0.0f, -1.0f, 1.0f); 502 503 return true; 504} 505 506/** 507 * Read the documentation of createLayer() before doing anything in this method. 508 */ 509void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) { 510 if (!current->layer) { 511 LOGE("Attempting to compose a layer that does not exist"); 512 return; 513 } 514 515 const bool fboLayer = current->flags & Snapshot::kFlagIsFboLayer; 516 517 if (fboLayer) { 518 // Unbind current FBO and restore previous one 519 glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo); 520 } 521 522 Layer* layer = current->layer; 523 const Rect& rect = layer->layer; 524 525 if (!fboLayer && layer->alpha < 255) { 526 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, 527 layer->alpha << 24, SkXfermode::kDstIn_Mode, true); 528 // Required below, composeLayerRect() will divide by 255 529 layer->alpha = 255; 530 } 531 532 mCaches.unbindMeshBuffer(); 533 534 glActiveTexture(gTextureUnits[0]); 535 536 // When the layer is stored in an FBO, we can save a bit of fillrate by 537 // drawing only the dirty region 538 if (fboLayer) { 539 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform); 540 composeLayerRegion(layer, rect); 541 } else { 542 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom); 543 composeLayerRect(layer, rect, true); 544 } 545 546 if (fboLayer) { 547 // Detach the texture from the FBO 548 glBindFramebuffer(GL_FRAMEBUFFER, current->fbo); 549 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); 550 glBindFramebuffer(GL_FRAMEBUFFER, previous->fbo); 551 552 // Put the FBO name back in the cache, if it doesn't fit, it will be destroyed 553 mCaches.fboCache.put(current->fbo); 554 } 555 556 dirtyClip(); 557 558 // Failing to add the layer to the cache should happen only if the layer is too large 559 if (!mCaches.layerCache.put(layer)) { 560 LAYER_LOGD("Deleting layer"); 561 glDeleteTextures(1, &layer->texture); 562 delete layer; 563 } 564} 565 566void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect, bool swap) { 567 const Rect& texCoords = layer->texCoords; 568 resetDrawTextureTexCoords(texCoords.left, texCoords.top, texCoords.right, texCoords.bottom); 569 570 drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture, 571 layer->alpha / 255.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0], 572 &mMeshVertices[0].texture[0], GL_TRIANGLE_STRIP, gMeshCount, swap, swap); 573 574 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 575} 576 577void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) { 578#if RENDER_LAYERS_AS_REGIONS 579 if (layer->region.isRect()) { 580 composeLayerRect(layer, rect); 581 layer->region.clear(); 582 return; 583 } 584 585 if (!layer->region.isEmpty()) { 586 size_t count; 587 const android::Rect* rects = layer->region.getArray(&count); 588 589 setupDraw(); 590 591 ProgramDescription description; 592 description.hasTexture = true; 593 594 const float alpha = layer->alpha / 255.0f; 595 const bool setColor = description.setColor(alpha, alpha, alpha, alpha); 596 chooseBlending(layer->blend || layer->alpha < 255, layer->mode, description, false); 597 598 useProgram(mCaches.programCache.get(description)); 599 600 // Texture 601 bindTexture(layer->texture); 602 glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0); 603 604 // Always premultiplied 605 if (setColor) { 606 mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha); 607 } 608 609 // Mesh 610 int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 611 glEnableVertexAttribArray(texCoordsSlot); 612 613 mModelView.loadIdentity(); 614 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 615 616 const float texX = 1.0f / float(layer->width); 617 const float texY = 1.0f / float(layer->height); 618 619 TextureVertex* mesh = mCaches.getRegionMesh(); 620 GLsizei numQuads = 0; 621 622 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 623 gMeshStride, &mesh[0].position[0]); 624 glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, 625 gMeshStride, &mesh[0].texture[0]); 626 627 for (size_t i = 0; i < count; i++) { 628 const android::Rect* r = &rects[i]; 629 630 const float u1 = r->left * texX; 631 const float v1 = (rect.getHeight() - r->top) * texY; 632 const float u2 = r->right * texX; 633 const float v2 = (rect.getHeight() - r->bottom) * texY; 634 635 // TODO: Reject quads outside of the clip 636 TextureVertex::set(mesh++, r->left, r->top, u1, v1); 637 TextureVertex::set(mesh++, r->right, r->top, u2, v1); 638 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2); 639 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2); 640 641 numQuads++; 642 643 if (numQuads >= REGION_MESH_QUAD_COUNT) { 644 glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL); 645 numQuads = 0; 646 mesh = mCaches.getRegionMesh(); 647 } 648 } 649 650 if (numQuads > 0) { 651 glDrawElements(GL_TRIANGLES, numQuads * 6, GL_UNSIGNED_SHORT, NULL); 652 } 653 654 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); 655 glDisableVertexAttribArray(texCoordsSlot); 656 657#if DEBUG_LAYERS_AS_REGIONS 658 uint32_t colors[] = { 659 0x7fff0000, 0x7f00ff00, 660 0x7f0000ff, 0x7fff00ff, 661 }; 662 663 int offset = 0; 664 int32_t top = rects[0].top; 665 int i = 0; 666 667 for (size_t i = 0; i < count; i++) { 668 if (top != rects[i].top) { 669 offset ^= 0x2; 670 top = rects[i].top; 671 } 672 673 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom); 674 drawColorRect(r.left, r.top, r.right, r.bottom, colors[offset + (i & 0x1)], 675 SkXfermode::kSrcOver_Mode); 676 } 677#endif 678 679 layer->region.clear(); 680 } 681#else 682 composeLayerRect(layer, rect); 683#endif 684} 685 686void OpenGLRenderer::dirtyLayer(const float left, const float top, 687 const float right, const float bottom, const mat4 transform) { 688#if RENDER_LAYERS_AS_REGIONS 689 if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region) { 690 Rect bounds(left, top, right, bottom); 691 transform.mapRect(bounds); 692 bounds.intersect(*mSnapshot->clipRect); 693 bounds.snapToPixelBoundaries(); 694 695 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 696 if (!dirty.isEmpty()) { 697 mSnapshot->region->orSelf(dirty); 698 } 699 } 700#endif 701} 702 703void OpenGLRenderer::dirtyLayer(const float left, const float top, 704 const float right, const float bottom) { 705#if RENDER_LAYERS_AS_REGIONS 706 if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region) { 707 Rect bounds(left, top, right, bottom); 708 bounds.intersect(*mSnapshot->clipRect); 709 bounds.snapToPixelBoundaries(); 710 711 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 712 if (!dirty.isEmpty()) { 713 mSnapshot->region->orSelf(dirty); 714 } 715 } 716#endif 717} 718 719void OpenGLRenderer::setupDraw() { 720 clearLayerRegions(); 721 if (mDirtyClip) { 722 setScissorFromClip(); 723 } 724} 725 726void OpenGLRenderer::clearLayerRegions() { 727 if (mLayers.size() == 0 || mSnapshot->invisible) return; 728 729 Rect clipRect(*mSnapshot->clipRect); 730 clipRect.snapToPixelBoundaries(); 731 732 for (uint32_t i = 0; i < mLayers.size(); i++) { 733 Rect* bounds = mLayers.itemAt(i); 734 if (clipRect.intersects(*bounds)) { 735 // Clear the framebuffer where the layer will draw 736 glScissor(bounds->left, mSnapshot->height - bounds->bottom, 737 bounds->getWidth(), bounds->getHeight()); 738 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 739 glClear(GL_COLOR_BUFFER_BIT); 740 741 // Restore the clip 742 dirtyClip(); 743 } 744 745 delete bounds; 746 } 747 748 mLayers.clear(); 749} 750 751/////////////////////////////////////////////////////////////////////////////// 752// Transforms 753/////////////////////////////////////////////////////////////////////////////// 754 755void OpenGLRenderer::translate(float dx, float dy) { 756 mSnapshot->transform->translate(dx, dy, 0.0f); 757} 758 759void OpenGLRenderer::rotate(float degrees) { 760 mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f); 761} 762 763void OpenGLRenderer::scale(float sx, float sy) { 764 mSnapshot->transform->scale(sx, sy, 1.0f); 765} 766 767void OpenGLRenderer::setMatrix(SkMatrix* matrix) { 768 mSnapshot->transform->load(*matrix); 769} 770 771const float* OpenGLRenderer::getMatrix() const { 772 if (mSnapshot->fbo != 0) { 773 return &mSnapshot->transform->data[0]; 774 } 775 return &mIdentity.data[0]; 776} 777 778void OpenGLRenderer::getMatrix(SkMatrix* matrix) { 779 mSnapshot->transform->copyTo(*matrix); 780} 781 782void OpenGLRenderer::concatMatrix(SkMatrix* matrix) { 783 SkMatrix transform; 784 mSnapshot->transform->copyTo(transform); 785 transform.preConcat(*matrix); 786 mSnapshot->transform->load(transform); 787} 788 789/////////////////////////////////////////////////////////////////////////////// 790// Clipping 791/////////////////////////////////////////////////////////////////////////////// 792 793void OpenGLRenderer::setScissorFromClip() { 794 Rect clip(*mSnapshot->clipRect); 795 clip.snapToPixelBoundaries(); 796 glScissor(clip.left, mSnapshot->height - clip.bottom, clip.getWidth(), clip.getHeight()); 797 mDirtyClip = false; 798} 799 800const Rect& OpenGLRenderer::getClipBounds() { 801 return mSnapshot->getLocalClip(); 802} 803 804bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) { 805 if (mSnapshot->invisible) { 806 return true; 807 } 808 809 Rect r(left, top, right, bottom); 810 mSnapshot->transform->mapRect(r); 811 r.snapToPixelBoundaries(); 812 813 Rect clipRect(*mSnapshot->clipRect); 814 clipRect.snapToPixelBoundaries(); 815 816 return !clipRect.intersects(r); 817} 818 819bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 820 bool clipped = mSnapshot->clip(left, top, right, bottom, op); 821 if (clipped) { 822 dirtyClip(); 823 } 824 return !mSnapshot->clipRect->isEmpty(); 825} 826 827/////////////////////////////////////////////////////////////////////////////// 828// Drawing 829/////////////////////////////////////////////////////////////////////////////// 830 831void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, SkPaint* paint) { 832 const float right = left + bitmap->width(); 833 const float bottom = top + bitmap->height(); 834 835 if (quickReject(left, top, right, bottom)) { 836 return; 837 } 838 839 glActiveTexture(GL_TEXTURE0); 840 Texture* texture = mCaches.textureCache.get(bitmap); 841 if (!texture) return; 842 const AutoTexture autoCleanup(texture); 843 844 drawTextureRect(left, top, right, bottom, texture, paint); 845} 846 847void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, SkMatrix* matrix, SkPaint* paint) { 848 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height()); 849 const mat4 transform(*matrix); 850 transform.mapRect(r); 851 852 if (quickReject(r.left, r.top, r.right, r.bottom)) { 853 return; 854 } 855 856 glActiveTexture(GL_TEXTURE0); 857 Texture* texture = mCaches.textureCache.get(bitmap); 858 if (!texture) return; 859 const AutoTexture autoCleanup(texture); 860 861 // This could be done in a cheaper way, all we need is pass the matrix 862 // to the vertex shader. The save/restore is a bit overkill. 863 save(SkCanvas::kMatrix_SaveFlag); 864 concatMatrix(matrix); 865 drawTextureRect(0.0f, 0.0f, bitmap->width(), bitmap->height(), texture, paint); 866 restore(); 867} 868 869void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, 870 float srcLeft, float srcTop, float srcRight, float srcBottom, 871 float dstLeft, float dstTop, float dstRight, float dstBottom, 872 SkPaint* paint) { 873 if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) { 874 return; 875 } 876 877 glActiveTexture(gTextureUnits[0]); 878 Texture* texture = mCaches.textureCache.get(bitmap); 879 if (!texture) return; 880 const AutoTexture autoCleanup(texture); 881 setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); 882 883 const float width = texture->width; 884 const float height = texture->height; 885 886 const float u1 = srcLeft / width; 887 const float v1 = srcTop / height; 888 const float u2 = srcRight / width; 889 const float v2 = srcBottom / height; 890 891 mCaches.unbindMeshBuffer(); 892 resetDrawTextureTexCoords(u1, v1, u2, v2); 893 894 int alpha; 895 SkXfermode::Mode mode; 896 getAlphaAndMode(paint, &alpha, &mode); 897 898 drawTextureMesh(dstLeft, dstTop, dstRight, dstBottom, texture->id, alpha / 255.0f, 899 mode, texture->blend, &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], 900 GL_TRIANGLE_STRIP, gMeshCount); 901 902 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 903} 904 905void OpenGLRenderer::drawPatch(SkBitmap* bitmap, const int32_t* xDivs, const int32_t* yDivs, 906 const uint32_t* colors, uint32_t width, uint32_t height, int8_t numColors, 907 float left, float top, float right, float bottom, SkPaint* paint) { 908 if (quickReject(left, top, right, bottom)) { 909 return; 910 } 911 912 glActiveTexture(gTextureUnits[0]); 913 Texture* texture = mCaches.textureCache.get(bitmap); 914 if (!texture) return; 915 const AutoTexture autoCleanup(texture); 916 setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); 917 918 int alpha; 919 SkXfermode::Mode mode; 920 getAlphaAndMode(paint, &alpha, &mode); 921 922 const Patch* mesh = mCaches.patchCache.get(bitmap->width(), bitmap->height(), 923 right - left, bottom - top, xDivs, yDivs, colors, width, height, numColors); 924 925 if (mesh) { 926 // Mark the current layer dirty where we are going to draw the patch 927 if ((mSnapshot->flags & Snapshot::kFlagFboTarget) && 928 mSnapshot->region && mesh->hasEmptyQuads) { 929 const size_t count = mesh->quads.size(); 930 for (size_t i = 0; i < count; i++) { 931 Rect bounds = mesh->quads.itemAt(i); 932 dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, 933 *mSnapshot->transform); 934 } 935 } 936 937 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, 938 mode, texture->blend, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 939 GL_TRIANGLES, mesh->verticesCount, false, false, mesh->meshBuffer, 940 true, !mesh->hasEmptyQuads); 941 } 942} 943 944void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) { 945 if (mSnapshot->invisible) return; 946 947 int alpha; 948 SkXfermode::Mode mode; 949 getAlphaAndMode(paint, &alpha, &mode); 950 951 uint32_t color = paint->getColor(); 952 const GLfloat a = alpha / 255.0f; 953 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 954 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 955 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 956 957 const bool isAA = paint->isAntiAlias(); 958 if (isAA) { 959 GLuint textureUnit = 0; 960 glActiveTexture(gTextureUnits[textureUnit]); 961 setupTextureAlpha8(mCaches.line.getTexture(), 0, 0, textureUnit, 0.0f, 0.0f, r, g, b, a, 962 mode, false, true, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset, 963 mCaches.line.getMeshBuffer()); 964 } else { 965 setupColorRect(0.0f, 0.0f, 1.0f, 1.0f, r, g, b, a, mode, false); 966 } 967 968 const float strokeWidth = paint->getStrokeWidth(); 969 const GLsizei elementsCount = isAA ? mCaches.line.getElementsCount() : gMeshCount; 970 const GLenum drawMode = isAA ? GL_TRIANGLES : GL_TRIANGLE_STRIP; 971 972 for (int i = 0; i < count; i += 4) { 973 float tx = 0.0f; 974 float ty = 0.0f; 975 976 if (isAA) { 977 mCaches.line.update(points[i], points[i + 1], points[i + 2], points[i + 3], 978 strokeWidth, tx, ty); 979 } else { 980 ty = strokeWidth <= 1.0f ? 0.0f : -strokeWidth * 0.5f; 981 } 982 983 const float dx = points[i + 2] - points[i]; 984 const float dy = points[i + 3] - points[i + 1]; 985 const float mag = sqrtf(dx * dx + dy * dy); 986 const float angle = acos(dx / mag); 987 988 mModelView.loadTranslate(points[i], points[i + 1], 0.0f); 989 if (angle > MIN_ANGLE || angle < -MIN_ANGLE) { 990 mModelView.rotate(angle * RAD_TO_DEG, 0.0f, 0.0f, 1.0f); 991 } 992 mModelView.translate(tx, ty, 0.0f); 993 if (!isAA) { 994 float length = mCaches.line.getLength(points[i], points[i + 1], 995 points[i + 2], points[i + 3]); 996 mModelView.scale(length, strokeWidth, 1.0f); 997 } 998 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 999 // TODO: Add bounds to the layer's region 1000 1001 if (mShader) { 1002 mShader->updateTransforms(mCaches.currentProgram, mModelView, *mSnapshot); 1003 } 1004 1005 glDrawArrays(drawMode, 0, elementsCount); 1006 } 1007 1008 if (isAA) { 1009 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 1010 } 1011} 1012 1013void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 1014 Rect& clip(*mSnapshot->clipRect); 1015 clip.snapToPixelBoundaries(); 1016 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true); 1017} 1018 1019void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, SkPaint* p) { 1020 if (quickReject(left, top, right, bottom)) { 1021 return; 1022 } 1023 1024 SkXfermode::Mode mode; 1025 if (!mCaches.extensions.hasFramebufferFetch()) { 1026 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 1027 if (!isMode) { 1028 // Assume SRC_OVER 1029 mode = SkXfermode::kSrcOver_Mode; 1030 } 1031 } else { 1032 mode = getXfermode(p->getXfermode()); 1033 } 1034 1035 // Skia draws using the color's alpha channel if < 255 1036 // Otherwise, it uses the paint's alpha 1037 int color = p->getColor(); 1038 if (((color >> 24) & 0xff) == 255) { 1039 color |= p->getAlpha() << 24; 1040 } 1041 1042 drawColorRect(left, top, right, bottom, color, mode); 1043} 1044 1045void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, 1046 float x, float y, SkPaint* paint) { 1047 if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) { 1048 return; 1049 } 1050 if (mSnapshot->invisible) return; 1051 1052 paint->setAntiAlias(true); 1053 1054 float length = -1.0f; 1055 switch (paint->getTextAlign()) { 1056 case SkPaint::kCenter_Align: 1057 length = paint->measureText(text, bytesCount); 1058 x -= length / 2.0f; 1059 break; 1060 case SkPaint::kRight_Align: 1061 length = paint->measureText(text, bytesCount); 1062 x -= length; 1063 break; 1064 default: 1065 break; 1066 } 1067 1068 int alpha; 1069 SkXfermode::Mode mode; 1070 getAlphaAndMode(paint, &alpha, &mode); 1071 1072 uint32_t color = paint->getColor(); 1073 const GLfloat a = alpha / 255.0f; 1074 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 1075 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 1076 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 1077 1078 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint); 1079 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 1080 paint->getTextSize()); 1081 1082 setupDraw(); 1083 1084 if (mHasShadow) { 1085 glActiveTexture(gTextureUnits[0]); 1086 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 1087 const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount, 1088 count, mShadowRadius); 1089 const AutoTexture autoCleanup(shadow); 1090 1091 setupShadow(shadow, x, y, mode, a); 1092 1093 // Draw the mesh 1094 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 1095 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 1096 } 1097 1098 GLuint textureUnit = 0; 1099 glActiveTexture(gTextureUnits[textureUnit]); 1100 1101 // Assume that the modelView matrix does not force scales, rotates, etc. 1102 const bool linearFilter = mSnapshot->transform->changesBounds(); 1103 1104 // Dimensions are set to (0,0), the layer (if any) won't be dirtied 1105 setupTextureAlpha8(fontRenderer.getTexture(linearFilter), 0, 0, textureUnit, 1106 x, y, r, g, b, a, mode, false, true, NULL, NULL); 1107 1108 const Rect& clip = mSnapshot->getLocalClip(); 1109 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 1110 1111#if RENDER_LAYERS_AS_REGIONS 1112 bool hasLayer = (mSnapshot->flags & Snapshot::kFlagFboTarget) && mSnapshot->region; 1113#else 1114 bool hasLayer = false; 1115#endif 1116 1117 mCaches.unbindMeshBuffer(); 1118 if (fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y, 1119 hasLayer ? &bounds : NULL)) { 1120#if RENDER_LAYERS_AS_REGIONS 1121 if (hasLayer) { 1122 mSnapshot->transform->mapRect(bounds); 1123 bounds.intersect(*mSnapshot->clipRect); 1124 bounds.snapToPixelBoundaries(); 1125 1126 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 1127 mSnapshot->region->orSelf(dirty); 1128 } 1129#endif 1130 } 1131 1132 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); 1133 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 1134 1135 drawTextDecorations(text, bytesCount, length, x, y, paint); 1136} 1137 1138void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) { 1139 if (mSnapshot->invisible) return; 1140 1141 GLuint textureUnit = 0; 1142 glActiveTexture(gTextureUnits[textureUnit]); 1143 1144 const PathTexture* texture = mCaches.pathCache.get(path, paint); 1145 if (!texture) return; 1146 const AutoTexture autoCleanup(texture); 1147 1148 const float x = texture->left - texture->offset; 1149 const float y = texture->top - texture->offset; 1150 1151 if (quickReject(x, y, x + texture->width, y + texture->height)) { 1152 return; 1153 } 1154 1155 int alpha; 1156 SkXfermode::Mode mode; 1157 getAlphaAndMode(paint, &alpha, &mode); 1158 1159 uint32_t color = paint->getColor(); 1160 const GLfloat a = alpha / 255.0f; 1161 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 1162 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 1163 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 1164 1165 setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true); 1166 1167 setupDraw(); 1168 1169 // Draw the mesh 1170 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 1171 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 1172} 1173 1174/////////////////////////////////////////////////////////////////////////////// 1175// Shaders 1176/////////////////////////////////////////////////////////////////////////////// 1177 1178void OpenGLRenderer::resetShader() { 1179 mShader = NULL; 1180} 1181 1182void OpenGLRenderer::setupShader(SkiaShader* shader) { 1183 mShader = shader; 1184 if (mShader) { 1185 mShader->set(&mCaches.textureCache, &mCaches.gradientCache); 1186 } 1187} 1188 1189/////////////////////////////////////////////////////////////////////////////// 1190// Color filters 1191/////////////////////////////////////////////////////////////////////////////// 1192 1193void OpenGLRenderer::resetColorFilter() { 1194 mColorFilter = NULL; 1195} 1196 1197void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) { 1198 mColorFilter = filter; 1199} 1200 1201/////////////////////////////////////////////////////////////////////////////// 1202// Drop shadow 1203/////////////////////////////////////////////////////////////////////////////// 1204 1205void OpenGLRenderer::resetShadow() { 1206 mHasShadow = false; 1207} 1208 1209void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) { 1210 mHasShadow = true; 1211 mShadowRadius = radius; 1212 mShadowDx = dx; 1213 mShadowDy = dy; 1214 mShadowColor = color; 1215} 1216 1217/////////////////////////////////////////////////////////////////////////////// 1218// Drawing implementation 1219/////////////////////////////////////////////////////////////////////////////// 1220 1221void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y, 1222 SkXfermode::Mode mode, float alpha) { 1223 const float sx = x - texture->left + mShadowDx; 1224 const float sy = y - texture->top + mShadowDy; 1225 1226 const int shadowAlpha = ((mShadowColor >> 24) & 0xFF); 1227 const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha; 1228 const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f; 1229 const GLfloat g = a * ((mShadowColor >> 8) & 0xFF) / 255.0f; 1230 const GLfloat b = a * ((mShadowColor ) & 0xFF) / 255.0f; 1231 1232 GLuint textureUnit = 0; 1233 setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false); 1234} 1235 1236void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit, 1237 float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode, 1238 bool transforms, bool applyFilters) { 1239 setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit, 1240 x, y, r, g, b, a, mode, transforms, applyFilters, 1241 (GLvoid*) 0, (GLvoid*) gMeshTextureOffset); 1242} 1243 1244void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height, 1245 GLuint& textureUnit, float x, float y, float r, float g, float b, float a, 1246 SkXfermode::Mode mode, bool transforms, bool applyFilters) { 1247 setupTextureAlpha8(texture, width, height, textureUnit, x, y, r, g, b, a, mode, 1248 transforms, applyFilters, (GLvoid*) 0, (GLvoid*) gMeshTextureOffset); 1249} 1250 1251void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height, 1252 GLuint& textureUnit, float x, float y, float r, float g, float b, float a, 1253 SkXfermode::Mode mode, bool transforms, bool applyFilters, 1254 GLvoid* vertices, GLvoid* texCoords, GLuint vbo) { 1255 // Describe the required shaders 1256 ProgramDescription description; 1257 description.hasTexture = true; 1258 description.hasAlpha8Texture = true; 1259 const bool setColor = description.setAlpha8Color(r, g, b, a); 1260 1261 if (applyFilters) { 1262 if (mShader) { 1263 mShader->describe(description, mCaches.extensions); 1264 } 1265 if (mColorFilter) { 1266 mColorFilter->describe(description, mCaches.extensions); 1267 } 1268 } 1269 1270 // Setup the blending mode 1271 chooseBlending(true, mode, description); 1272 1273 // Build and use the appropriate shader 1274 useProgram(mCaches.programCache.get(description)); 1275 1276 bindTexture(texture); 1277 glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit); 1278 1279 int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 1280 glEnableVertexAttribArray(texCoordsSlot); 1281 1282 if (texCoords) { 1283 // Setup attributes 1284 if (!vertices) { 1285 mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1286 } else { 1287 mCaches.unbindMeshBuffer(); 1288 } 1289 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 1290 gMeshStride, vertices); 1291 glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords); 1292 } 1293 1294 // Setup uniforms 1295 if (transforms) { 1296 mModelView.loadTranslate(x, y, 0.0f); 1297 mModelView.scale(width, height, 1.0f); 1298 } else { 1299 mModelView.loadIdentity(); 1300 } 1301 1302 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1303 if (width > 0 && height > 0) { 1304 dirtyLayer(x, y, x + width, y + height, *mSnapshot->transform); 1305 } 1306 1307 if (setColor) { 1308 mCaches.currentProgram->setColor(r, g, b, a); 1309 } 1310 1311 textureUnit++; 1312 if (applyFilters) { 1313 // Setup attributes and uniforms required by the shaders 1314 if (mShader) { 1315 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit); 1316 } 1317 if (mColorFilter) { 1318 mColorFilter->setupProgram(mCaches.currentProgram); 1319 } 1320 } 1321} 1322 1323// Same values used by Skia 1324#define kStdStrikeThru_Offset (-6.0f / 21.0f) 1325#define kStdUnderline_Offset (1.0f / 9.0f) 1326#define kStdUnderline_Thickness (1.0f / 18.0f) 1327 1328void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length, 1329 float x, float y, SkPaint* paint) { 1330 // Handle underline and strike-through 1331 uint32_t flags = paint->getFlags(); 1332 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 1333 float underlineWidth = length; 1334 // If length is > 0.0f, we already measured the text for the text alignment 1335 if (length <= 0.0f) { 1336 underlineWidth = paint->measureText(text, bytesCount); 1337 } 1338 1339 float offsetX = 0; 1340 switch (paint->getTextAlign()) { 1341 case SkPaint::kCenter_Align: 1342 offsetX = underlineWidth * 0.5f; 1343 break; 1344 case SkPaint::kRight_Align: 1345 offsetX = underlineWidth; 1346 break; 1347 default: 1348 break; 1349 } 1350 1351 if (underlineWidth > 0.0f) { 1352 const float textSize = paint->getTextSize(); 1353 const float strokeWidth = textSize * kStdUnderline_Thickness; 1354 1355 const float left = x - offsetX; 1356 float top = 0.0f; 1357 1358 const int pointsCount = 4 * (flags & SkPaint::kStrikeThruText_Flag ? 2 : 1); 1359 float points[pointsCount]; 1360 int currentPoint = 0; 1361 1362 if (flags & SkPaint::kUnderlineText_Flag) { 1363 top = y + textSize * kStdUnderline_Offset; 1364 points[currentPoint++] = left; 1365 points[currentPoint++] = top; 1366 points[currentPoint++] = left + underlineWidth; 1367 points[currentPoint++] = top; 1368 } 1369 1370 if (flags & SkPaint::kStrikeThruText_Flag) { 1371 top = y + textSize * kStdStrikeThru_Offset; 1372 points[currentPoint++] = left; 1373 points[currentPoint++] = top; 1374 points[currentPoint++] = left + underlineWidth; 1375 points[currentPoint++] = top; 1376 } 1377 1378 SkPaint linesPaint(*paint); 1379 linesPaint.setStrokeWidth(strokeWidth); 1380 1381 drawLines(&points[0], pointsCount, &linesPaint); 1382 } 1383 } 1384} 1385 1386void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 1387 int color, SkXfermode::Mode mode, bool ignoreTransform) { 1388 setupDraw(); 1389 1390 // If a shader is set, preserve only the alpha 1391 if (mShader) { 1392 color |= 0x00ffffff; 1393 } 1394 1395 // Render using pre-multiplied alpha 1396 const int alpha = (color >> 24) & 0xFF; 1397 const GLfloat a = alpha / 255.0f; 1398 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 1399 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 1400 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 1401 1402 setupColorRect(left, top, right, bottom, r, g, b, a, mode, ignoreTransform); 1403 1404 // Draw the mesh 1405 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 1406} 1407 1408void OpenGLRenderer::setupColorRect(float left, float top, float right, float bottom, 1409 float r, float g, float b, float a, SkXfermode::Mode mode, bool ignoreTransform) { 1410 GLuint textureUnit = 0; 1411 1412 // Describe the required shaders 1413 ProgramDescription description; 1414 const bool setColor = description.setColor(r, g, b, a); 1415 1416 if (mShader) { 1417 mShader->describe(description, mCaches.extensions); 1418 } 1419 if (mColorFilter) { 1420 mColorFilter->describe(description, mCaches.extensions); 1421 } 1422 1423 // Setup the blending mode 1424 chooseBlending(a < 1.0f || (mShader && mShader->blend()), mode, description); 1425 1426 // Build and use the appropriate shader 1427 useProgram(mCaches.programCache.get(description)); 1428 1429 // Setup attributes 1430 mCaches.bindMeshBuffer(); 1431 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 1432 gMeshStride, 0); 1433 1434 // Setup uniforms 1435 mModelView.loadTranslate(left, top, 0.0f); 1436 mModelView.scale(right - left, bottom - top, 1.0f); 1437 if (!ignoreTransform) { 1438 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1439 dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1440 } else { 1441 mat4 identity; 1442 mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity); 1443 dirtyLayer(left, top, right, bottom); 1444 } 1445 mCaches.currentProgram->setColor(r, g, b, a); 1446 1447 // Setup attributes and uniforms required by the shaders 1448 if (mShader) { 1449 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit); 1450 } 1451 if (mColorFilter) { 1452 mColorFilter->setupProgram(mCaches.currentProgram); 1453 } 1454} 1455 1456void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 1457 Texture* texture, SkPaint* paint) { 1458 int alpha; 1459 SkXfermode::Mode mode; 1460 getAlphaAndMode(paint, &alpha, &mode); 1461 1462 setTextureWrapModes(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); 1463 1464 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, 1465 texture->blend, (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, 1466 GL_TRIANGLE_STRIP, gMeshCount); 1467} 1468 1469void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 1470 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) { 1471 drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend, 1472 (GLvoid*) NULL, (GLvoid*) gMeshTextureOffset, GL_TRIANGLE_STRIP, gMeshCount); 1473} 1474 1475void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 1476 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend, 1477 GLvoid* vertices, GLvoid* texCoords, GLenum drawMode, GLsizei elementsCount, 1478 bool swapSrcDst, bool ignoreTransform, GLuint vbo, bool ignoreScale, bool dirty) { 1479 setupDraw(); 1480 1481 ProgramDescription description; 1482 description.hasTexture = true; 1483 const bool setColor = description.setColor(alpha, alpha, alpha, alpha); 1484 if (mColorFilter) { 1485 mColorFilter->describe(description, mCaches.extensions); 1486 } 1487 1488 mModelView.loadTranslate(left, top, 0.0f); 1489 if (!ignoreScale) { 1490 mModelView.scale(right - left, bottom - top, 1.0f); 1491 } 1492 1493 chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst); 1494 1495 useProgram(mCaches.programCache.get(description)); 1496 if (!ignoreTransform) { 1497 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 1498 if (dirty) dirtyLayer(left, top, right, bottom, *mSnapshot->transform); 1499 } else { 1500 mat4 identity; 1501 mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity); 1502 if (dirty) dirtyLayer(left, top, right, bottom); 1503 } 1504 1505 // Texture 1506 bindTexture(texture); 1507 glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0); 1508 1509 // Always premultiplied 1510 if (setColor) { 1511 mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha); 1512 } 1513 1514 // Mesh 1515 int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 1516 glEnableVertexAttribArray(texCoordsSlot); 1517 1518 if (!vertices) { 1519 mCaches.bindMeshBuffer(vbo == 0 ? mCaches.meshBuffer : vbo); 1520 } else { 1521 mCaches.unbindMeshBuffer(); 1522 } 1523 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 1524 gMeshStride, vertices); 1525 glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords); 1526 1527 // Color filter 1528 if (mColorFilter) { 1529 mColorFilter->setupProgram(mCaches.currentProgram); 1530 } 1531 1532 glDrawArrays(drawMode, 0, elementsCount); 1533 glDisableVertexAttribArray(texCoordsSlot); 1534} 1535 1536void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 1537 ProgramDescription& description, bool swapSrcDst) { 1538 blend = blend || mode != SkXfermode::kSrcOver_Mode; 1539 if (blend) { 1540 if (mode < SkXfermode::kPlus_Mode) { 1541 if (!mCaches.blend) { 1542 glEnable(GL_BLEND); 1543 } 1544 1545 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 1546 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 1547 1548 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 1549 glBlendFunc(sourceMode, destMode); 1550 mCaches.lastSrcMode = sourceMode; 1551 mCaches.lastDstMode = destMode; 1552 } 1553 } else { 1554 // These blend modes are not supported by OpenGL directly and have 1555 // to be implemented using shaders. Since the shader will perform 1556 // the blending, turn blending off here 1557 if (mCaches.extensions.hasFramebufferFetch()) { 1558 description.framebufferMode = mode; 1559 description.swapSrcDst = swapSrcDst; 1560 } 1561 1562 if (mCaches.blend) { 1563 glDisable(GL_BLEND); 1564 } 1565 blend = false; 1566 } 1567 } else if (mCaches.blend) { 1568 glDisable(GL_BLEND); 1569 } 1570 mCaches.blend = blend; 1571} 1572 1573bool OpenGLRenderer::useProgram(Program* program) { 1574 if (!program->isInUse()) { 1575 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 1576 program->use(); 1577 mCaches.currentProgram = program; 1578 return false; 1579 } 1580 return true; 1581} 1582 1583void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 1584 TextureVertex* v = &mMeshVertices[0]; 1585 TextureVertex::setUV(v++, u1, v1); 1586 TextureVertex::setUV(v++, u2, v1); 1587 TextureVertex::setUV(v++, u1, v2); 1588 TextureVertex::setUV(v++, u2, v2); 1589} 1590 1591void OpenGLRenderer::getAlphaAndMode(SkPaint* paint, int* alpha, SkXfermode::Mode* mode) { 1592 if (paint) { 1593 if (!mCaches.extensions.hasFramebufferFetch()) { 1594 const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode); 1595 if (!isMode) { 1596 // Assume SRC_OVER 1597 *mode = SkXfermode::kSrcOver_Mode; 1598 } 1599 } else { 1600 *mode = getXfermode(paint->getXfermode()); 1601 } 1602 1603 // Skia draws using the color's alpha channel if < 255 1604 // Otherwise, it uses the paint's alpha 1605 int color = paint->getColor(); 1606 *alpha = (color >> 24) & 0xFF; 1607 if (*alpha == 255) { 1608 *alpha = paint->getAlpha(); 1609 } 1610 } else { 1611 *mode = SkXfermode::kSrcOver_Mode; 1612 *alpha = 255; 1613 } 1614} 1615 1616SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) { 1617 if (mode == NULL) { 1618 return SkXfermode::kSrcOver_Mode; 1619 } 1620 return mode->fMode; 1621} 1622 1623void OpenGLRenderer::setTextureWrapModes(Texture* texture, GLenum wrapS, GLenum wrapT) { 1624 bool bound = false; 1625 if (wrapS != texture->wrapS) { 1626 glBindTexture(GL_TEXTURE_2D, texture->id); 1627 bound = true; 1628 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS); 1629 texture->wrapS = wrapS; 1630 } 1631 if (wrapT != texture->wrapT) { 1632 if (!bound) { 1633 glBindTexture(GL_TEXTURE_2D, texture->id); 1634 } 1635 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT); 1636 texture->wrapT = wrapT; 1637 } 1638} 1639 1640}; // namespace uirenderer 1641}; // namespace android 1642