OpenGLRenderer.cpp revision 1c740bce8a762f02b5283045a0e2de7c8fb41277
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 28#include "OpenGLRenderer.h" 29 30namespace android { 31namespace uirenderer { 32 33/////////////////////////////////////////////////////////////////////////////// 34// Defines 35/////////////////////////////////////////////////////////////////////////////// 36 37#define REQUIRED_TEXTURE_UNITS_COUNT 3 38 39// Generates simple and textured vertices 40#define FV(x, y, u, v) { { x, y }, { u, v } } 41 42/////////////////////////////////////////////////////////////////////////////// 43// Globals 44/////////////////////////////////////////////////////////////////////////////// 45 46// This array is never used directly but used as a memcpy source in the 47// OpenGLRenderer constructor 48static const TextureVertex gMeshVertices[] = { 49 FV(0.0f, 0.0f, 0.0f, 0.0f), 50 FV(1.0f, 0.0f, 1.0f, 0.0f), 51 FV(0.0f, 1.0f, 0.0f, 1.0f), 52 FV(1.0f, 1.0f, 1.0f, 1.0f) 53}; 54static const GLsizei gMeshStride = sizeof(TextureVertex); 55static const GLsizei gMeshCount = 4; 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_ZERO }, 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}; 82 83static const Blender gBlendsSwap[] = { 84 { SkXfermode::kClear_Mode, GL_ZERO, GL_ZERO }, 85 { SkXfermode::kSrc_Mode, GL_ZERO, GL_ONE }, 86 { SkXfermode::kDst_Mode, GL_ONE, GL_ZERO }, 87 { SkXfermode::kSrcOver_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE }, 88 { SkXfermode::kDstOver_Mode, GL_ONE, GL_ONE_MINUS_SRC_ALPHA }, 89 { SkXfermode::kSrcIn_Mode, GL_ZERO, GL_SRC_ALPHA }, 90 { SkXfermode::kDstIn_Mode, GL_DST_ALPHA, GL_ZERO }, 91 { SkXfermode::kSrcOut_Mode, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA }, 92 { SkXfermode::kDstOut_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ZERO }, 93 { SkXfermode::kSrcATop_Mode, GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA }, 94 { SkXfermode::kDstATop_Mode, GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, 95 { SkXfermode::kXor_Mode, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA } 96}; 97 98static const GLenum gTextureUnits[] = { 99 GL_TEXTURE0, 100 GL_TEXTURE1, 101 GL_TEXTURE2 102}; 103 104/////////////////////////////////////////////////////////////////////////////// 105// Constructors/destructor 106/////////////////////////////////////////////////////////////////////////////// 107 108OpenGLRenderer::OpenGLRenderer(): mCaches(Caches::getInstance()) { 109 LOGD("Create OpenGLRenderer"); 110 111 mShader = NULL; 112 mColorFilter = NULL; 113 mHasShadow = false; 114 115 memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices)); 116 117 mFirstSnapshot = new Snapshot; 118 119 GLint maxTextureUnits; 120 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits); 121 if (maxTextureUnits < REQUIRED_TEXTURE_UNITS_COUNT) { 122 LOGW("At least %d texture units are required!", REQUIRED_TEXTURE_UNITS_COUNT); 123 } 124} 125 126OpenGLRenderer::~OpenGLRenderer() { 127 LOGD("Destroy OpenGLRenderer"); 128} 129 130/////////////////////////////////////////////////////////////////////////////// 131// Setup 132/////////////////////////////////////////////////////////////////////////////// 133 134void OpenGLRenderer::setViewport(int width, int height) { 135 glViewport(0, 0, width, height); 136 mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1); 137 138 mWidth = width; 139 mHeight = height; 140} 141 142void OpenGLRenderer::prepare() { 143 mSnapshot = new Snapshot(mFirstSnapshot, 144 SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag); 145 mSaveCount = 1; 146 147 glViewport(0, 0, mWidth, mHeight); 148 149 glDisable(GL_DITHER); 150 glDisable(GL_SCISSOR_TEST); 151 152 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 153 glClear(GL_COLOR_BUFFER_BIT); 154 155 glEnable(GL_SCISSOR_TEST); 156 glScissor(0, 0, mWidth, mHeight); 157 158 mSnapshot->setClip(0.0f, 0.0f, mWidth, mHeight); 159} 160 161void OpenGLRenderer::acquireContext() { 162 if (mCaches.currentProgram) { 163 if (mCaches.currentProgram->isInUse()) { 164 mCaches.currentProgram->remove(); 165 mCaches.currentProgram = NULL; 166 } 167 } 168} 169 170void OpenGLRenderer::releaseContext() { 171 glViewport(0, 0, mWidth, mHeight); 172 173 glEnable(GL_SCISSOR_TEST); 174 setScissorFromClip(); 175 176 glDisable(GL_DITHER); 177 178 glBindFramebuffer(GL_FRAMEBUFFER, 0); 179 180 if (mCaches.blend) { 181 glEnable(GL_BLEND); 182 glBlendFunc(mCaches.lastSrcMode, mCaches.lastDstMode); 183 glBlendEquation(GL_FUNC_ADD); 184 } else { 185 glDisable(GL_BLEND); 186 } 187} 188 189/////////////////////////////////////////////////////////////////////////////// 190// State management 191/////////////////////////////////////////////////////////////////////////////// 192 193int OpenGLRenderer::getSaveCount() const { 194 return mSaveCount; 195} 196 197int OpenGLRenderer::save(int flags) { 198 return saveSnapshot(flags); 199} 200 201void OpenGLRenderer::restore() { 202 if (mSaveCount > 1) { 203 restoreSnapshot(); 204 } 205} 206 207void OpenGLRenderer::restoreToCount(int saveCount) { 208 if (saveCount < 1) saveCount = 1; 209 210 while (mSaveCount > saveCount) { 211 restoreSnapshot(); 212 } 213} 214 215int OpenGLRenderer::saveSnapshot(int flags) { 216 mSnapshot = new Snapshot(mSnapshot, flags); 217 return mSaveCount++; 218} 219 220bool OpenGLRenderer::restoreSnapshot() { 221 bool restoreClip = mSnapshot->flags & Snapshot::kFlagClipSet; 222 bool restoreLayer = mSnapshot->flags & Snapshot::kFlagIsLayer; 223 224 sp<Snapshot> current = mSnapshot; 225 sp<Snapshot> previous = mSnapshot->previous; 226 227 mSaveCount--; 228 mSnapshot = previous; 229 230 if (restoreLayer) { 231 composeLayer(current, previous); 232 } 233 234 if (restoreClip) { 235 setScissorFromClip(); 236 } 237 238 return restoreClip; 239} 240 241/////////////////////////////////////////////////////////////////////////////// 242// Layers 243/////////////////////////////////////////////////////////////////////////////// 244 245int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 246 const SkPaint* p, int flags) { 247 int count = saveSnapshot(flags); 248 249 int alpha = 255; 250 SkXfermode::Mode mode; 251 252 if (p) { 253 alpha = p->getAlpha(); 254 if (!mExtensions.hasFramebufferFetch()) { 255 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 256 if (!isMode) { 257 // Assume SRC_OVER 258 mode = SkXfermode::kSrcOver_Mode; 259 } 260 } else { 261 mode = getXfermode(p->getXfermode()); 262 } 263 } else { 264 mode = SkXfermode::kSrcOver_Mode; 265 } 266 267 createLayer(mSnapshot, left, top, right, bottom, alpha, mode, flags); 268 269 return count; 270} 271 272int OpenGLRenderer::saveLayerAlpha(float left, float top, float right, float bottom, 273 int alpha, int flags) { 274 if (alpha == 0xff) { 275 return saveLayer(left, top, right, bottom, NULL, flags); 276 } else { 277 SkPaint paint; 278 paint.setAlpha(alpha); 279 return saveLayer(left, top, right, bottom, &paint, flags); 280 } 281} 282 283/** 284 * Layers are viewed by Skia are slightly different than layers in image editing 285 * programs (for instance.) When a layer is created, previously created layers 286 * and the frame buffer still receive every drawing command. For instance, if a 287 * layer is created and a shape intersecting the bounds of the layers and the 288 * framebuffer is draw, the shape will be drawn on both (unless the layer was 289 * created with the SkCanvas::kClipToLayer_SaveFlag flag.) 290 * 291 * A way to implement layers is to create an FBO for each layer, backed by an RGBA 292 * texture. Unfortunately, this is inefficient as it requires every primitive to 293 * be drawn n + 1 times, where n is the number of active layers. In practice this 294 * means, for every primitive: 295 * - Switch active frame buffer 296 * - Change viewport, clip and projection matrix 297 * - Issue the drawing 298 * 299 * Switching rendering target n + 1 times per drawn primitive is extremely costly. 300 * To avoid this, layers are implemented in a different way here. 301 * 302 * This implementation relies on the frame buffer being at least RGBA 8888. When 303 * a layer is created, only a texture is created, not an FBO. The content of the 304 * frame buffer contained within the layer's bounds is copied into this texture 305 * using glCopyTexImage2D(). The layer's region is then cleared in the frame 306 * buffer and drawing continues as normal. This technique therefore treats the 307 * frame buffer as a scratch buffer for the layers. 308 * 309 * To compose the layers back onto the frame buffer, each layer texture 310 * (containing the original frame buffer data) is drawn as a simple quad over 311 * the frame buffer. The trick is that the quad is set as the composition 312 * destination in the blending equation, and the frame buffer becomes the source 313 * of the composition. 314 * 315 * Drawing layers with an alpha value requires an extra step before composition. 316 * An empty quad is drawn over the layer's region in the frame buffer. This quad 317 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the 318 * quad is used to multiply the colors in the frame buffer. This is achieved by 319 * changing the GL blend functions for the GL_FUNC_ADD blend equation to 320 * GL_ZERO, GL_SRC_ALPHA. 321 * 322 * Because glCopyTexImage2D() can be slow, an alternative implementation might 323 * be use to draw a single clipped layer. The implementation described above 324 * is correct in every case. 325 */ 326bool OpenGLRenderer::createLayer(sp<Snapshot> snapshot, float left, float top, 327 float right, float bottom, int alpha, SkXfermode::Mode mode,int flags) { 328 LAYER_LOGD("Requesting layer %fx%f", right - left, bottom - top); 329 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize()); 330 331 // Window coordinates of the layer 332 Rect bounds(left, top, right, bottom); 333 mSnapshot->transform->mapRect(bounds); 334 335 // Layers only make sense if they are in the framebuffer's bounds 336 bounds.intersect(*mSnapshot->clipRect); 337 if (bounds.isEmpty()) return false; 338 339 LayerSize size(bounds.getWidth(), bounds.getHeight()); 340 Layer* layer = mCaches.layerCache.get(size); 341 if (!layer) { 342 return false; 343 } 344 345 layer->mode = mode; 346 layer->alpha = alpha; 347 layer->layer.set(bounds); 348 349 // Save the layer in the snapshot 350 snapshot->flags |= Snapshot::kFlagIsLayer; 351 snapshot->layer = layer; 352 353 // Copy the framebuffer into the layer 354 glBindTexture(GL_TEXTURE_2D, layer->texture); 355 glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.left, mHeight - bounds.bottom, 356 bounds.getWidth(), bounds.getHeight(), 0); 357 358 if (flags & SkCanvas::kClipToLayer_SaveFlag) { 359 if (mSnapshot->clipTransformed(bounds)) setScissorFromClip(); 360 } 361 362 // Enqueue the buffer coordinates to clear the corresponding region later 363 mLayers.push(new Rect(bounds)); 364 365 return true; 366} 367 368/** 369 * Read the documentation of createLayer() before doing anything in this method. 370 */ 371void OpenGLRenderer::composeLayer(sp<Snapshot> current, sp<Snapshot> previous) { 372 if (!current->layer) { 373 LOGE("Attempting to compose a layer that does not exist"); 374 return; 375 } 376 377 // Restore the clip from the previous snapshot 378 const Rect& clip = *previous->clipRect; 379 glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight()); 380 381 Layer* layer = current->layer; 382 const Rect& rect = layer->layer; 383 384 if (layer->alpha < 255) { 385 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, 386 layer->alpha << 24, SkXfermode::kDstIn_Mode, true); 387 } 388 389 // Layers are already drawn with a top-left origin, don't flip the texture 390 resetDrawTextureTexCoords(0.0f, 1.0f, 1.0f, 0.0f); 391 392 drawTextureMesh(rect.left, rect.top, rect.right, rect.bottom, layer->texture, 393 1.0f, layer->mode, layer->blend, &mMeshVertices[0].position[0], 394 &mMeshVertices[0].texture[0], NULL, 0, true, true); 395 396 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 397 398 LayerSize size(rect.getWidth(), rect.getHeight()); 399 // Failing to add the layer to the cache should happen only if the 400 // layer is too large 401 if (!mCaches.layerCache.put(size, layer)) { 402 LAYER_LOGD("Deleting layer"); 403 404 glDeleteTextures(1, &layer->texture); 405 406 delete layer; 407 } 408} 409 410void OpenGLRenderer::clearLayerRegions() { 411 if (mLayers.size() == 0) return; 412 413 for (uint32_t i = 0; i < mLayers.size(); i++) { 414 Rect* bounds = mLayers.itemAt(i); 415 416 // Clear the framebuffer where the layer will draw 417 glScissor(bounds->left, mHeight - bounds->bottom, 418 bounds->getWidth(), bounds->getHeight()); 419 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 420 glClear(GL_COLOR_BUFFER_BIT); 421 422 delete bounds; 423 } 424 mLayers.clear(); 425 426 // Restore the clip 427 setScissorFromClip(); 428} 429 430/////////////////////////////////////////////////////////////////////////////// 431// Transforms 432/////////////////////////////////////////////////////////////////////////////// 433 434void OpenGLRenderer::translate(float dx, float dy) { 435 mSnapshot->transform->translate(dx, dy, 0.0f); 436} 437 438void OpenGLRenderer::rotate(float degrees) { 439 mSnapshot->transform->rotate(degrees, 0.0f, 0.0f, 1.0f); 440} 441 442void OpenGLRenderer::scale(float sx, float sy) { 443 mSnapshot->transform->scale(sx, sy, 1.0f); 444} 445 446void OpenGLRenderer::setMatrix(SkMatrix* matrix) { 447 mSnapshot->transform->load(*matrix); 448} 449 450void OpenGLRenderer::getMatrix(SkMatrix* matrix) { 451 mSnapshot->transform->copyTo(*matrix); 452} 453 454void OpenGLRenderer::concatMatrix(SkMatrix* matrix) { 455 mat4 m(*matrix); 456 mSnapshot->transform->multiply(m); 457} 458 459/////////////////////////////////////////////////////////////////////////////// 460// Clipping 461/////////////////////////////////////////////////////////////////////////////// 462 463void OpenGLRenderer::setScissorFromClip() { 464 const Rect& clip = *mSnapshot->clipRect; 465 glScissor(clip.left, mHeight - clip.bottom, clip.getWidth(), clip.getHeight()); 466} 467 468const Rect& OpenGLRenderer::getClipBounds() { 469 return mSnapshot->getLocalClip(); 470} 471 472bool OpenGLRenderer::quickReject(float left, float top, float right, float bottom) { 473 Rect r(left, top, right, bottom); 474 mSnapshot->transform->mapRect(r); 475 return !mSnapshot->clipRect->intersects(r); 476} 477 478bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 479 bool clipped = mSnapshot->clip(left, top, right, bottom, op); 480 if (clipped) { 481 setScissorFromClip(); 482 } 483 return !mSnapshot->clipRect->isEmpty(); 484} 485 486/////////////////////////////////////////////////////////////////////////////// 487// Drawing 488/////////////////////////////////////////////////////////////////////////////// 489 490void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, float left, float top, const SkPaint* paint) { 491 const float right = left + bitmap->width(); 492 const float bottom = top + bitmap->height(); 493 494 if (quickReject(left, top, right, bottom)) { 495 return; 496 } 497 498 glActiveTexture(GL_TEXTURE0); 499 const Texture* texture = mCaches.textureCache.get(bitmap); 500 if (!texture) return; 501 const AutoTexture autoCleanup(texture); 502 503 drawTextureRect(left, top, right, bottom, texture, paint); 504} 505 506void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, const SkMatrix* matrix, const SkPaint* paint) { 507 Rect r(0.0f, 0.0f, bitmap->width(), bitmap->height()); 508 const mat4 transform(*matrix); 509 transform.mapRect(r); 510 511 if (quickReject(r.left, r.top, r.right, r.bottom)) { 512 return; 513 } 514 515 glActiveTexture(GL_TEXTURE0); 516 const Texture* texture = mCaches.textureCache.get(bitmap); 517 if (!texture) return; 518 const AutoTexture autoCleanup(texture); 519 520 drawTextureRect(r.left, r.top, r.right, r.bottom, texture, paint); 521} 522 523void OpenGLRenderer::drawBitmap(SkBitmap* bitmap, 524 float srcLeft, float srcTop, float srcRight, float srcBottom, 525 float dstLeft, float dstTop, float dstRight, float dstBottom, 526 const SkPaint* paint) { 527 if (quickReject(dstLeft, dstTop, dstRight, dstBottom)) { 528 return; 529 } 530 531 glActiveTexture(GL_TEXTURE0); 532 const Texture* texture = mCaches.textureCache.get(bitmap); 533 if (!texture) return; 534 const AutoTexture autoCleanup(texture); 535 536 const float width = texture->width; 537 const float height = texture->height; 538 539 const float u1 = srcLeft / width; 540 const float v1 = srcTop / height; 541 const float u2 = srcRight / width; 542 const float v2 = srcBottom / height; 543 544 resetDrawTextureTexCoords(u1, v1, u2, v2); 545 546 drawTextureRect(dstLeft, dstTop, dstRight, dstBottom, texture, paint); 547 548 resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f); 549} 550 551void OpenGLRenderer::drawPatch(SkBitmap* bitmap, Res_png_9patch* patch, 552 float left, float top, float right, float bottom, const SkPaint* paint) { 553 if (quickReject(left, top, right, bottom)) { 554 return; 555 } 556 557 glActiveTexture(GL_TEXTURE0); 558 const Texture* texture = mCaches.textureCache.get(bitmap); 559 if (!texture) return; 560 const AutoTexture autoCleanup(texture); 561 562 int alpha; 563 SkXfermode::Mode mode; 564 getAlphaAndMode(paint, &alpha, &mode); 565 566 Patch* mesh = mCaches.patchCache.get(patch); 567 mesh->updateVertices(bitmap, left, top, right, bottom, 568 &patch->xDivs[0], &patch->yDivs[0], patch->numXDivs, patch->numYDivs); 569 mesh->dump(); 570 571 // Specify right and bottom as +1.0f from left/top to prevent scaling since the 572 // patch mesh already defines the final size 573 drawTextureMesh(left, top, left + 1.0f, top + 1.0f, texture->id, alpha / 255.0f, 574 mode, texture->blend, &mesh->vertices[0].position[0], 575 &mesh->vertices[0].texture[0], mesh->indices, mesh->indicesCount); 576} 577 578void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 579 const Rect& clip = *mSnapshot->clipRect; 580 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, color, mode, true); 581} 582 583void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, const SkPaint* p) { 584 if (quickReject(left, top, right, bottom)) { 585 return; 586 } 587 588 SkXfermode::Mode mode; 589 if (!mExtensions.hasFramebufferFetch()) { 590 const bool isMode = SkXfermode::IsMode(p->getXfermode(), &mode); 591 if (!isMode) { 592 // Assume SRC_OVER 593 mode = SkXfermode::kSrcOver_Mode; 594 } 595 } else { 596 mode = getXfermode(p->getXfermode()); 597 } 598 599 // Skia draws using the color's alpha channel if < 255 600 // Otherwise, it uses the paint's alpha 601 int color = p->getColor(); 602 if (((color >> 24) & 0xff) == 255) { 603 color |= p->getAlpha() << 24; 604 } 605 606 drawColorRect(left, top, right, bottom, color, mode); 607} 608 609void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, 610 float x, float y, SkPaint* paint) { 611 if (text == NULL || count == 0 || (paint->getAlpha() == 0 && paint->getXfermode() == NULL)) { 612 return; 613 } 614 paint->setAntiAlias(true); 615 616 float length = -1.0f; 617 switch (paint->getTextAlign()) { 618 case SkPaint::kCenter_Align: 619 length = paint->measureText(text, bytesCount); 620 x -= length / 2.0f; 621 break; 622 case SkPaint::kRight_Align: 623 length = paint->measureText(text, bytesCount); 624 x -= length; 625 break; 626 default: 627 break; 628 } 629 630 int alpha; 631 SkXfermode::Mode mode; 632 getAlphaAndMode(paint, &alpha, &mode); 633 634 uint32_t color = paint->getColor(); 635 const GLfloat a = alpha / 255.0f; 636 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 637 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 638 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 639 640 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(paint); 641 fontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), 642 paint->getTextSize()); 643 if (mHasShadow) { 644 glActiveTexture(gTextureUnits[0]); 645 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 646 const ShadowTexture* shadow = mCaches.dropShadowCache.get(paint, text, bytesCount, 647 count, mShadowRadius); 648 const AutoTexture autoCleanup(shadow); 649 650 setupShadow(shadow, x, y, mode, a); 651 652 // Draw the mesh 653 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 654 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 655 } 656 657 GLuint textureUnit = 0; 658 glActiveTexture(gTextureUnits[textureUnit]); 659 660 setupTextureAlpha8(fontRenderer.getTexture(), 0, 0, textureUnit, x, y, r, g, b, a, 661 mode, false, true); 662 663 const Rect& clip = mSnapshot->getLocalClip(); 664 clearLayerRegions(); 665 fontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y); 666 667 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); 668 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 669 670 drawTextDecorations(text, bytesCount, length, x, y, paint); 671} 672 673void OpenGLRenderer::drawPath(SkPath* path, SkPaint* paint) { 674 GLuint textureUnit = 0; 675 glActiveTexture(gTextureUnits[textureUnit]); 676 677 const PathTexture* texture = mCaches.pathCache.get(path, paint); 678 if (!texture) return; 679 const AutoTexture autoCleanup(texture); 680 681 const float x = texture->left - texture->offset; 682 const float y = texture->top - texture->offset; 683 684 if (quickReject(x, y, x + texture->width, y + texture->height)) { 685 return; 686 } 687 688 int alpha; 689 SkXfermode::Mode mode; 690 getAlphaAndMode(paint, &alpha, &mode); 691 692 uint32_t color = paint->getColor(); 693 const GLfloat a = alpha / 255.0f; 694 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 695 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 696 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 697 698 setupTextureAlpha8(texture, textureUnit, x, y, r, g, b, a, mode, true, true); 699 700 clearLayerRegions(); 701 702 // Draw the mesh 703 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 704 glDisableVertexAttribArray(mCaches.currentProgram->getAttrib("texCoords")); 705} 706 707/////////////////////////////////////////////////////////////////////////////// 708// Shaders 709/////////////////////////////////////////////////////////////////////////////// 710 711void OpenGLRenderer::resetShader() { 712 mShader = NULL; 713} 714 715void OpenGLRenderer::setupShader(SkiaShader* shader) { 716 mShader = shader; 717 if (mShader) { 718 mShader->set(&mCaches.textureCache, &mCaches.gradientCache); 719 } 720} 721 722/////////////////////////////////////////////////////////////////////////////// 723// Color filters 724/////////////////////////////////////////////////////////////////////////////// 725 726void OpenGLRenderer::resetColorFilter() { 727 mColorFilter = NULL; 728} 729 730void OpenGLRenderer::setupColorFilter(SkiaColorFilter* filter) { 731 mColorFilter = filter; 732} 733 734/////////////////////////////////////////////////////////////////////////////// 735// Drop shadow 736/////////////////////////////////////////////////////////////////////////////// 737 738void OpenGLRenderer::resetShadow() { 739 mHasShadow = false; 740} 741 742void OpenGLRenderer::setupShadow(float radius, float dx, float dy, int color) { 743 mHasShadow = true; 744 mShadowRadius = radius; 745 mShadowDx = dx; 746 mShadowDy = dy; 747 mShadowColor = color; 748} 749 750/////////////////////////////////////////////////////////////////////////////// 751// Drawing implementation 752/////////////////////////////////////////////////////////////////////////////// 753 754void OpenGLRenderer::setupShadow(const ShadowTexture* texture, float x, float y, 755 SkXfermode::Mode mode, float alpha) { 756 const float sx = x - texture->left + mShadowDx; 757 const float sy = y - texture->top + mShadowDy; 758 759 const int shadowAlpha = ((mShadowColor >> 24) & 0xFF); 760 const GLfloat a = shadowAlpha < 255 ? shadowAlpha / 255.0f : alpha; 761 const GLfloat r = a * ((mShadowColor >> 16) & 0xFF) / 255.0f; 762 const GLfloat g = a * ((mShadowColor >> 8) & 0xFF) / 255.0f; 763 const GLfloat b = a * ((mShadowColor ) & 0xFF) / 255.0f; 764 765 GLuint textureUnit = 0; 766 setupTextureAlpha8(texture, textureUnit, sx, sy, r, g, b, a, mode, true, false); 767} 768 769void OpenGLRenderer::setupTextureAlpha8(const Texture* texture, GLuint& textureUnit, 770 float x, float y, float r, float g, float b, float a, SkXfermode::Mode mode, 771 bool transforms, bool applyFilters) { 772 setupTextureAlpha8(texture->id, texture->width, texture->height, textureUnit, 773 x, y, r, g, b, a, mode, transforms, applyFilters); 774} 775 776void OpenGLRenderer::setupTextureAlpha8(GLuint texture, uint32_t width, uint32_t height, 777 GLuint& textureUnit, float x, float y, float r, float g, float b, float a, 778 SkXfermode::Mode mode, bool transforms, bool applyFilters) { 779 // Describe the required shaders 780 ProgramDescription description; 781 description.hasTexture = true; 782 description.hasAlpha8Texture = true; 783 784 if (applyFilters) { 785 if (mShader) { 786 mShader->describe(description, mExtensions); 787 } 788 if (mColorFilter) { 789 mColorFilter->describe(description, mExtensions); 790 } 791 } 792 793 // Setup the blending mode 794 chooseBlending(true, mode, description); 795 796 // Build and use the appropriate shader 797 useProgram(mCaches.programCache.get(description)); 798 799 bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, textureUnit); 800 glUniform1i(mCaches.currentProgram->getUniform("sampler"), textureUnit); 801 802 int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 803 glEnableVertexAttribArray(texCoordsSlot); 804 805 // Setup attributes 806 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 807 gMeshStride, &mMeshVertices[0].position[0]); 808 glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, 809 gMeshStride, &mMeshVertices[0].texture[0]); 810 811 // Setup uniforms 812 if (transforms) { 813 mModelView.loadTranslate(x, y, 0.0f); 814 mModelView.scale(width, height, 1.0f); 815 } else { 816 mModelView.loadIdentity(); 817 } 818 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 819 glUniform4f(mCaches.currentProgram->color, r, g, b, a); 820 821 textureUnit++; 822 if (applyFilters) { 823 // Setup attributes and uniforms required by the shaders 824 if (mShader) { 825 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit); 826 } 827 if (mColorFilter) { 828 mColorFilter->setupProgram(mCaches.currentProgram); 829 } 830 } 831} 832 833// Same values used by Skia 834#define kStdStrikeThru_Offset (-6.0f / 21.0f) 835#define kStdUnderline_Offset (1.0f / 9.0f) 836#define kStdUnderline_Thickness (1.0f / 18.0f) 837 838void OpenGLRenderer::drawTextDecorations(const char* text, int bytesCount, float length, 839 float x, float y, SkPaint* paint) { 840 // Handle underline and strike-through 841 uint32_t flags = paint->getFlags(); 842 if (flags & (SkPaint::kUnderlineText_Flag | SkPaint::kStrikeThruText_Flag)) { 843 float underlineWidth = length; 844 // If length is > 0.0f, we already measured the text for the text alignment 845 if (length <= 0.0f) { 846 underlineWidth = paint->measureText(text, bytesCount); 847 } 848 849 float offsetX = 0; 850 switch (paint->getTextAlign()) { 851 case SkPaint::kCenter_Align: 852 offsetX = underlineWidth * 0.5f; 853 break; 854 case SkPaint::kRight_Align: 855 offsetX = underlineWidth; 856 break; 857 default: 858 break; 859 } 860 861 if (underlineWidth > 0.0f) { 862 float textSize = paint->getTextSize(); 863 float height = textSize * kStdUnderline_Thickness; 864 865 float left = x - offsetX; 866 float top = 0.0f; 867 float right = left + underlineWidth; 868 float bottom = 0.0f; 869 870 if (flags & SkPaint::kUnderlineText_Flag) { 871 top = y + textSize * kStdUnderline_Offset; 872 bottom = top + height; 873 drawRect(left, top, right, bottom, paint); 874 } 875 876 if (flags & SkPaint::kStrikeThruText_Flag) { 877 top = y + textSize * kStdStrikeThru_Offset; 878 bottom = top + height; 879 drawRect(left, top, right, bottom, paint); 880 } 881 } 882 } 883} 884 885void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 886 int color, SkXfermode::Mode mode, bool ignoreTransform) { 887 clearLayerRegions(); 888 889 // If a shader is set, preserve only the alpha 890 if (mShader) { 891 color |= 0x00ffffff; 892 } 893 894 // Render using pre-multiplied alpha 895 const int alpha = (color >> 24) & 0xFF; 896 const GLfloat a = alpha / 255.0f; 897 const GLfloat r = a * ((color >> 16) & 0xFF) / 255.0f; 898 const GLfloat g = a * ((color >> 8) & 0xFF) / 255.0f; 899 const GLfloat b = a * ((color ) & 0xFF) / 255.0f; 900 901 GLuint textureUnit = 0; 902 903 // Describe the required shaders 904 ProgramDescription description; 905 if (mShader) { 906 mShader->describe(description, mExtensions); 907 } 908 if (mColorFilter) { 909 mColorFilter->describe(description, mExtensions); 910 } 911 912 // Setup the blending mode 913 chooseBlending(alpha < 255 || (mShader && mShader->blend()), mode, description); 914 915 // Build and use the appropriate shader 916 useProgram(mCaches.programCache.get(description)); 917 918 // Setup attributes 919 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 920 gMeshStride, &mMeshVertices[0].position[0]); 921 922 // Setup uniforms 923 mModelView.loadTranslate(left, top, 0.0f); 924 mModelView.scale(right - left, bottom - top, 1.0f); 925 if (!ignoreTransform) { 926 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 927 } else { 928 mat4 identity; 929 mCaches.currentProgram->set(mOrthoMatrix, mModelView, identity); 930 } 931 glUniform4f(mCaches.currentProgram->color, r, g, b, a); 932 933 // Setup attributes and uniforms required by the shaders 934 if (mShader) { 935 mShader->setupProgram(mCaches.currentProgram, mModelView, *mSnapshot, &textureUnit); 936 } 937 if (mColorFilter) { 938 mColorFilter->setupProgram(mCaches.currentProgram); 939 } 940 941 // Draw the mesh 942 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 943} 944 945void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 946 const Texture* texture, const SkPaint* paint) { 947 int alpha; 948 SkXfermode::Mode mode; 949 getAlphaAndMode(paint, &alpha, &mode); 950 951 drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, texture->blend, 952 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL); 953} 954 955void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom, 956 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) { 957 drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend, 958 &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL); 959} 960 961void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom, 962 GLuint texture, float alpha, SkXfermode::Mode mode, bool blend, 963 GLvoid* vertices, GLvoid* texCoords, GLvoid* indices, GLsizei elementsCount, 964 bool swapSrcDst, bool ignoreTransform) { 965 clearLayerRegions(); 966 967 ProgramDescription description; 968 description.hasTexture = true; 969 if (mColorFilter) { 970 mColorFilter->describe(description, mExtensions); 971 } 972 973 mModelView.loadTranslate(left, top, 0.0f); 974 mModelView.scale(right - left, bottom - top, 1.0f); 975 976 chooseBlending(blend || alpha < 1.0f, mode, description, swapSrcDst); 977 978 useProgram(mCaches.programCache.get(description)); 979 if (!ignoreTransform) { 980 mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform); 981 } else { 982 mat4 m; 983 mCaches.currentProgram->set(mOrthoMatrix, mModelView, m); 984 } 985 986 // Texture 987 bindTexture(texture, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, 0); 988 glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0); 989 990 // Always premultiplied 991 glUniform4f(mCaches.currentProgram->color, alpha, alpha, alpha, alpha); 992 993 // Mesh 994 int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords"); 995 glEnableVertexAttribArray(texCoordsSlot); 996 glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE, 997 gMeshStride, vertices); 998 glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE, gMeshStride, texCoords); 999 1000 // Color filter 1001 if (mColorFilter) { 1002 mColorFilter->setupProgram(mCaches.currentProgram); 1003 } 1004 1005 if (!indices) { 1006 glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount); 1007 } else { 1008 glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_SHORT, indices); 1009 } 1010 glDisableVertexAttribArray(texCoordsSlot); 1011} 1012 1013void OpenGLRenderer::chooseBlending(bool blend, SkXfermode::Mode mode, 1014 ProgramDescription& description, bool swapSrcDst) { 1015 blend = blend || mode != SkXfermode::kSrcOver_Mode; 1016 if (blend) { 1017 if (mode < SkXfermode::kPlus_Mode) { 1018 if (!mCaches.blend) { 1019 glEnable(GL_BLEND); 1020 } 1021 1022 GLenum sourceMode = swapSrcDst ? gBlendsSwap[mode].src : gBlends[mode].src; 1023 GLenum destMode = swapSrcDst ? gBlendsSwap[mode].dst : gBlends[mode].dst; 1024 1025 if (sourceMode != mCaches.lastSrcMode || destMode != mCaches.lastDstMode) { 1026 glBlendFunc(sourceMode, destMode); 1027 mCaches.lastSrcMode = sourceMode; 1028 mCaches.lastDstMode = destMode; 1029 } 1030 } else { 1031 // These blend modes are not supported by OpenGL directly and have 1032 // to be implemented using shaders. Since the shader will perform 1033 // the blending, turn blending off here 1034 if (mExtensions.hasFramebufferFetch()) { 1035 description.framebufferMode = mode; 1036 description.swapSrcDst = swapSrcDst; 1037 } 1038 1039 if (mCaches.blend) { 1040 glDisable(GL_BLEND); 1041 } 1042 blend = false; 1043 } 1044 } else if (mCaches.blend) { 1045 glDisable(GL_BLEND); 1046 } 1047 mCaches.blend = blend; 1048} 1049 1050bool OpenGLRenderer::useProgram(Program* program) { 1051 if (!program->isInUse()) { 1052 if (mCaches.currentProgram != NULL) mCaches.currentProgram->remove(); 1053 program->use(); 1054 mCaches.currentProgram = program; 1055 return false; 1056 } 1057 return true; 1058} 1059 1060void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) { 1061 TextureVertex* v = &mMeshVertices[0]; 1062 TextureVertex::setUV(v++, u1, v1); 1063 TextureVertex::setUV(v++, u2, v1); 1064 TextureVertex::setUV(v++, u1, v2); 1065 TextureVertex::setUV(v++, u2, v2); 1066} 1067 1068void OpenGLRenderer::getAlphaAndMode(const SkPaint* paint, int* alpha, SkXfermode::Mode* mode) { 1069 if (paint) { 1070 if (!mExtensions.hasFramebufferFetch()) { 1071 const bool isMode = SkXfermode::IsMode(paint->getXfermode(), mode); 1072 if (!isMode) { 1073 // Assume SRC_OVER 1074 *mode = SkXfermode::kSrcOver_Mode; 1075 } 1076 } else { 1077 *mode = getXfermode(paint->getXfermode()); 1078 } 1079 1080 // Skia draws using the color's alpha channel if < 255 1081 // Otherwise, it uses the paint's alpha 1082 int color = paint->getColor(); 1083 *alpha = (color >> 24) & 0xFF; 1084 if (*alpha == 255) { 1085 *alpha = paint->getAlpha(); 1086 } 1087 } else { 1088 *mode = SkXfermode::kSrcOver_Mode; 1089 *alpha = 255; 1090 } 1091} 1092 1093SkXfermode::Mode OpenGLRenderer::getXfermode(SkXfermode* mode) { 1094 if (mode == NULL) { 1095 return SkXfermode::kSrcOver_Mode; 1096 } 1097 return mode->fMode; 1098} 1099 1100void OpenGLRenderer::bindTexture(GLuint texture, GLenum wrapS, GLenum wrapT, GLuint textureUnit) { 1101 glActiveTexture(gTextureUnits[textureUnit]); 1102 glBindTexture(GL_TEXTURE_2D, texture); 1103 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS); 1104 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT); 1105} 1106 1107}; // namespace uirenderer 1108}; // namespace android 1109