OpenGLRenderer.cpp revision 15c3f19a445b8df575911a16e8a6dba755a084b5
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#include "OpenGLRenderer.h" 18 19#include "DeferredDisplayList.h" 20#include "GammaFontRenderer.h" 21#include "Glop.h" 22#include "GlopBuilder.h" 23#include "Patch.h" 24#include "PathTessellator.h" 25#include "Properties.h" 26#include "RenderNode.h" 27#include "renderstate/MeshState.h" 28#include "renderstate/RenderState.h" 29#include "ShadowTessellator.h" 30#include "SkiaShader.h" 31#include "Vector.h" 32#include "VertexBuffer.h" 33#include "utils/GLUtils.h" 34#include "utils/PaintUtils.h" 35#include "utils/TraceUtils.h" 36 37#include <stdlib.h> 38#include <stdint.h> 39#include <sys/types.h> 40 41#include <SkCanvas.h> 42#include <SkColor.h> 43#include <SkPathOps.h> 44#include <SkShader.h> 45#include <SkTypeface.h> 46 47#include <utils/Log.h> 48#include <utils/StopWatch.h> 49 50#include <private/hwui/DrawGlInfo.h> 51 52#include <ui/Rect.h> 53 54#if DEBUG_DETAILED_EVENTS 55 #define EVENT_LOGD(...) eventMarkDEBUG(__VA_ARGS__) 56#else 57 #define EVENT_LOGD(...) 58#endif 59 60namespace android { 61namespace uirenderer { 62 63/////////////////////////////////////////////////////////////////////////////// 64// Constructors/destructor 65/////////////////////////////////////////////////////////////////////////////// 66 67OpenGLRenderer::OpenGLRenderer(RenderState& renderState) 68 : mState(*this) 69 , mCaches(Caches::getInstance()) 70 , mRenderState(renderState) 71 , mFrameStarted(false) 72 , mScissorOptimizationDisabled(false) 73 , mDirty(false) 74 , mLightCenter((Vector3){FLT_MIN, FLT_MIN, FLT_MIN}) 75 , mLightRadius(FLT_MIN) 76 , mAmbientShadowAlpha(0) 77 , mSpotShadowAlpha(0) { 78} 79 80OpenGLRenderer::~OpenGLRenderer() { 81 // The context has already been destroyed at this point, do not call 82 // GL APIs. All GL state should be kept in Caches.h 83} 84 85void OpenGLRenderer::initProperties() { 86 char property[PROPERTY_VALUE_MAX]; 87 if (property_get(PROPERTY_DISABLE_SCISSOR_OPTIMIZATION, property, "false")) { 88 mScissorOptimizationDisabled = !strcasecmp(property, "true"); 89 INIT_LOGD(" Scissor optimization %s", 90 mScissorOptimizationDisabled ? "disabled" : "enabled"); 91 } else { 92 INIT_LOGD(" Scissor optimization enabled"); 93 } 94} 95 96void OpenGLRenderer::initLight(float lightRadius, uint8_t ambientShadowAlpha, 97 uint8_t spotShadowAlpha) { 98 mLightRadius = lightRadius; 99 mAmbientShadowAlpha = ambientShadowAlpha; 100 mSpotShadowAlpha = spotShadowAlpha; 101} 102 103void OpenGLRenderer::setLightCenter(const Vector3& lightCenter) { 104 mLightCenter = lightCenter; 105} 106 107/////////////////////////////////////////////////////////////////////////////// 108// Setup 109/////////////////////////////////////////////////////////////////////////////// 110 111void OpenGLRenderer::onViewportInitialized() { 112 glDisable(GL_DITHER); 113 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 114} 115 116void OpenGLRenderer::setupFrameState(int viewportWidth, int viewportHeight, 117 float left, float top, float right, float bottom, bool opaque) { 118 mCaches.clearGarbage(); 119 mState.initializeSaveStack(viewportWidth, viewportHeight, 120 left, top, right, bottom, mLightCenter); 121 mOpaque = opaque; 122 mTilingClip.set(left, top, right, bottom); 123} 124 125void OpenGLRenderer::startFrame() { 126 if (mFrameStarted) return; 127 mFrameStarted = true; 128 129 mState.setDirtyClip(true); 130 131 discardFramebuffer(mTilingClip.left, mTilingClip.top, mTilingClip.right, mTilingClip.bottom); 132 133 mRenderState.setViewport(mState.getWidth(), mState.getHeight()); 134 135 debugOverdraw(true, true); 136 137 clear(mTilingClip.left, mTilingClip.top, 138 mTilingClip.right, mTilingClip.bottom, mOpaque); 139} 140 141void OpenGLRenderer::prepareDirty(int viewportWidth, int viewportHeight, 142 float left, float top, float right, float bottom, bool opaque) { 143 144 setupFrameState(viewportWidth, viewportHeight, left, top, right, bottom, opaque); 145 146 // Layer renderers will start the frame immediately 147 // The framebuffer renderer will first defer the display list 148 // for each layer and wait until the first drawing command 149 // to start the frame 150 if (currentSnapshot()->fbo == 0) { 151 mRenderState.blend().syncEnabled(); 152 updateLayers(); 153 } else { 154 startFrame(); 155 } 156} 157 158void OpenGLRenderer::discardFramebuffer(float left, float top, float right, float bottom) { 159 // If we know that we are going to redraw the entire framebuffer, 160 // perform a discard to let the driver know we don't need to preserve 161 // the back buffer for this frame. 162 if (mCaches.extensions().hasDiscardFramebuffer() && 163 left <= 0.0f && top <= 0.0f && right >= mState.getWidth() && bottom >= mState.getHeight()) { 164 const bool isFbo = getTargetFbo() == 0; 165 const GLenum attachments[] = { 166 isFbo ? (const GLenum) GL_COLOR_EXT : (const GLenum) GL_COLOR_ATTACHMENT0, 167 isFbo ? (const GLenum) GL_STENCIL_EXT : (const GLenum) GL_STENCIL_ATTACHMENT }; 168 glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments); 169 } 170} 171 172void OpenGLRenderer::clear(float left, float top, float right, float bottom, bool opaque) { 173 if (!opaque) { 174 mRenderState.scissor().setEnabled(true); 175 mRenderState.scissor().set(left, getViewportHeight() - bottom, right - left, bottom - top); 176 glClear(GL_COLOR_BUFFER_BIT); 177 mDirty = true; 178 return; 179 } 180 181 mRenderState.scissor().reset(); 182} 183 184bool OpenGLRenderer::finish() { 185 renderOverdraw(); 186 mTempPaths.clear(); 187 188 // When finish() is invoked on FBO 0 we've reached the end 189 // of the current frame 190 if (getTargetFbo() == 0) { 191 mCaches.pathCache.trim(); 192 mCaches.tessellationCache.trim(); 193 } 194 195 if (!suppressErrorChecks()) { 196#if DEBUG_OPENGL 197 GLUtils::dumpGLErrors(); 198#endif 199 200#if DEBUG_MEMORY_USAGE 201 mCaches.dumpMemoryUsage(); 202#else 203 if (Properties::debugLevel & kDebugMemory) { 204 mCaches.dumpMemoryUsage(); 205 } 206#endif 207 } 208 209 mFrameStarted = false; 210 211 return reportAndClearDirty(); 212} 213 214void OpenGLRenderer::resumeAfterLayer() { 215 mRenderState.setViewport(getViewportWidth(), getViewportHeight()); 216 mRenderState.bindFramebuffer(currentSnapshot()->fbo); 217 debugOverdraw(true, false); 218 219 mRenderState.scissor().reset(); 220 dirtyClip(); 221} 222 223void OpenGLRenderer::callDrawGLFunction(Functor* functor, Rect& dirty) { 224 if (mState.currentlyIgnored()) return; 225 226 Rect clip(mState.currentRenderTargetClip()); 227 clip.snapToPixelBoundaries(); 228 229 // Since we don't know what the functor will draw, let's dirty 230 // the entire clip region 231 if (hasLayer()) { 232 dirtyLayerUnchecked(clip, getRegion()); 233 } 234 235 DrawGlInfo info; 236 info.clipLeft = clip.left; 237 info.clipTop = clip.top; 238 info.clipRight = clip.right; 239 info.clipBottom = clip.bottom; 240 info.isLayer = hasLayer(); 241 info.width = getViewportWidth(); 242 info.height = getViewportHeight(); 243 currentTransform()->copyTo(&info.transform[0]); 244 245 bool prevDirtyClip = mState.getDirtyClip(); 246 // setup GL state for functor 247 if (mState.getDirtyClip()) { 248 setStencilFromClip(); // can issue draws, so must precede enableScissor()/interrupt() 249 } 250 if (mRenderState.scissor().setEnabled(true) || prevDirtyClip) { 251 setScissorFromClip(); 252 } 253 254 mRenderState.invokeFunctor(functor, DrawGlInfo::kModeDraw, &info); 255 // Scissor may have been modified, reset dirty clip 256 dirtyClip(); 257 258 mDirty = true; 259} 260 261/////////////////////////////////////////////////////////////////////////////// 262// Debug 263/////////////////////////////////////////////////////////////////////////////// 264 265void OpenGLRenderer::eventMarkDEBUG(const char* fmt, ...) const { 266#if DEBUG_DETAILED_EVENTS 267 const int BUFFER_SIZE = 256; 268 va_list ap; 269 char buf[BUFFER_SIZE]; 270 271 va_start(ap, fmt); 272 vsnprintf(buf, BUFFER_SIZE, fmt, ap); 273 va_end(ap); 274 275 eventMark(buf); 276#endif 277} 278 279 280void OpenGLRenderer::eventMark(const char* name) const { 281 mCaches.eventMark(0, name); 282} 283 284void OpenGLRenderer::startMark(const char* name) const { 285 mCaches.startMark(0, name); 286} 287 288void OpenGLRenderer::endMark() const { 289 mCaches.endMark(); 290} 291 292void OpenGLRenderer::debugOverdraw(bool enable, bool clear) { 293 mRenderState.debugOverdraw(enable, clear); 294} 295 296void OpenGLRenderer::renderOverdraw() { 297 if (Properties::debugOverdraw && getTargetFbo() == 0) { 298 const Rect* clip = &mTilingClip; 299 300 mRenderState.scissor().setEnabled(true); 301 mRenderState.scissor().set(clip->left, 302 mState.firstSnapshot()->getViewportHeight() - clip->bottom, 303 clip->right - clip->left, 304 clip->bottom - clip->top); 305 306 // 1x overdraw 307 mRenderState.stencil().enableDebugTest(2); 308 drawColor(mCaches.getOverdrawColor(1), SkXfermode::kSrcOver_Mode); 309 310 // 2x overdraw 311 mRenderState.stencil().enableDebugTest(3); 312 drawColor(mCaches.getOverdrawColor(2), SkXfermode::kSrcOver_Mode); 313 314 // 3x overdraw 315 mRenderState.stencil().enableDebugTest(4); 316 drawColor(mCaches.getOverdrawColor(3), SkXfermode::kSrcOver_Mode); 317 318 // 4x overdraw and higher 319 mRenderState.stencil().enableDebugTest(4, true); 320 drawColor(mCaches.getOverdrawColor(4), SkXfermode::kSrcOver_Mode); 321 322 mRenderState.stencil().disable(); 323 } 324} 325 326/////////////////////////////////////////////////////////////////////////////// 327// Layers 328/////////////////////////////////////////////////////////////////////////////// 329 330bool OpenGLRenderer::updateLayer(Layer* layer, bool inFrame) { 331 if (layer->deferredUpdateScheduled && layer->renderer 332 && layer->renderNode.get() && layer->renderNode->isRenderable()) { 333 334 if (inFrame) { 335 debugOverdraw(false, false); 336 } 337 338 if (CC_UNLIKELY(inFrame || Properties::drawDeferDisabled)) { 339 layer->render(*this); 340 } else { 341 layer->defer(*this); 342 } 343 344 if (inFrame) { 345 resumeAfterLayer(); 346 } 347 348 layer->debugDrawUpdate = Properties::debugLayersUpdates; 349 layer->hasDrawnSinceUpdate = false; 350 351 return true; 352 } 353 354 return false; 355} 356 357void OpenGLRenderer::updateLayers() { 358 // If draw deferring is enabled this method will simply defer 359 // the display list of each individual layer. The layers remain 360 // in the layer updates list which will be cleared by flushLayers(). 361 int count = mLayerUpdates.size(); 362 if (count > 0) { 363 if (CC_UNLIKELY(Properties::drawDeferDisabled)) { 364 startMark("Layer Updates"); 365 } else { 366 startMark("Defer Layer Updates"); 367 } 368 369 // Note: it is very important to update the layers in order 370 for (int i = 0; i < count; i++) { 371 Layer* layer = mLayerUpdates[i].get(); 372 updateLayer(layer, false); 373 } 374 375 if (CC_UNLIKELY(Properties::drawDeferDisabled)) { 376 mLayerUpdates.clear(); 377 mRenderState.bindFramebuffer(getTargetFbo()); 378 } 379 endMark(); 380 } 381} 382 383void OpenGLRenderer::flushLayers() { 384 int count = mLayerUpdates.size(); 385 if (count > 0) { 386 startMark("Apply Layer Updates"); 387 388 // Note: it is very important to update the layers in order 389 for (int i = 0; i < count; i++) { 390 mLayerUpdates[i]->flush(); 391 } 392 393 mLayerUpdates.clear(); 394 mRenderState.bindFramebuffer(getTargetFbo()); 395 396 endMark(); 397 } 398} 399 400void OpenGLRenderer::pushLayerUpdate(Layer* layer) { 401 if (layer) { 402 // Make sure we don't introduce duplicates. 403 // SortedVector would do this automatically but we need to respect 404 // the insertion order. The linear search is not an issue since 405 // this list is usually very short (typically one item, at most a few) 406 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 407 if (mLayerUpdates[i] == layer) { 408 return; 409 } 410 } 411 mLayerUpdates.push_back(layer); 412 } 413} 414 415void OpenGLRenderer::cancelLayerUpdate(Layer* layer) { 416 if (layer) { 417 for (int i = mLayerUpdates.size() - 1; i >= 0; i--) { 418 if (mLayerUpdates[i] == layer) { 419 mLayerUpdates.erase(mLayerUpdates.begin() + i); 420 break; 421 } 422 } 423 } 424} 425 426void OpenGLRenderer::flushLayerUpdates() { 427 ATRACE_NAME("Update HW Layers"); 428 mRenderState.blend().syncEnabled(); 429 updateLayers(); 430 flushLayers(); 431 // Wait for all the layer updates to be executed 432 glFinish(); 433} 434 435void OpenGLRenderer::markLayersAsBuildLayers() { 436 for (size_t i = 0; i < mLayerUpdates.size(); i++) { 437 mLayerUpdates[i]->wasBuildLayered = true; 438 } 439} 440 441/////////////////////////////////////////////////////////////////////////////// 442// State management 443/////////////////////////////////////////////////////////////////////////////// 444 445void OpenGLRenderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) { 446 bool restoreViewport = removed.flags & Snapshot::kFlagIsFboLayer; 447 bool restoreClip = removed.flags & Snapshot::kFlagClipSet; 448 bool restoreLayer = removed.flags & Snapshot::kFlagIsLayer; 449 450 if (restoreViewport) { 451 mRenderState.setViewport(getViewportWidth(), getViewportHeight()); 452 } 453 454 if (restoreClip) { 455 dirtyClip(); 456 } 457 458 if (restoreLayer) { 459 endMark(); // Savelayer 460 ATRACE_END(); // SaveLayer 461 startMark("ComposeLayer"); 462 composeLayer(removed, restored); 463 endMark(); 464 } 465} 466 467/////////////////////////////////////////////////////////////////////////////// 468// Layers 469/////////////////////////////////////////////////////////////////////////////// 470 471int OpenGLRenderer::saveLayer(float left, float top, float right, float bottom, 472 const SkPaint* paint, int flags, const SkPath* convexMask) { 473 // force matrix/clip isolation for layer 474 flags |= SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag; 475 476 const int count = mState.saveSnapshot(flags); 477 478 if (!mState.currentlyIgnored()) { 479 createLayer(left, top, right, bottom, paint, flags, convexMask); 480 } 481 482 return count; 483} 484 485void OpenGLRenderer::calculateLayerBoundsAndClip(Rect& bounds, Rect& clip, bool fboLayer) { 486 const Rect untransformedBounds(bounds); 487 488 currentTransform()->mapRect(bounds); 489 490 // Layers only make sense if they are in the framebuffer's bounds 491 bounds.doIntersect(mState.currentRenderTargetClip()); 492 if (!bounds.isEmpty()) { 493 // We cannot work with sub-pixels in this case 494 bounds.snapToPixelBoundaries(); 495 496 // When the layer is not an FBO, we may use glCopyTexImage so we 497 // need to make sure the layer does not extend outside the bounds 498 // of the framebuffer 499 const Snapshot& previous = *(currentSnapshot()->previous); 500 Rect previousViewport(0, 0, previous.getViewportWidth(), previous.getViewportHeight()); 501 502 bounds.doIntersect(previousViewport); 503 if (!bounds.isEmpty() && fboLayer) { 504 clip.set(bounds); 505 mat4 inverse; 506 inverse.loadInverse(*currentTransform()); 507 inverse.mapRect(clip); 508 clip.snapToPixelBoundaries(); 509 clip.doIntersect(untransformedBounds); 510 if (!clip.isEmpty()) { 511 clip.translate(-untransformedBounds.left, -untransformedBounds.top); 512 bounds.set(untransformedBounds); 513 } 514 } 515 } 516} 517 518void OpenGLRenderer::updateSnapshotIgnoreForLayer(const Rect& bounds, const Rect& clip, 519 bool fboLayer, int alpha) { 520 if (bounds.isEmpty() || bounds.getWidth() > mCaches.maxTextureSize || 521 bounds.getHeight() > mCaches.maxTextureSize || 522 (fboLayer && clip.isEmpty())) { 523 writableSnapshot()->empty = fboLayer; 524 } else { 525 writableSnapshot()->invisible = writableSnapshot()->invisible || (alpha <= 0 && fboLayer); 526 } 527} 528 529int OpenGLRenderer::saveLayerDeferred(float left, float top, float right, float bottom, 530 const SkPaint* paint, int flags) { 531 const int count = mState.saveSnapshot(flags); 532 533 if (!mState.currentlyIgnored() && (flags & SkCanvas::kClipToLayer_SaveFlag)) { 534 // initialize the snapshot as though it almost represents an FBO layer so deferred draw 535 // operations will be able to store and restore the current clip and transform info, and 536 // quick rejection will be correct (for display lists) 537 538 Rect bounds(left, top, right, bottom); 539 Rect clip; 540 calculateLayerBoundsAndClip(bounds, clip, true); 541 updateSnapshotIgnoreForLayer(bounds, clip, true, PaintUtils::getAlphaDirect(paint)); 542 543 if (!mState.currentlyIgnored()) { 544 writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f); 545 writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom); 546 writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight()); 547 writableSnapshot()->roundRectClipState = nullptr; 548 } 549 } 550 551 return count; 552} 553 554/** 555 * Layers are viewed by Skia are slightly different than layers in image editing 556 * programs (for instance.) When a layer is created, previously created layers 557 * and the frame buffer still receive every drawing command. For instance, if a 558 * layer is created and a shape intersecting the bounds of the layers and the 559 * framebuffer is draw, the shape will be drawn on both (unless the layer was 560 * created with the SkCanvas::kClipToLayer_SaveFlag flag.) 561 * 562 * A way to implement layers is to create an FBO for each layer, backed by an RGBA 563 * texture. Unfortunately, this is inefficient as it requires every primitive to 564 * be drawn n + 1 times, where n is the number of active layers. In practice this 565 * means, for every primitive: 566 * - Switch active frame buffer 567 * - Change viewport, clip and projection matrix 568 * - Issue the drawing 569 * 570 * Switching rendering target n + 1 times per drawn primitive is extremely costly. 571 * To avoid this, layers are implemented in a different way here, at least in the 572 * general case. FBOs are used, as an optimization, when the "clip to layer" flag 573 * is set. When this flag is set we can redirect all drawing operations into a 574 * single FBO. 575 * 576 * This implementation relies on the frame buffer being at least RGBA 8888. When 577 * a layer is created, only a texture is created, not an FBO. The content of the 578 * frame buffer contained within the layer's bounds is copied into this texture 579 * using glCopyTexImage2D(). The layer's region is then cleared(1) in the frame 580 * buffer and drawing continues as normal. This technique therefore treats the 581 * frame buffer as a scratch buffer for the layers. 582 * 583 * To compose the layers back onto the frame buffer, each layer texture 584 * (containing the original frame buffer data) is drawn as a simple quad over 585 * the frame buffer. The trick is that the quad is set as the composition 586 * destination in the blending equation, and the frame buffer becomes the source 587 * of the composition. 588 * 589 * Drawing layers with an alpha value requires an extra step before composition. 590 * An empty quad is drawn over the layer's region in the frame buffer. This quad 591 * is drawn with the rgba color (0,0,0,alpha). The alpha value offered by the 592 * quad is used to multiply the colors in the frame buffer. This is achieved by 593 * changing the GL blend functions for the GL_FUNC_ADD blend equation to 594 * GL_ZERO, GL_SRC_ALPHA. 595 * 596 * Because glCopyTexImage2D() can be slow, an alternative implementation might 597 * be use to draw a single clipped layer. The implementation described above 598 * is correct in every case. 599 * 600 * (1) The frame buffer is actually not cleared right away. To allow the GPU 601 * to potentially optimize series of calls to glCopyTexImage2D, the frame 602 * buffer is left untouched until the first drawing operation. Only when 603 * something actually gets drawn are the layers regions cleared. 604 */ 605bool OpenGLRenderer::createLayer(float left, float top, float right, float bottom, 606 const SkPaint* paint, int flags, const SkPath* convexMask) { 607 LAYER_LOGD("Requesting layer %.2fx%.2f", right - left, bottom - top); 608 LAYER_LOGD("Layer cache size = %d", mCaches.layerCache.getSize()); 609 610 const bool fboLayer = flags & SkCanvas::kClipToLayer_SaveFlag; 611 612 // Window coordinates of the layer 613 Rect clip; 614 Rect bounds(left, top, right, bottom); 615 calculateLayerBoundsAndClip(bounds, clip, fboLayer); 616 updateSnapshotIgnoreForLayer(bounds, clip, fboLayer, PaintUtils::getAlphaDirect(paint)); 617 618 // Bail out if we won't draw in this snapshot 619 if (mState.currentlyIgnored()) { 620 return false; 621 } 622 623 mCaches.textureState().activateTexture(0); 624 Layer* layer = mCaches.layerCache.get(mRenderState, bounds.getWidth(), bounds.getHeight()); 625 if (!layer) { 626 return false; 627 } 628 629 layer->setPaint(paint); 630 layer->layer.set(bounds); 631 layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->getHeight()), 632 bounds.getWidth() / float(layer->getWidth()), 0.0f); 633 634 layer->setBlend(true); 635 layer->setDirty(false); 636 layer->setConvexMask(convexMask); // note: the mask must be cleared before returning to the cache 637 638 // Save the layer in the snapshot 639 writableSnapshot()->flags |= Snapshot::kFlagIsLayer; 640 writableSnapshot()->layer = layer; 641 642 ATRACE_FORMAT_BEGIN("%ssaveLayer %ux%u", 643 fboLayer ? "" : "unclipped ", 644 layer->getWidth(), layer->getHeight()); 645 startMark("SaveLayer"); 646 if (fboLayer) { 647 return createFboLayer(layer, bounds, clip); 648 } else { 649 // Copy the framebuffer into the layer 650 layer->bindTexture(); 651 if (!bounds.isEmpty()) { 652 if (layer->isEmpty()) { 653 // Workaround for some GL drivers. When reading pixels lying outside 654 // of the window we should get undefined values for those pixels. 655 // Unfortunately some drivers will turn the entire target texture black 656 // when reading outside of the window. 657 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, layer->getWidth(), layer->getHeight(), 658 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); 659 layer->setEmpty(false); 660 } 661 662 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 663 bounds.left, getViewportHeight() - bounds.bottom, 664 bounds.getWidth(), bounds.getHeight()); 665 666 // Enqueue the buffer coordinates to clear the corresponding region later 667 mLayers.push_back(Rect(bounds)); 668 } 669 } 670 671 return true; 672} 673 674bool OpenGLRenderer::createFboLayer(Layer* layer, Rect& bounds, Rect& clip) { 675 layer->clipRect.set(clip); 676 layer->setFbo(mRenderState.genFramebuffer()); 677 678 writableSnapshot()->region = &writableSnapshot()->layer->region; 679 writableSnapshot()->flags |= Snapshot::kFlagFboTarget | Snapshot::kFlagIsFboLayer; 680 writableSnapshot()->fbo = layer->getFbo(); 681 writableSnapshot()->resetTransform(-bounds.left, -bounds.top, 0.0f); 682 writableSnapshot()->resetClip(clip.left, clip.top, clip.right, clip.bottom); 683 writableSnapshot()->initializeViewport(bounds.getWidth(), bounds.getHeight()); 684 writableSnapshot()->roundRectClipState = nullptr; 685 686 debugOverdraw(false, false); 687 // Bind texture to FBO 688 mRenderState.bindFramebuffer(layer->getFbo()); 689 layer->bindTexture(); 690 691 // Initialize the texture if needed 692 if (layer->isEmpty()) { 693 layer->allocateTexture(); 694 layer->setEmpty(false); 695 } 696 697 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 698 layer->getTextureId(), 0); 699 700 // Clear the FBO, expand the clear region by 1 to get nice bilinear filtering 701 mRenderState.scissor().setEnabled(true); 702 mRenderState.scissor().set(clip.left - 1.0f, bounds.getHeight() - clip.bottom - 1.0f, 703 clip.getWidth() + 2.0f, clip.getHeight() + 2.0f); 704 glClear(GL_COLOR_BUFFER_BIT); 705 706 dirtyClip(); 707 708 // Change the ortho projection 709 mRenderState.setViewport(bounds.getWidth(), bounds.getHeight()); 710 return true; 711} 712 713/** 714 * Read the documentation of createLayer() before doing anything in this method. 715 */ 716void OpenGLRenderer::composeLayer(const Snapshot& removed, const Snapshot& restored) { 717 if (!removed.layer) { 718 ALOGE("Attempting to compose a layer that does not exist"); 719 return; 720 } 721 722 Layer* layer = removed.layer; 723 const Rect& rect = layer->layer; 724 const bool fboLayer = removed.flags & Snapshot::kFlagIsFboLayer; 725 726 bool clipRequired = false; 727 mState.calculateQuickRejectForScissor(rect.left, rect.top, rect.right, rect.bottom, 728 &clipRequired, nullptr, false); // safely ignore return, should never be rejected 729 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 730 731 if (fboLayer) { 732 // Detach the texture from the FBO 733 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); 734 735 layer->removeFbo(false); 736 737 // Unbind current FBO and restore previous one 738 mRenderState.bindFramebuffer(restored.fbo); 739 debugOverdraw(true, false); 740 } 741 742 if (!fboLayer && layer->getAlpha() < 255) { 743 SkPaint layerPaint; 744 layerPaint.setAlpha(layer->getAlpha()); 745 layerPaint.setXfermodeMode(SkXfermode::kDstIn_Mode); 746 layerPaint.setColorFilter(layer->getColorFilter()); 747 748 drawColorRect(rect.left, rect.top, rect.right, rect.bottom, &layerPaint, true); 749 // Required below, composeLayerRect() will divide by 255 750 layer->setAlpha(255); 751 } 752 753 mRenderState.meshState().unbindMeshBuffer(); 754 755 mCaches.textureState().activateTexture(0); 756 757 // When the layer is stored in an FBO, we can save a bit of fillrate by 758 // drawing only the dirty region 759 if (fboLayer) { 760 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *restored.transform); 761 composeLayerRegion(layer, rect); 762 } else if (!rect.isEmpty()) { 763 dirtyLayer(rect.left, rect.top, rect.right, rect.bottom); 764 765 save(0); 766 // the layer contains screen buffer content that shouldn't be alpha modulated 767 // (and any necessary alpha modulation was handled drawing into the layer) 768 writableSnapshot()->alpha = 1.0f; 769 composeLayerRectSwapped(layer, rect); 770 restore(); 771 } 772 773 dirtyClip(); 774 775 // Failing to add the layer to the cache should happen only if the layer is too large 776 layer->setConvexMask(nullptr); 777 if (!mCaches.layerCache.put(layer)) { 778 LAYER_LOGD("Deleting layer"); 779 layer->decStrong(nullptr); 780 } 781} 782 783void OpenGLRenderer::drawTextureLayer(Layer* layer, const Rect& rect) { 784 const bool tryToSnap = !layer->getForceFilter() 785 && layer->getWidth() == (uint32_t) rect.getWidth() 786 && layer->getHeight() == (uint32_t) rect.getHeight(); 787 Glop glop; 788 GlopBuilder(mRenderState, mCaches, &glop) 789 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 790 .setMeshTexturedUvQuad(nullptr, Rect(0, 1, 1, 0)) // TODO: simplify with VBO 791 .setFillTextureLayer(*layer, getLayerAlpha(layer)) 792 .setTransform(*currentSnapshot(), TransformFlags::None) 793 .setModelViewMapUnitToRectOptionalSnap(tryToSnap, rect) 794 .build(); 795 renderGlop(glop); 796} 797 798void OpenGLRenderer::composeLayerRectSwapped(Layer* layer, const Rect& rect) { 799 Glop glop; 800 GlopBuilder(mRenderState, mCaches, &glop) 801 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 802 .setMeshTexturedUvQuad(nullptr, layer->texCoords) 803 .setFillLayer(layer->getTexture(), layer->getColorFilter(), 804 getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::Swap) 805 .setTransform(*currentSnapshot(), TransformFlags::MeshIgnoresCanvasTransform) 806 .setModelViewMapUnitToRect(rect) 807 .build(); 808 renderGlop(glop); 809} 810 811void OpenGLRenderer::composeLayerRect(Layer* layer, const Rect& rect) { 812 if (layer->isTextureLayer()) { 813 EVENT_LOGD("composeTextureLayerRect"); 814 drawTextureLayer(layer, rect); 815 } else { 816 EVENT_LOGD("composeHardwareLayerRect"); 817 818 const bool tryToSnap = layer->getWidth() == static_cast<uint32_t>(rect.getWidth()) 819 && layer->getHeight() == static_cast<uint32_t>(rect.getHeight()); 820 Glop glop; 821 GlopBuilder(mRenderState, mCaches, &glop) 822 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 823 .setMeshTexturedUvQuad(nullptr, layer->texCoords) 824 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap) 825 .setTransform(*currentSnapshot(), TransformFlags::None) 826 .setModelViewMapUnitToRectOptionalSnap(tryToSnap, rect) 827 .build(); 828 renderGlop(glop); 829 } 830} 831 832/** 833 * Issues the command X, and if we're composing a save layer to the fbo or drawing a newly updated 834 * hardware layer with overdraw debug on, draws again to the stencil only, so that these draw 835 * operations are correctly counted twice for overdraw. NOTE: assumes composeLayerRegion only used 836 * by saveLayer's restore 837 */ 838#define DRAW_DOUBLE_STENCIL_IF(COND, DRAW_COMMAND) { \ 839 DRAW_COMMAND; \ 840 if (CC_UNLIKELY(Properties::debugOverdraw && getTargetFbo() == 0 && COND)) { \ 841 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); \ 842 DRAW_COMMAND; \ 843 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); \ 844 } \ 845 } 846 847#define DRAW_DOUBLE_STENCIL(DRAW_COMMAND) DRAW_DOUBLE_STENCIL_IF(true, DRAW_COMMAND) 848 849// This class is purely for inspection. It inherits from SkShader, but Skia does not know how to 850// use it. The OpenGLRenderer will look at it to find its Layer and whether it is opaque. 851class LayerShader : public SkShader { 852public: 853 LayerShader(Layer* layer, const SkMatrix* localMatrix) 854 : INHERITED(localMatrix) 855 , mLayer(layer) { 856 } 857 858 virtual bool asACustomShader(void** data) const override { 859 if (data) { 860 *data = static_cast<void*>(mLayer); 861 } 862 return true; 863 } 864 865 virtual bool isOpaque() const override { 866 return !mLayer->isBlend(); 867 } 868 869protected: 870 virtual void shadeSpan(int x, int y, SkPMColor[], int count) { 871 LOG_ALWAYS_FATAL("LayerShader should never be drawn with raster backend."); 872 } 873 874 virtual void flatten(SkWriteBuffer&) const override { 875 LOG_ALWAYS_FATAL("LayerShader should never be flattened."); 876 } 877 878 virtual Factory getFactory() const override { 879 LOG_ALWAYS_FATAL("LayerShader should never be created from a stream."); 880 return nullptr; 881 } 882private: 883 // Unowned. 884 Layer* mLayer; 885 typedef SkShader INHERITED; 886}; 887 888void OpenGLRenderer::composeLayerRegion(Layer* layer, const Rect& rect) { 889 if (CC_UNLIKELY(layer->region.isEmpty())) return; // nothing to draw 890 891 if (layer->getConvexMask()) { 892 save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag); 893 894 // clip to the area of the layer the mask can be larger 895 clipRect(rect.left, rect.top, rect.right, rect.bottom, SkRegion::kIntersect_Op); 896 897 SkPaint paint; 898 paint.setAntiAlias(true); 899 paint.setColor(SkColorSetARGB(int(getLayerAlpha(layer) * 255), 0, 0, 0)); 900 901 // create LayerShader to map SaveLayer content into subsequent draw 902 SkMatrix shaderMatrix; 903 shaderMatrix.setTranslate(rect.left, rect.bottom); 904 shaderMatrix.preScale(1, -1); 905 LayerShader layerShader(layer, &shaderMatrix); 906 paint.setShader(&layerShader); 907 908 // Since the drawing primitive is defined in local drawing space, 909 // we don't need to modify the draw matrix 910 const SkPath* maskPath = layer->getConvexMask(); 911 DRAW_DOUBLE_STENCIL(drawConvexPath(*maskPath, &paint)); 912 913 paint.setShader(nullptr); 914 restore(); 915 916 return; 917 } 918 919 if (layer->region.isRect()) { 920 layer->setRegionAsRect(); 921 922 DRAW_DOUBLE_STENCIL(composeLayerRect(layer, layer->regionRect)); 923 924 layer->region.clear(); 925 return; 926 } 927 928 EVENT_LOGD("composeLayerRegion"); 929 // standard Region based draw 930 size_t count; 931 const android::Rect* rects; 932 Region safeRegion; 933 if (CC_LIKELY(hasRectToRectTransform())) { 934 rects = layer->region.getArray(&count); 935 } else { 936 safeRegion = Region::createTJunctionFreeRegion(layer->region); 937 rects = safeRegion.getArray(&count); 938 } 939 940 const float texX = 1.0f / float(layer->getWidth()); 941 const float texY = 1.0f / float(layer->getHeight()); 942 const float height = rect.getHeight(); 943 944 TextureVertex quadVertices[count * 4]; 945 TextureVertex* mesh = &quadVertices[0]; 946 for (size_t i = 0; i < count; i++) { 947 const android::Rect* r = &rects[i]; 948 949 const float u1 = r->left * texX; 950 const float v1 = (height - r->top) * texY; 951 const float u2 = r->right * texX; 952 const float v2 = (height - r->bottom) * texY; 953 954 // TODO: Reject quads outside of the clip 955 TextureVertex::set(mesh++, r->left, r->top, u1, v1); 956 TextureVertex::set(mesh++, r->right, r->top, u2, v1); 957 TextureVertex::set(mesh++, r->left, r->bottom, u1, v2); 958 TextureVertex::set(mesh++, r->right, r->bottom, u2, v2); 959 } 960 Rect modelRect = Rect(rect.getWidth(), rect.getHeight()); 961 Glop glop; 962 GlopBuilder(mRenderState, mCaches, &glop) 963 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 964 .setMeshTexturedIndexedQuads(&quadVertices[0], count * 6) 965 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap) 966 .setTransform(*currentSnapshot(), TransformFlags::None) 967 .setModelViewOffsetRectSnap(rect.left, rect.top, modelRect) 968 .build(); 969 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop)); 970 971#if DEBUG_LAYERS_AS_REGIONS 972 drawRegionRectsDebug(layer->region); 973#endif 974 975 layer->region.clear(); 976} 977 978#if DEBUG_LAYERS_AS_REGIONS 979void OpenGLRenderer::drawRegionRectsDebug(const Region& region) { 980 size_t count; 981 const android::Rect* rects = region.getArray(&count); 982 983 uint32_t colors[] = { 984 0x7fff0000, 0x7f00ff00, 985 0x7f0000ff, 0x7fff00ff, 986 }; 987 988 int offset = 0; 989 int32_t top = rects[0].top; 990 991 for (size_t i = 0; i < count; i++) { 992 if (top != rects[i].top) { 993 offset ^= 0x2; 994 top = rects[i].top; 995 } 996 997 SkPaint paint; 998 paint.setColor(colors[offset + (i & 0x1)]); 999 Rect r(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom); 1000 drawColorRect(r.left, r.top, r.right, r.bottom, paint); 1001 } 1002} 1003#endif 1004 1005void OpenGLRenderer::drawRegionRects(const SkRegion& region, const SkPaint& paint, bool dirty) { 1006 Vector<float> rects; 1007 1008 SkRegion::Iterator it(region); 1009 while (!it.done()) { 1010 const SkIRect& r = it.rect(); 1011 rects.push(r.fLeft); 1012 rects.push(r.fTop); 1013 rects.push(r.fRight); 1014 rects.push(r.fBottom); 1015 it.next(); 1016 } 1017 1018 drawColorRects(rects.array(), rects.size(), &paint, true, dirty, false); 1019} 1020 1021void OpenGLRenderer::dirtyLayer(const float left, const float top, 1022 const float right, const float bottom, const Matrix4& transform) { 1023 if (hasLayer()) { 1024 Rect bounds(left, top, right, bottom); 1025 transform.mapRect(bounds); 1026 dirtyLayerUnchecked(bounds, getRegion()); 1027 } 1028} 1029 1030void OpenGLRenderer::dirtyLayer(const float left, const float top, 1031 const float right, const float bottom) { 1032 if (hasLayer()) { 1033 Rect bounds(left, top, right, bottom); 1034 dirtyLayerUnchecked(bounds, getRegion()); 1035 } 1036} 1037 1038void OpenGLRenderer::dirtyLayerUnchecked(Rect& bounds, Region* region) { 1039 bounds.doIntersect(mState.currentRenderTargetClip()); 1040 if (!bounds.isEmpty()) { 1041 bounds.snapToPixelBoundaries(); 1042 android::Rect dirty(bounds.left, bounds.top, bounds.right, bounds.bottom); 1043 if (!dirty.isEmpty()) { 1044 region->orSelf(dirty); 1045 } 1046 } 1047} 1048 1049void OpenGLRenderer::clearLayerRegions() { 1050 const size_t quadCount = mLayers.size(); 1051 if (quadCount == 0) return; 1052 1053 if (!mState.currentlyIgnored()) { 1054 EVENT_LOGD("clearLayerRegions"); 1055 // Doing several glScissor/glClear here can negatively impact 1056 // GPUs with a tiler architecture, instead we draw quads with 1057 // the Clear blending mode 1058 1059 // The list contains bounds that have already been clipped 1060 // against their initial clip rect, and the current clip 1061 // is likely different so we need to disable clipping here 1062 bool scissorChanged = mRenderState.scissor().setEnabled(false); 1063 1064 Vertex mesh[quadCount * 4]; 1065 Vertex* vertex = mesh; 1066 1067 for (uint32_t i = 0; i < quadCount; i++) { 1068 const Rect& bounds = mLayers[i]; 1069 1070 Vertex::set(vertex++, bounds.left, bounds.top); 1071 Vertex::set(vertex++, bounds.right, bounds.top); 1072 Vertex::set(vertex++, bounds.left, bounds.bottom); 1073 Vertex::set(vertex++, bounds.right, bounds.bottom); 1074 } 1075 // We must clear the list of dirty rects before we 1076 // call clearLayerRegions() in renderGlop to prevent 1077 // stencil setup from doing the same thing again 1078 mLayers.clear(); 1079 1080 const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform; 1081 Glop glop; 1082 GlopBuilder(mRenderState, mCaches, &glop) 1083 .setRoundRectClipState(nullptr) // clear ignores clip state 1084 .setMeshIndexedQuads(&mesh[0], quadCount) 1085 .setFillClear() 1086 .setTransform(*currentSnapshot(), transformFlags) 1087 .setModelViewOffsetRect(0, 0, Rect(currentSnapshot()->getRenderTargetClip())) 1088 .build(); 1089 renderGlop(glop, GlopRenderType::LayerClear); 1090 1091 if (scissorChanged) mRenderState.scissor().setEnabled(true); 1092 } else { 1093 mLayers.clear(); 1094 } 1095} 1096 1097/////////////////////////////////////////////////////////////////////////////// 1098// State Deferral 1099/////////////////////////////////////////////////////////////////////////////// 1100 1101bool OpenGLRenderer::storeDisplayState(DeferredDisplayState& state, int stateDeferFlags) { 1102 const Rect& currentClip = mState.currentRenderTargetClip(); 1103 const mat4* currentMatrix = currentTransform(); 1104 1105 if (stateDeferFlags & kStateDeferFlag_Draw) { 1106 // state has bounds initialized in local coordinates 1107 if (!state.mBounds.isEmpty()) { 1108 currentMatrix->mapRect(state.mBounds); 1109 Rect clippedBounds(state.mBounds); 1110 // NOTE: if we ever want to use this clipping info to drive whether the scissor 1111 // is used, it should more closely duplicate the quickReject logic (in how it uses 1112 // snapToPixelBoundaries) 1113 1114 clippedBounds.doIntersect(currentClip); 1115 if (clippedBounds.isEmpty()) { 1116 // quick rejected 1117 return true; 1118 } 1119 1120 state.mClipSideFlags = kClipSide_None; 1121 if (!currentClip.contains(state.mBounds)) { 1122 int& flags = state.mClipSideFlags; 1123 // op partially clipped, so record which sides are clipped for clip-aware merging 1124 if (currentClip.left > state.mBounds.left) flags |= kClipSide_Left; 1125 if (currentClip.top > state.mBounds.top) flags |= kClipSide_Top; 1126 if (currentClip.right < state.mBounds.right) flags |= kClipSide_Right; 1127 if (currentClip.bottom < state.mBounds.bottom) flags |= kClipSide_Bottom; 1128 } 1129 state.mBounds.set(clippedBounds); 1130 } else { 1131 // Empty bounds implies size unknown. Label op as conservatively clipped to disable 1132 // overdraw avoidance (since we don't know what it overlaps) 1133 state.mClipSideFlags = kClipSide_ConservativeFull; 1134 state.mBounds.set(currentClip); 1135 } 1136 } 1137 1138 state.mClipValid = (stateDeferFlags & kStateDeferFlag_Clip); 1139 if (state.mClipValid) { 1140 state.mClip.set(currentClip); 1141 } 1142 1143 // Transform and alpha always deferred, since they are used by state operations 1144 // (Note: saveLayer/restore use colorFilter and alpha, so we just save restore everything) 1145 state.mMatrix = *currentMatrix; 1146 state.mAlpha = currentSnapshot()->alpha; 1147 1148 // always store/restore, since these are just pointers 1149 state.mRoundRectClipState = currentSnapshot()->roundRectClipState; 1150 state.mProjectionPathMask = currentSnapshot()->projectionPathMask; 1151 return false; 1152} 1153 1154void OpenGLRenderer::restoreDisplayState(const DeferredDisplayState& state, bool skipClipRestore) { 1155 setGlobalMatrix(state.mMatrix); 1156 writableSnapshot()->alpha = state.mAlpha; 1157 writableSnapshot()->roundRectClipState = state.mRoundRectClipState; 1158 writableSnapshot()->projectionPathMask = state.mProjectionPathMask; 1159 1160 if (state.mClipValid && !skipClipRestore) { 1161 writableSnapshot()->setClip(state.mClip.left, state.mClip.top, 1162 state.mClip.right, state.mClip.bottom); 1163 dirtyClip(); 1164 } 1165} 1166 1167/** 1168 * Merged multidraw (such as in drawText and drawBitmaps rely on the fact that no clipping is done 1169 * in the draw path. Instead, clipping is done ahead of time - either as a single clip rect (when at 1170 * least one op is clipped), or disabled entirely (because no merged op is clipped) 1171 * 1172 * This method should be called when restoreDisplayState() won't be restoring the clip 1173 */ 1174void OpenGLRenderer::setupMergedMultiDraw(const Rect* clipRect) { 1175 if (clipRect != nullptr) { 1176 writableSnapshot()->setClip(clipRect->left, clipRect->top, clipRect->right, clipRect->bottom); 1177 } else { 1178 writableSnapshot()->setClip(0, 0, mState.getWidth(), mState.getHeight()); 1179 } 1180 dirtyClip(); 1181 bool enableScissor = (clipRect != nullptr) || mScissorOptimizationDisabled; 1182 mRenderState.scissor().setEnabled(enableScissor); 1183} 1184 1185/////////////////////////////////////////////////////////////////////////////// 1186// Clipping 1187/////////////////////////////////////////////////////////////////////////////// 1188 1189void OpenGLRenderer::setScissorFromClip() { 1190 Rect clip(mState.currentRenderTargetClip()); 1191 clip.snapToPixelBoundaries(); 1192 1193 if (mRenderState.scissor().set(clip.left, getViewportHeight() - clip.bottom, 1194 clip.getWidth(), clip.getHeight())) { 1195 mState.setDirtyClip(false); 1196 } 1197} 1198 1199void OpenGLRenderer::ensureStencilBuffer() { 1200 // Thanks to the mismatch between EGL and OpenGL ES FBO we 1201 // cannot attach a stencil buffer to fbo0 dynamically. Let's 1202 // just hope we have one when hasLayer() returns false. 1203 if (hasLayer()) { 1204 attachStencilBufferToLayer(currentSnapshot()->layer); 1205 } 1206} 1207 1208void OpenGLRenderer::attachStencilBufferToLayer(Layer* layer) { 1209 // The layer's FBO is already bound when we reach this stage 1210 if (!layer->getStencilRenderBuffer()) { 1211 RenderBuffer* buffer = mCaches.renderBufferCache.get( 1212 Stencil::getLayerStencilFormat(), 1213 layer->getWidth(), layer->getHeight()); 1214 layer->setStencilRenderBuffer(buffer); 1215 } 1216} 1217 1218static void handlePoint(std::vector<Vertex>& rectangleVertices, const Matrix4& transform, 1219 float x, float y) { 1220 Vertex v; 1221 v.x = x; 1222 v.y = y; 1223 transform.mapPoint(v.x, v.y); 1224 rectangleVertices.push_back(v); 1225} 1226 1227static void handlePointNoTransform(std::vector<Vertex>& rectangleVertices, float x, float y) { 1228 Vertex v; 1229 v.x = x; 1230 v.y = y; 1231 rectangleVertices.push_back(v); 1232} 1233 1234void OpenGLRenderer::drawRectangleList(const RectangleList& rectangleList) { 1235 int quadCount = rectangleList.getTransformedRectanglesCount(); 1236 std::vector<Vertex> rectangleVertices(quadCount * 4); 1237 Rect scissorBox = rectangleList.calculateBounds(); 1238 scissorBox.snapToPixelBoundaries(); 1239 for (int i = 0; i < quadCount; ++i) { 1240 const TransformedRectangle& tr(rectangleList.getTransformedRectangle(i)); 1241 const Matrix4& transform = tr.getTransform(); 1242 Rect bounds = tr.getBounds(); 1243 if (transform.rectToRect()) { 1244 transform.mapRect(bounds); 1245 bounds.doIntersect(scissorBox); 1246 if (!bounds.isEmpty()) { 1247 handlePointNoTransform(rectangleVertices, bounds.left, bounds.top); 1248 handlePointNoTransform(rectangleVertices, bounds.right, bounds.top); 1249 handlePointNoTransform(rectangleVertices, bounds.left, bounds.bottom); 1250 handlePointNoTransform(rectangleVertices, bounds.right, bounds.bottom); 1251 } 1252 } else { 1253 handlePoint(rectangleVertices, transform, bounds.left, bounds.top); 1254 handlePoint(rectangleVertices, transform, bounds.right, bounds.top); 1255 handlePoint(rectangleVertices, transform, bounds.left, bounds.bottom); 1256 handlePoint(rectangleVertices, transform, bounds.right, bounds.bottom); 1257 } 1258 } 1259 1260 mRenderState.scissor().set(scissorBox.left, getViewportHeight() - scissorBox.bottom, 1261 scissorBox.getWidth(), scissorBox.getHeight()); 1262 const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform; 1263 Glop glop; 1264 Vertex* vertices = &rectangleVertices[0]; 1265 GlopBuilder(mRenderState, mCaches, &glop) 1266 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1267 .setMeshIndexedQuads(vertices, rectangleVertices.size() / 4) 1268 .setFillBlack() 1269 .setTransform(*currentSnapshot(), transformFlags) 1270 .setModelViewOffsetRect(0, 0, scissorBox) 1271 .build(); 1272 renderGlop(glop); 1273} 1274 1275void OpenGLRenderer::setStencilFromClip() { 1276 if (!Properties::debugOverdraw) { 1277 if (!currentSnapshot()->clipIsSimple()) { 1278 int incrementThreshold; 1279 EVENT_LOGD("setStencilFromClip - enabling"); 1280 1281 // NOTE: The order here is important, we must set dirtyClip to false 1282 // before any draw call to avoid calling back into this method 1283 mState.setDirtyClip(false); 1284 1285 ensureStencilBuffer(); 1286 1287 const ClipArea& clipArea = currentSnapshot()->getClipArea(); 1288 1289 bool isRectangleList = clipArea.isRectangleList(); 1290 if (isRectangleList) { 1291 incrementThreshold = clipArea.getRectangleList().getTransformedRectanglesCount(); 1292 } else { 1293 incrementThreshold = 0; 1294 } 1295 1296 mRenderState.stencil().enableWrite(incrementThreshold); 1297 1298 // Clean and update the stencil, but first make sure we restrict drawing 1299 // to the region's bounds 1300 bool resetScissor = mRenderState.scissor().setEnabled(true); 1301 if (resetScissor) { 1302 // The scissor was not set so we now need to update it 1303 setScissorFromClip(); 1304 } 1305 1306 mRenderState.stencil().clear(); 1307 1308 // stash and disable the outline clip state, since stencil doesn't account for outline 1309 bool storedSkipOutlineClip = mSkipOutlineClip; 1310 mSkipOutlineClip = true; 1311 1312 SkPaint paint; 1313 paint.setColor(SK_ColorBLACK); 1314 paint.setXfermodeMode(SkXfermode::kSrc_Mode); 1315 1316 if (isRectangleList) { 1317 drawRectangleList(clipArea.getRectangleList()); 1318 } else { 1319 // NOTE: We could use the region contour path to generate a smaller mesh 1320 // Since we are using the stencil we could use the red book path 1321 // drawing technique. It might increase bandwidth usage though. 1322 1323 // The last parameter is important: we are not drawing in the color buffer 1324 // so we don't want to dirty the current layer, if any 1325 drawRegionRects(clipArea.getClipRegion(), paint, false); 1326 } 1327 if (resetScissor) mRenderState.scissor().setEnabled(false); 1328 mSkipOutlineClip = storedSkipOutlineClip; 1329 1330 mRenderState.stencil().enableTest(incrementThreshold); 1331 1332 // Draw the region used to generate the stencil if the appropriate debug 1333 // mode is enabled 1334 // TODO: Implement for rectangle list clip areas 1335 if (Properties::debugStencilClip == StencilClipDebug::ShowRegion 1336 && !clipArea.isRectangleList()) { 1337 paint.setColor(0x7f0000ff); 1338 paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); 1339 drawRegionRects(currentSnapshot()->getClipRegion(), paint); 1340 } 1341 } else { 1342 EVENT_LOGD("setStencilFromClip - disabling"); 1343 mRenderState.stencil().disable(); 1344 } 1345 } 1346} 1347 1348/** 1349 * Returns false and sets scissor enable based upon bounds if drawing won't be clipped out. 1350 * 1351 * @param paint if not null, the bounds will be expanded to account for stroke depending on paint 1352 * style, and tessellated AA ramp 1353 */ 1354bool OpenGLRenderer::quickRejectSetupScissor(float left, float top, float right, float bottom, 1355 const SkPaint* paint) { 1356 bool snapOut = paint && paint->isAntiAlias(); 1357 1358 if (paint && paint->getStyle() != SkPaint::kFill_Style) { 1359 float outset = paint->getStrokeWidth() * 0.5f; 1360 left -= outset; 1361 top -= outset; 1362 right += outset; 1363 bottom += outset; 1364 } 1365 1366 bool clipRequired = false; 1367 bool roundRectClipRequired = false; 1368 if (mState.calculateQuickRejectForScissor(left, top, right, bottom, 1369 &clipRequired, &roundRectClipRequired, snapOut)) { 1370 return true; 1371 } 1372 1373 // not quick rejected, so enable the scissor if clipRequired 1374 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 1375 mSkipOutlineClip = !roundRectClipRequired; 1376 return false; 1377} 1378 1379void OpenGLRenderer::debugClip() { 1380#if DEBUG_CLIP_REGIONS 1381 if (!currentSnapshot()->clipRegion->isEmpty()) { 1382 SkPaint paint; 1383 paint.setColor(0x7f00ff00); 1384 drawRegionRects(*(currentSnapshot()->clipRegion, paint); 1385 1386 } 1387#endif 1388} 1389 1390void OpenGLRenderer::renderGlop(const Glop& glop, GlopRenderType type) { 1391 // TODO: It would be best if we could do this before quickRejectSetupScissor() 1392 // changes the scissor test state 1393 if (type != GlopRenderType::LayerClear) { 1394 // Regular draws need to clear the dirty area on the layer before they start drawing on top 1395 // of it. If this draw *is* a layer clear, it skips the clear step (since it would 1396 // infinitely recurse) 1397 clearLayerRegions(); 1398 } 1399 1400 if (mState.getDirtyClip()) { 1401 if (mRenderState.scissor().isEnabled()) { 1402 setScissorFromClip(); 1403 } 1404 1405 setStencilFromClip(); 1406 } 1407 mRenderState.render(glop, currentSnapshot()->getOrthoMatrix()); 1408 if (type == GlopRenderType::Standard && !mRenderState.stencil().isWriteEnabled()) { 1409 // TODO: specify more clearly when a draw should dirty the layer. 1410 // is writing to the stencil the only time we should ignore this? 1411 dirtyLayer(glop.bounds.left, glop.bounds.top, glop.bounds.right, glop.bounds.bottom); 1412 mDirty = true; 1413 } 1414} 1415 1416/////////////////////////////////////////////////////////////////////////////// 1417// Drawing 1418/////////////////////////////////////////////////////////////////////////////// 1419 1420void OpenGLRenderer::drawRenderNode(RenderNode* renderNode, Rect& dirty, int32_t replayFlags) { 1421 // All the usual checks and setup operations (quickReject, setupDraw, etc.) 1422 // will be performed by the display list itself 1423 if (renderNode && renderNode->isRenderable()) { 1424 // compute 3d ordering 1425 renderNode->computeOrdering(); 1426 if (CC_UNLIKELY(Properties::drawDeferDisabled)) { 1427 startFrame(); 1428 ReplayStateStruct replayStruct(*this, dirty, replayFlags); 1429 renderNode->replay(replayStruct, 0); 1430 return; 1431 } 1432 1433 DeferredDisplayList deferredList(mState.currentRenderTargetClip()); 1434 DeferStateStruct deferStruct(deferredList, *this, replayFlags); 1435 renderNode->defer(deferStruct, 0); 1436 1437 flushLayers(); 1438 startFrame(); 1439 1440 deferredList.flush(*this, dirty); 1441 } else { 1442 // Even if there is no drawing command(Ex: invisible), 1443 // it still needs startFrame to clear buffer and start tiling. 1444 startFrame(); 1445 } 1446} 1447 1448/** 1449 * Important note: this method is intended to draw batches of bitmaps and 1450 * will not set the scissor enable or dirty the current layer, if any. 1451 * The caller is responsible for properly dirtying the current layer. 1452 */ 1453void OpenGLRenderer::drawBitmaps(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 1454 int bitmapCount, TextureVertex* vertices, bool pureTranslate, 1455 const Rect& bounds, const SkPaint* paint) { 1456 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 1457 if (!texture) return; 1458 1459 const AutoTexture autoCleanup(texture); 1460 1461 // TODO: remove layer dirty in multi-draw callers 1462 // TODO: snap doesn't need to touch transform, only texture filter. 1463 bool snap = pureTranslate; 1464 const float x = floorf(bounds.left + 0.5f); 1465 const float y = floorf(bounds.top + 0.5f); 1466 1467 const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType) 1468 ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None; 1469 const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform; 1470 Glop glop; 1471 GlopBuilder(mRenderState, mCaches, &glop) 1472 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1473 .setMeshTexturedMesh(vertices, bitmapCount * 6) 1474 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1475 .setTransform(*currentSnapshot(), transformFlags) 1476 .setModelViewOffsetRectOptionalSnap(snap, x, y, Rect(0, 0, bounds.getWidth(), bounds.getHeight())) 1477 .build(); 1478 renderGlop(glop, GlopRenderType::Multi); 1479} 1480 1481void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) { 1482 if (quickRejectSetupScissor(0, 0, bitmap->width(), bitmap->height())) { 1483 return; 1484 } 1485 1486 mCaches.textureState().activateTexture(0); 1487 Texture* texture = getTexture(bitmap); 1488 if (!texture) return; 1489 const AutoTexture autoCleanup(texture); 1490 1491 const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType) 1492 ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None; 1493 Glop glop; 1494 GlopBuilder(mRenderState, mCaches, &glop) 1495 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1496 .setMeshTexturedUnitQuad(texture->uvMapper) 1497 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1498 .setTransform(*currentSnapshot(), TransformFlags::None) 1499 .setModelViewMapUnitToRectSnap(Rect(0, 0, texture->width, texture->height)) 1500 .build(); 1501 renderGlop(glop); 1502} 1503 1504void OpenGLRenderer::drawBitmapMesh(const SkBitmap* bitmap, int meshWidth, int meshHeight, 1505 const float* vertices, const int* colors, const SkPaint* paint) { 1506 if (!vertices || mState.currentlyIgnored()) { 1507 return; 1508 } 1509 1510 float left = FLT_MAX; 1511 float top = FLT_MAX; 1512 float right = FLT_MIN; 1513 float bottom = FLT_MIN; 1514 1515 const uint32_t elementCount = meshWidth * meshHeight * 6; 1516 1517 std::unique_ptr<ColorTextureVertex[]> mesh(new ColorTextureVertex[elementCount]); 1518 ColorTextureVertex* vertex = &mesh[0]; 1519 1520 std::unique_ptr<int[]> tempColors; 1521 if (!colors) { 1522 uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1); 1523 tempColors.reset(new int[colorsCount]); 1524 memset(tempColors.get(), 0xff, colorsCount * sizeof(int)); 1525 colors = tempColors.get(); 1526 } 1527 1528 Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap->pixelRef()); 1529 const UvMapper& mapper(getMapper(texture)); 1530 1531 for (int32_t y = 0; y < meshHeight; y++) { 1532 for (int32_t x = 0; x < meshWidth; x++) { 1533 uint32_t i = (y * (meshWidth + 1) + x) * 2; 1534 1535 float u1 = float(x) / meshWidth; 1536 float u2 = float(x + 1) / meshWidth; 1537 float v1 = float(y) / meshHeight; 1538 float v2 = float(y + 1) / meshHeight; 1539 1540 mapper.map(u1, v1, u2, v2); 1541 1542 int ax = i + (meshWidth + 1) * 2; 1543 int ay = ax + 1; 1544 int bx = i; 1545 int by = bx + 1; 1546 int cx = i + 2; 1547 int cy = cx + 1; 1548 int dx = i + (meshWidth + 1) * 2 + 2; 1549 int dy = dx + 1; 1550 1551 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 1552 ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]); 1553 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 1554 1555 ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]); 1556 ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]); 1557 ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]); 1558 1559 left = std::min(left, std::min(vertices[ax], std::min(vertices[bx], vertices[cx]))); 1560 top = std::min(top, std::min(vertices[ay], std::min(vertices[by], vertices[cy]))); 1561 right = std::max(right, std::max(vertices[ax], std::max(vertices[bx], vertices[cx]))); 1562 bottom = std::max(bottom, std::max(vertices[ay], std::max(vertices[by], vertices[cy]))); 1563 } 1564 } 1565 1566 if (quickRejectSetupScissor(left, top, right, bottom)) { 1567 return; 1568 } 1569 1570 if (!texture) { 1571 texture = mCaches.textureCache.get(bitmap); 1572 if (!texture) { 1573 return; 1574 } 1575 } 1576 const AutoTexture autoCleanup(texture); 1577 1578 /* 1579 * TODO: handle alpha_8 textures correctly by applying paint color, but *not* 1580 * shader in that case to mimic the behavior in SkiaCanvas::drawBitmapMesh. 1581 */ 1582 const int textureFillFlags = TextureFillFlags::None; 1583 Glop glop; 1584 GlopBuilder(mRenderState, mCaches, &glop) 1585 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1586 .setMeshColoredTexturedMesh(mesh.get(), elementCount) 1587 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1588 .setTransform(*currentSnapshot(), TransformFlags::None) 1589 .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom)) 1590 .build(); 1591 renderGlop(glop); 1592} 1593 1594void OpenGLRenderer::drawBitmap(const SkBitmap* bitmap, Rect src, Rect dst, const SkPaint* paint) { 1595 if (quickRejectSetupScissor(dst)) { 1596 return; 1597 } 1598 1599 Texture* texture = getTexture(bitmap); 1600 if (!texture) return; 1601 const AutoTexture autoCleanup(texture); 1602 1603 Rect uv(std::max(0.0f, src.left / texture->width), 1604 std::max(0.0f, src.top / texture->height), 1605 std::min(1.0f, src.right / texture->width), 1606 std::min(1.0f, src.bottom / texture->height)); 1607 1608 const int textureFillFlags = (bitmap->colorType() == kAlpha_8_SkColorType) 1609 ? TextureFillFlags::IsAlphaMaskTexture : TextureFillFlags::None; 1610 const bool tryToSnap = MathUtils::areEqual(src.getWidth(), dst.getWidth()) 1611 && MathUtils::areEqual(src.getHeight(), dst.getHeight()); 1612 Glop glop; 1613 GlopBuilder(mRenderState, mCaches, &glop) 1614 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1615 .setMeshTexturedUvQuad(texture->uvMapper, uv) 1616 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1617 .setTransform(*currentSnapshot(), TransformFlags::None) 1618 .setModelViewMapUnitToRectOptionalSnap(tryToSnap, dst) 1619 .build(); 1620 renderGlop(glop); 1621} 1622 1623void OpenGLRenderer::drawPatch(const SkBitmap* bitmap, const Patch* mesh, 1624 AssetAtlas::Entry* entry, float left, float top, float right, float bottom, 1625 const SkPaint* paint) { 1626 if (!mesh || !mesh->verticesCount || quickRejectSetupScissor(left, top, right, bottom)) { 1627 return; 1628 } 1629 1630 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 1631 if (!texture) return; 1632 1633 // 9 patches are built for stretching - always filter 1634 int textureFillFlags = TextureFillFlags::ForceFilter; 1635 if (bitmap->colorType() == kAlpha_8_SkColorType) { 1636 textureFillFlags |= TextureFillFlags::IsAlphaMaskTexture; 1637 } 1638 Glop glop; 1639 GlopBuilder(mRenderState, mCaches, &glop) 1640 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1641 .setMeshPatchQuads(*mesh) 1642 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1643 .setTransform(*currentSnapshot(), TransformFlags::None) 1644 .setModelViewOffsetRectSnap(left, top, Rect(0, 0, right - left, bottom - top)) // TODO: get minimal bounds from patch 1645 .build(); 1646 renderGlop(glop); 1647} 1648 1649/** 1650 * Important note: this method is intended to draw batches of 9-patch objects and 1651 * will not set the scissor enable or dirty the current layer, if any. 1652 * The caller is responsible for properly dirtying the current layer. 1653 */ 1654void OpenGLRenderer::drawPatches(const SkBitmap* bitmap, AssetAtlas::Entry* entry, 1655 TextureVertex* vertices, uint32_t elementCount, const SkPaint* paint) { 1656 mCaches.textureState().activateTexture(0); 1657 Texture* texture = entry ? entry->texture : mCaches.textureCache.get(bitmap); 1658 if (!texture) return; 1659 const AutoTexture autoCleanup(texture); 1660 1661 // TODO: get correct bounds from caller 1662 const int transformFlags = TransformFlags::MeshIgnoresCanvasTransform; 1663 // 9 patches are built for stretching - always filter 1664 int textureFillFlags = TextureFillFlags::ForceFilter; 1665 if (bitmap->colorType() == kAlpha_8_SkColorType) { 1666 textureFillFlags |= TextureFillFlags::IsAlphaMaskTexture; 1667 } 1668 Glop glop; 1669 GlopBuilder(mRenderState, mCaches, &glop) 1670 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1671 .setMeshTexturedIndexedQuads(vertices, elementCount) 1672 .setFillTexturePaint(*texture, textureFillFlags, paint, currentSnapshot()->alpha) 1673 .setTransform(*currentSnapshot(), transformFlags) 1674 .setModelViewOffsetRect(0, 0, Rect(0, 0, 0, 0)) 1675 .build(); 1676 renderGlop(glop, GlopRenderType::Multi); 1677} 1678 1679void OpenGLRenderer::drawVertexBuffer(float translateX, float translateY, 1680 const VertexBuffer& vertexBuffer, const SkPaint* paint, int displayFlags) { 1681 // not missing call to quickReject/dirtyLayer, always done at a higher level 1682 if (!vertexBuffer.getVertexCount()) { 1683 // no vertices to draw 1684 return; 1685 } 1686 1687 bool shadowInterp = displayFlags & kVertexBuffer_ShadowInterp; 1688 const int transformFlags = TransformFlags::OffsetByFudgeFactor; 1689 Glop glop; 1690 GlopBuilder(mRenderState, mCaches, &glop) 1691 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1692 .setMeshVertexBuffer(vertexBuffer, shadowInterp) 1693 .setFillPaint(*paint, currentSnapshot()->alpha) 1694 .setTransform(*currentSnapshot(), transformFlags) 1695 .setModelViewOffsetRect(translateX, translateY, vertexBuffer.getBounds()) 1696 .build(); 1697 renderGlop(glop); 1698} 1699 1700/** 1701 * Renders a convex path via tessellation. For AA paths, this function uses a similar approach to 1702 * that of AA lines in the drawLines() function. We expand the convex path by a half pixel in 1703 * screen space in all directions. However, instead of using a fragment shader to compute the 1704 * translucency of the color from its position, we simply use a varying parameter to define how far 1705 * a given pixel is from the edge. For non-AA paths, the expansion and alpha varying are not used. 1706 * 1707 * Doesn't yet support joins, caps, or path effects. 1708 */ 1709void OpenGLRenderer::drawConvexPath(const SkPath& path, const SkPaint* paint) { 1710 VertexBuffer vertexBuffer; 1711 // TODO: try clipping large paths to viewport 1712 1713 PathTessellator::tessellatePath(path, paint, *currentTransform(), vertexBuffer); 1714 drawVertexBuffer(vertexBuffer, paint); 1715} 1716 1717/** 1718 * We create tristrips for the lines much like shape stroke tessellation, using a per-vertex alpha 1719 * and additional geometry for defining an alpha slope perimeter. 1720 * 1721 * Using GL_LINES can be difficult because the rasterization rules for those lines produces some 1722 * unexpected results, and may vary between hardware devices. Previously we used a varying-base 1723 * in-shader alpha region, but found it to be taxing on some GPUs. 1724 * 1725 * TODO: try using a fixed input buffer for non-capped lines as in text rendering. this may reduce 1726 * memory transfer by removing need for degenerate vertices. 1727 */ 1728void OpenGLRenderer::drawLines(const float* points, int count, const SkPaint* paint) { 1729 if (mState.currentlyIgnored() || count < 4) return; 1730 1731 count &= ~0x3; // round down to nearest four 1732 1733 VertexBuffer buffer; 1734 PathTessellator::tessellateLines(points, count, paint, *currentTransform(), buffer); 1735 const Rect& bounds = buffer.getBounds(); 1736 1737 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) { 1738 return; 1739 } 1740 1741 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset; 1742 drawVertexBuffer(buffer, paint, displayFlags); 1743} 1744 1745void OpenGLRenderer::drawPoints(const float* points, int count, const SkPaint* paint) { 1746 if (mState.currentlyIgnored() || count < 2) return; 1747 1748 count &= ~0x1; // round down to nearest two 1749 1750 VertexBuffer buffer; 1751 PathTessellator::tessellatePoints(points, count, paint, *currentTransform(), buffer); 1752 1753 const Rect& bounds = buffer.getBounds(); 1754 if (quickRejectSetupScissor(bounds.left, bounds.top, bounds.right, bounds.bottom)) { 1755 return; 1756 } 1757 1758 int displayFlags = paint->isAntiAlias() ? 0 : kVertexBuffer_Offset; 1759 drawVertexBuffer(buffer, paint, displayFlags); 1760 1761 mDirty = true; 1762} 1763 1764void OpenGLRenderer::drawColor(int color, SkXfermode::Mode mode) { 1765 // No need to check against the clip, we fill the clip region 1766 if (mState.currentlyIgnored()) return; 1767 1768 Rect clip(mState.currentRenderTargetClip()); 1769 clip.snapToPixelBoundaries(); 1770 1771 SkPaint paint; 1772 paint.setColor(color); 1773 paint.setXfermodeMode(mode); 1774 1775 drawColorRect(clip.left, clip.top, clip.right, clip.bottom, &paint, true); 1776 1777 mDirty = true; 1778} 1779 1780void OpenGLRenderer::drawShape(float left, float top, PathTexture* texture, 1781 const SkPaint* paint) { 1782 if (!texture) return; 1783 const AutoTexture autoCleanup(texture); 1784 1785 const float x = left + texture->left - texture->offset; 1786 const float y = top + texture->top - texture->offset; 1787 1788 drawPathTexture(texture, x, y, paint); 1789 1790 mDirty = true; 1791} 1792 1793void OpenGLRenderer::drawRoundRect(float left, float top, float right, float bottom, 1794 float rx, float ry, const SkPaint* p) { 1795 if (mState.currentlyIgnored() 1796 || quickRejectSetupScissor(left, top, right, bottom, p) 1797 || PaintUtils::paintWillNotDraw(*p)) { 1798 return; 1799 } 1800 1801 if (p->getPathEffect() != nullptr) { 1802 mCaches.textureState().activateTexture(0); 1803 PathTexture* texture = mCaches.pathCache.getRoundRect( 1804 right - left, bottom - top, rx, ry, p); 1805 drawShape(left, top, texture, p); 1806 } else { 1807 const VertexBuffer* vertexBuffer = mCaches.tessellationCache.getRoundRect( 1808 *currentTransform(), *p, right - left, bottom - top, rx, ry); 1809 drawVertexBuffer(left, top, *vertexBuffer, p); 1810 } 1811} 1812 1813void OpenGLRenderer::drawCircle(float x, float y, float radius, const SkPaint* p) { 1814 if (mState.currentlyIgnored() 1815 || quickRejectSetupScissor(x - radius, y - radius, x + radius, y + radius, p) 1816 || PaintUtils::paintWillNotDraw(*p)) { 1817 return; 1818 } 1819 1820 if (p->getPathEffect() != nullptr) { 1821 mCaches.textureState().activateTexture(0); 1822 PathTexture* texture = mCaches.pathCache.getCircle(radius, p); 1823 drawShape(x - radius, y - radius, texture, p); 1824 return; 1825 } 1826 1827 SkPath path; 1828 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 1829 path.addCircle(x, y, radius + p->getStrokeWidth() / 2); 1830 } else { 1831 path.addCircle(x, y, radius); 1832 } 1833 1834 if (CC_UNLIKELY(currentSnapshot()->projectionPathMask != nullptr)) { 1835 // mask ripples with projection mask 1836 SkPath maskPath = *(currentSnapshot()->projectionPathMask->projectionMask); 1837 1838 Matrix4 screenSpaceTransform; 1839 currentSnapshot()->buildScreenSpaceTransform(&screenSpaceTransform); 1840 1841 Matrix4 totalTransform; 1842 totalTransform.loadInverse(screenSpaceTransform); 1843 totalTransform.multiply(currentSnapshot()->projectionPathMask->projectionMaskTransform); 1844 1845 SkMatrix skTotalTransform; 1846 totalTransform.copyTo(skTotalTransform); 1847 maskPath.transform(skTotalTransform); 1848 1849 // Mask the ripple path by the projection mask, now that it's 1850 // in local space. Note that this can create CCW paths. 1851 Op(path, maskPath, kIntersect_SkPathOp, &path); 1852 } 1853 drawConvexPath(path, p); 1854} 1855 1856void OpenGLRenderer::drawOval(float left, float top, float right, float bottom, 1857 const SkPaint* p) { 1858 if (mState.currentlyIgnored() 1859 || quickRejectSetupScissor(left, top, right, bottom, p) 1860 || PaintUtils::paintWillNotDraw(*p)) { 1861 return; 1862 } 1863 1864 if (p->getPathEffect() != nullptr) { 1865 mCaches.textureState().activateTexture(0); 1866 PathTexture* texture = mCaches.pathCache.getOval(right - left, bottom - top, p); 1867 drawShape(left, top, texture, p); 1868 } else { 1869 SkPath path; 1870 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 1871 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 1872 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 1873 } 1874 path.addOval(rect); 1875 drawConvexPath(path, p); 1876 } 1877} 1878 1879void OpenGLRenderer::drawArc(float left, float top, float right, float bottom, 1880 float startAngle, float sweepAngle, bool useCenter, const SkPaint* p) { 1881 if (mState.currentlyIgnored() 1882 || quickRejectSetupScissor(left, top, right, bottom, p) 1883 || PaintUtils::paintWillNotDraw(*p)) { 1884 return; 1885 } 1886 1887 // TODO: support fills (accounting for concavity if useCenter && sweepAngle > 180) 1888 if (p->getStyle() != SkPaint::kStroke_Style || p->getPathEffect() != nullptr || useCenter) { 1889 mCaches.textureState().activateTexture(0); 1890 PathTexture* texture = mCaches.pathCache.getArc(right - left, bottom - top, 1891 startAngle, sweepAngle, useCenter, p); 1892 drawShape(left, top, texture, p); 1893 return; 1894 } 1895 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 1896 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 1897 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 1898 } 1899 1900 SkPath path; 1901 if (useCenter) { 1902 path.moveTo(rect.centerX(), rect.centerY()); 1903 } 1904 path.arcTo(rect, startAngle, sweepAngle, !useCenter); 1905 if (useCenter) { 1906 path.close(); 1907 } 1908 drawConvexPath(path, p); 1909} 1910 1911// See SkPaintDefaults.h 1912#define SkPaintDefaults_MiterLimit SkIntToScalar(4) 1913 1914void OpenGLRenderer::drawRect(float left, float top, float right, float bottom, 1915 const SkPaint* p) { 1916 if (mState.currentlyIgnored() 1917 || quickRejectSetupScissor(left, top, right, bottom, p) 1918 || PaintUtils::paintWillNotDraw(*p)) { 1919 return; 1920 } 1921 1922 if (p->getStyle() != SkPaint::kFill_Style) { 1923 // only fill style is supported by drawConvexPath, since others have to handle joins 1924 if (p->getPathEffect() != nullptr || p->getStrokeJoin() != SkPaint::kMiter_Join || 1925 p->getStrokeMiter() != SkPaintDefaults_MiterLimit) { 1926 mCaches.textureState().activateTexture(0); 1927 PathTexture* texture = 1928 mCaches.pathCache.getRect(right - left, bottom - top, p); 1929 drawShape(left, top, texture, p); 1930 } else { 1931 SkPath path; 1932 SkRect rect = SkRect::MakeLTRB(left, top, right, bottom); 1933 if (p->getStyle() == SkPaint::kStrokeAndFill_Style) { 1934 rect.outset(p->getStrokeWidth() / 2, p->getStrokeWidth() / 2); 1935 } 1936 path.addRect(rect); 1937 drawConvexPath(path, p); 1938 } 1939 } else { 1940 if (p->isAntiAlias() && !currentTransform()->isSimple()) { 1941 SkPath path; 1942 path.addRect(left, top, right, bottom); 1943 drawConvexPath(path, p); 1944 } else { 1945 drawColorRect(left, top, right, bottom, p); 1946 1947 mDirty = true; 1948 } 1949 } 1950} 1951 1952void OpenGLRenderer::drawTextShadow(const SkPaint* paint, const char* text, 1953 int count, const float* positions, 1954 FontRenderer& fontRenderer, int alpha, float x, float y) { 1955 mCaches.textureState().activateTexture(0); 1956 1957 PaintUtils::TextShadow textShadow; 1958 if (!PaintUtils::getTextShadow(paint, &textShadow)) { 1959 LOG_ALWAYS_FATAL("failed to query shadow attributes"); 1960 } 1961 1962 // NOTE: The drop shadow will not perform gamma correction 1963 // if shader-based correction is enabled 1964 mCaches.dropShadowCache.setFontRenderer(fontRenderer); 1965 ShadowTexture* texture = mCaches.dropShadowCache.get( 1966 paint, text, count, textShadow.radius, positions); 1967 // If the drop shadow exceeds the max texture size or couldn't be 1968 // allocated, skip drawing 1969 if (!texture) return; 1970 const AutoTexture autoCleanup(texture); 1971 1972 const float sx = x - texture->left + textShadow.dx; 1973 const float sy = y - texture->top + textShadow.dy; 1974 1975 Glop glop; 1976 GlopBuilder(mRenderState, mCaches, &glop) 1977 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 1978 .setMeshTexturedUnitQuad(nullptr) 1979 .setFillShadowTexturePaint(*texture, textShadow.color, *paint, currentSnapshot()->alpha) 1980 .setTransform(*currentSnapshot(), TransformFlags::None) 1981 .setModelViewMapUnitToRect(Rect(sx, sy, sx + texture->width, sy + texture->height)) 1982 .build(); 1983 renderGlop(glop); 1984} 1985 1986// TODO: remove this, once mState.currentlyIgnored captures snapshot alpha 1987bool OpenGLRenderer::canSkipText(const SkPaint* paint) const { 1988 float alpha = (PaintUtils::hasTextShadow(paint) 1989 ? 1.0f : paint->getAlpha()) * currentSnapshot()->alpha; 1990 return MathUtils::isZero(alpha) 1991 && PaintUtils::getXfermode(paint->getXfermode()) == SkXfermode::kSrcOver_Mode; 1992} 1993 1994bool OpenGLRenderer::findBestFontTransform(const mat4& transform, SkMatrix* outMatrix) const { 1995 if (CC_LIKELY(transform.isPureTranslate())) { 1996 outMatrix->setIdentity(); 1997 return false; 1998 } else if (CC_UNLIKELY(transform.isPerspective())) { 1999 outMatrix->setIdentity(); 2000 return true; 2001 } 2002 2003 /** 2004 * Input is a non-perspective, scaling transform. Generate a scale-only transform, 2005 * with values rounded to the nearest int. 2006 */ 2007 float sx, sy; 2008 transform.decomposeScale(sx, sy); 2009 outMatrix->setScale( 2010 roundf(std::max(1.0f, sx)), 2011 roundf(std::max(1.0f, sy))); 2012 return true; 2013} 2014 2015int OpenGLRenderer::getSaveCount() const { 2016 return mState.getSaveCount(); 2017} 2018 2019int OpenGLRenderer::save(int flags) { 2020 return mState.save(flags); 2021} 2022 2023void OpenGLRenderer::restore() { 2024 mState.restore(); 2025} 2026 2027void OpenGLRenderer::restoreToCount(int saveCount) { 2028 mState.restoreToCount(saveCount); 2029} 2030 2031 2032void OpenGLRenderer::translate(float dx, float dy, float dz) { 2033 mState.translate(dx, dy, dz); 2034} 2035 2036void OpenGLRenderer::rotate(float degrees) { 2037 mState.rotate(degrees); 2038} 2039 2040void OpenGLRenderer::scale(float sx, float sy) { 2041 mState.scale(sx, sy); 2042} 2043 2044void OpenGLRenderer::skew(float sx, float sy) { 2045 mState.skew(sx, sy); 2046} 2047 2048void OpenGLRenderer::setLocalMatrix(const Matrix4& matrix) { 2049 mState.setMatrix(mBaseTransform); 2050 mState.concatMatrix(matrix); 2051} 2052 2053void OpenGLRenderer::setLocalMatrix(const SkMatrix& matrix) { 2054 mState.setMatrix(mBaseTransform); 2055 mState.concatMatrix(matrix); 2056} 2057 2058void OpenGLRenderer::concatMatrix(const Matrix4& matrix) { 2059 mState.concatMatrix(matrix); 2060} 2061 2062bool OpenGLRenderer::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) { 2063 return mState.clipRect(left, top, right, bottom, op); 2064} 2065 2066bool OpenGLRenderer::clipPath(const SkPath* path, SkRegion::Op op) { 2067 return mState.clipPath(path, op); 2068} 2069 2070bool OpenGLRenderer::clipRegion(const SkRegion* region, SkRegion::Op op) { 2071 return mState.clipRegion(region, op); 2072} 2073 2074void OpenGLRenderer::setClippingOutline(LinearAllocator& allocator, const Outline* outline) { 2075 mState.setClippingOutline(allocator, outline); 2076} 2077 2078void OpenGLRenderer::setClippingRoundRect(LinearAllocator& allocator, 2079 const Rect& rect, float radius, bool highPriority) { 2080 mState.setClippingRoundRect(allocator, rect, radius, highPriority); 2081} 2082 2083void OpenGLRenderer::setProjectionPathMask(LinearAllocator& allocator, const SkPath* path) { 2084 mState.setProjectionPathMask(allocator, path); 2085} 2086 2087void OpenGLRenderer::drawText(const char* text, int bytesCount, int count, float x, float y, 2088 const float* positions, const SkPaint* paint, float totalAdvance, const Rect& bounds, 2089 DrawOpMode drawOpMode) { 2090 2091 if (drawOpMode == DrawOpMode::kImmediate) { 2092 // The checks for corner-case ignorable text and quick rejection is only done for immediate 2093 // drawing as ops from DeferredDisplayList are already filtered for these 2094 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint) || 2095 quickRejectSetupScissor(bounds)) { 2096 return; 2097 } 2098 } 2099 2100 const float oldX = x; 2101 const float oldY = y; 2102 2103 const mat4& transform = *currentTransform(); 2104 const bool pureTranslate = transform.isPureTranslate(); 2105 2106 if (CC_LIKELY(pureTranslate)) { 2107 x = floorf(x + transform.getTranslateX() + 0.5f); 2108 y = floorf(y + transform.getTranslateY() + 0.5f); 2109 } 2110 2111 int alpha = PaintUtils::getAlphaDirect(paint) * currentSnapshot()->alpha; 2112 SkXfermode::Mode mode = PaintUtils::getXfermodeDirect(paint); 2113 2114 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(); 2115 2116 if (CC_UNLIKELY(PaintUtils::hasTextShadow(paint))) { 2117 fontRenderer.setFont(paint, SkMatrix::I()); 2118 drawTextShadow(paint, text, count, positions, fontRenderer, 2119 alpha, oldX, oldY); 2120 } 2121 2122 const bool hasActiveLayer = hasLayer(); 2123 2124 // We only pass a partial transform to the font renderer. That partial 2125 // matrix defines how glyphs are rasterized. Typically we want glyphs 2126 // to be rasterized at their final size on screen, which means the partial 2127 // matrix needs to take the scale factor into account. 2128 // When a partial matrix is used to transform glyphs during rasterization, 2129 // the mesh is generated with the inverse transform (in the case of scale, 2130 // the mesh is generated at 1.0 / scale for instance.) This allows us to 2131 // apply the full transform matrix at draw time in the vertex shader. 2132 // Applying the full matrix in the shader is the easiest way to handle 2133 // rotation and perspective and allows us to always generated quads in the 2134 // font renderer which greatly simplifies the code, clipping in particular. 2135 SkMatrix fontTransform; 2136 bool linearFilter = findBestFontTransform(transform, &fontTransform) 2137 || fabs(y - (int) y) > 0.0f 2138 || fabs(x - (int) x) > 0.0f; 2139 fontRenderer.setFont(paint, fontTransform); 2140 fontRenderer.setTextureFiltering(linearFilter); 2141 2142 // TODO: Implement better clipping for scaled/rotated text 2143 const Rect* clip = !pureTranslate ? nullptr : &mState.currentRenderTargetClip(); 2144 Rect layerBounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2145 2146 bool status; 2147#if HWUI_NEW_OPS 2148 LOG_ALWAYS_FATAL("unsupported"); 2149 TextDrawFunctor functor(nullptr, nullptr, nullptr, x, y, pureTranslate, alpha, mode, paint); 2150#else 2151 TextDrawFunctor functor(this, x, y, pureTranslate, alpha, mode, paint); 2152#endif 2153 2154 // don't call issuedrawcommand, do it at end of batch 2155 bool forceFinish = (drawOpMode != DrawOpMode::kDefer); 2156 if (CC_UNLIKELY(paint->getTextAlign() != SkPaint::kLeft_Align)) { 2157 SkPaint paintCopy(*paint); 2158 paintCopy.setTextAlign(SkPaint::kLeft_Align); 2159 status = fontRenderer.renderPosText(&paintCopy, clip, text, count, x, y, 2160 positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish); 2161 } else { 2162 status = fontRenderer.renderPosText(paint, clip, text, count, x, y, 2163 positions, hasActiveLayer ? &layerBounds : nullptr, &functor, forceFinish); 2164 } 2165 2166 if ((status || drawOpMode != DrawOpMode::kImmediate) && hasActiveLayer) { 2167 if (!pureTranslate) { 2168 transform.mapRect(layerBounds); 2169 } 2170 dirtyLayerUnchecked(layerBounds, getRegion()); 2171 } 2172 2173 mDirty = true; 2174} 2175 2176void OpenGLRenderer::drawTextOnPath(const char* text, int bytesCount, int count, 2177 const SkPath* path, float hOffset, float vOffset, const SkPaint* paint) { 2178 if (text == nullptr || count == 0 || mState.currentlyIgnored() || canSkipText(paint)) { 2179 return; 2180 } 2181 2182 // TODO: avoid scissor by calculating maximum bounds using path bounds + font metrics 2183 mRenderState.scissor().setEnabled(true); 2184 2185 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(); 2186 fontRenderer.setFont(paint, SkMatrix::I()); 2187 fontRenderer.setTextureFiltering(true); 2188 2189 int alpha = PaintUtils::getAlphaDirect(paint) * currentSnapshot()->alpha; 2190 SkXfermode::Mode mode = PaintUtils::getXfermodeDirect(paint); 2191#if HWUI_NEW_OPS 2192 LOG_ALWAYS_FATAL("unsupported"); 2193 TextDrawFunctor functor(nullptr, nullptr, nullptr, 0.0f, 0.0f, false, alpha, mode, paint); 2194#else 2195 TextDrawFunctor functor(this, 0.0f, 0.0f, false, alpha, mode, paint); 2196#endif 2197 2198 const Rect* clip = &writableSnapshot()->getLocalClip(); 2199 Rect bounds(FLT_MAX / 2.0f, FLT_MAX / 2.0f, FLT_MIN / 2.0f, FLT_MIN / 2.0f); 2200 2201 if (fontRenderer.renderTextOnPath(paint, clip, text, count, path, 2202 hOffset, vOffset, hasLayer() ? &bounds : nullptr, &functor)) { 2203 dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, *currentTransform()); 2204 mDirty = true; 2205 } 2206} 2207 2208void OpenGLRenderer::drawPath(const SkPath* path, const SkPaint* paint) { 2209 if (mState.currentlyIgnored()) return; 2210 2211 mCaches.textureState().activateTexture(0); 2212 2213 PathTexture* texture = mCaches.pathCache.get(path, paint); 2214 if (!texture) return; 2215 2216 const float x = texture->left - texture->offset; 2217 const float y = texture->top - texture->offset; 2218 2219 drawPathTexture(texture, x, y, paint); 2220 2221 if (texture->cleanup) { 2222 mCaches.pathCache.remove(path, paint); 2223 } 2224 mDirty = true; 2225} 2226 2227void OpenGLRenderer::drawLayer(Layer* layer) { 2228 if (!layer) { 2229 return; 2230 } 2231 2232 mat4* transform = nullptr; 2233 if (layer->isTextureLayer()) { 2234 transform = &layer->getTransform(); 2235 if (!transform->isIdentity()) { 2236 save(SkCanvas::kMatrix_SaveFlag); 2237 concatMatrix(*transform); 2238 } 2239 } 2240 2241 bool clipRequired = false; 2242 const bool rejected = mState.calculateQuickRejectForScissor( 2243 0, 0, layer->layer.getWidth(), layer->layer.getHeight(), 2244 &clipRequired, nullptr, false); 2245 2246 if (rejected) { 2247 if (transform && !transform->isIdentity()) { 2248 restore(); 2249 } 2250 return; 2251 } 2252 2253 EVENT_LOGD("drawLayer," RECT_STRING ", clipRequired %d", x, y, 2254 x + layer->layer.getWidth(), y + layer->layer.getHeight(), clipRequired); 2255 2256 updateLayer(layer, true); 2257 2258 mRenderState.scissor().setEnabled(mScissorOptimizationDisabled || clipRequired); 2259 mCaches.textureState().activateTexture(0); 2260 2261 if (CC_LIKELY(!layer->region.isEmpty())) { 2262 if (layer->region.isRect()) { 2263 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, 2264 composeLayerRect(layer, layer->regionRect)); 2265 } else if (layer->mesh) { 2266 Glop glop; 2267 GlopBuilder(mRenderState, mCaches, &glop) 2268 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2269 .setMeshTexturedIndexedQuads(layer->mesh, layer->meshElementCount) 2270 .setFillLayer(layer->getTexture(), layer->getColorFilter(), getLayerAlpha(layer), layer->getMode(), Blend::ModeOrderSwap::NoSwap) 2271 .setTransform(*currentSnapshot(), TransformFlags::None) 2272 .setModelViewOffsetRectSnap(0, 0, Rect(0, 0, layer->layer.getWidth(), layer->layer.getHeight())) 2273 .build(); 2274 DRAW_DOUBLE_STENCIL_IF(!layer->hasDrawnSinceUpdate, renderGlop(glop)); 2275#if DEBUG_LAYERS_AS_REGIONS 2276 drawRegionRectsDebug(layer->region); 2277#endif 2278 } 2279 2280 if (layer->debugDrawUpdate) { 2281 layer->debugDrawUpdate = false; 2282 2283 SkPaint paint; 2284 paint.setColor(0x7f00ff00); 2285 drawColorRect(0, 0, layer->layer.getWidth(), layer->layer.getHeight(), &paint); 2286 } 2287 } 2288 layer->hasDrawnSinceUpdate = true; 2289 2290 if (transform && !transform->isIdentity()) { 2291 restore(); 2292 } 2293 2294 mDirty = true; 2295} 2296 2297/////////////////////////////////////////////////////////////////////////////// 2298// Draw filters 2299/////////////////////////////////////////////////////////////////////////////// 2300void OpenGLRenderer::setDrawFilter(SkDrawFilter* filter) { 2301 // We should never get here since we apply the draw filter when stashing 2302 // the paints in the DisplayList. 2303 LOG_ALWAYS_FATAL("OpenGLRenderer does not directly support DrawFilters"); 2304} 2305 2306/////////////////////////////////////////////////////////////////////////////// 2307// Drawing implementation 2308/////////////////////////////////////////////////////////////////////////////// 2309 2310Texture* OpenGLRenderer::getTexture(const SkBitmap* bitmap) { 2311 Texture* texture = mRenderState.assetAtlas().getEntryTexture(bitmap->pixelRef()); 2312 if (!texture) { 2313 return mCaches.textureCache.get(bitmap); 2314 } 2315 return texture; 2316} 2317 2318void OpenGLRenderer::drawPathTexture(PathTexture* texture, float x, float y, 2319 const SkPaint* paint) { 2320 if (quickRejectSetupScissor(x, y, x + texture->width, y + texture->height)) { 2321 return; 2322 } 2323 2324 Glop glop; 2325 GlopBuilder(mRenderState, mCaches, &glop) 2326 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2327 .setMeshTexturedUnitQuad(nullptr) 2328 .setFillPathTexturePaint(*texture, *paint, currentSnapshot()->alpha) 2329 .setTransform(*currentSnapshot(), TransformFlags::None) 2330 .setModelViewMapUnitToRect(Rect(x, y, x + texture->width, y + texture->height)) 2331 .build(); 2332 renderGlop(glop); 2333} 2334 2335void OpenGLRenderer::drawRects(const float* rects, int count, const SkPaint* paint) { 2336 if (mState.currentlyIgnored()) { 2337 return; 2338 } 2339 2340 drawColorRects(rects, count, paint, false, true, true); 2341} 2342 2343void OpenGLRenderer::drawShadow(float casterAlpha, 2344 const VertexBuffer* ambientShadowVertexBuffer, const VertexBuffer* spotShadowVertexBuffer) { 2345 if (mState.currentlyIgnored()) return; 2346 2347 // TODO: use quickRejectWithScissor. For now, always force enable scissor. 2348 mRenderState.scissor().setEnabled(true); 2349 2350 SkPaint paint; 2351 paint.setAntiAlias(true); // want to use AlphaVertex 2352 2353 // The caller has made sure casterAlpha > 0. 2354 float ambientShadowAlpha = mAmbientShadowAlpha; 2355 if (CC_UNLIKELY(Properties::overrideAmbientShadowStrength >= 0)) { 2356 ambientShadowAlpha = Properties::overrideAmbientShadowStrength; 2357 } 2358 if (ambientShadowVertexBuffer && ambientShadowAlpha > 0) { 2359 paint.setARGB(casterAlpha * ambientShadowAlpha, 0, 0, 0); 2360 drawVertexBuffer(*ambientShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp); 2361 } 2362 2363 float spotShadowAlpha = mSpotShadowAlpha; 2364 if (CC_UNLIKELY(Properties::overrideSpotShadowStrength >= 0)) { 2365 spotShadowAlpha = Properties::overrideSpotShadowStrength; 2366 } 2367 if (spotShadowVertexBuffer && spotShadowAlpha > 0) { 2368 paint.setARGB(casterAlpha * spotShadowAlpha, 0, 0, 0); 2369 drawVertexBuffer(*spotShadowVertexBuffer, &paint, kVertexBuffer_ShadowInterp); 2370 } 2371 2372 mDirty=true; 2373} 2374 2375void OpenGLRenderer::drawColorRects(const float* rects, int count, const SkPaint* paint, 2376 bool ignoreTransform, bool dirty, bool clip) { 2377 if (count == 0) { 2378 return; 2379 } 2380 2381 float left = FLT_MAX; 2382 float top = FLT_MAX; 2383 float right = FLT_MIN; 2384 float bottom = FLT_MIN; 2385 2386 Vertex mesh[count]; 2387 Vertex* vertex = mesh; 2388 2389 for (int index = 0; index < count; index += 4) { 2390 float l = rects[index + 0]; 2391 float t = rects[index + 1]; 2392 float r = rects[index + 2]; 2393 float b = rects[index + 3]; 2394 2395 Vertex::set(vertex++, l, t); 2396 Vertex::set(vertex++, r, t); 2397 Vertex::set(vertex++, l, b); 2398 Vertex::set(vertex++, r, b); 2399 2400 left = std::min(left, l); 2401 top = std::min(top, t); 2402 right = std::max(right, r); 2403 bottom = std::max(bottom, b); 2404 } 2405 2406 if (clip && quickRejectSetupScissor(left, top, right, bottom)) { 2407 return; 2408 } 2409 2410 const int transformFlags = ignoreTransform 2411 ? TransformFlags::MeshIgnoresCanvasTransform : TransformFlags::None; 2412 Glop glop; 2413 GlopBuilder(mRenderState, mCaches, &glop) 2414 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2415 .setMeshIndexedQuads(&mesh[0], count / 4) 2416 .setFillPaint(*paint, currentSnapshot()->alpha) 2417 .setTransform(*currentSnapshot(), transformFlags) 2418 .setModelViewOffsetRect(0, 0, Rect(left, top, right, bottom)) 2419 .build(); 2420 renderGlop(glop); 2421} 2422 2423void OpenGLRenderer::drawColorRect(float left, float top, float right, float bottom, 2424 const SkPaint* paint, bool ignoreTransform) { 2425 const int transformFlags = ignoreTransform 2426 ? TransformFlags::MeshIgnoresCanvasTransform : TransformFlags::None; 2427 Glop glop; 2428 GlopBuilder(mRenderState, mCaches, &glop) 2429 .setRoundRectClipState(currentSnapshot()->roundRectClipState) 2430 .setMeshUnitQuad() 2431 .setFillPaint(*paint, currentSnapshot()->alpha) 2432 .setTransform(*currentSnapshot(), transformFlags) 2433 .setModelViewMapUnitToRect(Rect(left, top, right, bottom)) 2434 .build(); 2435 renderGlop(glop); 2436} 2437 2438float OpenGLRenderer::getLayerAlpha(const Layer* layer) const { 2439 return (layer->getAlpha() / 255.0f) * currentSnapshot()->alpha; 2440} 2441 2442}; // namespace uirenderer 2443}; // namespace android 2444