Landing Recent QUIC changes until 8/19/2015 17:00 UTC.
[chromium-blink-merge.git] / cc / output / gl_renderer.cc
blob74148110ae04024678027ad342006f67cd52abf5
1 // Copyright 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/output/gl_renderer.h"
7 #include <algorithm>
8 #include <limits>
9 #include <set>
10 #include <string>
11 #include <vector>
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "build/build_config.h"
19 #include "base/trace_event/trace_event.h"
20 #include "cc/base/math_util.h"
21 #include "cc/output/compositor_frame.h"
22 #include "cc/output/compositor_frame_metadata.h"
23 #include "cc/output/context_provider.h"
24 #include "cc/output/copy_output_request.h"
25 #include "cc/output/dynamic_geometry_binding.h"
26 #include "cc/output/gl_frame_data.h"
27 #include "cc/output/layer_quad.h"
28 #include "cc/output/output_surface.h"
29 #include "cc/output/render_surface_filters.h"
30 #include "cc/output/static_geometry_binding.h"
31 #include "cc/output/texture_mailbox_deleter.h"
32 #include "cc/quads/draw_polygon.h"
33 #include "cc/quads/picture_draw_quad.h"
34 #include "cc/quads/render_pass.h"
35 #include "cc/quads/stream_video_draw_quad.h"
36 #include "cc/quads/texture_draw_quad.h"
37 #include "cc/raster/scoped_gpu_raster.h"
38 #include "cc/resources/scoped_resource.h"
39 #include "gpu/GLES2/gl2extchromium.h"
40 #include "gpu/command_buffer/client/context_support.h"
41 #include "gpu/command_buffer/client/gles2_interface.h"
42 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
43 #include "third_party/skia/include/core/SkBitmap.h"
44 #include "third_party/skia/include/core/SkColor.h"
45 #include "third_party/skia/include/core/SkColorFilter.h"
46 #include "third_party/skia/include/core/SkImage.h"
47 #include "third_party/skia/include/core/SkSurface.h"
48 #include "third_party/skia/include/gpu/GrContext.h"
49 #include "third_party/skia/include/gpu/GrTexture.h"
50 #include "third_party/skia/include/gpu/GrTextureProvider.h"
51 #include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
52 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
53 #include "ui/gfx/geometry/quad_f.h"
54 #include "ui/gfx/geometry/rect_conversions.h"
56 using gpu::gles2::GLES2Interface;
58 namespace cc {
59 namespace {
61 bool NeedsIOSurfaceReadbackWorkaround() {
62 #if defined(OS_MACOSX)
63 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
64 // but it doesn't seem to hurt.
65 return true;
66 #else
67 return false;
68 #endif
71 Float4 UVTransform(const TextureDrawQuad* quad) {
72 gfx::PointF uv0 = quad->uv_top_left;
73 gfx::PointF uv1 = quad->uv_bottom_right;
74 Float4 xform = {{uv0.x(), uv0.y(), uv1.x() - uv0.x(), uv1.y() - uv0.y()}};
75 if (quad->y_flipped) {
76 xform.data[1] = 1.0f - xform.data[1];
77 xform.data[3] = -xform.data[3];
79 return xform;
82 Float4 PremultipliedColor(SkColor color) {
83 const float factor = 1.0f / 255.0f;
84 const float alpha = SkColorGetA(color) * factor;
86 Float4 result = {
87 {SkColorGetR(color) * factor * alpha, SkColorGetG(color) * factor * alpha,
88 SkColorGetB(color) * factor * alpha, alpha}};
89 return result;
92 SamplerType SamplerTypeFromTextureTarget(GLenum target) {
93 switch (target) {
94 case GL_TEXTURE_2D:
95 return SAMPLER_TYPE_2D;
96 case GL_TEXTURE_RECTANGLE_ARB:
97 return SAMPLER_TYPE_2D_RECT;
98 case GL_TEXTURE_EXTERNAL_OES:
99 return SAMPLER_TYPE_EXTERNAL_OES;
100 default:
101 NOTREACHED();
102 return SAMPLER_TYPE_2D;
106 BlendMode BlendModeFromSkXfermode(SkXfermode::Mode mode) {
107 switch (mode) {
108 case SkXfermode::kSrcOver_Mode:
109 return BLEND_MODE_NORMAL;
110 case SkXfermode::kScreen_Mode:
111 return BLEND_MODE_SCREEN;
112 case SkXfermode::kOverlay_Mode:
113 return BLEND_MODE_OVERLAY;
114 case SkXfermode::kDarken_Mode:
115 return BLEND_MODE_DARKEN;
116 case SkXfermode::kLighten_Mode:
117 return BLEND_MODE_LIGHTEN;
118 case SkXfermode::kColorDodge_Mode:
119 return BLEND_MODE_COLOR_DODGE;
120 case SkXfermode::kColorBurn_Mode:
121 return BLEND_MODE_COLOR_BURN;
122 case SkXfermode::kHardLight_Mode:
123 return BLEND_MODE_HARD_LIGHT;
124 case SkXfermode::kSoftLight_Mode:
125 return BLEND_MODE_SOFT_LIGHT;
126 case SkXfermode::kDifference_Mode:
127 return BLEND_MODE_DIFFERENCE;
128 case SkXfermode::kExclusion_Mode:
129 return BLEND_MODE_EXCLUSION;
130 case SkXfermode::kMultiply_Mode:
131 return BLEND_MODE_MULTIPLY;
132 case SkXfermode::kHue_Mode:
133 return BLEND_MODE_HUE;
134 case SkXfermode::kSaturation_Mode:
135 return BLEND_MODE_SATURATION;
136 case SkXfermode::kColor_Mode:
137 return BLEND_MODE_COLOR;
138 case SkXfermode::kLuminosity_Mode:
139 return BLEND_MODE_LUMINOSITY;
140 default:
141 NOTREACHED();
142 return BLEND_MODE_NONE;
146 // Smallest unit that impact anti-aliasing output. We use this to
147 // determine when anti-aliasing is unnecessary.
148 const float kAntiAliasingEpsilon = 1.0f / 1024.0f;
150 // Block or crash if the number of pending sync queries reach this high as
151 // something is seriously wrong on the service side if this happens.
152 const size_t kMaxPendingSyncQueries = 16;
154 } // anonymous namespace
156 static GLint GetActiveTextureUnit(GLES2Interface* gl) {
157 GLint active_unit = 0;
158 gl->GetIntegerv(GL_ACTIVE_TEXTURE, &active_unit);
159 return active_unit;
162 class GLRenderer::ScopedUseGrContext {
163 public:
164 static scoped_ptr<ScopedUseGrContext> Create(GLRenderer* renderer,
165 DrawingFrame* frame) {
166 // GrContext for filters is created lazily, and may fail if the context
167 // is lost.
168 // TODO(vmiura,bsalomon): crbug.com/487850 Ensure that
169 // ContextProvider::GrContext() does not return NULL.
170 if (renderer->output_surface_->context_provider()->GrContext())
171 return make_scoped_ptr(new ScopedUseGrContext(renderer, frame));
172 return nullptr;
175 ~ScopedUseGrContext() {
176 // Pass context control back to GLrenderer.
177 scoped_gpu_raster_ = nullptr;
178 renderer_->RestoreGLState();
179 renderer_->RestoreFramebuffer(frame_);
182 GrContext* context() const {
183 return renderer_->output_surface_->context_provider()->GrContext();
186 private:
187 ScopedUseGrContext(GLRenderer* renderer, DrawingFrame* frame)
188 : scoped_gpu_raster_(
189 new ScopedGpuRaster(renderer->output_surface_->context_provider())),
190 renderer_(renderer),
191 frame_(frame) {
192 // scoped_gpu_raster_ passes context control to Skia.
195 scoped_ptr<ScopedGpuRaster> scoped_gpu_raster_;
196 GLRenderer* renderer_;
197 DrawingFrame* frame_;
199 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext);
202 struct GLRenderer::PendingAsyncReadPixels {
203 PendingAsyncReadPixels() : buffer(0) {}
205 scoped_ptr<CopyOutputRequest> copy_request;
206 base::CancelableClosure finished_read_pixels_callback;
207 unsigned buffer;
209 private:
210 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels);
213 class GLRenderer::SyncQuery {
214 public:
215 explicit SyncQuery(gpu::gles2::GLES2Interface* gl)
216 : gl_(gl), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
217 gl_->GenQueriesEXT(1, &query_id_);
219 virtual ~SyncQuery() { gl_->DeleteQueriesEXT(1, &query_id_); }
221 scoped_refptr<ResourceProvider::Fence> Begin() {
222 DCHECK(!IsPending());
223 // Invalidate weak pointer held by old fence.
224 weak_ptr_factory_.InvalidateWeakPtrs();
225 // Note: In case the set of drawing commands issued before End() do not
226 // depend on the query, defer BeginQueryEXT call until Set() is called and
227 // query is required.
228 return make_scoped_refptr<ResourceProvider::Fence>(
229 new Fence(weak_ptr_factory_.GetWeakPtr()));
232 void Set() {
233 if (is_pending_)
234 return;
236 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
237 // noop relative to GL, so it doesn't matter where it happens but we still
238 // make sure to issue this command when Set() is called (prior to issuing
239 // any drawing commands that depend on query), in case some future extension
240 // can take advantage of this.
241 gl_->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM, query_id_);
242 is_pending_ = true;
245 void End() {
246 if (!is_pending_)
247 return;
249 gl_->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM);
252 bool IsPending() {
253 if (!is_pending_)
254 return false;
256 unsigned result_available = 1;
257 gl_->GetQueryObjectuivEXT(
258 query_id_, GL_QUERY_RESULT_AVAILABLE_EXT, &result_available);
259 is_pending_ = !result_available;
260 return is_pending_;
263 void Wait() {
264 if (!is_pending_)
265 return;
267 unsigned result = 0;
268 gl_->GetQueryObjectuivEXT(query_id_, GL_QUERY_RESULT_EXT, &result);
269 is_pending_ = false;
272 private:
273 class Fence : public ResourceProvider::Fence {
274 public:
275 explicit Fence(base::WeakPtr<GLRenderer::SyncQuery> query)
276 : query_(query) {}
278 // Overridden from ResourceProvider::Fence:
279 void Set() override {
280 DCHECK(query_);
281 query_->Set();
283 bool HasPassed() override { return !query_ || !query_->IsPending(); }
284 void Wait() override {
285 if (query_)
286 query_->Wait();
289 private:
290 ~Fence() override {}
292 base::WeakPtr<SyncQuery> query_;
294 DISALLOW_COPY_AND_ASSIGN(Fence);
297 gpu::gles2::GLES2Interface* gl_;
298 unsigned query_id_;
299 bool is_pending_;
300 base::WeakPtrFactory<SyncQuery> weak_ptr_factory_;
302 DISALLOW_COPY_AND_ASSIGN(SyncQuery);
305 scoped_ptr<GLRenderer> GLRenderer::Create(
306 RendererClient* client,
307 const RendererSettings* settings,
308 OutputSurface* output_surface,
309 ResourceProvider* resource_provider,
310 TextureMailboxDeleter* texture_mailbox_deleter,
311 int highp_threshold_min) {
312 return make_scoped_ptr(new GLRenderer(client,
313 settings,
314 output_surface,
315 resource_provider,
316 texture_mailbox_deleter,
317 highp_threshold_min));
320 GLRenderer::GLRenderer(RendererClient* client,
321 const RendererSettings* settings,
322 OutputSurface* output_surface,
323 ResourceProvider* resource_provider,
324 TextureMailboxDeleter* texture_mailbox_deleter,
325 int highp_threshold_min)
326 : DirectRenderer(client, settings, output_surface, resource_provider),
327 offscreen_framebuffer_id_(0),
328 shared_geometry_quad_(QuadVertexRect()),
329 gl_(output_surface->context_provider()->ContextGL()),
330 context_support_(output_surface->context_provider()->ContextSupport()),
331 texture_mailbox_deleter_(texture_mailbox_deleter),
332 is_backbuffer_discarded_(false),
333 is_scissor_enabled_(false),
334 scissor_rect_needs_reset_(true),
335 stencil_shadow_(false),
336 blend_shadow_(false),
337 highp_threshold_min_(highp_threshold_min),
338 highp_threshold_cache_(0),
339 use_sync_query_(false),
340 on_demand_tile_raster_resource_id_(0),
341 bound_geometry_(NO_BINDING) {
342 DCHECK(gl_);
343 DCHECK(context_support_);
345 ContextProvider::Capabilities context_caps =
346 output_surface_->context_provider()->ContextCapabilities();
348 capabilities_.using_partial_swap =
349 settings_->partial_swap_enabled && context_caps.gpu.post_sub_buffer;
351 DCHECK(!context_caps.gpu.iosurface || context_caps.gpu.texture_rectangle);
353 capabilities_.using_egl_image = context_caps.gpu.egl_image_external;
355 capabilities_.max_texture_size = resource_provider_->max_texture_size();
356 capabilities_.best_texture_format = resource_provider_->best_texture_format();
358 // The updater can access textures while the GLRenderer is using them.
359 capabilities_.allow_partial_texture_updates = true;
361 capabilities_.using_image = context_caps.gpu.image;
363 capabilities_.using_discard_framebuffer =
364 context_caps.gpu.discard_framebuffer;
366 capabilities_.allow_rasterize_on_demand = true;
367 capabilities_.max_msaa_samples = context_caps.gpu.max_samples;
369 use_sync_query_ = context_caps.gpu.sync_query;
370 use_blend_equation_advanced_ = context_caps.gpu.blend_equation_advanced;
371 use_blend_equation_advanced_coherent_ =
372 context_caps.gpu.blend_equation_advanced_coherent;
374 InitializeSharedObjects();
377 GLRenderer::~GLRenderer() {
378 while (!pending_async_read_pixels_.empty()) {
379 PendingAsyncReadPixels* pending_read = pending_async_read_pixels_.back();
380 pending_read->finished_read_pixels_callback.Cancel();
381 pending_async_read_pixels_.pop_back();
384 in_use_overlay_resources_.clear();
386 CleanupSharedObjects();
389 const RendererCapabilitiesImpl& GLRenderer::Capabilities() const {
390 return capabilities_;
393 void GLRenderer::DidChangeVisibility() {
394 EnforceMemoryPolicy();
396 context_support_->SetSurfaceVisible(visible());
398 // If we are not visible, we ask the context to aggressively free resources.
399 context_support_->SetAggressivelyFreeResources(!visible());
402 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_.clear(); }
404 void GLRenderer::DiscardPixels() {
405 if (!capabilities_.using_discard_framebuffer)
406 return;
407 bool using_default_framebuffer =
408 !current_framebuffer_lock_ &&
409 output_surface_->capabilities().uses_default_gl_framebuffer;
410 GLenum attachments[] = {static_cast<GLenum>(
411 using_default_framebuffer ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0_EXT)};
412 gl_->DiscardFramebufferEXT(
413 GL_FRAMEBUFFER, arraysize(attachments), attachments);
416 void GLRenderer::PrepareSurfaceForPass(
417 DrawingFrame* frame,
418 SurfaceInitializationMode initialization_mode,
419 const gfx::Rect& render_pass_scissor) {
420 SetViewport();
422 switch (initialization_mode) {
423 case SURFACE_INITIALIZATION_MODE_PRESERVE:
424 EnsureScissorTestDisabled();
425 return;
426 case SURFACE_INITIALIZATION_MODE_FULL_SURFACE_CLEAR:
427 EnsureScissorTestDisabled();
428 DiscardPixels();
429 ClearFramebuffer(frame);
430 break;
431 case SURFACE_INITIALIZATION_MODE_SCISSORED_CLEAR:
432 SetScissorTestRect(render_pass_scissor);
433 ClearFramebuffer(frame);
434 break;
438 void GLRenderer::ClearFramebuffer(DrawingFrame* frame) {
439 // On DEBUG builds, opaque render passes are cleared to blue to easily see
440 // regions that were not drawn on the screen.
441 if (frame->current_render_pass->has_transparent_background)
442 gl_->ClearColor(0, 0, 0, 0);
443 else
444 gl_->ClearColor(0, 0, 1, 1);
446 bool always_clear = false;
447 #ifndef NDEBUG
448 always_clear = true;
449 #endif
450 if (always_clear || frame->current_render_pass->has_transparent_background) {
451 GLbitfield clear_bits = GL_COLOR_BUFFER_BIT;
452 if (always_clear)
453 clear_bits |= GL_STENCIL_BUFFER_BIT;
454 gl_->Clear(clear_bits);
458 void GLRenderer::BeginDrawingFrame(DrawingFrame* frame) {
459 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
461 scoped_refptr<ResourceProvider::Fence> read_lock_fence;
462 if (use_sync_query_) {
463 // Block until oldest sync query has passed if the number of pending queries
464 // ever reach kMaxPendingSyncQueries.
465 if (pending_sync_queries_.size() >= kMaxPendingSyncQueries) {
466 LOG(ERROR) << "Reached limit of pending sync queries.";
468 pending_sync_queries_.front()->Wait();
469 DCHECK(!pending_sync_queries_.front()->IsPending());
472 while (!pending_sync_queries_.empty()) {
473 if (pending_sync_queries_.front()->IsPending())
474 break;
476 available_sync_queries_.push_back(pending_sync_queries_.take_front());
479 current_sync_query_ = available_sync_queries_.empty()
480 ? make_scoped_ptr(new SyncQuery(gl_))
481 : available_sync_queries_.take_front();
483 read_lock_fence = current_sync_query_->Begin();
484 } else {
485 read_lock_fence =
486 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_));
488 resource_provider_->SetReadLockFence(read_lock_fence.get());
490 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
491 // so that drawing can proceed without GL context switching interruptions.
492 ResourceProvider* resource_provider = resource_provider_;
493 for (const auto& pass : *frame->render_passes_in_draw_order) {
494 for (const auto& quad : pass->quad_list) {
495 for (ResourceId resource_id : quad->resources)
496 resource_provider->WaitSyncPointIfNeeded(resource_id);
500 // TODO(enne): Do we need to reinitialize all of this state per frame?
501 ReinitializeGLState();
504 void GLRenderer::DoNoOp() {
505 gl_->BindFramebuffer(GL_FRAMEBUFFER, 0);
506 gl_->Flush();
509 void GLRenderer::DoDrawQuad(DrawingFrame* frame,
510 const DrawQuad* quad,
511 const gfx::QuadF* clip_region) {
512 DCHECK(quad->rect.Contains(quad->visible_rect));
513 if (quad->material != DrawQuad::TEXTURE_CONTENT) {
514 FlushTextureQuadCache(SHARED_BINDING);
517 switch (quad->material) {
518 case DrawQuad::INVALID:
519 NOTREACHED();
520 break;
521 case DrawQuad::DEBUG_BORDER:
522 DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
523 break;
524 case DrawQuad::IO_SURFACE_CONTENT:
525 DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad),
526 clip_region);
527 break;
528 case DrawQuad::PICTURE_CONTENT:
529 // PictureDrawQuad should only be used for resourceless software draws.
530 NOTREACHED();
531 break;
532 case DrawQuad::RENDER_PASS:
533 DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad),
534 clip_region);
535 break;
536 case DrawQuad::SOLID_COLOR:
537 DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad),
538 clip_region);
539 break;
540 case DrawQuad::STREAM_VIDEO_CONTENT:
541 DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad),
542 clip_region);
543 break;
544 case DrawQuad::SURFACE_CONTENT:
545 // Surface content should be fully resolved to other quad types before
546 // reaching a direct renderer.
547 NOTREACHED();
548 break;
549 case DrawQuad::TEXTURE_CONTENT:
550 EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad),
551 clip_region);
552 break;
553 case DrawQuad::TILED_CONTENT:
554 DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad), clip_region);
555 break;
556 case DrawQuad::YUV_VIDEO_CONTENT:
557 DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad),
558 clip_region);
559 break;
563 // This function does not handle 3D sorting right now, since the debug border
564 // quads are just drawn as their original quads and not in split pieces. This
565 // results in some debug border quads drawing over foreground quads.
566 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
567 const DebugBorderDrawQuad* quad) {
568 SetBlendEnabled(quad->ShouldDrawWithBlending());
570 static float gl_matrix[16];
571 const DebugBorderProgram* program = GetDebugBorderProgram();
572 DCHECK(program && (program->initialized() || IsContextLost()));
573 SetUseProgram(program->program());
575 // Use the full quad_rect for debug quads to not move the edges based on
576 // partial swaps.
577 gfx::Rect layer_rect = quad->rect;
578 gfx::Transform render_matrix;
579 QuadRectTransform(&render_matrix,
580 quad->shared_quad_state->quad_to_target_transform,
581 layer_rect);
582 GLRenderer::ToGLMatrix(&gl_matrix[0],
583 frame->projection_matrix * render_matrix);
584 gl_->UniformMatrix4fv(program->vertex_shader().matrix_location(), 1, false,
585 &gl_matrix[0]);
587 SkColor color = quad->color;
588 float alpha = SkColorGetA(color) * (1.0f / 255.0f);
590 gl_->Uniform4f(program->fragment_shader().color_location(),
591 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
592 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
593 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha, alpha);
595 gl_->LineWidth(quad->width);
597 // The indices for the line are stored in the same array as the triangle
598 // indices.
599 gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0);
602 static skia::RefPtr<SkImage> ApplyImageFilter(
603 scoped_ptr<GLRenderer::ScopedUseGrContext> use_gr_context,
604 ResourceProvider* resource_provider,
605 const gfx::Rect& rect,
606 const gfx::Vector2dF& scale,
607 SkImageFilter* filter,
608 ScopedResource* source_texture_resource) {
609 if (!filter)
610 return skia::RefPtr<SkImage>();
612 if (!use_gr_context)
613 return skia::RefPtr<SkImage>();
615 ResourceProvider::ScopedReadLockGL lock(resource_provider,
616 source_texture_resource->id());
618 // Wrap the source texture in a Ganesh platform texture.
619 GrBackendTextureDesc backend_texture_description;
620 backend_texture_description.fWidth = source_texture_resource->size().width();
621 backend_texture_description.fHeight =
622 source_texture_resource->size().height();
623 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
624 backend_texture_description.fTextureHandle = lock.texture_id();
625 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
626 skia::RefPtr<GrTexture> texture = skia::AdoptRef(
627 use_gr_context->context()->textureProvider()->wrapBackendTexture(
628 backend_texture_description));
629 if (!texture) {
630 TRACE_EVENT_INSTANT0("cc",
631 "ApplyImageFilter wrap background texture failed",
632 TRACE_EVENT_SCOPE_THREAD);
633 return skia::RefPtr<SkImage>();
636 SkImageInfo src_info =
637 SkImageInfo::MakeN32Premul(source_texture_resource->size().width(),
638 source_texture_resource->size().height());
639 // Place the platform texture inside an SkBitmap.
640 SkBitmap source;
641 source.setInfo(src_info);
642 skia::RefPtr<SkGrPixelRef> pixel_ref =
643 skia::AdoptRef(new SkGrPixelRef(src_info, texture.get()));
644 source.setPixelRef(pixel_ref.get());
646 // Create surface to draw into.
647 SkImageInfo dst_info =
648 SkImageInfo::MakeN32Premul(source.width(), source.height());
649 skia::RefPtr<SkSurface> surface = skia::AdoptRef(SkSurface::NewRenderTarget(
650 use_gr_context->context(), SkSurface::kYes_Budgeted, dst_info, 0));
651 if (!surface) {
652 TRACE_EVENT_INSTANT0("cc", "ApplyImageFilter surface allocation failed",
653 TRACE_EVENT_SCOPE_THREAD);
654 return skia::RefPtr<SkImage>();
656 skia::RefPtr<SkCanvas> canvas = skia::SharePtr(surface->getCanvas());
658 // Draw the source bitmap through the filter to the canvas.
659 SkPaint paint;
660 paint.setImageFilter(filter);
661 canvas->clear(SK_ColorTRANSPARENT);
663 // The origin of the filter is top-left and the origin of the source is
664 // bottom-left, but the orientation is the same, so we must translate the
665 // filter so that it renders at the bottom of the texture to avoid
666 // misregistration.
667 int y_translate = source.height() - rect.height() - rect.origin().y();
668 canvas->translate(-rect.origin().x(), y_translate);
669 canvas->scale(scale.x(), scale.y());
670 canvas->drawSprite(source, 0, 0, &paint);
672 skia::RefPtr<SkImage> image = skia::AdoptRef(surface->newImageSnapshot());
673 if (!image || !image->isTextureBacked()) {
674 return skia::RefPtr<SkImage>();
677 return image;
680 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
681 return use_blend_equation_advanced_ ||
682 blend_mode == SkXfermode::kScreen_Mode ||
683 blend_mode == SkXfermode::kSrcOver_Mode;
686 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
687 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode));
689 // Any modes set here must be reset in RestoreBlendFuncToDefault
690 if (use_blend_equation_advanced_) {
691 GLenum equation = GL_FUNC_ADD;
693 switch (blend_mode) {
694 case SkXfermode::kScreen_Mode:
695 equation = GL_SCREEN_KHR;
696 break;
697 case SkXfermode::kOverlay_Mode:
698 equation = GL_OVERLAY_KHR;
699 break;
700 case SkXfermode::kDarken_Mode:
701 equation = GL_DARKEN_KHR;
702 break;
703 case SkXfermode::kLighten_Mode:
704 equation = GL_LIGHTEN_KHR;
705 break;
706 case SkXfermode::kColorDodge_Mode:
707 equation = GL_COLORDODGE_KHR;
708 break;
709 case SkXfermode::kColorBurn_Mode:
710 equation = GL_COLORBURN_KHR;
711 break;
712 case SkXfermode::kHardLight_Mode:
713 equation = GL_HARDLIGHT_KHR;
714 break;
715 case SkXfermode::kSoftLight_Mode:
716 equation = GL_SOFTLIGHT_KHR;
717 break;
718 case SkXfermode::kDifference_Mode:
719 equation = GL_DIFFERENCE_KHR;
720 break;
721 case SkXfermode::kExclusion_Mode:
722 equation = GL_EXCLUSION_KHR;
723 break;
724 case SkXfermode::kMultiply_Mode:
725 equation = GL_MULTIPLY_KHR;
726 break;
727 case SkXfermode::kHue_Mode:
728 equation = GL_HSL_HUE_KHR;
729 break;
730 case SkXfermode::kSaturation_Mode:
731 equation = GL_HSL_SATURATION_KHR;
732 break;
733 case SkXfermode::kColor_Mode:
734 equation = GL_HSL_COLOR_KHR;
735 break;
736 case SkXfermode::kLuminosity_Mode:
737 equation = GL_HSL_LUMINOSITY_KHR;
738 break;
739 default:
740 return;
743 gl_->BlendEquation(equation);
744 } else {
745 if (blend_mode == SkXfermode::kScreen_Mode) {
746 gl_->BlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE);
751 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode) {
752 if (blend_mode == SkXfermode::kSrcOver_Mode)
753 return;
755 if (use_blend_equation_advanced_) {
756 gl_->BlendEquation(GL_FUNC_ADD);
757 } else {
758 gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
762 bool GLRenderer::ShouldApplyBackgroundFilters(const RenderPassDrawQuad* quad) {
763 if (quad->background_filters.IsEmpty())
764 return false;
766 // TODO(hendrikw): Look into allowing background filters to see pixels from
767 // other render targets. See crbug.com/314867.
769 return true;
772 // This takes a gfx::Rect and a clip region quad in the same space,
773 // and returns a quad with the same proportions in the space -0.5->0.5.
774 bool GetScaledRegion(const gfx::Rect& rect,
775 const gfx::QuadF* clip,
776 gfx::QuadF* scaled_region) {
777 if (!clip)
778 return false;
780 gfx::PointF p1(((clip->p1().x() - rect.x()) / rect.width()) - 0.5f,
781 ((clip->p1().y() - rect.y()) / rect.height()) - 0.5f);
782 gfx::PointF p2(((clip->p2().x() - rect.x()) / rect.width()) - 0.5f,
783 ((clip->p2().y() - rect.y()) / rect.height()) - 0.5f);
784 gfx::PointF p3(((clip->p3().x() - rect.x()) / rect.width()) - 0.5f,
785 ((clip->p3().y() - rect.y()) / rect.height()) - 0.5f);
786 gfx::PointF p4(((clip->p4().x() - rect.x()) / rect.width()) - 0.5f,
787 ((clip->p4().y() - rect.y()) / rect.height()) - 0.5f);
788 *scaled_region = gfx::QuadF(p1, p2, p3, p4);
789 return true;
792 // This takes a gfx::Rect and a clip region quad in the same space,
793 // and returns the proportional uv's in the space 0->1.
794 bool GetScaledUVs(const gfx::Rect& rect, const gfx::QuadF* clip, float uvs[8]) {
795 if (!clip)
796 return false;
798 uvs[0] = ((clip->p1().x() - rect.x()) / rect.width());
799 uvs[1] = ((clip->p1().y() - rect.y()) / rect.height());
800 uvs[2] = ((clip->p2().x() - rect.x()) / rect.width());
801 uvs[3] = ((clip->p2().y() - rect.y()) / rect.height());
802 uvs[4] = ((clip->p3().x() - rect.x()) / rect.width());
803 uvs[5] = ((clip->p3().y() - rect.y()) / rect.height());
804 uvs[6] = ((clip->p4().x() - rect.x()) / rect.width());
805 uvs[7] = ((clip->p4().y() - rect.y()) / rect.height());
806 return true;
809 gfx::Rect GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
810 DrawingFrame* frame,
811 const RenderPassDrawQuad* quad,
812 const gfx::Transform& contents_device_transform,
813 const gfx::QuadF* clip_region,
814 bool use_aa) {
815 gfx::QuadF scaled_region;
816 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
817 scaled_region = SharedGeometryQuad().BoundingBox();
820 gfx::Rect backdrop_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
821 contents_device_transform, scaled_region.BoundingBox()));
823 if (ShouldApplyBackgroundFilters(quad)) {
824 int top, right, bottom, left;
825 quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
826 backdrop_rect.Inset(-left, -top, -right, -bottom);
829 if (!backdrop_rect.IsEmpty() && use_aa) {
830 const int kOutsetForAntialiasing = 1;
831 backdrop_rect.Inset(-kOutsetForAntialiasing, -kOutsetForAntialiasing);
834 backdrop_rect.Intersect(MoveFromDrawToWindowSpace(
835 frame, frame->current_render_pass->output_rect));
836 return backdrop_rect;
839 scoped_ptr<ScopedResource> GLRenderer::GetBackdropTexture(
840 const gfx::Rect& bounding_rect) {
841 scoped_ptr<ScopedResource> device_background_texture =
842 ScopedResource::Create(resource_provider_);
843 // CopyTexImage2D fails when called on a texture having immutable storage.
844 device_background_texture->Allocate(
845 bounding_rect.size(), ResourceProvider::TEXTURE_HINT_DEFAULT, RGBA_8888);
847 ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
848 device_background_texture->id());
849 GetFramebufferTexture(
850 lock.texture_id(), device_background_texture->format(), bounding_rect);
852 return device_background_texture.Pass();
855 skia::RefPtr<SkImage> GLRenderer::ApplyBackgroundFilters(
856 DrawingFrame* frame,
857 const RenderPassDrawQuad* quad,
858 ScopedResource* background_texture) {
859 DCHECK(ShouldApplyBackgroundFilters(quad));
860 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
861 quad->background_filters, background_texture->size());
863 skia::RefPtr<SkImage> background_with_filters = ApplyImageFilter(
864 ScopedUseGrContext::Create(this, frame), resource_provider_, quad->rect,
865 quad->filters_scale, filter.get(), background_texture);
866 return background_with_filters;
869 void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
870 const RenderPassDrawQuad* quad,
871 const gfx::QuadF* clip_region) {
872 ScopedResource* contents_texture =
873 render_pass_textures_.get(quad->render_pass_id);
874 DCHECK(contents_texture);
875 DCHECK(contents_texture->id());
877 gfx::Transform quad_rect_matrix;
878 QuadRectTransform(&quad_rect_matrix,
879 quad->shared_quad_state->quad_to_target_transform,
880 quad->rect);
881 gfx::Transform contents_device_transform =
882 frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
883 contents_device_transform.FlattenTo2d();
885 // Can only draw surface if device matrix is invertible.
886 if (!contents_device_transform.IsInvertible())
887 return;
889 gfx::QuadF surface_quad = SharedGeometryQuad();
891 gfx::QuadF device_layer_quad;
892 bool use_aa = false;
893 if (settings_->allow_antialiasing) {
894 bool clipped = false;
895 device_layer_quad =
896 MathUtil::MapQuad(contents_device_transform, surface_quad, &clipped);
897 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped,
898 settings_->force_antialiasing);
901 float edge[24];
902 const gfx::QuadF* aa_quad = use_aa ? &device_layer_quad : nullptr;
903 SetupRenderPassQuadForClippingAndAntialiasing(contents_device_transform, quad,
904 aa_quad, clip_region,
905 &surface_quad, edge);
906 SkXfermode::Mode blend_mode = quad->shared_quad_state->blend_mode;
907 bool use_shaders_for_blending =
908 !CanApplyBlendModeUsingBlendFunc(blend_mode) ||
909 ShouldApplyBackgroundFilters(quad) ||
910 settings_->force_blending_with_shaders;
912 scoped_ptr<ScopedResource> background_texture;
913 skia::RefPtr<SkImage> background_image;
914 GLuint background_image_id = 0;
915 gfx::Rect background_rect;
916 if (use_shaders_for_blending) {
917 // Compute a bounding box around the pixels that will be visible through
918 // the quad.
919 background_rect = GetBackdropBoundingBoxForRenderPassQuad(
920 frame, quad, contents_device_transform, clip_region, use_aa);
922 if (!background_rect.IsEmpty()) {
923 // The pixels from the filtered background should completely replace the
924 // current pixel values.
925 if (blend_enabled())
926 SetBlendEnabled(false);
928 // Read the pixels in the bounding box into a buffer R.
929 // This function allocates a texture, which should contribute to the
930 // amount of memory used by render surfaces:
931 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
932 background_texture = GetBackdropTexture(background_rect);
934 if (ShouldApplyBackgroundFilters(quad) && background_texture) {
935 // Apply the background filters to R, so that it is applied in the
936 // pixels' coordinate space.
937 background_image =
938 ApplyBackgroundFilters(frame, quad, background_texture.get());
939 if (background_image)
940 background_image_id = background_image->getTextureHandle(true);
941 DCHECK(background_image_id);
945 if (!background_texture) {
946 // Something went wrong with reading the backdrop.
947 DCHECK(!background_image_id);
948 use_shaders_for_blending = false;
949 } else if (background_image_id) {
950 // Reset original background texture if there is not any mask
951 if (!quad->mask_resource_id())
952 background_texture.reset();
953 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode) &&
954 ShouldApplyBackgroundFilters(quad)) {
955 // Something went wrong with applying background filters to the backdrop.
956 use_shaders_for_blending = false;
957 background_texture.reset();
960 // Need original background texture for mask?
961 bool mask_for_background =
962 background_texture && // Have original background texture
963 background_image_id && // Have filtered background texture
964 quad->mask_resource_id(); // Have mask texture
965 SetBlendEnabled(
966 !use_shaders_for_blending &&
967 (quad->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode)));
969 // TODO(senorblanco): Cache this value so that we don't have to do it for both
970 // the surface and its replica. Apply filters to the contents texture.
971 skia::RefPtr<SkImage> filter_image;
972 GLuint filter_image_id = 0;
973 SkScalar color_matrix[20];
974 bool use_color_matrix = false;
975 if (!quad->filters.IsEmpty()) {
976 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
977 quad->filters, contents_texture->size());
978 if (filter) {
979 skia::RefPtr<SkColorFilter> cf;
982 SkColorFilter* colorfilter_rawptr = NULL;
983 filter->asColorFilter(&colorfilter_rawptr);
984 cf = skia::AdoptRef(colorfilter_rawptr);
987 if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
988 // We have a single color matrix as a filter; apply it locally
989 // in the compositor.
990 use_color_matrix = true;
991 } else {
992 filter_image = ApplyImageFilter(
993 ScopedUseGrContext::Create(this, frame), resource_provider_,
994 quad->rect, quad->filters_scale, filter.get(), contents_texture);
995 if (filter_image) {
996 filter_image_id = filter_image->getTextureHandle(true);
997 DCHECK(filter_image_id);
1003 scoped_ptr<ResourceProvider::ScopedSamplerGL> mask_resource_lock;
1004 unsigned mask_texture_id = 0;
1005 SamplerType mask_sampler = SAMPLER_TYPE_NA;
1006 if (quad->mask_resource_id()) {
1007 mask_resource_lock.reset(new ResourceProvider::ScopedSamplerGL(
1008 resource_provider_, quad->mask_resource_id(), GL_TEXTURE1, GL_LINEAR));
1009 mask_texture_id = mask_resource_lock->texture_id();
1010 mask_sampler = SamplerTypeFromTextureTarget(mask_resource_lock->target());
1013 scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
1014 if (filter_image_id) {
1015 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
1016 gl_->BindTexture(GL_TEXTURE_2D, filter_image_id);
1017 } else {
1018 contents_resource_lock =
1019 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1020 resource_provider_, contents_texture->id(), GL_LINEAR));
1021 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1022 contents_resource_lock->target());
1025 if (!use_shaders_for_blending) {
1026 if (!use_blend_equation_advanced_coherent_ && use_blend_equation_advanced_)
1027 gl_->BlendBarrierKHR();
1029 ApplyBlendModeUsingBlendFunc(blend_mode);
1032 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1033 gl_, &highp_threshold_cache_, highp_threshold_min_,
1034 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
1036 ShaderLocations locations;
1038 DCHECK_EQ(background_texture || background_image_id,
1039 use_shaders_for_blending);
1040 BlendMode shader_blend_mode = use_shaders_for_blending
1041 ? BlendModeFromSkXfermode(blend_mode)
1042 : BLEND_MODE_NONE;
1044 if (use_aa && mask_texture_id && !use_color_matrix) {
1045 const RenderPassMaskProgramAA* program = GetRenderPassMaskProgramAA(
1046 tex_coord_precision, mask_sampler,
1047 shader_blend_mode, mask_for_background);
1048 SetUseProgram(program->program());
1049 program->vertex_shader().FillLocations(&locations);
1050 program->fragment_shader().FillLocations(&locations);
1051 gl_->Uniform1i(locations.sampler, 0);
1052 } else if (!use_aa && mask_texture_id && !use_color_matrix) {
1053 const RenderPassMaskProgram* program = GetRenderPassMaskProgram(
1054 tex_coord_precision, mask_sampler,
1055 shader_blend_mode, mask_for_background);
1056 SetUseProgram(program->program());
1057 program->vertex_shader().FillLocations(&locations);
1058 program->fragment_shader().FillLocations(&locations);
1059 gl_->Uniform1i(locations.sampler, 0);
1060 } else if (use_aa && !mask_texture_id && !use_color_matrix) {
1061 const RenderPassProgramAA* program =
1062 GetRenderPassProgramAA(tex_coord_precision, shader_blend_mode);
1063 SetUseProgram(program->program());
1064 program->vertex_shader().FillLocations(&locations);
1065 program->fragment_shader().FillLocations(&locations);
1066 gl_->Uniform1i(locations.sampler, 0);
1067 } else if (use_aa && mask_texture_id && use_color_matrix) {
1068 const RenderPassMaskColorMatrixProgramAA* program =
1069 GetRenderPassMaskColorMatrixProgramAA(
1070 tex_coord_precision, mask_sampler,
1071 shader_blend_mode, mask_for_background);
1072 SetUseProgram(program->program());
1073 program->vertex_shader().FillLocations(&locations);
1074 program->fragment_shader().FillLocations(&locations);
1075 gl_->Uniform1i(locations.sampler, 0);
1076 } else if (use_aa && !mask_texture_id && use_color_matrix) {
1077 const RenderPassColorMatrixProgramAA* program =
1078 GetRenderPassColorMatrixProgramAA(tex_coord_precision,
1079 shader_blend_mode);
1080 SetUseProgram(program->program());
1081 program->vertex_shader().FillLocations(&locations);
1082 program->fragment_shader().FillLocations(&locations);
1083 gl_->Uniform1i(locations.sampler, 0);
1084 } else if (!use_aa && mask_texture_id && use_color_matrix) {
1085 const RenderPassMaskColorMatrixProgram* program =
1086 GetRenderPassMaskColorMatrixProgram(
1087 tex_coord_precision, mask_sampler,
1088 shader_blend_mode, mask_for_background);
1089 SetUseProgram(program->program());
1090 program->vertex_shader().FillLocations(&locations);
1091 program->fragment_shader().FillLocations(&locations);
1092 gl_->Uniform1i(locations.sampler, 0);
1093 } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1094 const RenderPassColorMatrixProgram* program =
1095 GetRenderPassColorMatrixProgram(tex_coord_precision, shader_blend_mode);
1096 SetUseProgram(program->program());
1097 program->vertex_shader().FillLocations(&locations);
1098 program->fragment_shader().FillLocations(&locations);
1099 gl_->Uniform1i(locations.sampler, 0);
1100 } else {
1101 const RenderPassProgram* program =
1102 GetRenderPassProgram(tex_coord_precision, shader_blend_mode);
1103 SetUseProgram(program->program());
1104 program->vertex_shader().FillLocations(&locations);
1105 program->fragment_shader().FillLocations(&locations);
1106 gl_->Uniform1i(locations.sampler, 0);
1108 float tex_scale_x =
1109 quad->rect.width() / static_cast<float>(contents_texture->size().width());
1110 float tex_scale_y = quad->rect.height() /
1111 static_cast<float>(contents_texture->size().height());
1112 DCHECK_LE(tex_scale_x, 1.0f);
1113 DCHECK_LE(tex_scale_y, 1.0f);
1115 DCHECK(locations.tex_transform != -1 || IsContextLost());
1116 // Flip the content vertically in the shader, as the RenderPass input
1117 // texture is already oriented the same way as the framebuffer, but the
1118 // projection transform does a flip.
1119 gl_->Uniform4f(locations.tex_transform, 0.0f, tex_scale_y, tex_scale_x,
1120 -tex_scale_y);
1122 GLint last_texture_unit = 0;
1123 if (locations.mask_sampler != -1) {
1124 DCHECK_NE(locations.mask_tex_coord_scale, 1);
1125 DCHECK_NE(locations.mask_tex_coord_offset, 1);
1126 gl_->Uniform1i(locations.mask_sampler, 1);
1128 gfx::RectF mask_uv_rect = quad->MaskUVRect();
1129 if (mask_sampler != SAMPLER_TYPE_2D) {
1130 mask_uv_rect.Scale(quad->mask_texture_size.width(),
1131 quad->mask_texture_size.height());
1134 // Mask textures are oriented vertically flipped relative to the framebuffer
1135 // and the RenderPass contents texture, so we flip the tex coords from the
1136 // RenderPass texture to find the mask texture coords.
1137 gl_->Uniform2f(locations.mask_tex_coord_offset, mask_uv_rect.x(),
1138 mask_uv_rect.bottom());
1139 gl_->Uniform2f(locations.mask_tex_coord_scale,
1140 mask_uv_rect.width() / tex_scale_x,
1141 -mask_uv_rect.height() / tex_scale_y);
1143 last_texture_unit = 1;
1146 if (locations.edge != -1)
1147 gl_->Uniform3fv(locations.edge, 8, edge);
1149 if (locations.viewport != -1) {
1150 float viewport[4] = {
1151 static_cast<float>(current_window_space_viewport_.x()),
1152 static_cast<float>(current_window_space_viewport_.y()),
1153 static_cast<float>(current_window_space_viewport_.width()),
1154 static_cast<float>(current_window_space_viewport_.height()),
1156 gl_->Uniform4fv(locations.viewport, 1, viewport);
1159 if (locations.color_matrix != -1) {
1160 float matrix[16];
1161 for (int i = 0; i < 4; ++i) {
1162 for (int j = 0; j < 4; ++j)
1163 matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1165 gl_->UniformMatrix4fv(locations.color_matrix, 1, false, matrix);
1167 static const float kScale = 1.0f / 255.0f;
1168 if (locations.color_offset != -1) {
1169 float offset[4];
1170 for (int i = 0; i < 4; ++i)
1171 offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1173 gl_->Uniform4fv(locations.color_offset, 1, offset);
1176 scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_background_sampler_lock;
1177 if (locations.backdrop != -1) {
1178 DCHECK(background_texture || background_image_id);
1179 DCHECK_NE(locations.backdrop, 0);
1180 DCHECK_NE(locations.backdrop_rect, 0);
1182 gl_->Uniform1i(locations.backdrop, ++last_texture_unit);
1184 gl_->Uniform4f(locations.backdrop_rect, background_rect.x(),
1185 background_rect.y(), background_rect.width(),
1186 background_rect.height());
1188 if (background_image_id) {
1189 gl_->ActiveTexture(GL_TEXTURE0 + last_texture_unit);
1190 gl_->BindTexture(GL_TEXTURE_2D, background_image_id);
1191 gl_->ActiveTexture(GL_TEXTURE0);
1192 if (mask_for_background)
1193 gl_->Uniform1i(locations.original_backdrop, ++last_texture_unit);
1195 if (background_texture) {
1196 shader_background_sampler_lock = make_scoped_ptr(
1197 new ResourceProvider::ScopedSamplerGL(resource_provider_,
1198 background_texture->id(),
1199 GL_TEXTURE0 + last_texture_unit,
1200 GL_LINEAR));
1201 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1202 shader_background_sampler_lock->target());
1206 SetShaderOpacity(quad->shared_quad_state->opacity, locations.alpha);
1207 SetShaderQuadF(surface_quad, locations.quad);
1208 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1209 quad->rect, locations.matrix);
1211 // Flush the compositor context before the filter bitmap goes out of
1212 // scope, so the draw gets processed before the filter texture gets deleted.
1213 if (filter_image_id)
1214 gl_->Flush();
1216 if (!use_shaders_for_blending)
1217 RestoreBlendFuncToDefault(blend_mode);
1220 struct SolidColorProgramUniforms {
1221 unsigned program;
1222 unsigned matrix_location;
1223 unsigned viewport_location;
1224 unsigned quad_location;
1225 unsigned edge_location;
1226 unsigned color_location;
1229 template <class T>
1230 static void SolidColorUniformLocation(T program,
1231 SolidColorProgramUniforms* uniforms) {
1232 uniforms->program = program->program();
1233 uniforms->matrix_location = program->vertex_shader().matrix_location();
1234 uniforms->viewport_location = program->vertex_shader().viewport_location();
1235 uniforms->quad_location = program->vertex_shader().quad_location();
1236 uniforms->edge_location = program->vertex_shader().edge_location();
1237 uniforms->color_location = program->fragment_shader().color_location();
1240 namespace {
1241 // These functions determine if a quad, clipped by a clip_region contains
1242 // the entire {top|bottom|left|right} edge.
1243 bool is_top(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1244 if (!quad->IsTopEdge())
1245 return false;
1246 if (!clip_region)
1247 return true;
1249 return std::abs(clip_region->p1().y()) < kAntiAliasingEpsilon &&
1250 std::abs(clip_region->p2().y()) < kAntiAliasingEpsilon;
1253 bool is_bottom(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1254 if (!quad->IsBottomEdge())
1255 return false;
1256 if (!clip_region)
1257 return true;
1259 return std::abs(clip_region->p3().y() -
1260 quad->shared_quad_state->quad_layer_bounds.height()) <
1261 kAntiAliasingEpsilon &&
1262 std::abs(clip_region->p4().y() -
1263 quad->shared_quad_state->quad_layer_bounds.height()) <
1264 kAntiAliasingEpsilon;
1267 bool is_left(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1268 if (!quad->IsLeftEdge())
1269 return false;
1270 if (!clip_region)
1271 return true;
1273 return std::abs(clip_region->p1().x()) < kAntiAliasingEpsilon &&
1274 std::abs(clip_region->p4().x()) < kAntiAliasingEpsilon;
1277 bool is_right(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1278 if (!quad->IsRightEdge())
1279 return false;
1280 if (!clip_region)
1281 return true;
1283 return std::abs(clip_region->p2().x() -
1284 quad->shared_quad_state->quad_layer_bounds.width()) <
1285 kAntiAliasingEpsilon &&
1286 std::abs(clip_region->p3().x() -
1287 quad->shared_quad_state->quad_layer_bounds.width()) <
1288 kAntiAliasingEpsilon;
1290 } // anonymous namespace
1292 static gfx::QuadF GetDeviceQuadWithAntialiasingOnExteriorEdges(
1293 const LayerQuad& device_layer_edges,
1294 const gfx::Transform& device_transform,
1295 const gfx::QuadF& tile_quad,
1296 const gfx::QuadF* clip_region,
1297 const DrawQuad* quad) {
1298 gfx::RectF tile_rect = quad->visible_rect;
1300 gfx::PointF bottom_right = tile_quad.p3();
1301 gfx::PointF bottom_left = tile_quad.p4();
1302 gfx::PointF top_left = tile_quad.p1();
1303 gfx::PointF top_right = tile_quad.p2();
1304 bool clipped = false;
1306 // Map points to device space. We ignore |clipped|, since the result of
1307 // |MapPoint()| still produces a valid point to draw the quad with. When
1308 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1309 bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1310 bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1311 top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1312 top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1314 LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1315 LayerQuad::Edge left_edge(bottom_left, top_left);
1316 LayerQuad::Edge top_edge(top_left, top_right);
1317 LayerQuad::Edge right_edge(top_right, bottom_right);
1319 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1320 // If an edge is degenerate we do not want to replace it with a "proper" edge
1321 // as that will cause the quad to possibly expand is strange ways.
1322 if (!top_edge.degenerate() && is_top(clip_region, quad) &&
1323 tile_rect.y() == quad->rect.y()) {
1324 top_edge = device_layer_edges.top();
1326 if (!left_edge.degenerate() && is_left(clip_region, quad) &&
1327 tile_rect.x() == quad->rect.x()) {
1328 left_edge = device_layer_edges.left();
1330 if (!right_edge.degenerate() && is_right(clip_region, quad) &&
1331 tile_rect.right() == quad->rect.right()) {
1332 right_edge = device_layer_edges.right();
1334 if (!bottom_edge.degenerate() && is_bottom(clip_region, quad) &&
1335 tile_rect.bottom() == quad->rect.bottom()) {
1336 bottom_edge = device_layer_edges.bottom();
1339 float sign = tile_quad.IsCounterClockwise() ? -1 : 1;
1340 bottom_edge.scale(sign);
1341 left_edge.scale(sign);
1342 top_edge.scale(sign);
1343 right_edge.scale(sign);
1345 // Create device space quad.
1346 return LayerQuad(left_edge, top_edge, right_edge, bottom_edge).ToQuadF();
1349 float GetTotalQuadError(const gfx::QuadF* clipped_quad,
1350 const gfx::QuadF* ideal_rect) {
1351 return (clipped_quad->p1() - ideal_rect->p1()).LengthSquared() +
1352 (clipped_quad->p2() - ideal_rect->p2()).LengthSquared() +
1353 (clipped_quad->p3() - ideal_rect->p3()).LengthSquared() +
1354 (clipped_quad->p4() - ideal_rect->p4()).LengthSquared();
1357 // Attempt to rotate the clipped quad until it lines up the most
1358 // correctly. This is necessary because we check the edges of this
1359 // quad against the expected left/right/top/bottom for anti-aliasing.
1360 void AlignQuadToBoundingBox(gfx::QuadF* clipped_quad) {
1361 gfx::QuadF bounding_quad = gfx::QuadF(clipped_quad->BoundingBox());
1362 gfx::QuadF best_rotation = *clipped_quad;
1363 float least_error_amount = GetTotalQuadError(clipped_quad, &bounding_quad);
1364 for (size_t i = 1; i < 4; ++i) {
1365 clipped_quad->Realign(1);
1366 float new_error = GetTotalQuadError(clipped_quad, &bounding_quad);
1367 if (new_error < least_error_amount) {
1368 least_error_amount = new_error;
1369 best_rotation = *clipped_quad;
1372 *clipped_quad = best_rotation;
1375 // Map device space quad to local space. Device_transform has no 3d
1376 // component since it was flattened, so we don't need to project. We should
1377 // have already checked that the transform was uninvertible before this call.
1378 gfx::QuadF MapQuadToLocalSpace(const gfx::Transform& device_transform,
1379 const gfx::QuadF& device_quad) {
1380 gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1381 DCHECK(device_transform.IsInvertible());
1382 bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1383 DCHECK(did_invert);
1384 bool clipped = false;
1385 gfx::QuadF local_quad =
1386 MathUtil::MapQuad(inverse_device_transform, device_quad, &clipped);
1387 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1388 // cause device_quad to become clipped. To our knowledge this scenario does
1389 // not need to be handled differently than the unclipped case.
1390 return local_quad;
1393 void InflateAntiAliasingDistances(const gfx::QuadF& quad,
1394 LayerQuad* device_layer_edges,
1395 float edge[24]) {
1396 DCHECK(!quad.BoundingBox().IsEmpty());
1397 LayerQuad device_layer_bounds(gfx::QuadF(quad.BoundingBox()));
1399 device_layer_edges->InflateAntiAliasingDistance();
1400 device_layer_edges->ToFloatArray(edge);
1402 device_layer_bounds.InflateAntiAliasingDistance();
1403 device_layer_bounds.ToFloatArray(&edge[12]);
1406 // static
1407 bool GLRenderer::ShouldAntialiasQuad(const gfx::QuadF& device_layer_quad,
1408 bool clipped,
1409 bool force_aa) {
1410 // AAing clipped quads is not supported by the code yet.
1411 if (clipped)
1412 return false;
1413 if (device_layer_quad.BoundingBox().IsEmpty())
1414 return false;
1415 if (force_aa)
1416 return true;
1418 bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1419 bool is_nearest_rect_within_epsilon =
1420 is_axis_aligned_in_target &&
1421 gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1422 kAntiAliasingEpsilon);
1423 return !is_nearest_rect_within_epsilon;
1426 // static
1427 void GLRenderer::SetupQuadForClippingAndAntialiasing(
1428 const gfx::Transform& device_transform,
1429 const DrawQuad* quad,
1430 const gfx::QuadF* aa_quad,
1431 const gfx::QuadF* clip_region,
1432 gfx::QuadF* local_quad,
1433 float edge[24]) {
1434 gfx::QuadF rotated_clip;
1435 const gfx::QuadF* local_clip_region = clip_region;
1436 if (local_clip_region) {
1437 rotated_clip = *clip_region;
1438 AlignQuadToBoundingBox(&rotated_clip);
1439 local_clip_region = &rotated_clip;
1442 if (!aa_quad) {
1443 if (local_clip_region)
1444 *local_quad = *local_clip_region;
1445 return;
1448 LayerQuad device_layer_edges(*aa_quad);
1449 InflateAntiAliasingDistances(*aa_quad, &device_layer_edges, edge);
1451 // If we have a clip region then we are split, and therefore
1452 // by necessity, at least one of our edges is not an external
1453 // one.
1454 bool is_full_rect = quad->visible_rect == quad->rect;
1456 bool region_contains_all_outside_edges =
1457 is_full_rect &&
1458 (is_top(local_clip_region, quad) && is_left(local_clip_region, quad) &&
1459 is_bottom(local_clip_region, quad) && is_right(local_clip_region, quad));
1461 bool use_aa_on_all_four_edges =
1462 !local_clip_region && region_contains_all_outside_edges;
1464 gfx::QuadF device_quad;
1465 if (use_aa_on_all_four_edges) {
1466 device_quad = device_layer_edges.ToQuadF();
1467 } else {
1468 gfx::QuadF tile_quad(local_clip_region ? *local_clip_region
1469 : gfx::QuadF(quad->visible_rect));
1470 device_quad = GetDeviceQuadWithAntialiasingOnExteriorEdges(
1471 device_layer_edges, device_transform, tile_quad, local_clip_region,
1472 quad);
1475 *local_quad = MapQuadToLocalSpace(device_transform, device_quad);
1478 // static
1479 void GLRenderer::SetupRenderPassQuadForClippingAndAntialiasing(
1480 const gfx::Transform& device_transform,
1481 const RenderPassDrawQuad* quad,
1482 const gfx::QuadF* aa_quad,
1483 const gfx::QuadF* clip_region,
1484 gfx::QuadF* local_quad,
1485 float edge[24]) {
1486 gfx::QuadF rotated_clip;
1487 const gfx::QuadF* local_clip_region = clip_region;
1488 if (local_clip_region) {
1489 rotated_clip = *clip_region;
1490 AlignQuadToBoundingBox(&rotated_clip);
1491 local_clip_region = &rotated_clip;
1494 if (!aa_quad) {
1495 GetScaledRegion(quad->rect, local_clip_region, local_quad);
1496 return;
1499 LayerQuad device_layer_edges(*aa_quad);
1500 InflateAntiAliasingDistances(*aa_quad, &device_layer_edges, edge);
1502 gfx::QuadF device_quad;
1504 // Apply anti-aliasing only to the edges that are not being clipped
1505 if (local_clip_region) {
1506 gfx::QuadF tile_quad(quad->visible_rect);
1507 GetScaledRegion(quad->rect, local_clip_region, &tile_quad);
1508 device_quad = GetDeviceQuadWithAntialiasingOnExteriorEdges(
1509 device_layer_edges, device_transform, tile_quad, local_clip_region,
1510 quad);
1511 } else {
1512 device_quad = device_layer_edges.ToQuadF();
1515 *local_quad = MapQuadToLocalSpace(device_transform, device_quad);
1518 void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1519 const SolidColorDrawQuad* quad,
1520 const gfx::QuadF* clip_region) {
1521 gfx::Rect tile_rect = quad->visible_rect;
1523 SkColor color = quad->color;
1524 float opacity = quad->shared_quad_state->opacity;
1525 float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1527 // Early out if alpha is small enough that quad doesn't contribute to output.
1528 if (alpha < std::numeric_limits<float>::epsilon() &&
1529 quad->ShouldDrawWithBlending())
1530 return;
1532 gfx::Transform device_transform =
1533 frame->window_matrix * frame->projection_matrix *
1534 quad->shared_quad_state->quad_to_target_transform;
1535 device_transform.FlattenTo2d();
1536 if (!device_transform.IsInvertible())
1537 return;
1539 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1541 gfx::QuadF device_layer_quad;
1542 bool use_aa = false;
1543 bool allow_aa = settings_->allow_antialiasing &&
1544 !quad->force_anti_aliasing_off && quad->IsEdge();
1546 if (allow_aa) {
1547 bool clipped = false;
1548 bool force_aa = false;
1549 device_layer_quad = MathUtil::MapQuad(
1550 device_transform,
1551 gfx::QuadF(quad->shared_quad_state->visible_quad_layer_rect), &clipped);
1552 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped, force_aa);
1555 float edge[24];
1556 const gfx::QuadF* aa_quad = use_aa ? &device_layer_quad : nullptr;
1557 SetupQuadForClippingAndAntialiasing(device_transform, quad, aa_quad,
1558 clip_region, &local_quad, edge);
1560 SolidColorProgramUniforms uniforms;
1561 if (use_aa) {
1562 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1563 } else {
1564 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1566 SetUseProgram(uniforms.program);
1568 gl_->Uniform4f(uniforms.color_location,
1569 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1570 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1571 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha, alpha);
1572 if (use_aa) {
1573 float viewport[4] = {
1574 static_cast<float>(current_window_space_viewport_.x()),
1575 static_cast<float>(current_window_space_viewport_.y()),
1576 static_cast<float>(current_window_space_viewport_.width()),
1577 static_cast<float>(current_window_space_viewport_.height()),
1579 gl_->Uniform4fv(uniforms.viewport_location, 1, viewport);
1580 gl_->Uniform3fv(uniforms.edge_location, 8, edge);
1583 // Enable blending when the quad properties require it or if we decided
1584 // to use antialiasing.
1585 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1587 // Antialising requires a normalized quad, but this could lead to floating
1588 // point precision errors, so only normalize when antialising is on.
1589 if (use_aa) {
1590 // Normalize to tile_rect.
1591 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1593 SetShaderQuadF(local_quad, uniforms.quad_location);
1595 // The transform and vertex data are used to figure out the extents that the
1596 // un-antialiased quad should have and which vertex this is and the float
1597 // quad passed in via uniform is the actual geometry that gets used to draw
1598 // it. This is why this centered rect is used and not the original
1599 // quad_rect.
1600 gfx::RectF centered_rect(
1601 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1602 tile_rect.size());
1603 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1604 centered_rect, uniforms.matrix_location);
1605 } else {
1606 PrepareGeometry(SHARED_BINDING);
1607 SetShaderQuadF(local_quad, uniforms.quad_location);
1608 static float gl_matrix[16];
1609 ToGLMatrix(&gl_matrix[0],
1610 frame->projection_matrix *
1611 quad->shared_quad_state->quad_to_target_transform);
1612 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]);
1614 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
1618 struct TileProgramUniforms {
1619 unsigned program;
1620 unsigned matrix_location;
1621 unsigned viewport_location;
1622 unsigned quad_location;
1623 unsigned edge_location;
1624 unsigned vertex_tex_transform_location;
1625 unsigned sampler_location;
1626 unsigned fragment_tex_transform_location;
1627 unsigned alpha_location;
1630 template <class T>
1631 static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1632 uniforms->program = program->program();
1633 uniforms->matrix_location = program->vertex_shader().matrix_location();
1634 uniforms->viewport_location = program->vertex_shader().viewport_location();
1635 uniforms->quad_location = program->vertex_shader().quad_location();
1636 uniforms->edge_location = program->vertex_shader().edge_location();
1637 uniforms->vertex_tex_transform_location =
1638 program->vertex_shader().vertex_tex_transform_location();
1640 uniforms->sampler_location = program->fragment_shader().sampler_location();
1641 uniforms->alpha_location = program->fragment_shader().alpha_location();
1642 uniforms->fragment_tex_transform_location =
1643 program->fragment_shader().fragment_tex_transform_location();
1646 void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1647 const TileDrawQuad* quad,
1648 const gfx::QuadF* clip_region) {
1649 DrawContentQuad(frame, quad, quad->resource_id(), clip_region);
1652 void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1653 const ContentDrawQuadBase* quad,
1654 ResourceId resource_id,
1655 const gfx::QuadF* clip_region) {
1656 gfx::Transform device_transform =
1657 frame->window_matrix * frame->projection_matrix *
1658 quad->shared_quad_state->quad_to_target_transform;
1659 device_transform.FlattenTo2d();
1661 gfx::QuadF device_layer_quad;
1662 bool use_aa = false;
1663 bool allow_aa = settings_->allow_antialiasing && quad->IsEdge();
1664 if (allow_aa) {
1665 bool clipped = false;
1666 bool force_aa = false;
1667 device_layer_quad = MathUtil::MapQuad(
1668 device_transform,
1669 gfx::QuadF(quad->shared_quad_state->visible_quad_layer_rect), &clipped);
1670 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped, force_aa);
1673 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1674 // similar to the way DrawContentQuadNoAA works and then consider
1675 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1676 if (use_aa)
1677 DrawContentQuadAA(frame, quad, resource_id, device_transform,
1678 device_layer_quad, clip_region);
1679 else
1680 DrawContentQuadNoAA(frame, quad, resource_id, clip_region);
1683 void GLRenderer::DrawContentQuadAA(const DrawingFrame* frame,
1684 const ContentDrawQuadBase* quad,
1685 ResourceId resource_id,
1686 const gfx::Transform& device_transform,
1687 const gfx::QuadF& aa_quad,
1688 const gfx::QuadF* clip_region) {
1689 if (!device_transform.IsInvertible())
1690 return;
1692 gfx::Rect tile_rect = quad->visible_rect;
1694 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1695 quad->tex_coord_rect, quad->rect, tile_rect);
1696 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1697 float tex_to_geom_scale_y =
1698 quad->rect.height() / quad->tex_coord_rect.height();
1700 gfx::RectF clamp_geom_rect(tile_rect);
1701 gfx::RectF clamp_tex_rect(tex_coord_rect);
1702 // Clamp texture coordinates to avoid sampling outside the layer
1703 // by deflating the tile region half a texel or half a texel
1704 // minus epsilon for one pixel layers. The resulting clamp region
1705 // is mapped to the unit square by the vertex shader and mapped
1706 // back to normalized texture coordinates by the fragment shader
1707 // after being clamped to 0-1 range.
1708 float tex_clamp_x =
1709 std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1710 float tex_clamp_y =
1711 std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1712 float geom_clamp_x =
1713 std::min(tex_clamp_x * tex_to_geom_scale_x,
1714 0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1715 float geom_clamp_y =
1716 std::min(tex_clamp_y * tex_to_geom_scale_y,
1717 0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1718 clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1719 clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1721 // Map clamping rectangle to unit square.
1722 float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1723 float vertex_tex_translate_y =
1724 -clamp_geom_rect.y() / clamp_geom_rect.height();
1725 float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1726 float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1728 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1729 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1731 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1732 float edge[24];
1733 SetupQuadForClippingAndAntialiasing(device_transform, quad, &aa_quad,
1734 clip_region, &local_quad, edge);
1735 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1736 resource_provider_, resource_id,
1737 quad->nearest_neighbor ? GL_NEAREST : GL_LINEAR);
1738 SamplerType sampler =
1739 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1741 float fragment_tex_translate_x = clamp_tex_rect.x();
1742 float fragment_tex_translate_y = clamp_tex_rect.y();
1743 float fragment_tex_scale_x = clamp_tex_rect.width();
1744 float fragment_tex_scale_y = clamp_tex_rect.height();
1746 // Map to normalized texture coordinates.
1747 if (sampler != SAMPLER_TYPE_2D_RECT) {
1748 gfx::Size texture_size = quad->texture_size;
1749 DCHECK(!texture_size.IsEmpty());
1750 fragment_tex_translate_x /= texture_size.width();
1751 fragment_tex_translate_y /= texture_size.height();
1752 fragment_tex_scale_x /= texture_size.width();
1753 fragment_tex_scale_y /= texture_size.height();
1756 TileProgramUniforms uniforms;
1757 if (quad->swizzle_contents) {
1758 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1759 &uniforms);
1760 } else {
1761 TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1762 &uniforms);
1765 SetUseProgram(uniforms.program);
1766 gl_->Uniform1i(uniforms.sampler_location, 0);
1768 float viewport[4] = {
1769 static_cast<float>(current_window_space_viewport_.x()),
1770 static_cast<float>(current_window_space_viewport_.y()),
1771 static_cast<float>(current_window_space_viewport_.width()),
1772 static_cast<float>(current_window_space_viewport_.height()),
1774 gl_->Uniform4fv(uniforms.viewport_location, 1, viewport);
1775 gl_->Uniform3fv(uniforms.edge_location, 8, edge);
1777 gl_->Uniform4f(uniforms.vertex_tex_transform_location, vertex_tex_translate_x,
1778 vertex_tex_translate_y, vertex_tex_scale_x,
1779 vertex_tex_scale_y);
1780 gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1781 fragment_tex_translate_x, fragment_tex_translate_y,
1782 fragment_tex_scale_x, fragment_tex_scale_y);
1784 // Blending is required for antialiasing.
1785 SetBlendEnabled(true);
1787 // Normalize to tile_rect.
1788 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1790 SetShaderOpacity(quad->shared_quad_state->opacity, uniforms.alpha_location);
1791 SetShaderQuadF(local_quad, uniforms.quad_location);
1793 // The transform and vertex data are used to figure out the extents that the
1794 // un-antialiased quad should have and which vertex this is and the float
1795 // quad passed in via uniform is the actual geometry that gets used to draw
1796 // it. This is why this centered rect is used and not the original quad_rect.
1797 gfx::RectF centered_rect(
1798 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1799 tile_rect.size());
1800 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1801 centered_rect, uniforms.matrix_location);
1804 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame* frame,
1805 const ContentDrawQuadBase* quad,
1806 ResourceId resource_id,
1807 const gfx::QuadF* clip_region) {
1808 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1809 quad->tex_coord_rect, quad->rect, quad->visible_rect);
1810 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1811 float tex_to_geom_scale_y =
1812 quad->rect.height() / quad->tex_coord_rect.height();
1814 bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1815 GLenum filter = (scaled ||
1816 !quad->shared_quad_state->quad_to_target_transform
1817 .IsIdentityOrIntegerTranslation()) &&
1818 !quad->nearest_neighbor
1819 ? GL_LINEAR
1820 : GL_NEAREST;
1822 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1823 resource_provider_, resource_id, filter);
1824 SamplerType sampler =
1825 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1827 float vertex_tex_translate_x = tex_coord_rect.x();
1828 float vertex_tex_translate_y = tex_coord_rect.y();
1829 float vertex_tex_scale_x = tex_coord_rect.width();
1830 float vertex_tex_scale_y = tex_coord_rect.height();
1832 // Map to normalized texture coordinates.
1833 if (sampler != SAMPLER_TYPE_2D_RECT) {
1834 gfx::Size texture_size = quad->texture_size;
1835 DCHECK(!texture_size.IsEmpty());
1836 vertex_tex_translate_x /= texture_size.width();
1837 vertex_tex_translate_y /= texture_size.height();
1838 vertex_tex_scale_x /= texture_size.width();
1839 vertex_tex_scale_y /= texture_size.height();
1842 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1843 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1845 TileProgramUniforms uniforms;
1846 if (quad->ShouldDrawWithBlending()) {
1847 if (quad->swizzle_contents) {
1848 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1849 &uniforms);
1850 } else {
1851 TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1852 &uniforms);
1854 } else {
1855 if (quad->swizzle_contents) {
1856 TileUniformLocation(
1857 GetTileProgramSwizzleOpaque(tex_coord_precision, sampler), &uniforms);
1858 } else {
1859 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1860 &uniforms);
1864 SetUseProgram(uniforms.program);
1865 gl_->Uniform1i(uniforms.sampler_location, 0);
1867 gl_->Uniform4f(uniforms.vertex_tex_transform_location, vertex_tex_translate_x,
1868 vertex_tex_translate_y, vertex_tex_scale_x,
1869 vertex_tex_scale_y);
1871 SetBlendEnabled(quad->ShouldDrawWithBlending());
1873 SetShaderOpacity(quad->shared_quad_state->opacity, uniforms.alpha_location);
1875 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1876 // does, then vertices will match the texture mapping in the vertex buffer.
1877 // The method SetShaderQuadF() changes the order of vertices and so it's
1878 // not used here.
1879 gfx::QuadF tile_rect(quad->visible_rect);
1880 float width = quad->visible_rect.width();
1881 float height = quad->visible_rect.height();
1882 gfx::PointF top_left = quad->visible_rect.origin();
1883 if (clip_region) {
1884 tile_rect = *clip_region;
1885 float gl_uv[8] = {
1886 (tile_rect.p4().x() - top_left.x()) / width,
1887 (tile_rect.p4().y() - top_left.y()) / height,
1888 (tile_rect.p1().x() - top_left.x()) / width,
1889 (tile_rect.p1().y() - top_left.y()) / height,
1890 (tile_rect.p2().x() - top_left.x()) / width,
1891 (tile_rect.p2().y() - top_left.y()) / height,
1892 (tile_rect.p3().x() - top_left.x()) / width,
1893 (tile_rect.p3().y() - top_left.y()) / height,
1895 PrepareGeometry(CLIPPED_BINDING);
1896 clipped_geometry_->InitializeCustomQuadWithUVs(
1897 gfx::QuadF(quad->visible_rect), gl_uv);
1898 } else {
1899 PrepareGeometry(SHARED_BINDING);
1901 float gl_quad[8] = {
1902 tile_rect.p4().x(),
1903 tile_rect.p4().y(),
1904 tile_rect.p1().x(),
1905 tile_rect.p1().y(),
1906 tile_rect.p2().x(),
1907 tile_rect.p2().y(),
1908 tile_rect.p3().x(),
1909 tile_rect.p3().y(),
1911 gl_->Uniform2fv(uniforms.quad_location, 4, gl_quad);
1913 static float gl_matrix[16];
1914 ToGLMatrix(&gl_matrix[0],
1915 frame->projection_matrix *
1916 quad->shared_quad_state->quad_to_target_transform);
1917 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]);
1919 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
1922 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1923 const YUVVideoDrawQuad* quad,
1924 const gfx::QuadF* clip_region) {
1925 SetBlendEnabled(quad->ShouldDrawWithBlending());
1927 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1928 gl_, &highp_threshold_cache_, highp_threshold_min_,
1929 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
1931 bool use_alpha_plane = quad->a_plane_resource_id() != 0;
1933 ResourceProvider::ScopedSamplerGL y_plane_lock(
1934 resource_provider_, quad->y_plane_resource_id(), GL_TEXTURE1, GL_LINEAR);
1935 ResourceProvider::ScopedSamplerGL u_plane_lock(
1936 resource_provider_, quad->u_plane_resource_id(), GL_TEXTURE2, GL_LINEAR);
1937 DCHECK_EQ(y_plane_lock.target(), u_plane_lock.target());
1938 ResourceProvider::ScopedSamplerGL v_plane_lock(
1939 resource_provider_, quad->v_plane_resource_id(), GL_TEXTURE3, GL_LINEAR);
1940 DCHECK_EQ(y_plane_lock.target(), v_plane_lock.target());
1941 scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1942 if (use_alpha_plane) {
1943 a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1944 resource_provider_, quad->a_plane_resource_id(), GL_TEXTURE4,
1945 GL_LINEAR));
1946 DCHECK_EQ(y_plane_lock.target(), a_plane_lock->target());
1949 // All planes must have the same sampler type.
1950 SamplerType sampler = SamplerTypeFromTextureTarget(y_plane_lock.target());
1952 int matrix_location = -1;
1953 int ya_tex_scale_location = -1;
1954 int ya_tex_offset_location = -1;
1955 int uv_tex_scale_location = -1;
1956 int uv_tex_offset_location = -1;
1957 int ya_clamp_rect_location = -1;
1958 int uv_clamp_rect_location = -1;
1959 int y_texture_location = -1;
1960 int u_texture_location = -1;
1961 int v_texture_location = -1;
1962 int a_texture_location = -1;
1963 int yuv_matrix_location = -1;
1964 int yuv_adj_location = -1;
1965 int alpha_location = -1;
1966 if (use_alpha_plane) {
1967 const VideoYUVAProgram* program =
1968 GetVideoYUVAProgram(tex_coord_precision, sampler);
1969 DCHECK(program && (program->initialized() || IsContextLost()));
1970 SetUseProgram(program->program());
1971 matrix_location = program->vertex_shader().matrix_location();
1972 ya_tex_scale_location = program->vertex_shader().ya_tex_scale_location();
1973 ya_tex_offset_location = program->vertex_shader().ya_tex_offset_location();
1974 uv_tex_scale_location = program->vertex_shader().uv_tex_scale_location();
1975 uv_tex_offset_location = program->vertex_shader().uv_tex_offset_location();
1976 y_texture_location = program->fragment_shader().y_texture_location();
1977 u_texture_location = program->fragment_shader().u_texture_location();
1978 v_texture_location = program->fragment_shader().v_texture_location();
1979 a_texture_location = program->fragment_shader().a_texture_location();
1980 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1981 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1982 ya_clamp_rect_location =
1983 program->fragment_shader().ya_clamp_rect_location();
1984 uv_clamp_rect_location =
1985 program->fragment_shader().uv_clamp_rect_location();
1986 alpha_location = program->fragment_shader().alpha_location();
1987 } else {
1988 const VideoYUVProgram* program =
1989 GetVideoYUVProgram(tex_coord_precision, sampler);
1990 DCHECK(program && (program->initialized() || IsContextLost()));
1991 SetUseProgram(program->program());
1992 matrix_location = program->vertex_shader().matrix_location();
1993 ya_tex_scale_location = program->vertex_shader().ya_tex_scale_location();
1994 ya_tex_offset_location = program->vertex_shader().ya_tex_offset_location();
1995 uv_tex_scale_location = program->vertex_shader().uv_tex_scale_location();
1996 uv_tex_offset_location = program->vertex_shader().uv_tex_offset_location();
1997 y_texture_location = program->fragment_shader().y_texture_location();
1998 u_texture_location = program->fragment_shader().u_texture_location();
1999 v_texture_location = program->fragment_shader().v_texture_location();
2000 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
2001 yuv_adj_location = program->fragment_shader().yuv_adj_location();
2002 ya_clamp_rect_location =
2003 program->fragment_shader().ya_clamp_rect_location();
2004 uv_clamp_rect_location =
2005 program->fragment_shader().uv_clamp_rect_location();
2006 alpha_location = program->fragment_shader().alpha_location();
2009 gfx::SizeF ya_tex_scale(1.0f, 1.0f);
2010 gfx::SizeF uv_tex_scale(1.0f, 1.0f);
2011 if (sampler != SAMPLER_TYPE_2D_RECT) {
2012 DCHECK(!quad->ya_tex_size.IsEmpty());
2013 DCHECK(!quad->uv_tex_size.IsEmpty());
2014 ya_tex_scale = gfx::SizeF(1.0f / quad->ya_tex_size.width(),
2015 1.0f / quad->ya_tex_size.height());
2016 uv_tex_scale = gfx::SizeF(1.0f / quad->uv_tex_size.width(),
2017 1.0f / quad->uv_tex_size.height());
2020 float ya_vertex_tex_translate_x =
2021 quad->ya_tex_coord_rect.x() * ya_tex_scale.width();
2022 float ya_vertex_tex_translate_y =
2023 quad->ya_tex_coord_rect.y() * ya_tex_scale.height();
2024 float ya_vertex_tex_scale_x =
2025 quad->ya_tex_coord_rect.width() * ya_tex_scale.width();
2026 float ya_vertex_tex_scale_y =
2027 quad->ya_tex_coord_rect.height() * ya_tex_scale.height();
2029 float uv_vertex_tex_translate_x =
2030 quad->uv_tex_coord_rect.x() * uv_tex_scale.width();
2031 float uv_vertex_tex_translate_y =
2032 quad->uv_tex_coord_rect.y() * uv_tex_scale.height();
2033 float uv_vertex_tex_scale_x =
2034 quad->uv_tex_coord_rect.width() * uv_tex_scale.width();
2035 float uv_vertex_tex_scale_y =
2036 quad->uv_tex_coord_rect.height() * uv_tex_scale.height();
2038 gl_->Uniform2f(ya_tex_scale_location, ya_vertex_tex_scale_x,
2039 ya_vertex_tex_scale_y);
2040 gl_->Uniform2f(ya_tex_offset_location, ya_vertex_tex_translate_x,
2041 ya_vertex_tex_translate_y);
2042 gl_->Uniform2f(uv_tex_scale_location, uv_vertex_tex_scale_x,
2043 uv_vertex_tex_scale_y);
2044 gl_->Uniform2f(uv_tex_offset_location, uv_vertex_tex_translate_x,
2045 uv_vertex_tex_translate_y);
2047 gfx::RectF ya_clamp_rect(ya_vertex_tex_translate_x, ya_vertex_tex_translate_y,
2048 ya_vertex_tex_scale_x, ya_vertex_tex_scale_y);
2049 ya_clamp_rect.Inset(0.5f * ya_tex_scale.width(),
2050 0.5f * ya_tex_scale.height());
2051 gfx::RectF uv_clamp_rect(uv_vertex_tex_translate_x, uv_vertex_tex_translate_y,
2052 uv_vertex_tex_scale_x, uv_vertex_tex_scale_y);
2053 uv_clamp_rect.Inset(0.5f * uv_tex_scale.width(),
2054 0.5f * uv_tex_scale.height());
2055 gl_->Uniform4f(ya_clamp_rect_location, ya_clamp_rect.x(), ya_clamp_rect.y(),
2056 ya_clamp_rect.right(), ya_clamp_rect.bottom());
2057 gl_->Uniform4f(uv_clamp_rect_location, uv_clamp_rect.x(), uv_clamp_rect.y(),
2058 uv_clamp_rect.right(), uv_clamp_rect.bottom());
2060 gl_->Uniform1i(y_texture_location, 1);
2061 gl_->Uniform1i(u_texture_location, 2);
2062 gl_->Uniform1i(v_texture_location, 3);
2063 if (use_alpha_plane)
2064 gl_->Uniform1i(a_texture_location, 4);
2066 // These values are magic numbers that are used in the transformation from YUV
2067 // to RGB color values. They are taken from the following webpage:
2068 // http://www.fourcc.org/fccyvrgb.php
2069 float yuv_to_rgb_rec601[9] = {
2070 1.164f, 1.164f, 1.164f, 0.0f, -.391f, 2.018f, 1.596f, -.813f, 0.0f,
2072 float yuv_to_rgb_jpeg[9] = {
2073 1.f, 1.f, 1.f, 0.0f, -.34414f, 1.772f, 1.402f, -.71414f, 0.0f,
2075 float yuv_to_rgb_rec709[9] = {
2076 1.164f, 1.164f, 1.164f, 0.0f, -0.213f, 2.112f, 1.793f, -0.533f, 0.0f,
2079 // These values map to 16, 128, and 128 respectively, and are computed
2080 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
2081 // They are used in the YUV to RGBA conversion formula:
2082 // Y - 16 : Gives 16 values of head and footroom for overshooting
2083 // U - 128 : Turns unsigned U into signed U [-128,127]
2084 // V - 128 : Turns unsigned V into signed V [-128,127]
2085 float yuv_adjust_constrained[3] = {
2086 -0.0625f, -0.5f, -0.5f,
2089 // Same as above, but without the head and footroom.
2090 float yuv_adjust_full[3] = {
2091 0.0f, -0.5f, -0.5f,
2094 float* yuv_to_rgb = NULL;
2095 float* yuv_adjust = NULL;
2097 switch (quad->color_space) {
2098 case YUVVideoDrawQuad::REC_601:
2099 yuv_to_rgb = yuv_to_rgb_rec601;
2100 yuv_adjust = yuv_adjust_constrained;
2101 break;
2102 case YUVVideoDrawQuad::REC_709:
2103 yuv_to_rgb = yuv_to_rgb_rec709;
2104 yuv_adjust = yuv_adjust_constrained;
2105 break;
2106 case YUVVideoDrawQuad::JPEG:
2107 yuv_to_rgb = yuv_to_rgb_jpeg;
2108 yuv_adjust = yuv_adjust_full;
2109 break;
2112 // The transform and vertex data are used to figure out the extents that the
2113 // un-antialiased quad should have and which vertex this is and the float
2114 // quad passed in via uniform is the actual geometry that gets used to draw
2115 // it. This is why this centered rect is used and not the original quad_rect.
2116 gfx::RectF tile_rect = quad->rect;
2117 gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb);
2118 gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust);
2120 SetShaderOpacity(quad->shared_quad_state->opacity, alpha_location);
2121 if (!clip_region) {
2122 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2123 tile_rect, matrix_location);
2124 } else {
2125 float uvs[8] = {0};
2126 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2127 gfx::QuadF region_quad = *clip_region;
2128 region_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
2129 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2130 DrawQuadGeometryClippedByQuadF(
2131 frame, quad->shared_quad_state->quad_to_target_transform, tile_rect,
2132 region_quad, matrix_location, uvs);
2136 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
2137 const StreamVideoDrawQuad* quad,
2138 const gfx::QuadF* clip_region) {
2139 SetBlendEnabled(quad->ShouldDrawWithBlending());
2141 static float gl_matrix[16];
2143 DCHECK(capabilities_.using_egl_image);
2145 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2146 gl_, &highp_threshold_cache_, highp_threshold_min_,
2147 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2149 const VideoStreamTextureProgram* program =
2150 GetVideoStreamTextureProgram(tex_coord_precision);
2151 SetUseProgram(program->program());
2153 ToGLMatrix(&gl_matrix[0], quad->matrix);
2154 gl_->UniformMatrix4fv(program->vertex_shader().tex_matrix_location(), 1,
2155 false, gl_matrix);
2157 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2158 quad->resource_id());
2159 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2160 gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id());
2162 gl_->Uniform1i(program->fragment_shader().sampler_location(), 0);
2164 SetShaderOpacity(quad->shared_quad_state->opacity,
2165 program->fragment_shader().alpha_location());
2166 if (!clip_region) {
2167 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2168 quad->rect, program->vertex_shader().matrix_location());
2169 } else {
2170 gfx::QuadF region_quad(*clip_region);
2171 region_quad.Scale(1.0f / quad->rect.width(), 1.0f / quad->rect.height());
2172 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2173 float uvs[8] = {0};
2174 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2175 DrawQuadGeometryClippedByQuadF(
2176 frame, quad->shared_quad_state->quad_to_target_transform, quad->rect,
2177 region_quad, program->vertex_shader().matrix_location(), uvs);
2181 struct TextureProgramBinding {
2182 template <class Program>
2183 void Set(Program* program) {
2184 DCHECK(program);
2185 program_id = program->program();
2186 sampler_location = program->fragment_shader().sampler_location();
2187 matrix_location = program->vertex_shader().matrix_location();
2188 background_color_location =
2189 program->fragment_shader().background_color_location();
2191 int program_id;
2192 int sampler_location;
2193 int matrix_location;
2194 int transform_location;
2195 int background_color_location;
2198 struct TexTransformTextureProgramBinding : TextureProgramBinding {
2199 template <class Program>
2200 void Set(Program* program) {
2201 TextureProgramBinding::Set(program);
2202 tex_transform_location = program->vertex_shader().tex_transform_location();
2203 vertex_opacity_location =
2204 program->vertex_shader().vertex_opacity_location();
2206 int tex_transform_location;
2207 int vertex_opacity_location;
2210 void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding) {
2211 // Check to see if we have anything to draw.
2212 if (draw_cache_.program_id == -1)
2213 return;
2215 PrepareGeometry(flush_binding);
2217 // Set the correct blending mode.
2218 SetBlendEnabled(draw_cache_.needs_blending);
2220 // Bind the program to the GL state.
2221 SetUseProgram(draw_cache_.program_id);
2223 // Bind the correct texture sampler location.
2224 gl_->Uniform1i(draw_cache_.sampler_location, 0);
2226 // Assume the current active textures is 0.
2227 ResourceProvider::ScopedSamplerGL locked_quad(
2228 resource_provider_,
2229 draw_cache_.resource_id,
2230 draw_cache_.nearest_neighbor ? GL_NEAREST : GL_LINEAR);
2231 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2232 gl_->BindTexture(locked_quad.target(), locked_quad.texture_id());
2234 static_assert(sizeof(Float4) == 4 * sizeof(float),
2235 "Float4 struct should be densely packed");
2236 static_assert(sizeof(Float16) == 16 * sizeof(float),
2237 "Float16 struct should be densely packed");
2239 // Upload the tranforms for both points and uvs.
2240 gl_->UniformMatrix4fv(
2241 static_cast<int>(draw_cache_.matrix_location),
2242 static_cast<int>(draw_cache_.matrix_data.size()), false,
2243 reinterpret_cast<float*>(&draw_cache_.matrix_data.front()));
2244 gl_->Uniform4fv(static_cast<int>(draw_cache_.uv_xform_location),
2245 static_cast<int>(draw_cache_.uv_xform_data.size()),
2246 reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front()));
2248 if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
2249 Float4 background_color = PremultipliedColor(draw_cache_.background_color);
2250 gl_->Uniform4fv(draw_cache_.background_color_location, 1,
2251 background_color.data);
2254 gl_->Uniform1fv(
2255 static_cast<int>(draw_cache_.vertex_opacity_location),
2256 static_cast<int>(draw_cache_.vertex_opacity_data.size()),
2257 static_cast<float*>(&draw_cache_.vertex_opacity_data.front()));
2259 DCHECK_LE(draw_cache_.matrix_data.size(),
2260 static_cast<size_t>(std::numeric_limits<int>::max()) / 6u);
2261 // Draw the quads!
2262 gl_->DrawElements(GL_TRIANGLES,
2263 6 * static_cast<int>(draw_cache_.matrix_data.size()),
2264 GL_UNSIGNED_SHORT, 0);
2266 // Clear the cache.
2267 draw_cache_.program_id = -1;
2268 draw_cache_.uv_xform_data.resize(0);
2269 draw_cache_.vertex_opacity_data.resize(0);
2270 draw_cache_.matrix_data.resize(0);
2272 // If we had a clipped binding, prepare the shared binding for the
2273 // next inserts.
2274 if (flush_binding == CLIPPED_BINDING) {
2275 PrepareGeometry(SHARED_BINDING);
2279 void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
2280 const TextureDrawQuad* quad,
2281 const gfx::QuadF* clip_region) {
2282 // If we have a clip_region then we have to render the next quad
2283 // with dynamic geometry, therefore we must flush all pending
2284 // texture quads.
2285 if (clip_region) {
2286 // We send in false here because we want to flush what's currently in the
2287 // queue using the shared_geometry and not clipped_geometry
2288 FlushTextureQuadCache(SHARED_BINDING);
2291 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2292 gl_, &highp_threshold_cache_, highp_threshold_min_,
2293 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2295 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2296 quad->resource_id());
2297 const SamplerType sampler = SamplerTypeFromTextureTarget(lock.target());
2298 // Choose the correct texture program binding
2299 TexTransformTextureProgramBinding binding;
2300 if (quad->premultiplied_alpha) {
2301 if (quad->background_color == SK_ColorTRANSPARENT) {
2302 binding.Set(GetTextureProgram(tex_coord_precision, sampler));
2303 } else {
2304 binding.Set(GetTextureBackgroundProgram(tex_coord_precision, sampler));
2306 } else {
2307 if (quad->background_color == SK_ColorTRANSPARENT) {
2308 binding.Set(
2309 GetNonPremultipliedTextureProgram(tex_coord_precision, sampler));
2310 } else {
2311 binding.Set(GetNonPremultipliedTextureBackgroundProgram(
2312 tex_coord_precision, sampler));
2316 int resource_id = quad->resource_id();
2318 if (draw_cache_.program_id != binding.program_id ||
2319 draw_cache_.resource_id != resource_id ||
2320 draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
2321 draw_cache_.nearest_neighbor != quad->nearest_neighbor ||
2322 draw_cache_.background_color != quad->background_color ||
2323 draw_cache_.matrix_data.size() >= 8) {
2324 FlushTextureQuadCache(SHARED_BINDING);
2325 draw_cache_.program_id = binding.program_id;
2326 draw_cache_.resource_id = resource_id;
2327 draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
2328 draw_cache_.nearest_neighbor = quad->nearest_neighbor;
2329 draw_cache_.background_color = quad->background_color;
2331 draw_cache_.uv_xform_location = binding.tex_transform_location;
2332 draw_cache_.background_color_location = binding.background_color_location;
2333 draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
2334 draw_cache_.matrix_location = binding.matrix_location;
2335 draw_cache_.sampler_location = binding.sampler_location;
2338 // Generate the uv-transform
2339 if (!clip_region) {
2340 draw_cache_.uv_xform_data.push_back(UVTransform(quad));
2341 } else {
2342 Float4 uv_transform = {{0.0f, 0.0f, 1.0f, 1.0f}};
2343 draw_cache_.uv_xform_data.push_back(uv_transform);
2346 // Generate the vertex opacity
2347 const float opacity = quad->shared_quad_state->opacity;
2348 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
2349 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
2350 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
2351 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
2353 // Generate the transform matrix
2354 gfx::Transform quad_rect_matrix;
2355 QuadRectTransform(&quad_rect_matrix,
2356 quad->shared_quad_state->quad_to_target_transform,
2357 quad->rect);
2358 quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
2360 Float16 m;
2361 quad_rect_matrix.matrix().asColMajorf(m.data);
2362 draw_cache_.matrix_data.push_back(m);
2364 if (clip_region) {
2365 gfx::QuadF scaled_region;
2366 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
2367 scaled_region = SharedGeometryQuad().BoundingBox();
2369 // Both the scaled region and the SharedGeomtryQuad are in the space
2370 // -0.5->0.5. We need to move that to the space 0->1.
2371 float uv[8];
2372 uv[0] = scaled_region.p1().x() + 0.5f;
2373 uv[1] = scaled_region.p1().y() + 0.5f;
2374 uv[2] = scaled_region.p2().x() + 0.5f;
2375 uv[3] = scaled_region.p2().y() + 0.5f;
2376 uv[4] = scaled_region.p3().x() + 0.5f;
2377 uv[5] = scaled_region.p3().y() + 0.5f;
2378 uv[6] = scaled_region.p4().x() + 0.5f;
2379 uv[7] = scaled_region.p4().y() + 0.5f;
2380 PrepareGeometry(CLIPPED_BINDING);
2381 clipped_geometry_->InitializeCustomQuadWithUVs(scaled_region, uv);
2382 FlushTextureQuadCache(CLIPPED_BINDING);
2386 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
2387 const IOSurfaceDrawQuad* quad,
2388 const gfx::QuadF* clip_region) {
2389 SetBlendEnabled(quad->ShouldDrawWithBlending());
2391 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2392 gl_, &highp_threshold_cache_, highp_threshold_min_,
2393 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2395 TexTransformTextureProgramBinding binding;
2396 binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
2398 SetUseProgram(binding.program_id);
2399 gl_->Uniform1i(binding.sampler_location, 0);
2400 if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
2401 gl_->Uniform4f(
2402 binding.tex_transform_location, 0, quad->io_surface_size.height(),
2403 quad->io_surface_size.width(), quad->io_surface_size.height() * -1.0f);
2404 } else {
2405 gl_->Uniform4f(binding.tex_transform_location, 0, 0,
2406 quad->io_surface_size.width(),
2407 quad->io_surface_size.height());
2410 const float vertex_opacity[] = {quad->shared_quad_state->opacity,
2411 quad->shared_quad_state->opacity,
2412 quad->shared_quad_state->opacity,
2413 quad->shared_quad_state->opacity};
2414 gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity);
2416 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2417 quad->io_surface_resource_id());
2418 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2419 gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id());
2421 if (!clip_region) {
2422 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2423 quad->rect, binding.matrix_location);
2424 } else {
2425 float uvs[8] = {0};
2426 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2427 DrawQuadGeometryClippedByQuadF(
2428 frame, quad->shared_quad_state->quad_to_target_transform, quad->rect,
2429 *clip_region, binding.matrix_location, uvs);
2432 gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
2435 void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
2436 if (use_sync_query_) {
2437 DCHECK(current_sync_query_);
2438 current_sync_query_->End();
2439 pending_sync_queries_.push_back(current_sync_query_.Pass());
2442 current_framebuffer_lock_ = nullptr;
2443 swap_buffer_rect_.Union(gfx::ToEnclosingRect(frame->root_damage_rect));
2445 gl_->Disable(GL_BLEND);
2446 blend_shadow_ = false;
2448 ScheduleOverlays(frame);
2451 void GLRenderer::FinishDrawingQuadList() {
2452 FlushTextureQuadCache(SHARED_BINDING);
2455 bool GLRenderer::FlippedFramebuffer(const DrawingFrame* frame) const {
2456 if (frame->current_render_pass != frame->root_render_pass)
2457 return true;
2458 return FlippedRootFramebuffer();
2461 bool GLRenderer::FlippedRootFramebuffer() const {
2462 // GL is normally flipped, so a flipped output results in an unflipping.
2463 return !output_surface_->capabilities().flipped_output_surface;
2466 void GLRenderer::EnsureScissorTestEnabled() {
2467 if (is_scissor_enabled_)
2468 return;
2470 FlushTextureQuadCache(SHARED_BINDING);
2471 gl_->Enable(GL_SCISSOR_TEST);
2472 is_scissor_enabled_ = true;
2475 void GLRenderer::EnsureScissorTestDisabled() {
2476 if (!is_scissor_enabled_)
2477 return;
2479 FlushTextureQuadCache(SHARED_BINDING);
2480 gl_->Disable(GL_SCISSOR_TEST);
2481 is_scissor_enabled_ = false;
2484 void GLRenderer::CopyCurrentRenderPassToBitmap(
2485 DrawingFrame* frame,
2486 scoped_ptr<CopyOutputRequest> request) {
2487 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2488 gfx::Rect copy_rect = frame->current_render_pass->output_rect;
2489 if (request->has_area())
2490 copy_rect.Intersect(request->area());
2491 GetFramebufferPixelsAsync(frame, copy_rect, request.Pass());
2494 void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
2495 transform.matrix().asColMajorf(gl_matrix);
2498 void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
2499 if (quad_location == -1)
2500 return;
2502 float gl_quad[8];
2503 gl_quad[0] = quad.p1().x();
2504 gl_quad[1] = quad.p1().y();
2505 gl_quad[2] = quad.p2().x();
2506 gl_quad[3] = quad.p2().y();
2507 gl_quad[4] = quad.p3().x();
2508 gl_quad[5] = quad.p3().y();
2509 gl_quad[6] = quad.p4().x();
2510 gl_quad[7] = quad.p4().y();
2511 gl_->Uniform2fv(quad_location, 4, gl_quad);
2514 void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2515 if (alpha_location != -1)
2516 gl_->Uniform1f(alpha_location, opacity);
2519 void GLRenderer::SetStencilEnabled(bool enabled) {
2520 if (enabled == stencil_shadow_)
2521 return;
2523 if (enabled)
2524 gl_->Enable(GL_STENCIL_TEST);
2525 else
2526 gl_->Disable(GL_STENCIL_TEST);
2527 stencil_shadow_ = enabled;
2530 void GLRenderer::SetBlendEnabled(bool enabled) {
2531 if (enabled == blend_shadow_)
2532 return;
2534 if (enabled)
2535 gl_->Enable(GL_BLEND);
2536 else
2537 gl_->Disable(GL_BLEND);
2538 blend_shadow_ = enabled;
2541 void GLRenderer::SetUseProgram(unsigned program) {
2542 if (program == program_shadow_)
2543 return;
2544 gl_->UseProgram(program);
2545 program_shadow_ = program;
2548 void GLRenderer::DrawQuadGeometryClippedByQuadF(
2549 const DrawingFrame* frame,
2550 const gfx::Transform& draw_transform,
2551 const gfx::RectF& quad_rect,
2552 const gfx::QuadF& clipping_region_quad,
2553 int matrix_location,
2554 const float* uvs) {
2555 PrepareGeometry(CLIPPED_BINDING);
2556 if (uvs) {
2557 clipped_geometry_->InitializeCustomQuadWithUVs(clipping_region_quad, uvs);
2558 } else {
2559 clipped_geometry_->InitializeCustomQuad(clipping_region_quad);
2561 gfx::Transform quad_rect_matrix;
2562 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2563 static float gl_matrix[16];
2564 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2565 gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]);
2567 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,
2568 reinterpret_cast<const void*>(0));
2571 void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2572 const gfx::Transform& draw_transform,
2573 const gfx::RectF& quad_rect,
2574 int matrix_location) {
2575 PrepareGeometry(SHARED_BINDING);
2576 gfx::Transform quad_rect_matrix;
2577 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2578 static float gl_matrix[16];
2579 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2580 gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]);
2582 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
2585 void GLRenderer::Finish() {
2586 TRACE_EVENT0("cc", "GLRenderer::Finish");
2587 gl_->Finish();
2590 void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2591 DCHECK(!is_backbuffer_discarded_);
2593 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2594 // We're done! Time to swapbuffers!
2596 gfx::Size surface_size = output_surface_->SurfaceSize();
2598 CompositorFrame compositor_frame;
2599 compositor_frame.metadata = metadata;
2600 compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2601 compositor_frame.gl_frame_data->size = surface_size;
2602 if (capabilities_.using_partial_swap) {
2603 // If supported, we can save significant bandwidth by only swapping the
2604 // damaged/scissored region (clamped to the viewport).
2605 swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2606 int flipped_y_pos_of_rect_bottom = surface_size.height() -
2607 swap_buffer_rect_.y() -
2608 swap_buffer_rect_.height();
2609 compositor_frame.gl_frame_data->sub_buffer_rect =
2610 gfx::Rect(swap_buffer_rect_.x(),
2611 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2612 : swap_buffer_rect_.y(),
2613 swap_buffer_rect_.width(),
2614 swap_buffer_rect_.height());
2615 } else {
2616 compositor_frame.gl_frame_data->sub_buffer_rect =
2617 gfx::Rect(output_surface_->SurfaceSize());
2619 output_surface_->SwapBuffers(&compositor_frame);
2621 // Release previously used overlay resources and hold onto the pending ones
2622 // until the next swap buffers.
2623 in_use_overlay_resources_.clear();
2624 in_use_overlay_resources_.swap(pending_overlay_resources_);
2626 swap_buffer_rect_ = gfx::Rect();
2629 void GLRenderer::EnforceMemoryPolicy() {
2630 if (!visible()) {
2631 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2632 ReleaseRenderPassTextures();
2633 DiscardBackbuffer();
2634 output_surface_->context_provider()->DeleteCachedResources();
2635 gl_->Flush();
2637 PrepareGeometry(NO_BINDING);
2640 void GLRenderer::DiscardBackbuffer() {
2641 if (is_backbuffer_discarded_)
2642 return;
2644 output_surface_->DiscardBackbuffer();
2646 is_backbuffer_discarded_ = true;
2648 // Damage tracker needs a full reset every time framebuffer is discarded.
2649 client_->SetFullRootLayerDamage();
2652 void GLRenderer::EnsureBackbuffer() {
2653 if (!is_backbuffer_discarded_)
2654 return;
2656 output_surface_->EnsureBackbuffer();
2657 is_backbuffer_discarded_ = false;
2660 void GLRenderer::GetFramebufferPixelsAsync(
2661 const DrawingFrame* frame,
2662 const gfx::Rect& rect,
2663 scoped_ptr<CopyOutputRequest> request) {
2664 DCHECK(!request->IsEmpty());
2665 if (request->IsEmpty())
2666 return;
2667 if (rect.IsEmpty())
2668 return;
2670 gfx::Rect window_rect = MoveFromDrawToWindowSpace(frame, rect);
2671 DCHECK_GE(window_rect.x(), 0);
2672 DCHECK_GE(window_rect.y(), 0);
2673 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2674 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2676 if (!request->force_bitmap_result()) {
2677 bool own_mailbox = !request->has_texture_mailbox();
2679 GLuint texture_id = 0;
2680 gpu::Mailbox mailbox;
2681 if (own_mailbox) {
2682 gl_->GenMailboxCHROMIUM(mailbox.name);
2683 gl_->GenTextures(1, &texture_id);
2684 gl_->BindTexture(GL_TEXTURE_2D, texture_id);
2686 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2687 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2688 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2689 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2690 gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name);
2691 } else {
2692 mailbox = request->texture_mailbox().mailbox();
2693 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2694 request->texture_mailbox().target());
2695 DCHECK(!mailbox.IsZero());
2696 unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2697 if (incoming_sync_point)
2698 gl_->WaitSyncPointCHROMIUM(incoming_sync_point);
2700 texture_id =
2701 gl_->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name);
2703 GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2705 unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2706 TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2708 scoped_ptr<SingleReleaseCallback> release_callback;
2709 if (own_mailbox) {
2710 gl_->BindTexture(GL_TEXTURE_2D, 0);
2711 release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2712 output_surface_->context_provider(), texture_id);
2713 } else {
2714 gl_->DeleteTextures(1, &texture_id);
2717 request->SendTextureResult(
2718 window_rect.size(), texture_mailbox, release_callback.Pass());
2719 return;
2722 DCHECK(request->force_bitmap_result());
2724 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2725 pending_read->copy_request = request.Pass();
2726 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2727 pending_read.Pass());
2729 bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2731 unsigned temporary_texture = 0;
2732 unsigned temporary_fbo = 0;
2734 if (do_workaround) {
2735 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2736 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2737 // calls, even those on different OpenGL contexts. It is believed that this
2738 // is the root cause of top crasher
2739 // http://crbug.com/99393. <rdar://problem/10949687>
2741 gl_->GenTextures(1, &temporary_texture);
2742 gl_->BindTexture(GL_TEXTURE_2D, temporary_texture);
2743 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2744 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2745 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2746 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2747 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2748 // temporary texture.
2749 GetFramebufferTexture(
2750 temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2751 gl_->GenFramebuffers(1, &temporary_fbo);
2752 // Attach this texture to an FBO, and perform the readback from that FBO.
2753 gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo);
2754 gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
2755 GL_TEXTURE_2D, temporary_texture, 0);
2757 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2758 gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2761 GLuint buffer = 0;
2762 gl_->GenBuffers(1, &buffer);
2763 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer);
2764 gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2765 4 * window_rect.size().GetArea(), NULL, GL_STREAM_READ);
2767 GLuint query = 0;
2768 gl_->GenQueriesEXT(1, &query);
2769 gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query);
2771 gl_->ReadPixels(window_rect.x(), window_rect.y(), window_rect.width(),
2772 window_rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2774 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0);
2776 if (do_workaround) {
2777 // Clean up.
2778 gl_->BindFramebuffer(GL_FRAMEBUFFER, 0);
2779 gl_->BindTexture(GL_TEXTURE_2D, 0);
2780 gl_->DeleteFramebuffers(1, &temporary_fbo);
2781 gl_->DeleteTextures(1, &temporary_texture);
2784 base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2785 base::Unretained(this),
2786 buffer,
2787 query,
2788 window_rect.size());
2789 // Save the finished_callback so it can be cancelled.
2790 pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2791 finished_callback);
2792 base::Closure cancelable_callback =
2793 pending_async_read_pixels_.front()->
2794 finished_read_pixels_callback.callback();
2796 // Save the buffer to verify the callbacks happen in the expected order.
2797 pending_async_read_pixels_.front()->buffer = buffer;
2799 gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM);
2800 context_support_->SignalQuery(query, cancelable_callback);
2802 EnforceMemoryPolicy();
2805 void GLRenderer::FinishedReadback(unsigned source_buffer,
2806 unsigned query,
2807 const gfx::Size& size) {
2808 DCHECK(!pending_async_read_pixels_.empty());
2810 if (query != 0) {
2811 gl_->DeleteQueriesEXT(1, &query);
2814 PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2815 // Make sure we service the readbacks in order.
2816 DCHECK_EQ(source_buffer, current_read->buffer);
2818 uint8* src_pixels = NULL;
2819 scoped_ptr<SkBitmap> bitmap;
2821 if (source_buffer != 0) {
2822 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer);
2823 src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2824 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2826 if (src_pixels) {
2827 bitmap.reset(new SkBitmap);
2828 bitmap->allocN32Pixels(size.width(), size.height());
2829 scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2830 uint8* dest_pixels = static_cast<uint8*>(bitmap->getPixels());
2832 size_t row_bytes = size.width() * 4;
2833 int num_rows = size.height();
2834 size_t total_bytes = num_rows * row_bytes;
2835 for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2836 // Flip Y axis.
2837 size_t src_y = total_bytes - dest_y - row_bytes;
2838 // Swizzle OpenGL -> Skia byte order.
2839 for (size_t x = 0; x < row_bytes; x += 4) {
2840 dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2841 src_pixels[src_y + x + 0];
2842 dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2843 src_pixels[src_y + x + 1];
2844 dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2845 src_pixels[src_y + x + 2];
2846 dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2847 src_pixels[src_y + x + 3];
2851 gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM);
2853 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0);
2854 gl_->DeleteBuffers(1, &source_buffer);
2857 if (bitmap)
2858 current_read->copy_request->SendBitmapResult(bitmap.Pass());
2859 pending_async_read_pixels_.pop_back();
2862 void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2863 ResourceFormat texture_format,
2864 const gfx::Rect& window_rect) {
2865 DCHECK(texture_id);
2866 DCHECK_GE(window_rect.x(), 0);
2867 DCHECK_GE(window_rect.y(), 0);
2868 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2869 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2871 gl_->BindTexture(GL_TEXTURE_2D, texture_id);
2872 gl_->CopyTexImage2D(GL_TEXTURE_2D, 0, GLDataFormat(texture_format),
2873 window_rect.x(), window_rect.y(), window_rect.width(),
2874 window_rect.height(), 0);
2875 gl_->BindTexture(GL_TEXTURE_2D, 0);
2878 bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2879 const ScopedResource* texture,
2880 const gfx::Rect& viewport_rect) {
2881 DCHECK(texture->id());
2882 frame->current_render_pass = NULL;
2883 frame->current_texture = texture;
2885 return BindFramebufferToTexture(frame, texture, viewport_rect);
2888 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2889 current_framebuffer_lock_ = nullptr;
2890 output_surface_->BindFramebuffer();
2892 if (output_surface_->HasExternalStencilTest()) {
2893 SetStencilEnabled(true);
2894 gl_->StencilFunc(GL_EQUAL, 1, 1);
2895 } else {
2896 SetStencilEnabled(false);
2900 bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2901 const ScopedResource* texture,
2902 const gfx::Rect& target_rect) {
2903 DCHECK(texture->id());
2905 // Explicitly release lock, otherwise we can crash when try to lock
2906 // same texture again.
2907 current_framebuffer_lock_ = nullptr;
2909 SetStencilEnabled(false);
2910 gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_);
2911 current_framebuffer_lock_ =
2912 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2913 resource_provider_, texture->id()));
2914 unsigned texture_id = current_framebuffer_lock_->texture_id();
2915 gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
2916 texture_id, 0);
2918 DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2919 GL_FRAMEBUFFER_COMPLETE ||
2920 IsContextLost());
2921 return true;
2924 void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2925 EnsureScissorTestEnabled();
2927 // Don't unnecessarily ask the context to change the scissor, because it
2928 // may cause undesired GPU pipeline flushes.
2929 if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2930 return;
2932 scissor_rect_ = scissor_rect;
2933 FlushTextureQuadCache(SHARED_BINDING);
2934 gl_->Scissor(scissor_rect.x(), scissor_rect.y(), scissor_rect.width(),
2935 scissor_rect.height());
2937 scissor_rect_needs_reset_ = false;
2940 void GLRenderer::SetViewport() {
2941 gl_->Viewport(current_window_space_viewport_.x(),
2942 current_window_space_viewport_.y(),
2943 current_window_space_viewport_.width(),
2944 current_window_space_viewport_.height());
2947 void GLRenderer::InitializeSharedObjects() {
2948 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2950 // Create an FBO for doing offscreen rendering.
2951 gl_->GenFramebuffers(1, &offscreen_framebuffer_id_);
2953 shared_geometry_ =
2954 make_scoped_ptr(new StaticGeometryBinding(gl_, QuadVertexRect()));
2955 clipped_geometry_ = make_scoped_ptr(new DynamicGeometryBinding(gl_));
2958 void GLRenderer::PrepareGeometry(BoundGeometry binding) {
2959 if (binding == bound_geometry_) {
2960 return;
2963 switch (binding) {
2964 case SHARED_BINDING:
2965 shared_geometry_->PrepareForDraw();
2966 break;
2967 case CLIPPED_BINDING:
2968 clipped_geometry_->PrepareForDraw();
2969 break;
2970 case NO_BINDING:
2971 break;
2973 bound_geometry_ = binding;
2976 const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
2977 if (!debug_border_program_.initialized()) {
2978 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2979 debug_border_program_.Initialize(output_surface_->context_provider(),
2980 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2982 return &debug_border_program_;
2985 const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
2986 if (!solid_color_program_.initialized()) {
2987 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2988 solid_color_program_.Initialize(output_surface_->context_provider(),
2989 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2991 return &solid_color_program_;
2994 const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
2995 if (!solid_color_program_aa_.initialized()) {
2996 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2997 solid_color_program_aa_.Initialize(output_surface_->context_provider(),
2998 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3000 return &solid_color_program_aa_;
3003 const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
3004 TexCoordPrecision precision,
3005 BlendMode blend_mode) {
3006 DCHECK_GE(precision, 0);
3007 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3008 DCHECK_GE(blend_mode, 0);
3009 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3010 RenderPassProgram* program = &render_pass_program_[precision][blend_mode];
3011 if (!program->initialized()) {
3012 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
3013 program->Initialize(output_surface_->context_provider(), precision,
3014 SAMPLER_TYPE_2D, blend_mode);
3016 return program;
3019 const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
3020 TexCoordPrecision precision,
3021 BlendMode blend_mode) {
3022 DCHECK_GE(precision, 0);
3023 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3024 DCHECK_GE(blend_mode, 0);
3025 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3026 RenderPassProgramAA* program =
3027 &render_pass_program_aa_[precision][blend_mode];
3028 if (!program->initialized()) {
3029 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
3030 program->Initialize(output_surface_->context_provider(), precision,
3031 SAMPLER_TYPE_2D, blend_mode);
3033 return program;
3036 const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
3037 TexCoordPrecision precision,
3038 SamplerType sampler,
3039 BlendMode blend_mode,
3040 bool mask_for_background) {
3041 DCHECK_GE(precision, 0);
3042 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3043 DCHECK_GE(sampler, 0);
3044 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3045 DCHECK_GE(blend_mode, 0);
3046 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3047 RenderPassMaskProgram* program =
3048 &render_pass_mask_program_[precision][sampler][blend_mode]
3049 [mask_for_background ? HAS_MASK : NO_MASK];
3050 if (!program->initialized()) {
3051 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
3052 program->Initialize(
3053 output_surface_->context_provider(), precision,
3054 sampler, blend_mode, mask_for_background);
3056 return program;
3059 const GLRenderer::RenderPassMaskProgramAA*
3060 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision,
3061 SamplerType sampler,
3062 BlendMode blend_mode,
3063 bool mask_for_background) {
3064 DCHECK_GE(precision, 0);
3065 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3066 DCHECK_GE(sampler, 0);
3067 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3068 DCHECK_GE(blend_mode, 0);
3069 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3070 RenderPassMaskProgramAA* program =
3071 &render_pass_mask_program_aa_[precision][sampler][blend_mode]
3072 [mask_for_background ? HAS_MASK : NO_MASK];
3073 if (!program->initialized()) {
3074 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
3075 program->Initialize(
3076 output_surface_->context_provider(), precision,
3077 sampler, blend_mode, mask_for_background);
3079 return program;
3082 const GLRenderer::RenderPassColorMatrixProgram*
3083 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision,
3084 BlendMode blend_mode) {
3085 DCHECK_GE(precision, 0);
3086 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3087 DCHECK_GE(blend_mode, 0);
3088 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3089 RenderPassColorMatrixProgram* program =
3090 &render_pass_color_matrix_program_[precision][blend_mode];
3091 if (!program->initialized()) {
3092 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
3093 program->Initialize(output_surface_->context_provider(), precision,
3094 SAMPLER_TYPE_2D, blend_mode);
3096 return program;
3099 const GLRenderer::RenderPassColorMatrixProgramAA*
3100 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision,
3101 BlendMode blend_mode) {
3102 DCHECK_GE(precision, 0);
3103 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3104 DCHECK_GE(blend_mode, 0);
3105 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3106 RenderPassColorMatrixProgramAA* program =
3107 &render_pass_color_matrix_program_aa_[precision][blend_mode];
3108 if (!program->initialized()) {
3109 TRACE_EVENT0("cc",
3110 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
3111 program->Initialize(output_surface_->context_provider(), precision,
3112 SAMPLER_TYPE_2D, blend_mode);
3114 return program;
3117 const GLRenderer::RenderPassMaskColorMatrixProgram*
3118 GLRenderer::GetRenderPassMaskColorMatrixProgram(
3119 TexCoordPrecision precision,
3120 SamplerType sampler,
3121 BlendMode blend_mode,
3122 bool mask_for_background) {
3123 DCHECK_GE(precision, 0);
3124 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3125 DCHECK_GE(sampler, 0);
3126 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3127 DCHECK_GE(blend_mode, 0);
3128 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3129 RenderPassMaskColorMatrixProgram* program =
3130 &render_pass_mask_color_matrix_program_[precision][sampler][blend_mode]
3131 [mask_for_background ? HAS_MASK : NO_MASK];
3132 if (!program->initialized()) {
3133 TRACE_EVENT0("cc",
3134 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
3135 program->Initialize(
3136 output_surface_->context_provider(), precision,
3137 sampler, blend_mode, mask_for_background);
3139 return program;
3142 const GLRenderer::RenderPassMaskColorMatrixProgramAA*
3143 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(
3144 TexCoordPrecision precision,
3145 SamplerType sampler,
3146 BlendMode blend_mode,
3147 bool mask_for_background) {
3148 DCHECK_GE(precision, 0);
3149 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3150 DCHECK_GE(sampler, 0);
3151 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3152 DCHECK_GE(blend_mode, 0);
3153 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3154 RenderPassMaskColorMatrixProgramAA* program =
3155 &render_pass_mask_color_matrix_program_aa_[precision][sampler][blend_mode]
3156 [mask_for_background ? HAS_MASK : NO_MASK];
3157 if (!program->initialized()) {
3158 TRACE_EVENT0("cc",
3159 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
3160 program->Initialize(
3161 output_surface_->context_provider(), precision,
3162 sampler, blend_mode, mask_for_background);
3164 return program;
3167 const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
3168 TexCoordPrecision precision,
3169 SamplerType sampler) {
3170 DCHECK_GE(precision, 0);
3171 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3172 DCHECK_GE(sampler, 0);
3173 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3174 TileProgram* program = &tile_program_[precision][sampler];
3175 if (!program->initialized()) {
3176 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
3177 program->Initialize(
3178 output_surface_->context_provider(), precision, sampler);
3180 return program;
3183 const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
3184 TexCoordPrecision precision,
3185 SamplerType sampler) {
3186 DCHECK_GE(precision, 0);
3187 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3188 DCHECK_GE(sampler, 0);
3189 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3190 TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
3191 if (!program->initialized()) {
3192 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3193 program->Initialize(
3194 output_surface_->context_provider(), precision, sampler);
3196 return program;
3199 const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
3200 TexCoordPrecision precision,
3201 SamplerType sampler) {
3202 DCHECK_GE(precision, 0);
3203 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3204 DCHECK_GE(sampler, 0);
3205 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3206 TileProgramAA* program = &tile_program_aa_[precision][sampler];
3207 if (!program->initialized()) {
3208 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3209 program->Initialize(
3210 output_surface_->context_provider(), precision, sampler);
3212 return program;
3215 const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
3216 TexCoordPrecision precision,
3217 SamplerType sampler) {
3218 DCHECK_GE(precision, 0);
3219 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3220 DCHECK_GE(sampler, 0);
3221 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3222 TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
3223 if (!program->initialized()) {
3224 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3225 program->Initialize(
3226 output_surface_->context_provider(), precision, sampler);
3228 return program;
3231 const GLRenderer::TileProgramSwizzleOpaque*
3232 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
3233 SamplerType sampler) {
3234 DCHECK_GE(precision, 0);
3235 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3236 DCHECK_GE(sampler, 0);
3237 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3238 TileProgramSwizzleOpaque* program =
3239 &tile_program_swizzle_opaque_[precision][sampler];
3240 if (!program->initialized()) {
3241 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3242 program->Initialize(
3243 output_surface_->context_provider(), precision, sampler);
3245 return program;
3248 const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
3249 TexCoordPrecision precision,
3250 SamplerType sampler) {
3251 DCHECK_GE(precision, 0);
3252 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3253 DCHECK_GE(sampler, 0);
3254 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3255 TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
3256 if (!program->initialized()) {
3257 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3258 program->Initialize(
3259 output_surface_->context_provider(), precision, sampler);
3261 return program;
3264 const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
3265 TexCoordPrecision precision,
3266 SamplerType sampler) {
3267 DCHECK_GE(precision, 0);
3268 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3269 DCHECK_GE(sampler, 0);
3270 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3271 TextureProgram* program = &texture_program_[precision][sampler];
3272 if (!program->initialized()) {
3273 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3274 program->Initialize(output_surface_->context_provider(), precision,
3275 sampler);
3277 return program;
3280 const GLRenderer::NonPremultipliedTextureProgram*
3281 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision,
3282 SamplerType sampler) {
3283 DCHECK_GE(precision, 0);
3284 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3285 DCHECK_GE(sampler, 0);
3286 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3287 NonPremultipliedTextureProgram* program =
3288 &nonpremultiplied_texture_program_[precision][sampler];
3289 if (!program->initialized()) {
3290 TRACE_EVENT0("cc",
3291 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3292 program->Initialize(output_surface_->context_provider(), precision,
3293 sampler);
3295 return program;
3298 const GLRenderer::TextureBackgroundProgram*
3299 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision,
3300 SamplerType sampler) {
3301 DCHECK_GE(precision, 0);
3302 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3303 DCHECK_GE(sampler, 0);
3304 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3305 TextureBackgroundProgram* program =
3306 &texture_background_program_[precision][sampler];
3307 if (!program->initialized()) {
3308 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3309 program->Initialize(output_surface_->context_provider(), precision,
3310 sampler);
3312 return program;
3315 const GLRenderer::NonPremultipliedTextureBackgroundProgram*
3316 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3317 TexCoordPrecision precision,
3318 SamplerType sampler) {
3319 DCHECK_GE(precision, 0);
3320 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3321 DCHECK_GE(sampler, 0);
3322 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3323 NonPremultipliedTextureBackgroundProgram* program =
3324 &nonpremultiplied_texture_background_program_[precision][sampler];
3325 if (!program->initialized()) {
3326 TRACE_EVENT0("cc",
3327 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3328 program->Initialize(output_surface_->context_provider(), precision,
3329 sampler);
3331 return program;
3334 const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
3335 TexCoordPrecision precision) {
3336 DCHECK_GE(precision, 0);
3337 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3338 TextureProgram* program = &texture_io_surface_program_[precision];
3339 if (!program->initialized()) {
3340 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3341 program->Initialize(output_surface_->context_provider(), precision,
3342 SAMPLER_TYPE_2D_RECT);
3344 return program;
3347 const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
3348 TexCoordPrecision precision,
3349 SamplerType sampler) {
3350 DCHECK_GE(precision, 0);
3351 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3352 DCHECK_GE(sampler, 0);
3353 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3354 VideoYUVProgram* program = &video_yuv_program_[precision][sampler];
3355 if (!program->initialized()) {
3356 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3357 program->Initialize(output_surface_->context_provider(), precision,
3358 sampler);
3360 return program;
3363 const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
3364 TexCoordPrecision precision,
3365 SamplerType sampler) {
3366 DCHECK_GE(precision, 0);
3367 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3368 DCHECK_GE(sampler, 0);
3369 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3370 VideoYUVAProgram* program = &video_yuva_program_[precision][sampler];
3371 if (!program->initialized()) {
3372 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3373 program->Initialize(output_surface_->context_provider(), precision,
3374 sampler);
3376 return program;
3379 const GLRenderer::VideoStreamTextureProgram*
3380 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
3381 if (!Capabilities().using_egl_image)
3382 return NULL;
3383 DCHECK_GE(precision, 0);
3384 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3385 VideoStreamTextureProgram* program =
3386 &video_stream_texture_program_[precision];
3387 if (!program->initialized()) {
3388 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3389 program->Initialize(output_surface_->context_provider(), precision,
3390 SAMPLER_TYPE_EXTERNAL_OES);
3392 return program;
3395 void GLRenderer::CleanupSharedObjects() {
3396 shared_geometry_ = nullptr;
3398 for (int i = 0; i <= LAST_TEX_COORD_PRECISION; ++i) {
3399 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3400 tile_program_[i][j].Cleanup(gl_);
3401 tile_program_opaque_[i][j].Cleanup(gl_);
3402 tile_program_swizzle_[i][j].Cleanup(gl_);
3403 tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
3404 tile_program_aa_[i][j].Cleanup(gl_);
3405 tile_program_swizzle_aa_[i][j].Cleanup(gl_);
3407 for (int k = 0; k <= LAST_BLEND_MODE; k++) {
3408 for (int l = 0; l <= LAST_MASK_VALUE; ++l) {
3409 render_pass_mask_program_[i][j][k][l].Cleanup(gl_);
3410 render_pass_mask_program_aa_[i][j][k][l].Cleanup(gl_);
3411 render_pass_mask_color_matrix_program_aa_[i][j][k][l].Cleanup(gl_);
3412 render_pass_mask_color_matrix_program_[i][j][k][l].Cleanup(gl_);
3416 video_yuv_program_[i][j].Cleanup(gl_);
3417 video_yuva_program_[i][j].Cleanup(gl_);
3419 for (int j = 0; j <= LAST_BLEND_MODE; j++) {
3420 render_pass_program_[i][j].Cleanup(gl_);
3421 render_pass_program_aa_[i][j].Cleanup(gl_);
3422 render_pass_color_matrix_program_[i][j].Cleanup(gl_);
3423 render_pass_color_matrix_program_aa_[i][j].Cleanup(gl_);
3426 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3427 texture_program_[i][j].Cleanup(gl_);
3428 nonpremultiplied_texture_program_[i][j].Cleanup(gl_);
3429 texture_background_program_[i][j].Cleanup(gl_);
3430 nonpremultiplied_texture_background_program_[i][j].Cleanup(gl_);
3432 texture_io_surface_program_[i].Cleanup(gl_);
3434 video_stream_texture_program_[i].Cleanup(gl_);
3437 debug_border_program_.Cleanup(gl_);
3438 solid_color_program_.Cleanup(gl_);
3439 solid_color_program_aa_.Cleanup(gl_);
3441 if (offscreen_framebuffer_id_)
3442 gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_);
3444 if (on_demand_tile_raster_resource_id_)
3445 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
3447 ReleaseRenderPassTextures();
3450 void GLRenderer::ReinitializeGLState() {
3451 is_scissor_enabled_ = false;
3452 scissor_rect_needs_reset_ = true;
3453 stencil_shadow_ = false;
3454 blend_shadow_ = true;
3455 program_shadow_ = 0;
3457 RestoreGLState();
3460 void GLRenderer::RestoreGLState() {
3461 // This restores the current GLRenderer state to the GL context.
3462 bound_geometry_ = NO_BINDING;
3463 PrepareGeometry(SHARED_BINDING);
3465 gl_->Disable(GL_DEPTH_TEST);
3466 gl_->Disable(GL_CULL_FACE);
3467 gl_->ColorMask(true, true, true, true);
3468 gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
3469 gl_->ActiveTexture(GL_TEXTURE0);
3471 if (program_shadow_)
3472 gl_->UseProgram(program_shadow_);
3474 if (stencil_shadow_)
3475 gl_->Enable(GL_STENCIL_TEST);
3476 else
3477 gl_->Disable(GL_STENCIL_TEST);
3479 if (blend_shadow_)
3480 gl_->Enable(GL_BLEND);
3481 else
3482 gl_->Disable(GL_BLEND);
3484 if (is_scissor_enabled_) {
3485 gl_->Enable(GL_SCISSOR_TEST);
3486 gl_->Scissor(scissor_rect_.x(), scissor_rect_.y(), scissor_rect_.width(),
3487 scissor_rect_.height());
3488 } else {
3489 gl_->Disable(GL_SCISSOR_TEST);
3493 void GLRenderer::RestoreFramebuffer(DrawingFrame* frame) {
3494 UseRenderPass(frame, frame->current_render_pass);
3496 // Call SetViewport directly, rather than through PrepareSurfaceForPass.
3497 // PrepareSurfaceForPass also clears the surface, which is not desired when
3498 // restoring.
3499 SetViewport();
3502 bool GLRenderer::IsContextLost() {
3503 return gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR;
3506 void GLRenderer::ScheduleOverlays(DrawingFrame* frame) {
3507 if (!frame->overlay_list.size())
3508 return;
3510 ResourceProvider::ResourceIdArray resources;
3511 OverlayCandidateList& overlays = frame->overlay_list;
3512 for (const OverlayCandidate& overlay : overlays) {
3513 // Skip primary plane.
3514 if (overlay.plane_z_order == 0)
3515 continue;
3517 unsigned texture_id = 0;
3518 if (overlay.use_output_surface_for_resource) {
3519 texture_id = output_surface_->GetOverlayTextureId();
3520 DCHECK(texture_id);
3521 } else {
3522 pending_overlay_resources_.push_back(
3523 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3524 resource_provider_, overlay.resource_id)));
3525 texture_id = pending_overlay_resources_.back()->texture_id();
3528 context_support_->ScheduleOverlayPlane(
3529 overlay.plane_z_order, overlay.transform, texture_id,
3530 ToNearestRect(overlay.display_rect), overlay.uv_rect);
3534 } // namespace cc