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