scheduler: Increase work batch size to 4
[chromium-blink-merge.git] / cc / output / gl_renderer.cc
blob3ffc676a66d18bced61279012515b50aa7ea7df0
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::CHECKERBOARD:
522 DrawCheckerboardQuad(frame, CheckerboardDrawQuad::MaterialCast(quad),
523 clip_region);
524 break;
525 case DrawQuad::DEBUG_BORDER:
526 DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
527 break;
528 case DrawQuad::IO_SURFACE_CONTENT:
529 DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad),
530 clip_region);
531 break;
532 case DrawQuad::PICTURE_CONTENT:
533 // PictureDrawQuad should only be used for resourceless software draws.
534 NOTREACHED();
535 break;
536 case DrawQuad::RENDER_PASS:
537 DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad),
538 clip_region);
539 break;
540 case DrawQuad::SOLID_COLOR:
541 DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad),
542 clip_region);
543 break;
544 case DrawQuad::STREAM_VIDEO_CONTENT:
545 DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad),
546 clip_region);
547 break;
548 case DrawQuad::SURFACE_CONTENT:
549 // Surface content should be fully resolved to other quad types before
550 // reaching a direct renderer.
551 NOTREACHED();
552 break;
553 case DrawQuad::TEXTURE_CONTENT:
554 EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad),
555 clip_region);
556 break;
557 case DrawQuad::TILED_CONTENT:
558 DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad), clip_region);
559 break;
560 case DrawQuad::YUV_VIDEO_CONTENT:
561 DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad),
562 clip_region);
563 break;
567 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame* frame,
568 const CheckerboardDrawQuad* quad,
569 const gfx::QuadF* clip_region) {
570 // TODO(enne) For now since checkerboards shouldn't be part of a 3D
571 // context, clipping regions aren't supported so we skip drawing them
572 // if this becomes the case.
573 if (clip_region) {
574 return;
576 SetBlendEnabled(quad->ShouldDrawWithBlending());
578 const TileCheckerboardProgram* program = GetTileCheckerboardProgram();
579 DCHECK(program && (program->initialized() || IsContextLost()));
580 SetUseProgram(program->program());
582 SkColor color = quad->color;
583 gl_->Uniform4f(program->fragment_shader().color_location(),
584 SkColorGetR(color) * (1.0f / 255.0f),
585 SkColorGetG(color) * (1.0f / 255.0f),
586 SkColorGetB(color) * (1.0f / 255.0f), 1);
588 const int kCheckerboardWidth = 16;
589 float frequency = 1.0f / kCheckerboardWidth;
591 gfx::Rect tile_rect = quad->rect;
592 float tex_offset_x =
593 static_cast<int>(tile_rect.x() / quad->scale) % kCheckerboardWidth;
594 float tex_offset_y =
595 static_cast<int>(tile_rect.y() / quad->scale) % kCheckerboardWidth;
596 float tex_scale_x = tile_rect.width() / quad->scale;
597 float tex_scale_y = tile_rect.height() / quad->scale;
598 gl_->Uniform4f(program->fragment_shader().tex_transform_location(),
599 tex_offset_x, tex_offset_y, tex_scale_x, tex_scale_y);
601 gl_->Uniform1f(program->fragment_shader().frequency_location(), frequency);
603 SetShaderOpacity(quad->shared_quad_state->opacity,
604 program->fragment_shader().alpha_location());
605 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
606 quad->rect, program->vertex_shader().matrix_location());
609 // This function does not handle 3D sorting right now, since the debug border
610 // quads are just drawn as their original quads and not in split pieces. This
611 // results in some debug border quads drawing over foreground quads.
612 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
613 const DebugBorderDrawQuad* quad) {
614 SetBlendEnabled(quad->ShouldDrawWithBlending());
616 static float gl_matrix[16];
617 const DebugBorderProgram* program = GetDebugBorderProgram();
618 DCHECK(program && (program->initialized() || IsContextLost()));
619 SetUseProgram(program->program());
621 // Use the full quad_rect for debug quads to not move the edges based on
622 // partial swaps.
623 gfx::Rect layer_rect = quad->rect;
624 gfx::Transform render_matrix;
625 QuadRectTransform(&render_matrix,
626 quad->shared_quad_state->quad_to_target_transform,
627 layer_rect);
628 GLRenderer::ToGLMatrix(&gl_matrix[0],
629 frame->projection_matrix * render_matrix);
630 gl_->UniformMatrix4fv(program->vertex_shader().matrix_location(), 1, false,
631 &gl_matrix[0]);
633 SkColor color = quad->color;
634 float alpha = SkColorGetA(color) * (1.0f / 255.0f);
636 gl_->Uniform4f(program->fragment_shader().color_location(),
637 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
638 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
639 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha, alpha);
641 gl_->LineWidth(quad->width);
643 // The indices for the line are stored in the same array as the triangle
644 // indices.
645 gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0);
648 static skia::RefPtr<SkImage> ApplyImageFilter(
649 scoped_ptr<GLRenderer::ScopedUseGrContext> use_gr_context,
650 ResourceProvider* resource_provider,
651 const gfx::Rect& rect,
652 const gfx::Vector2dF& scale,
653 SkImageFilter* filter,
654 ScopedResource* source_texture_resource) {
655 if (!filter)
656 return skia::RefPtr<SkImage>();
658 if (!use_gr_context)
659 return skia::RefPtr<SkImage>();
661 ResourceProvider::ScopedReadLockGL lock(resource_provider,
662 source_texture_resource->id());
664 // Wrap the source texture in a Ganesh platform texture.
665 GrBackendTextureDesc backend_texture_description;
666 backend_texture_description.fWidth = source_texture_resource->size().width();
667 backend_texture_description.fHeight =
668 source_texture_resource->size().height();
669 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
670 backend_texture_description.fTextureHandle = lock.texture_id();
671 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
672 skia::RefPtr<GrTexture> texture = skia::AdoptRef(
673 use_gr_context->context()->textureProvider()->wrapBackendTexture(
674 backend_texture_description));
675 if (!texture) {
676 TRACE_EVENT_INSTANT0("cc",
677 "ApplyImageFilter wrap background texture failed",
678 TRACE_EVENT_SCOPE_THREAD);
679 return skia::RefPtr<SkImage>();
682 SkImageInfo src_info =
683 SkImageInfo::MakeN32Premul(source_texture_resource->size().width(),
684 source_texture_resource->size().height());
685 // Place the platform texture inside an SkBitmap.
686 SkBitmap source;
687 source.setInfo(src_info);
688 skia::RefPtr<SkGrPixelRef> pixel_ref =
689 skia::AdoptRef(new SkGrPixelRef(src_info, texture.get()));
690 source.setPixelRef(pixel_ref.get());
692 // Create surface to draw into.
693 SkImageInfo dst_info =
694 SkImageInfo::MakeN32Premul(source.width(), source.height());
695 skia::RefPtr<SkSurface> surface = skia::AdoptRef(SkSurface::NewRenderTarget(
696 use_gr_context->context(), SkSurface::kYes_Budgeted, dst_info, 0));
697 if (!surface) {
698 TRACE_EVENT_INSTANT0("cc", "ApplyImageFilter surface allocation failed",
699 TRACE_EVENT_SCOPE_THREAD);
700 return skia::RefPtr<SkImage>();
702 skia::RefPtr<SkCanvas> canvas = skia::SharePtr(surface->getCanvas());
704 // Draw the source bitmap through the filter to the canvas.
705 SkPaint paint;
706 paint.setImageFilter(filter);
707 canvas->clear(SK_ColorTRANSPARENT);
709 // The origin of the filter is top-left and the origin of the source is
710 // bottom-left, but the orientation is the same, so we must translate the
711 // filter so that it renders at the bottom of the texture to avoid
712 // misregistration.
713 int y_translate = source.height() - rect.height() - rect.origin().y();
714 canvas->translate(-rect.origin().x(), y_translate);
715 canvas->scale(scale.x(), scale.y());
716 canvas->drawSprite(source, 0, 0, &paint);
718 skia::RefPtr<SkImage> image = skia::AdoptRef(surface->newImageSnapshot());
719 if (!image || !image->isTextureBacked()) {
720 return skia::RefPtr<SkImage>();
723 return image;
726 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
727 return use_blend_equation_advanced_ ||
728 blend_mode == SkXfermode::kScreen_Mode ||
729 blend_mode == SkXfermode::kSrcOver_Mode;
732 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
733 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode));
735 // Any modes set here must be reset in RestoreBlendFuncToDefault
736 if (use_blend_equation_advanced_) {
737 GLenum equation = GL_FUNC_ADD;
739 switch (blend_mode) {
740 case SkXfermode::kScreen_Mode:
741 equation = GL_SCREEN_KHR;
742 break;
743 case SkXfermode::kOverlay_Mode:
744 equation = GL_OVERLAY_KHR;
745 break;
746 case SkXfermode::kDarken_Mode:
747 equation = GL_DARKEN_KHR;
748 break;
749 case SkXfermode::kLighten_Mode:
750 equation = GL_LIGHTEN_KHR;
751 break;
752 case SkXfermode::kColorDodge_Mode:
753 equation = GL_COLORDODGE_KHR;
754 break;
755 case SkXfermode::kColorBurn_Mode:
756 equation = GL_COLORBURN_KHR;
757 break;
758 case SkXfermode::kHardLight_Mode:
759 equation = GL_HARDLIGHT_KHR;
760 break;
761 case SkXfermode::kSoftLight_Mode:
762 equation = GL_SOFTLIGHT_KHR;
763 break;
764 case SkXfermode::kDifference_Mode:
765 equation = GL_DIFFERENCE_KHR;
766 break;
767 case SkXfermode::kExclusion_Mode:
768 equation = GL_EXCLUSION_KHR;
769 break;
770 case SkXfermode::kMultiply_Mode:
771 equation = GL_MULTIPLY_KHR;
772 break;
773 case SkXfermode::kHue_Mode:
774 equation = GL_HSL_HUE_KHR;
775 break;
776 case SkXfermode::kSaturation_Mode:
777 equation = GL_HSL_SATURATION_KHR;
778 break;
779 case SkXfermode::kColor_Mode:
780 equation = GL_HSL_COLOR_KHR;
781 break;
782 case SkXfermode::kLuminosity_Mode:
783 equation = GL_HSL_LUMINOSITY_KHR;
784 break;
785 default:
786 return;
789 gl_->BlendEquation(equation);
790 } else {
791 if (blend_mode == SkXfermode::kScreen_Mode) {
792 gl_->BlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE);
797 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode) {
798 if (blend_mode == SkXfermode::kSrcOver_Mode)
799 return;
801 if (use_blend_equation_advanced_) {
802 gl_->BlendEquation(GL_FUNC_ADD);
803 } else {
804 gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
808 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame* frame,
809 const RenderPassDrawQuad* quad) {
810 if (quad->background_filters.IsEmpty())
811 return false;
813 // TODO(danakj): We only allow background filters on an opaque render surface
814 // because other surfaces may contain translucent pixels, and the contents
815 // behind those translucent pixels wouldn't have the filter applied.
816 if (frame->current_render_pass->has_transparent_background)
817 return false;
819 // TODO(ajuma): Add support for reference filters once
820 // FilterOperations::GetOutsets supports reference filters.
821 if (quad->background_filters.HasReferenceFilter())
822 return false;
823 return true;
826 // This takes a gfx::Rect and a clip region quad in the same space,
827 // and returns a quad with the same proportions in the space -0.5->0.5.
828 bool GetScaledRegion(const gfx::Rect& rect,
829 const gfx::QuadF* clip,
830 gfx::QuadF* scaled_region) {
831 if (!clip)
832 return false;
834 gfx::PointF p1(((clip->p1().x() - rect.x()) / rect.width()) - 0.5f,
835 ((clip->p1().y() - rect.y()) / rect.height()) - 0.5f);
836 gfx::PointF p2(((clip->p2().x() - rect.x()) / rect.width()) - 0.5f,
837 ((clip->p2().y() - rect.y()) / rect.height()) - 0.5f);
838 gfx::PointF p3(((clip->p3().x() - rect.x()) / rect.width()) - 0.5f,
839 ((clip->p3().y() - rect.y()) / rect.height()) - 0.5f);
840 gfx::PointF p4(((clip->p4().x() - rect.x()) / rect.width()) - 0.5f,
841 ((clip->p4().y() - rect.y()) / rect.height()) - 0.5f);
842 *scaled_region = gfx::QuadF(p1, p2, p3, p4);
843 return true;
846 // This takes a gfx::Rect and a clip region quad in the same space,
847 // and returns the proportional uv's in the space 0->1.
848 bool GetScaledUVs(const gfx::Rect& rect, const gfx::QuadF* clip, float uvs[8]) {
849 if (!clip)
850 return false;
852 uvs[0] = ((clip->p1().x() - rect.x()) / rect.width());
853 uvs[1] = ((clip->p1().y() - rect.y()) / rect.height());
854 uvs[2] = ((clip->p2().x() - rect.x()) / rect.width());
855 uvs[3] = ((clip->p2().y() - rect.y()) / rect.height());
856 uvs[4] = ((clip->p3().x() - rect.x()) / rect.width());
857 uvs[5] = ((clip->p3().y() - rect.y()) / rect.height());
858 uvs[6] = ((clip->p4().x() - rect.x()) / rect.width());
859 uvs[7] = ((clip->p4().y() - rect.y()) / rect.height());
860 return true;
863 gfx::Rect GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
864 DrawingFrame* frame,
865 const RenderPassDrawQuad* quad,
866 const gfx::Transform& contents_device_transform,
867 const gfx::QuadF* clip_region,
868 bool use_aa) {
869 gfx::QuadF scaled_region;
870 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
871 scaled_region = SharedGeometryQuad().BoundingBox();
874 gfx::Rect backdrop_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
875 contents_device_transform, scaled_region.BoundingBox()));
877 if (ShouldApplyBackgroundFilters(frame, quad)) {
878 int top, right, bottom, left;
879 quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
880 backdrop_rect.Inset(-left, -top, -right, -bottom);
883 if (!backdrop_rect.IsEmpty() && use_aa) {
884 const int kOutsetForAntialiasing = 1;
885 backdrop_rect.Inset(-kOutsetForAntialiasing, -kOutsetForAntialiasing);
888 backdrop_rect.Intersect(MoveFromDrawToWindowSpace(
889 frame, frame->current_render_pass->output_rect));
890 return backdrop_rect;
893 scoped_ptr<ScopedResource> GLRenderer::GetBackdropTexture(
894 const gfx::Rect& bounding_rect) {
895 scoped_ptr<ScopedResource> device_background_texture =
896 ScopedResource::Create(resource_provider_);
897 // CopyTexImage2D fails when called on a texture having immutable storage.
898 device_background_texture->Allocate(
899 bounding_rect.size(), ResourceProvider::TEXTURE_HINT_DEFAULT, RGBA_8888);
901 ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
902 device_background_texture->id());
903 GetFramebufferTexture(
904 lock.texture_id(), device_background_texture->format(), bounding_rect);
906 return device_background_texture.Pass();
909 skia::RefPtr<SkImage> GLRenderer::ApplyBackgroundFilters(
910 DrawingFrame* frame,
911 const RenderPassDrawQuad* quad,
912 ScopedResource* background_texture) {
913 DCHECK(ShouldApplyBackgroundFilters(frame, quad));
914 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
915 quad->background_filters, background_texture->size());
917 skia::RefPtr<SkImage> background_with_filters = ApplyImageFilter(
918 ScopedUseGrContext::Create(this, frame), resource_provider_, quad->rect,
919 quad->filters_scale, filter.get(), background_texture);
920 return background_with_filters;
923 void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
924 const RenderPassDrawQuad* quad,
925 const gfx::QuadF* clip_region) {
926 ScopedResource* contents_texture =
927 render_pass_textures_.get(quad->render_pass_id);
928 DCHECK(contents_texture);
929 DCHECK(contents_texture->id());
931 gfx::Transform quad_rect_matrix;
932 QuadRectTransform(&quad_rect_matrix,
933 quad->shared_quad_state->quad_to_target_transform,
934 quad->rect);
935 gfx::Transform contents_device_transform =
936 frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
937 contents_device_transform.FlattenTo2d();
939 // Can only draw surface if device matrix is invertible.
940 if (!contents_device_transform.IsInvertible())
941 return;
943 gfx::QuadF surface_quad = SharedGeometryQuad();
945 gfx::QuadF device_layer_quad;
946 bool use_aa = false;
947 if (settings_->allow_antialiasing) {
948 bool clipped = false;
949 device_layer_quad =
950 MathUtil::MapQuad(contents_device_transform, surface_quad, &clipped);
951 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped,
952 settings_->force_antialiasing);
955 float edge[24];
956 const gfx::QuadF* aa_quad = use_aa ? &device_layer_quad : nullptr;
957 SetupRenderPassQuadForClippingAndAntialiasing(contents_device_transform, quad,
958 aa_quad, clip_region,
959 &surface_quad, edge);
960 SkXfermode::Mode blend_mode = quad->shared_quad_state->blend_mode;
961 bool use_shaders_for_blending =
962 !CanApplyBlendModeUsingBlendFunc(blend_mode) ||
963 ShouldApplyBackgroundFilters(frame, quad) ||
964 settings_->force_blending_with_shaders;
966 scoped_ptr<ScopedResource> background_texture;
967 skia::RefPtr<SkImage> background_image;
968 GLuint background_image_id = 0;
969 gfx::Rect background_rect;
970 if (use_shaders_for_blending) {
971 // Compute a bounding box around the pixels that will be visible through
972 // the quad.
973 background_rect = GetBackdropBoundingBoxForRenderPassQuad(
974 frame, quad, contents_device_transform, clip_region, use_aa);
976 if (!background_rect.IsEmpty()) {
977 // The pixels from the filtered background should completely replace the
978 // current pixel values.
979 if (blend_enabled())
980 SetBlendEnabled(false);
982 // Read the pixels in the bounding box into a buffer R.
983 // This function allocates a texture, which should contribute to the
984 // amount of memory used by render surfaces:
985 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
986 background_texture = GetBackdropTexture(background_rect);
988 if (ShouldApplyBackgroundFilters(frame, quad) && background_texture) {
989 // Apply the background filters to R, so that it is applied in the
990 // pixels' coordinate space.
991 background_image =
992 ApplyBackgroundFilters(frame, quad, background_texture.get());
993 if (background_image)
994 background_image_id = background_image->getTextureHandle(true);
995 DCHECK(background_image_id);
999 if (!background_texture) {
1000 // Something went wrong with reading the backdrop.
1001 DCHECK(!background_image_id);
1002 use_shaders_for_blending = false;
1003 } else if (background_image_id) {
1004 // Reset original background texture if there is not any mask
1005 if (!quad->mask_resource_id())
1006 background_texture.reset();
1007 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode) &&
1008 ShouldApplyBackgroundFilters(frame, quad)) {
1009 // Something went wrong with applying background filters to the backdrop.
1010 use_shaders_for_blending = false;
1011 background_texture.reset();
1014 // Need original background texture for mask?
1015 bool mask_for_background =
1016 background_texture && // Have original background texture
1017 background_image_id && // Have filtered background texture
1018 quad->mask_resource_id(); // Have mask texture
1019 SetBlendEnabled(
1020 !use_shaders_for_blending &&
1021 (quad->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode)));
1023 // TODO(senorblanco): Cache this value so that we don't have to do it for both
1024 // the surface and its replica. Apply filters to the contents texture.
1025 skia::RefPtr<SkImage> filter_image;
1026 GLuint filter_image_id = 0;
1027 SkScalar color_matrix[20];
1028 bool use_color_matrix = false;
1029 if (!quad->filters.IsEmpty()) {
1030 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
1031 quad->filters, contents_texture->size());
1032 if (filter) {
1033 skia::RefPtr<SkColorFilter> cf;
1036 SkColorFilter* colorfilter_rawptr = NULL;
1037 filter->asColorFilter(&colorfilter_rawptr);
1038 cf = skia::AdoptRef(colorfilter_rawptr);
1041 if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
1042 // We have a single color matrix as a filter; apply it locally
1043 // in the compositor.
1044 use_color_matrix = true;
1045 } else {
1046 filter_image = ApplyImageFilter(
1047 ScopedUseGrContext::Create(this, frame), resource_provider_,
1048 quad->rect, quad->filters_scale, filter.get(), contents_texture);
1049 if (filter_image) {
1050 filter_image_id = filter_image->getTextureHandle(true);
1051 DCHECK(filter_image_id);
1057 scoped_ptr<ResourceProvider::ScopedSamplerGL> mask_resource_lock;
1058 unsigned mask_texture_id = 0;
1059 SamplerType mask_sampler = SAMPLER_TYPE_NA;
1060 if (quad->mask_resource_id()) {
1061 mask_resource_lock.reset(new ResourceProvider::ScopedSamplerGL(
1062 resource_provider_, quad->mask_resource_id(), GL_TEXTURE1, GL_LINEAR));
1063 mask_texture_id = mask_resource_lock->texture_id();
1064 mask_sampler = SamplerTypeFromTextureTarget(mask_resource_lock->target());
1067 scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
1068 if (filter_image_id) {
1069 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
1070 gl_->BindTexture(GL_TEXTURE_2D, filter_image_id);
1071 } else {
1072 contents_resource_lock =
1073 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1074 resource_provider_, contents_texture->id(), GL_LINEAR));
1075 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1076 contents_resource_lock->target());
1079 if (!use_shaders_for_blending) {
1080 if (!use_blend_equation_advanced_coherent_ && use_blend_equation_advanced_)
1081 gl_->BlendBarrierKHR();
1083 ApplyBlendModeUsingBlendFunc(blend_mode);
1086 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1087 gl_, &highp_threshold_cache_, highp_threshold_min_,
1088 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
1090 ShaderLocations locations;
1092 DCHECK_EQ(background_texture || background_image_id,
1093 use_shaders_for_blending);
1094 BlendMode shader_blend_mode = use_shaders_for_blending
1095 ? BlendModeFromSkXfermode(blend_mode)
1096 : BLEND_MODE_NONE;
1098 if (use_aa && mask_texture_id && !use_color_matrix) {
1099 const RenderPassMaskProgramAA* program = GetRenderPassMaskProgramAA(
1100 tex_coord_precision, mask_sampler,
1101 shader_blend_mode, mask_for_background);
1102 SetUseProgram(program->program());
1103 program->vertex_shader().FillLocations(&locations);
1104 program->fragment_shader().FillLocations(&locations);
1105 gl_->Uniform1i(locations.sampler, 0);
1106 } else if (!use_aa && mask_texture_id && !use_color_matrix) {
1107 const RenderPassMaskProgram* program = GetRenderPassMaskProgram(
1108 tex_coord_precision, mask_sampler,
1109 shader_blend_mode, mask_for_background);
1110 SetUseProgram(program->program());
1111 program->vertex_shader().FillLocations(&locations);
1112 program->fragment_shader().FillLocations(&locations);
1113 gl_->Uniform1i(locations.sampler, 0);
1114 } else if (use_aa && !mask_texture_id && !use_color_matrix) {
1115 const RenderPassProgramAA* program =
1116 GetRenderPassProgramAA(tex_coord_precision, shader_blend_mode);
1117 SetUseProgram(program->program());
1118 program->vertex_shader().FillLocations(&locations);
1119 program->fragment_shader().FillLocations(&locations);
1120 gl_->Uniform1i(locations.sampler, 0);
1121 } else if (use_aa && mask_texture_id && use_color_matrix) {
1122 const RenderPassMaskColorMatrixProgramAA* program =
1123 GetRenderPassMaskColorMatrixProgramAA(
1124 tex_coord_precision, mask_sampler,
1125 shader_blend_mode, mask_for_background);
1126 SetUseProgram(program->program());
1127 program->vertex_shader().FillLocations(&locations);
1128 program->fragment_shader().FillLocations(&locations);
1129 gl_->Uniform1i(locations.sampler, 0);
1130 } else if (use_aa && !mask_texture_id && use_color_matrix) {
1131 const RenderPassColorMatrixProgramAA* program =
1132 GetRenderPassColorMatrixProgramAA(tex_coord_precision,
1133 shader_blend_mode);
1134 SetUseProgram(program->program());
1135 program->vertex_shader().FillLocations(&locations);
1136 program->fragment_shader().FillLocations(&locations);
1137 gl_->Uniform1i(locations.sampler, 0);
1138 } else if (!use_aa && mask_texture_id && use_color_matrix) {
1139 const RenderPassMaskColorMatrixProgram* program =
1140 GetRenderPassMaskColorMatrixProgram(
1141 tex_coord_precision, mask_sampler,
1142 shader_blend_mode, mask_for_background);
1143 SetUseProgram(program->program());
1144 program->vertex_shader().FillLocations(&locations);
1145 program->fragment_shader().FillLocations(&locations);
1146 gl_->Uniform1i(locations.sampler, 0);
1147 } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1148 const RenderPassColorMatrixProgram* program =
1149 GetRenderPassColorMatrixProgram(tex_coord_precision, shader_blend_mode);
1150 SetUseProgram(program->program());
1151 program->vertex_shader().FillLocations(&locations);
1152 program->fragment_shader().FillLocations(&locations);
1153 gl_->Uniform1i(locations.sampler, 0);
1154 } else {
1155 const RenderPassProgram* program =
1156 GetRenderPassProgram(tex_coord_precision, shader_blend_mode);
1157 SetUseProgram(program->program());
1158 program->vertex_shader().FillLocations(&locations);
1159 program->fragment_shader().FillLocations(&locations);
1160 gl_->Uniform1i(locations.sampler, 0);
1162 float tex_scale_x =
1163 quad->rect.width() / static_cast<float>(contents_texture->size().width());
1164 float tex_scale_y = quad->rect.height() /
1165 static_cast<float>(contents_texture->size().height());
1166 DCHECK_LE(tex_scale_x, 1.0f);
1167 DCHECK_LE(tex_scale_y, 1.0f);
1169 DCHECK(locations.tex_transform != -1 || IsContextLost());
1170 // Flip the content vertically in the shader, as the RenderPass input
1171 // texture is already oriented the same way as the framebuffer, but the
1172 // projection transform does a flip.
1173 gl_->Uniform4f(locations.tex_transform, 0.0f, tex_scale_y, tex_scale_x,
1174 -tex_scale_y);
1176 GLint last_texture_unit = 0;
1177 if (locations.mask_sampler != -1) {
1178 DCHECK_NE(locations.mask_tex_coord_scale, 1);
1179 DCHECK_NE(locations.mask_tex_coord_offset, 1);
1180 gl_->Uniform1i(locations.mask_sampler, 1);
1182 gfx::RectF mask_uv_rect = quad->MaskUVRect();
1183 if (mask_sampler != SAMPLER_TYPE_2D) {
1184 mask_uv_rect.Scale(quad->mask_texture_size.width(),
1185 quad->mask_texture_size.height());
1188 // Mask textures are oriented vertically flipped relative to the framebuffer
1189 // and the RenderPass contents texture, so we flip the tex coords from the
1190 // RenderPass texture to find the mask texture coords.
1191 gl_->Uniform2f(locations.mask_tex_coord_offset, mask_uv_rect.x(),
1192 mask_uv_rect.bottom());
1193 gl_->Uniform2f(locations.mask_tex_coord_scale,
1194 mask_uv_rect.width() / tex_scale_x,
1195 -mask_uv_rect.height() / tex_scale_y);
1197 last_texture_unit = 1;
1200 if (locations.edge != -1)
1201 gl_->Uniform3fv(locations.edge, 8, edge);
1203 if (locations.viewport != -1) {
1204 float viewport[4] = {
1205 static_cast<float>(current_window_space_viewport_.x()),
1206 static_cast<float>(current_window_space_viewport_.y()),
1207 static_cast<float>(current_window_space_viewport_.width()),
1208 static_cast<float>(current_window_space_viewport_.height()),
1210 gl_->Uniform4fv(locations.viewport, 1, viewport);
1213 if (locations.color_matrix != -1) {
1214 float matrix[16];
1215 for (int i = 0; i < 4; ++i) {
1216 for (int j = 0; j < 4; ++j)
1217 matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1219 gl_->UniformMatrix4fv(locations.color_matrix, 1, false, matrix);
1221 static const float kScale = 1.0f / 255.0f;
1222 if (locations.color_offset != -1) {
1223 float offset[4];
1224 for (int i = 0; i < 4; ++i)
1225 offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1227 gl_->Uniform4fv(locations.color_offset, 1, offset);
1230 scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_background_sampler_lock;
1231 if (locations.backdrop != -1) {
1232 DCHECK(background_texture || background_image_id);
1233 DCHECK_NE(locations.backdrop, 0);
1234 DCHECK_NE(locations.backdrop_rect, 0);
1236 gl_->Uniform1i(locations.backdrop, ++last_texture_unit);
1238 gl_->Uniform4f(locations.backdrop_rect, background_rect.x(),
1239 background_rect.y(), background_rect.width(),
1240 background_rect.height());
1242 if (background_image_id) {
1243 gl_->ActiveTexture(GL_TEXTURE0 + last_texture_unit);
1244 gl_->BindTexture(GL_TEXTURE_2D, background_image_id);
1245 gl_->ActiveTexture(GL_TEXTURE0);
1246 if (mask_for_background)
1247 gl_->Uniform1i(locations.original_backdrop, ++last_texture_unit);
1249 if (background_texture) {
1250 shader_background_sampler_lock = make_scoped_ptr(
1251 new ResourceProvider::ScopedSamplerGL(resource_provider_,
1252 background_texture->id(),
1253 GL_TEXTURE0 + last_texture_unit,
1254 GL_LINEAR));
1255 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1256 shader_background_sampler_lock->target());
1260 SetShaderOpacity(quad->shared_quad_state->opacity, locations.alpha);
1261 SetShaderQuadF(surface_quad, locations.quad);
1262 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1263 quad->rect, locations.matrix);
1265 // Flush the compositor context before the filter bitmap goes out of
1266 // scope, so the draw gets processed before the filter texture gets deleted.
1267 if (filter_image_id)
1268 gl_->Flush();
1270 if (!use_shaders_for_blending)
1271 RestoreBlendFuncToDefault(blend_mode);
1274 struct SolidColorProgramUniforms {
1275 unsigned program;
1276 unsigned matrix_location;
1277 unsigned viewport_location;
1278 unsigned quad_location;
1279 unsigned edge_location;
1280 unsigned color_location;
1283 template <class T>
1284 static void SolidColorUniformLocation(T program,
1285 SolidColorProgramUniforms* uniforms) {
1286 uniforms->program = program->program();
1287 uniforms->matrix_location = program->vertex_shader().matrix_location();
1288 uniforms->viewport_location = program->vertex_shader().viewport_location();
1289 uniforms->quad_location = program->vertex_shader().quad_location();
1290 uniforms->edge_location = program->vertex_shader().edge_location();
1291 uniforms->color_location = program->fragment_shader().color_location();
1294 namespace {
1295 // These functions determine if a quad, clipped by a clip_region contains
1296 // the entire {top|bottom|left|right} edge.
1297 bool is_top(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1298 if (!quad->IsTopEdge())
1299 return false;
1300 if (!clip_region)
1301 return true;
1303 return std::abs(clip_region->p1().y()) < kAntiAliasingEpsilon &&
1304 std::abs(clip_region->p2().y()) < kAntiAliasingEpsilon;
1307 bool is_bottom(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1308 if (!quad->IsBottomEdge())
1309 return false;
1310 if (!clip_region)
1311 return true;
1313 return std::abs(clip_region->p3().y() -
1314 quad->shared_quad_state->quad_layer_bounds.height()) <
1315 kAntiAliasingEpsilon &&
1316 std::abs(clip_region->p4().y() -
1317 quad->shared_quad_state->quad_layer_bounds.height()) <
1318 kAntiAliasingEpsilon;
1321 bool is_left(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1322 if (!quad->IsLeftEdge())
1323 return false;
1324 if (!clip_region)
1325 return true;
1327 return std::abs(clip_region->p1().x()) < kAntiAliasingEpsilon &&
1328 std::abs(clip_region->p4().x()) < kAntiAliasingEpsilon;
1331 bool is_right(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1332 if (!quad->IsRightEdge())
1333 return false;
1334 if (!clip_region)
1335 return true;
1337 return std::abs(clip_region->p2().x() -
1338 quad->shared_quad_state->quad_layer_bounds.width()) <
1339 kAntiAliasingEpsilon &&
1340 std::abs(clip_region->p3().x() -
1341 quad->shared_quad_state->quad_layer_bounds.width()) <
1342 kAntiAliasingEpsilon;
1344 } // anonymous namespace
1346 static gfx::QuadF GetDeviceQuadWithAntialiasingOnExteriorEdges(
1347 const LayerQuad& device_layer_edges,
1348 const gfx::Transform& device_transform,
1349 const gfx::QuadF& tile_quad,
1350 const gfx::QuadF* clip_region,
1351 const DrawQuad* quad) {
1352 gfx::RectF tile_rect = quad->visible_rect;
1354 gfx::PointF bottom_right = tile_quad.p3();
1355 gfx::PointF bottom_left = tile_quad.p4();
1356 gfx::PointF top_left = tile_quad.p1();
1357 gfx::PointF top_right = tile_quad.p2();
1358 bool clipped = false;
1360 // Map points to device space. We ignore |clipped|, since the result of
1361 // |MapPoint()| still produces a valid point to draw the quad with. When
1362 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1363 bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1364 bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1365 top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1366 top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1368 LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1369 LayerQuad::Edge left_edge(bottom_left, top_left);
1370 LayerQuad::Edge top_edge(top_left, top_right);
1371 LayerQuad::Edge right_edge(top_right, bottom_right);
1373 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1374 // If an edge is degenerate we do not want to replace it with a "proper" edge
1375 // as that will cause the quad to possibly expand is strange ways.
1376 if (!top_edge.degenerate() && is_top(clip_region, quad) &&
1377 tile_rect.y() == quad->rect.y()) {
1378 top_edge = device_layer_edges.top();
1380 if (!left_edge.degenerate() && is_left(clip_region, quad) &&
1381 tile_rect.x() == quad->rect.x()) {
1382 left_edge = device_layer_edges.left();
1384 if (!right_edge.degenerate() && is_right(clip_region, quad) &&
1385 tile_rect.right() == quad->rect.right()) {
1386 right_edge = device_layer_edges.right();
1388 if (!bottom_edge.degenerate() && is_bottom(clip_region, quad) &&
1389 tile_rect.bottom() == quad->rect.bottom()) {
1390 bottom_edge = device_layer_edges.bottom();
1393 float sign = tile_quad.IsCounterClockwise() ? -1 : 1;
1394 bottom_edge.scale(sign);
1395 left_edge.scale(sign);
1396 top_edge.scale(sign);
1397 right_edge.scale(sign);
1399 // Create device space quad.
1400 return LayerQuad(left_edge, top_edge, right_edge, bottom_edge).ToQuadF();
1403 float GetTotalQuadError(const gfx::QuadF* clipped_quad,
1404 const gfx::QuadF* ideal_rect) {
1405 return (clipped_quad->p1() - ideal_rect->p1()).LengthSquared() +
1406 (clipped_quad->p2() - ideal_rect->p2()).LengthSquared() +
1407 (clipped_quad->p3() - ideal_rect->p3()).LengthSquared() +
1408 (clipped_quad->p4() - ideal_rect->p4()).LengthSquared();
1411 // Attempt to rotate the clipped quad until it lines up the most
1412 // correctly. This is necessary because we check the edges of this
1413 // quad against the expected left/right/top/bottom for anti-aliasing.
1414 void AlignQuadToBoundingBox(gfx::QuadF* clipped_quad) {
1415 gfx::QuadF bounding_quad = gfx::QuadF(clipped_quad->BoundingBox());
1416 gfx::QuadF best_rotation = *clipped_quad;
1417 float least_error_amount = GetTotalQuadError(clipped_quad, &bounding_quad);
1418 for (size_t i = 1; i < 4; ++i) {
1419 clipped_quad->Realign(1);
1420 float new_error = GetTotalQuadError(clipped_quad, &bounding_quad);
1421 if (new_error < least_error_amount) {
1422 least_error_amount = new_error;
1423 best_rotation = *clipped_quad;
1426 *clipped_quad = best_rotation;
1429 // Map device space quad to local space. Device_transform has no 3d
1430 // component since it was flattened, so we don't need to project. We should
1431 // have already checked that the transform was uninvertible before this call.
1432 gfx::QuadF MapQuadToLocalSpace(const gfx::Transform& device_transform,
1433 const gfx::QuadF& device_quad) {
1434 gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1435 DCHECK(device_transform.IsInvertible());
1436 bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1437 DCHECK(did_invert);
1438 bool clipped = false;
1439 gfx::QuadF local_quad =
1440 MathUtil::MapQuad(inverse_device_transform, device_quad, &clipped);
1441 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1442 // cause device_quad to become clipped. To our knowledge this scenario does
1443 // not need to be handled differently than the unclipped case.
1444 return local_quad;
1447 void InflateAntiAliasingDistances(const gfx::QuadF& quad,
1448 LayerQuad* device_layer_edges,
1449 float edge[24]) {
1450 DCHECK(!quad.BoundingBox().IsEmpty());
1451 LayerQuad device_layer_bounds(gfx::QuadF(quad.BoundingBox()));
1453 device_layer_edges->InflateAntiAliasingDistance();
1454 device_layer_edges->ToFloatArray(edge);
1456 device_layer_bounds.InflateAntiAliasingDistance();
1457 device_layer_bounds.ToFloatArray(&edge[12]);
1460 // static
1461 bool GLRenderer::ShouldAntialiasQuad(const gfx::QuadF& device_layer_quad,
1462 bool clipped,
1463 bool force_aa) {
1464 // AAing clipped quads is not supported by the code yet.
1465 if (clipped)
1466 return false;
1467 if (device_layer_quad.BoundingBox().IsEmpty())
1468 return false;
1469 if (force_aa)
1470 return true;
1472 bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1473 bool is_nearest_rect_within_epsilon =
1474 is_axis_aligned_in_target &&
1475 gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1476 kAntiAliasingEpsilon);
1477 return !is_nearest_rect_within_epsilon;
1480 // static
1481 void GLRenderer::SetupQuadForClippingAndAntialiasing(
1482 const gfx::Transform& device_transform,
1483 const DrawQuad* quad,
1484 const gfx::QuadF* aa_quad,
1485 const gfx::QuadF* clip_region,
1486 gfx::QuadF* local_quad,
1487 float edge[24]) {
1488 gfx::QuadF rotated_clip;
1489 const gfx::QuadF* local_clip_region = clip_region;
1490 if (local_clip_region) {
1491 rotated_clip = *clip_region;
1492 AlignQuadToBoundingBox(&rotated_clip);
1493 local_clip_region = &rotated_clip;
1496 if (!aa_quad) {
1497 if (local_clip_region)
1498 *local_quad = *local_clip_region;
1499 return;
1502 LayerQuad device_layer_edges(*aa_quad);
1503 InflateAntiAliasingDistances(*aa_quad, &device_layer_edges, edge);
1505 // If we have a clip region then we are split, and therefore
1506 // by necessity, at least one of our edges is not an external
1507 // one.
1508 bool is_full_rect = quad->visible_rect == quad->rect;
1510 bool region_contains_all_outside_edges =
1511 is_full_rect &&
1512 (is_top(local_clip_region, quad) && is_left(local_clip_region, quad) &&
1513 is_bottom(local_clip_region, quad) && is_right(local_clip_region, quad));
1515 bool use_aa_on_all_four_edges =
1516 !local_clip_region && region_contains_all_outside_edges;
1518 gfx::QuadF device_quad;
1519 if (use_aa_on_all_four_edges) {
1520 device_quad = device_layer_edges.ToQuadF();
1521 } else {
1522 gfx::QuadF tile_quad(local_clip_region ? *local_clip_region
1523 : gfx::QuadF(quad->visible_rect));
1524 device_quad = GetDeviceQuadWithAntialiasingOnExteriorEdges(
1525 device_layer_edges, device_transform, tile_quad, local_clip_region,
1526 quad);
1529 *local_quad = MapQuadToLocalSpace(device_transform, device_quad);
1532 // static
1533 void GLRenderer::SetupRenderPassQuadForClippingAndAntialiasing(
1534 const gfx::Transform& device_transform,
1535 const RenderPassDrawQuad* quad,
1536 const gfx::QuadF* aa_quad,
1537 const gfx::QuadF* clip_region,
1538 gfx::QuadF* local_quad,
1539 float edge[24]) {
1540 gfx::QuadF rotated_clip;
1541 const gfx::QuadF* local_clip_region = clip_region;
1542 if (local_clip_region) {
1543 rotated_clip = *clip_region;
1544 AlignQuadToBoundingBox(&rotated_clip);
1545 local_clip_region = &rotated_clip;
1548 if (!aa_quad) {
1549 GetScaledRegion(quad->rect, local_clip_region, local_quad);
1550 return;
1553 LayerQuad device_layer_edges(*aa_quad);
1554 InflateAntiAliasingDistances(*aa_quad, &device_layer_edges, edge);
1556 gfx::QuadF device_quad;
1558 // Apply anti-aliasing only to the edges that are not being clipped
1559 if (local_clip_region) {
1560 gfx::QuadF tile_quad(quad->visible_rect);
1561 GetScaledRegion(quad->rect, local_clip_region, &tile_quad);
1562 device_quad = GetDeviceQuadWithAntialiasingOnExteriorEdges(
1563 device_layer_edges, device_transform, tile_quad, local_clip_region,
1564 quad);
1565 } else {
1566 device_quad = device_layer_edges.ToQuadF();
1569 *local_quad = MapQuadToLocalSpace(device_transform, device_quad);
1572 void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1573 const SolidColorDrawQuad* quad,
1574 const gfx::QuadF* clip_region) {
1575 gfx::Rect tile_rect = quad->visible_rect;
1577 SkColor color = quad->color;
1578 float opacity = quad->shared_quad_state->opacity;
1579 float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1581 // Early out if alpha is small enough that quad doesn't contribute to output.
1582 if (alpha < std::numeric_limits<float>::epsilon() &&
1583 quad->ShouldDrawWithBlending())
1584 return;
1586 gfx::Transform device_transform =
1587 frame->window_matrix * frame->projection_matrix *
1588 quad->shared_quad_state->quad_to_target_transform;
1589 device_transform.FlattenTo2d();
1590 if (!device_transform.IsInvertible())
1591 return;
1593 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1595 gfx::QuadF device_layer_quad;
1596 bool use_aa = false;
1597 bool allow_aa = settings_->allow_antialiasing &&
1598 !quad->force_anti_aliasing_off && quad->IsEdge();
1600 if (allow_aa) {
1601 bool clipped = false;
1602 bool force_aa = false;
1603 device_layer_quad = MathUtil::MapQuad(
1604 device_transform,
1605 gfx::QuadF(quad->shared_quad_state->visible_quad_layer_rect), &clipped);
1606 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped, force_aa);
1609 float edge[24];
1610 const gfx::QuadF* aa_quad = use_aa ? &device_layer_quad : nullptr;
1611 SetupQuadForClippingAndAntialiasing(device_transform, quad, aa_quad,
1612 clip_region, &local_quad, edge);
1614 SolidColorProgramUniforms uniforms;
1615 if (use_aa) {
1616 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1617 } else {
1618 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1620 SetUseProgram(uniforms.program);
1622 gl_->Uniform4f(uniforms.color_location,
1623 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1624 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1625 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha, alpha);
1626 if (use_aa) {
1627 float viewport[4] = {
1628 static_cast<float>(current_window_space_viewport_.x()),
1629 static_cast<float>(current_window_space_viewport_.y()),
1630 static_cast<float>(current_window_space_viewport_.width()),
1631 static_cast<float>(current_window_space_viewport_.height()),
1633 gl_->Uniform4fv(uniforms.viewport_location, 1, viewport);
1634 gl_->Uniform3fv(uniforms.edge_location, 8, edge);
1637 // Enable blending when the quad properties require it or if we decided
1638 // to use antialiasing.
1639 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1641 // Antialising requires a normalized quad, but this could lead to floating
1642 // point precision errors, so only normalize when antialising is on.
1643 if (use_aa) {
1644 // Normalize to tile_rect.
1645 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1647 SetShaderQuadF(local_quad, uniforms.quad_location);
1649 // The transform and vertex data are used to figure out the extents that the
1650 // un-antialiased quad should have and which vertex this is and the float
1651 // quad passed in via uniform is the actual geometry that gets used to draw
1652 // it. This is why this centered rect is used and not the original
1653 // quad_rect.
1654 gfx::RectF centered_rect(
1655 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1656 tile_rect.size());
1657 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1658 centered_rect, uniforms.matrix_location);
1659 } else {
1660 PrepareGeometry(SHARED_BINDING);
1661 SetShaderQuadF(local_quad, uniforms.quad_location);
1662 static float gl_matrix[16];
1663 ToGLMatrix(&gl_matrix[0],
1664 frame->projection_matrix *
1665 quad->shared_quad_state->quad_to_target_transform);
1666 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]);
1668 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
1672 struct TileProgramUniforms {
1673 unsigned program;
1674 unsigned matrix_location;
1675 unsigned viewport_location;
1676 unsigned quad_location;
1677 unsigned edge_location;
1678 unsigned vertex_tex_transform_location;
1679 unsigned sampler_location;
1680 unsigned fragment_tex_transform_location;
1681 unsigned alpha_location;
1684 template <class T>
1685 static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1686 uniforms->program = program->program();
1687 uniforms->matrix_location = program->vertex_shader().matrix_location();
1688 uniforms->viewport_location = program->vertex_shader().viewport_location();
1689 uniforms->quad_location = program->vertex_shader().quad_location();
1690 uniforms->edge_location = program->vertex_shader().edge_location();
1691 uniforms->vertex_tex_transform_location =
1692 program->vertex_shader().vertex_tex_transform_location();
1694 uniforms->sampler_location = program->fragment_shader().sampler_location();
1695 uniforms->alpha_location = program->fragment_shader().alpha_location();
1696 uniforms->fragment_tex_transform_location =
1697 program->fragment_shader().fragment_tex_transform_location();
1700 void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1701 const TileDrawQuad* quad,
1702 const gfx::QuadF* clip_region) {
1703 DrawContentQuad(frame, quad, quad->resource_id(), clip_region);
1706 void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1707 const ContentDrawQuadBase* quad,
1708 ResourceId resource_id,
1709 const gfx::QuadF* clip_region) {
1710 gfx::Transform device_transform =
1711 frame->window_matrix * frame->projection_matrix *
1712 quad->shared_quad_state->quad_to_target_transform;
1713 device_transform.FlattenTo2d();
1715 gfx::QuadF device_layer_quad;
1716 bool use_aa = false;
1717 bool allow_aa = settings_->allow_antialiasing && quad->IsEdge();
1718 if (allow_aa) {
1719 bool clipped = false;
1720 bool force_aa = false;
1721 device_layer_quad = MathUtil::MapQuad(
1722 device_transform,
1723 gfx::QuadF(quad->shared_quad_state->visible_quad_layer_rect), &clipped);
1724 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped, force_aa);
1727 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1728 // similar to the way DrawContentQuadNoAA works and then consider
1729 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1730 if (use_aa)
1731 DrawContentQuadAA(frame, quad, resource_id, device_transform,
1732 device_layer_quad, clip_region);
1733 else
1734 DrawContentQuadNoAA(frame, quad, resource_id, clip_region);
1737 void GLRenderer::DrawContentQuadAA(const DrawingFrame* frame,
1738 const ContentDrawQuadBase* quad,
1739 ResourceId resource_id,
1740 const gfx::Transform& device_transform,
1741 const gfx::QuadF& aa_quad,
1742 const gfx::QuadF* clip_region) {
1743 if (!device_transform.IsInvertible())
1744 return;
1746 gfx::Rect tile_rect = quad->visible_rect;
1748 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1749 quad->tex_coord_rect, quad->rect, tile_rect);
1750 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1751 float tex_to_geom_scale_y =
1752 quad->rect.height() / quad->tex_coord_rect.height();
1754 gfx::RectF clamp_geom_rect(tile_rect);
1755 gfx::RectF clamp_tex_rect(tex_coord_rect);
1756 // Clamp texture coordinates to avoid sampling outside the layer
1757 // by deflating the tile region half a texel or half a texel
1758 // minus epsilon for one pixel layers. The resulting clamp region
1759 // is mapped to the unit square by the vertex shader and mapped
1760 // back to normalized texture coordinates by the fragment shader
1761 // after being clamped to 0-1 range.
1762 float tex_clamp_x =
1763 std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1764 float tex_clamp_y =
1765 std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1766 float geom_clamp_x =
1767 std::min(tex_clamp_x * tex_to_geom_scale_x,
1768 0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1769 float geom_clamp_y =
1770 std::min(tex_clamp_y * tex_to_geom_scale_y,
1771 0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1772 clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1773 clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1775 // Map clamping rectangle to unit square.
1776 float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1777 float vertex_tex_translate_y =
1778 -clamp_geom_rect.y() / clamp_geom_rect.height();
1779 float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1780 float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1782 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1783 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1785 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1786 float edge[24];
1787 SetupQuadForClippingAndAntialiasing(device_transform, quad, &aa_quad,
1788 clip_region, &local_quad, edge);
1789 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1790 resource_provider_, resource_id,
1791 quad->nearest_neighbor ? GL_NEAREST : GL_LINEAR);
1792 SamplerType sampler =
1793 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1795 float fragment_tex_translate_x = clamp_tex_rect.x();
1796 float fragment_tex_translate_y = clamp_tex_rect.y();
1797 float fragment_tex_scale_x = clamp_tex_rect.width();
1798 float fragment_tex_scale_y = clamp_tex_rect.height();
1800 // Map to normalized texture coordinates.
1801 if (sampler != SAMPLER_TYPE_2D_RECT) {
1802 gfx::Size texture_size = quad->texture_size;
1803 DCHECK(!texture_size.IsEmpty());
1804 fragment_tex_translate_x /= texture_size.width();
1805 fragment_tex_translate_y /= texture_size.height();
1806 fragment_tex_scale_x /= texture_size.width();
1807 fragment_tex_scale_y /= texture_size.height();
1810 TileProgramUniforms uniforms;
1811 if (quad->swizzle_contents) {
1812 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1813 &uniforms);
1814 } else {
1815 TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1816 &uniforms);
1819 SetUseProgram(uniforms.program);
1820 gl_->Uniform1i(uniforms.sampler_location, 0);
1822 float viewport[4] = {
1823 static_cast<float>(current_window_space_viewport_.x()),
1824 static_cast<float>(current_window_space_viewport_.y()),
1825 static_cast<float>(current_window_space_viewport_.width()),
1826 static_cast<float>(current_window_space_viewport_.height()),
1828 gl_->Uniform4fv(uniforms.viewport_location, 1, viewport);
1829 gl_->Uniform3fv(uniforms.edge_location, 8, edge);
1831 gl_->Uniform4f(uniforms.vertex_tex_transform_location, vertex_tex_translate_x,
1832 vertex_tex_translate_y, vertex_tex_scale_x,
1833 vertex_tex_scale_y);
1834 gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1835 fragment_tex_translate_x, fragment_tex_translate_y,
1836 fragment_tex_scale_x, fragment_tex_scale_y);
1838 // Blending is required for antialiasing.
1839 SetBlendEnabled(true);
1841 // Normalize to tile_rect.
1842 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1844 SetShaderOpacity(quad->shared_quad_state->opacity, uniforms.alpha_location);
1845 SetShaderQuadF(local_quad, uniforms.quad_location);
1847 // The transform and vertex data are used to figure out the extents that the
1848 // un-antialiased quad should have and which vertex this is and the float
1849 // quad passed in via uniform is the actual geometry that gets used to draw
1850 // it. This is why this centered rect is used and not the original quad_rect.
1851 gfx::RectF centered_rect(
1852 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1853 tile_rect.size());
1854 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1855 centered_rect, uniforms.matrix_location);
1858 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame* frame,
1859 const ContentDrawQuadBase* quad,
1860 ResourceId resource_id,
1861 const gfx::QuadF* clip_region) {
1862 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1863 quad->tex_coord_rect, quad->rect, quad->visible_rect);
1864 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1865 float tex_to_geom_scale_y =
1866 quad->rect.height() / quad->tex_coord_rect.height();
1868 bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1869 GLenum filter = (scaled ||
1870 !quad->shared_quad_state->quad_to_target_transform
1871 .IsIdentityOrIntegerTranslation()) &&
1872 !quad->nearest_neighbor
1873 ? GL_LINEAR
1874 : GL_NEAREST;
1876 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1877 resource_provider_, resource_id, filter);
1878 SamplerType sampler =
1879 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1881 float vertex_tex_translate_x = tex_coord_rect.x();
1882 float vertex_tex_translate_y = tex_coord_rect.y();
1883 float vertex_tex_scale_x = tex_coord_rect.width();
1884 float vertex_tex_scale_y = tex_coord_rect.height();
1886 // Map to normalized texture coordinates.
1887 if (sampler != SAMPLER_TYPE_2D_RECT) {
1888 gfx::Size texture_size = quad->texture_size;
1889 DCHECK(!texture_size.IsEmpty());
1890 vertex_tex_translate_x /= texture_size.width();
1891 vertex_tex_translate_y /= texture_size.height();
1892 vertex_tex_scale_x /= texture_size.width();
1893 vertex_tex_scale_y /= texture_size.height();
1896 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1897 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1899 TileProgramUniforms uniforms;
1900 if (quad->ShouldDrawWithBlending()) {
1901 if (quad->swizzle_contents) {
1902 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1903 &uniforms);
1904 } else {
1905 TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1906 &uniforms);
1908 } else {
1909 if (quad->swizzle_contents) {
1910 TileUniformLocation(
1911 GetTileProgramSwizzleOpaque(tex_coord_precision, sampler), &uniforms);
1912 } else {
1913 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1914 &uniforms);
1918 SetUseProgram(uniforms.program);
1919 gl_->Uniform1i(uniforms.sampler_location, 0);
1921 gl_->Uniform4f(uniforms.vertex_tex_transform_location, vertex_tex_translate_x,
1922 vertex_tex_translate_y, vertex_tex_scale_x,
1923 vertex_tex_scale_y);
1925 SetBlendEnabled(quad->ShouldDrawWithBlending());
1927 SetShaderOpacity(quad->shared_quad_state->opacity, uniforms.alpha_location);
1929 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1930 // does, then vertices will match the texture mapping in the vertex buffer.
1931 // The method SetShaderQuadF() changes the order of vertices and so it's
1932 // not used here.
1933 gfx::QuadF tile_rect(quad->visible_rect);
1934 float width = quad->visible_rect.width();
1935 float height = quad->visible_rect.height();
1936 gfx::PointF top_left = quad->visible_rect.origin();
1937 if (clip_region) {
1938 tile_rect = *clip_region;
1939 float gl_uv[8] = {
1940 (tile_rect.p4().x() - top_left.x()) / width,
1941 (tile_rect.p4().y() - top_left.y()) / height,
1942 (tile_rect.p1().x() - top_left.x()) / width,
1943 (tile_rect.p1().y() - top_left.y()) / height,
1944 (tile_rect.p2().x() - top_left.x()) / width,
1945 (tile_rect.p2().y() - top_left.y()) / height,
1946 (tile_rect.p3().x() - top_left.x()) / width,
1947 (tile_rect.p3().y() - top_left.y()) / height,
1949 PrepareGeometry(CLIPPED_BINDING);
1950 clipped_geometry_->InitializeCustomQuadWithUVs(
1951 gfx::QuadF(quad->visible_rect), gl_uv);
1952 } else {
1953 PrepareGeometry(SHARED_BINDING);
1955 float gl_quad[8] = {
1956 tile_rect.p4().x(),
1957 tile_rect.p4().y(),
1958 tile_rect.p1().x(),
1959 tile_rect.p1().y(),
1960 tile_rect.p2().x(),
1961 tile_rect.p2().y(),
1962 tile_rect.p3().x(),
1963 tile_rect.p3().y(),
1965 gl_->Uniform2fv(uniforms.quad_location, 4, gl_quad);
1967 static float gl_matrix[16];
1968 ToGLMatrix(&gl_matrix[0],
1969 frame->projection_matrix *
1970 quad->shared_quad_state->quad_to_target_transform);
1971 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]);
1973 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
1976 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1977 const YUVVideoDrawQuad* quad,
1978 const gfx::QuadF* clip_region) {
1979 SetBlendEnabled(quad->ShouldDrawWithBlending());
1981 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1982 gl_, &highp_threshold_cache_, highp_threshold_min_,
1983 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
1985 bool use_alpha_plane = quad->a_plane_resource_id() != 0;
1987 ResourceProvider::ScopedSamplerGL y_plane_lock(
1988 resource_provider_, quad->y_plane_resource_id(), GL_TEXTURE1, GL_LINEAR);
1989 ResourceProvider::ScopedSamplerGL u_plane_lock(
1990 resource_provider_, quad->u_plane_resource_id(), GL_TEXTURE2, GL_LINEAR);
1991 DCHECK_EQ(y_plane_lock.target(), u_plane_lock.target());
1992 ResourceProvider::ScopedSamplerGL v_plane_lock(
1993 resource_provider_, quad->v_plane_resource_id(), GL_TEXTURE3, GL_LINEAR);
1994 DCHECK_EQ(y_plane_lock.target(), v_plane_lock.target());
1995 scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1996 if (use_alpha_plane) {
1997 a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1998 resource_provider_, quad->a_plane_resource_id(), GL_TEXTURE4,
1999 GL_LINEAR));
2000 DCHECK_EQ(y_plane_lock.target(), a_plane_lock->target());
2003 // All planes must have the same sampler type.
2004 SamplerType sampler = SamplerTypeFromTextureTarget(y_plane_lock.target());
2006 int matrix_location = -1;
2007 int ya_tex_scale_location = -1;
2008 int ya_tex_offset_location = -1;
2009 int uv_tex_scale_location = -1;
2010 int uv_tex_offset_location = -1;
2011 int ya_clamp_rect_location = -1;
2012 int uv_clamp_rect_location = -1;
2013 int y_texture_location = -1;
2014 int u_texture_location = -1;
2015 int v_texture_location = -1;
2016 int a_texture_location = -1;
2017 int yuv_matrix_location = -1;
2018 int yuv_adj_location = -1;
2019 int alpha_location = -1;
2020 if (use_alpha_plane) {
2021 const VideoYUVAProgram* program =
2022 GetVideoYUVAProgram(tex_coord_precision, sampler);
2023 DCHECK(program && (program->initialized() || IsContextLost()));
2024 SetUseProgram(program->program());
2025 matrix_location = program->vertex_shader().matrix_location();
2026 ya_tex_scale_location = program->vertex_shader().ya_tex_scale_location();
2027 ya_tex_offset_location = program->vertex_shader().ya_tex_offset_location();
2028 uv_tex_scale_location = program->vertex_shader().uv_tex_scale_location();
2029 uv_tex_offset_location = program->vertex_shader().uv_tex_offset_location();
2030 y_texture_location = program->fragment_shader().y_texture_location();
2031 u_texture_location = program->fragment_shader().u_texture_location();
2032 v_texture_location = program->fragment_shader().v_texture_location();
2033 a_texture_location = program->fragment_shader().a_texture_location();
2034 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
2035 yuv_adj_location = program->fragment_shader().yuv_adj_location();
2036 ya_clamp_rect_location =
2037 program->fragment_shader().ya_clamp_rect_location();
2038 uv_clamp_rect_location =
2039 program->fragment_shader().uv_clamp_rect_location();
2040 alpha_location = program->fragment_shader().alpha_location();
2041 } else {
2042 const VideoYUVProgram* program =
2043 GetVideoYUVProgram(tex_coord_precision, sampler);
2044 DCHECK(program && (program->initialized() || IsContextLost()));
2045 SetUseProgram(program->program());
2046 matrix_location = program->vertex_shader().matrix_location();
2047 ya_tex_scale_location = program->vertex_shader().ya_tex_scale_location();
2048 ya_tex_offset_location = program->vertex_shader().ya_tex_offset_location();
2049 uv_tex_scale_location = program->vertex_shader().uv_tex_scale_location();
2050 uv_tex_offset_location = program->vertex_shader().uv_tex_offset_location();
2051 y_texture_location = program->fragment_shader().y_texture_location();
2052 u_texture_location = program->fragment_shader().u_texture_location();
2053 v_texture_location = program->fragment_shader().v_texture_location();
2054 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
2055 yuv_adj_location = program->fragment_shader().yuv_adj_location();
2056 ya_clamp_rect_location =
2057 program->fragment_shader().ya_clamp_rect_location();
2058 uv_clamp_rect_location =
2059 program->fragment_shader().uv_clamp_rect_location();
2060 alpha_location = program->fragment_shader().alpha_location();
2063 gfx::SizeF ya_tex_scale(1.0f, 1.0f);
2064 gfx::SizeF uv_tex_scale(1.0f, 1.0f);
2065 if (sampler != SAMPLER_TYPE_2D_RECT) {
2066 DCHECK(!quad->ya_tex_size.IsEmpty());
2067 DCHECK(!quad->uv_tex_size.IsEmpty());
2068 ya_tex_scale = gfx::SizeF(1.0f / quad->ya_tex_size.width(),
2069 1.0f / quad->ya_tex_size.height());
2070 uv_tex_scale = gfx::SizeF(1.0f / quad->uv_tex_size.width(),
2071 1.0f / quad->uv_tex_size.height());
2074 float ya_vertex_tex_translate_x =
2075 quad->ya_tex_coord_rect.x() * ya_tex_scale.width();
2076 float ya_vertex_tex_translate_y =
2077 quad->ya_tex_coord_rect.y() * ya_tex_scale.height();
2078 float ya_vertex_tex_scale_x =
2079 quad->ya_tex_coord_rect.width() * ya_tex_scale.width();
2080 float ya_vertex_tex_scale_y =
2081 quad->ya_tex_coord_rect.height() * ya_tex_scale.height();
2083 float uv_vertex_tex_translate_x =
2084 quad->uv_tex_coord_rect.x() * uv_tex_scale.width();
2085 float uv_vertex_tex_translate_y =
2086 quad->uv_tex_coord_rect.y() * uv_tex_scale.height();
2087 float uv_vertex_tex_scale_x =
2088 quad->uv_tex_coord_rect.width() * uv_tex_scale.width();
2089 float uv_vertex_tex_scale_y =
2090 quad->uv_tex_coord_rect.height() * uv_tex_scale.height();
2092 gl_->Uniform2f(ya_tex_scale_location, ya_vertex_tex_scale_x,
2093 ya_vertex_tex_scale_y);
2094 gl_->Uniform2f(ya_tex_offset_location, ya_vertex_tex_translate_x,
2095 ya_vertex_tex_translate_y);
2096 gl_->Uniform2f(uv_tex_scale_location, uv_vertex_tex_scale_x,
2097 uv_vertex_tex_scale_y);
2098 gl_->Uniform2f(uv_tex_offset_location, uv_vertex_tex_translate_x,
2099 uv_vertex_tex_translate_y);
2101 gfx::RectF ya_clamp_rect(ya_vertex_tex_translate_x, ya_vertex_tex_translate_y,
2102 ya_vertex_tex_scale_x, ya_vertex_tex_scale_y);
2103 ya_clamp_rect.Inset(0.5f * ya_tex_scale.width(),
2104 0.5f * ya_tex_scale.height());
2105 gfx::RectF uv_clamp_rect(uv_vertex_tex_translate_x, uv_vertex_tex_translate_y,
2106 uv_vertex_tex_scale_x, uv_vertex_tex_scale_y);
2107 uv_clamp_rect.Inset(0.5f * uv_tex_scale.width(),
2108 0.5f * uv_tex_scale.height());
2109 gl_->Uniform4f(ya_clamp_rect_location, ya_clamp_rect.x(), ya_clamp_rect.y(),
2110 ya_clamp_rect.right(), ya_clamp_rect.bottom());
2111 gl_->Uniform4f(uv_clamp_rect_location, uv_clamp_rect.x(), uv_clamp_rect.y(),
2112 uv_clamp_rect.right(), uv_clamp_rect.bottom());
2114 gl_->Uniform1i(y_texture_location, 1);
2115 gl_->Uniform1i(u_texture_location, 2);
2116 gl_->Uniform1i(v_texture_location, 3);
2117 if (use_alpha_plane)
2118 gl_->Uniform1i(a_texture_location, 4);
2120 // These values are magic numbers that are used in the transformation from YUV
2121 // to RGB color values. They are taken from the following webpage:
2122 // http://www.fourcc.org/fccyvrgb.php
2123 float yuv_to_rgb_rec601[9] = {
2124 1.164f, 1.164f, 1.164f, 0.0f, -.391f, 2.018f, 1.596f, -.813f, 0.0f,
2126 float yuv_to_rgb_jpeg[9] = {
2127 1.f, 1.f, 1.f, 0.0f, -.34414f, 1.772f, 1.402f, -.71414f, 0.0f,
2129 float yuv_to_rgb_rec709[9] = {
2130 1.164f, 1.164f, 1.164f, 0.0f, -0.213f, 2.112f, 1.793f, -0.533f, 0.0f,
2133 // These values map to 16, 128, and 128 respectively, and are computed
2134 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
2135 // They are used in the YUV to RGBA conversion formula:
2136 // Y - 16 : Gives 16 values of head and footroom for overshooting
2137 // U - 128 : Turns unsigned U into signed U [-128,127]
2138 // V - 128 : Turns unsigned V into signed V [-128,127]
2139 float yuv_adjust_constrained[3] = {
2140 -0.0625f, -0.5f, -0.5f,
2143 // Same as above, but without the head and footroom.
2144 float yuv_adjust_full[3] = {
2145 0.0f, -0.5f, -0.5f,
2148 float* yuv_to_rgb = NULL;
2149 float* yuv_adjust = NULL;
2151 switch (quad->color_space) {
2152 case YUVVideoDrawQuad::REC_601:
2153 yuv_to_rgb = yuv_to_rgb_rec601;
2154 yuv_adjust = yuv_adjust_constrained;
2155 break;
2156 case YUVVideoDrawQuad::REC_709:
2157 yuv_to_rgb = yuv_to_rgb_rec709;
2158 yuv_adjust = yuv_adjust_constrained;
2159 break;
2160 case YUVVideoDrawQuad::JPEG:
2161 yuv_to_rgb = yuv_to_rgb_jpeg;
2162 yuv_adjust = yuv_adjust_full;
2163 break;
2166 // The transform and vertex data are used to figure out the extents that the
2167 // un-antialiased quad should have and which vertex this is and the float
2168 // quad passed in via uniform is the actual geometry that gets used to draw
2169 // it. This is why this centered rect is used and not the original quad_rect.
2170 gfx::RectF tile_rect = quad->rect;
2171 gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb);
2172 gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust);
2174 SetShaderOpacity(quad->shared_quad_state->opacity, alpha_location);
2175 if (!clip_region) {
2176 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2177 tile_rect, matrix_location);
2178 } else {
2179 float uvs[8] = {0};
2180 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2181 gfx::QuadF region_quad = *clip_region;
2182 region_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
2183 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2184 DrawQuadGeometryClippedByQuadF(
2185 frame, quad->shared_quad_state->quad_to_target_transform, tile_rect,
2186 region_quad, matrix_location, uvs);
2190 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
2191 const StreamVideoDrawQuad* quad,
2192 const gfx::QuadF* clip_region) {
2193 SetBlendEnabled(quad->ShouldDrawWithBlending());
2195 static float gl_matrix[16];
2197 DCHECK(capabilities_.using_egl_image);
2199 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2200 gl_, &highp_threshold_cache_, highp_threshold_min_,
2201 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2203 const VideoStreamTextureProgram* program =
2204 GetVideoStreamTextureProgram(tex_coord_precision);
2205 SetUseProgram(program->program());
2207 ToGLMatrix(&gl_matrix[0], quad->matrix);
2208 gl_->UniformMatrix4fv(program->vertex_shader().tex_matrix_location(), 1,
2209 false, gl_matrix);
2211 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2212 quad->resource_id());
2213 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2214 gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id());
2216 gl_->Uniform1i(program->fragment_shader().sampler_location(), 0);
2218 SetShaderOpacity(quad->shared_quad_state->opacity,
2219 program->fragment_shader().alpha_location());
2220 if (!clip_region) {
2221 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2222 quad->rect, program->vertex_shader().matrix_location());
2223 } else {
2224 gfx::QuadF region_quad(*clip_region);
2225 region_quad.Scale(1.0f / quad->rect.width(), 1.0f / quad->rect.height());
2226 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2227 float uvs[8] = {0};
2228 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2229 DrawQuadGeometryClippedByQuadF(
2230 frame, quad->shared_quad_state->quad_to_target_transform, quad->rect,
2231 region_quad, program->vertex_shader().matrix_location(), uvs);
2235 struct TextureProgramBinding {
2236 template <class Program>
2237 void Set(Program* program) {
2238 DCHECK(program);
2239 program_id = program->program();
2240 sampler_location = program->fragment_shader().sampler_location();
2241 matrix_location = program->vertex_shader().matrix_location();
2242 background_color_location =
2243 program->fragment_shader().background_color_location();
2245 int program_id;
2246 int sampler_location;
2247 int matrix_location;
2248 int transform_location;
2249 int background_color_location;
2252 struct TexTransformTextureProgramBinding : TextureProgramBinding {
2253 template <class Program>
2254 void Set(Program* program) {
2255 TextureProgramBinding::Set(program);
2256 tex_transform_location = program->vertex_shader().tex_transform_location();
2257 vertex_opacity_location =
2258 program->vertex_shader().vertex_opacity_location();
2260 int tex_transform_location;
2261 int vertex_opacity_location;
2264 void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding) {
2265 // Check to see if we have anything to draw.
2266 if (draw_cache_.program_id == -1)
2267 return;
2269 PrepareGeometry(flush_binding);
2271 // Set the correct blending mode.
2272 SetBlendEnabled(draw_cache_.needs_blending);
2274 // Bind the program to the GL state.
2275 SetUseProgram(draw_cache_.program_id);
2277 // Bind the correct texture sampler location.
2278 gl_->Uniform1i(draw_cache_.sampler_location, 0);
2280 // Assume the current active textures is 0.
2281 ResourceProvider::ScopedSamplerGL locked_quad(
2282 resource_provider_,
2283 draw_cache_.resource_id,
2284 draw_cache_.nearest_neighbor ? GL_NEAREST : GL_LINEAR);
2285 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2286 gl_->BindTexture(locked_quad.target(), locked_quad.texture_id());
2288 static_assert(sizeof(Float4) == 4 * sizeof(float),
2289 "Float4 struct should be densely packed");
2290 static_assert(sizeof(Float16) == 16 * sizeof(float),
2291 "Float16 struct should be densely packed");
2293 // Upload the tranforms for both points and uvs.
2294 gl_->UniformMatrix4fv(
2295 static_cast<int>(draw_cache_.matrix_location),
2296 static_cast<int>(draw_cache_.matrix_data.size()), false,
2297 reinterpret_cast<float*>(&draw_cache_.matrix_data.front()));
2298 gl_->Uniform4fv(static_cast<int>(draw_cache_.uv_xform_location),
2299 static_cast<int>(draw_cache_.uv_xform_data.size()),
2300 reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front()));
2302 if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
2303 Float4 background_color = PremultipliedColor(draw_cache_.background_color);
2304 gl_->Uniform4fv(draw_cache_.background_color_location, 1,
2305 background_color.data);
2308 gl_->Uniform1fv(
2309 static_cast<int>(draw_cache_.vertex_opacity_location),
2310 static_cast<int>(draw_cache_.vertex_opacity_data.size()),
2311 static_cast<float*>(&draw_cache_.vertex_opacity_data.front()));
2313 DCHECK_LE(draw_cache_.matrix_data.size(),
2314 static_cast<size_t>(std::numeric_limits<int>::max()) / 6u);
2315 // Draw the quads!
2316 gl_->DrawElements(GL_TRIANGLES,
2317 6 * static_cast<int>(draw_cache_.matrix_data.size()),
2318 GL_UNSIGNED_SHORT, 0);
2320 // Clear the cache.
2321 draw_cache_.program_id = -1;
2322 draw_cache_.uv_xform_data.resize(0);
2323 draw_cache_.vertex_opacity_data.resize(0);
2324 draw_cache_.matrix_data.resize(0);
2326 // If we had a clipped binding, prepare the shared binding for the
2327 // next inserts.
2328 if (flush_binding == CLIPPED_BINDING) {
2329 PrepareGeometry(SHARED_BINDING);
2333 void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
2334 const TextureDrawQuad* quad,
2335 const gfx::QuadF* clip_region) {
2336 // If we have a clip_region then we have to render the next quad
2337 // with dynamic geometry, therefore we must flush all pending
2338 // texture quads.
2339 if (clip_region) {
2340 // We send in false here because we want to flush what's currently in the
2341 // queue using the shared_geometry and not clipped_geometry
2342 FlushTextureQuadCache(SHARED_BINDING);
2345 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2346 gl_, &highp_threshold_cache_, highp_threshold_min_,
2347 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2349 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2350 quad->resource_id());
2351 const SamplerType sampler = SamplerTypeFromTextureTarget(lock.target());
2352 // Choose the correct texture program binding
2353 TexTransformTextureProgramBinding binding;
2354 if (quad->premultiplied_alpha) {
2355 if (quad->background_color == SK_ColorTRANSPARENT) {
2356 binding.Set(GetTextureProgram(tex_coord_precision, sampler));
2357 } else {
2358 binding.Set(GetTextureBackgroundProgram(tex_coord_precision, sampler));
2360 } else {
2361 if (quad->background_color == SK_ColorTRANSPARENT) {
2362 binding.Set(
2363 GetNonPremultipliedTextureProgram(tex_coord_precision, sampler));
2364 } else {
2365 binding.Set(GetNonPremultipliedTextureBackgroundProgram(
2366 tex_coord_precision, sampler));
2370 int resource_id = quad->resource_id();
2372 if (draw_cache_.program_id != binding.program_id ||
2373 draw_cache_.resource_id != resource_id ||
2374 draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
2375 draw_cache_.nearest_neighbor != quad->nearest_neighbor ||
2376 draw_cache_.background_color != quad->background_color ||
2377 draw_cache_.matrix_data.size() >= 8) {
2378 FlushTextureQuadCache(SHARED_BINDING);
2379 draw_cache_.program_id = binding.program_id;
2380 draw_cache_.resource_id = resource_id;
2381 draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
2382 draw_cache_.nearest_neighbor = quad->nearest_neighbor;
2383 draw_cache_.background_color = quad->background_color;
2385 draw_cache_.uv_xform_location = binding.tex_transform_location;
2386 draw_cache_.background_color_location = binding.background_color_location;
2387 draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
2388 draw_cache_.matrix_location = binding.matrix_location;
2389 draw_cache_.sampler_location = binding.sampler_location;
2392 // Generate the uv-transform
2393 if (!clip_region) {
2394 draw_cache_.uv_xform_data.push_back(UVTransform(quad));
2395 } else {
2396 Float4 uv_transform = {{0.0f, 0.0f, 1.0f, 1.0f}};
2397 draw_cache_.uv_xform_data.push_back(uv_transform);
2400 // Generate the vertex opacity
2401 const float opacity = quad->shared_quad_state->opacity;
2402 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
2403 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
2404 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
2405 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
2407 // Generate the transform matrix
2408 gfx::Transform quad_rect_matrix;
2409 QuadRectTransform(&quad_rect_matrix,
2410 quad->shared_quad_state->quad_to_target_transform,
2411 quad->rect);
2412 quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
2414 Float16 m;
2415 quad_rect_matrix.matrix().asColMajorf(m.data);
2416 draw_cache_.matrix_data.push_back(m);
2418 if (clip_region) {
2419 gfx::QuadF scaled_region;
2420 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
2421 scaled_region = SharedGeometryQuad().BoundingBox();
2423 // Both the scaled region and the SharedGeomtryQuad are in the space
2424 // -0.5->0.5. We need to move that to the space 0->1.
2425 float uv[8];
2426 uv[0] = scaled_region.p1().x() + 0.5f;
2427 uv[1] = scaled_region.p1().y() + 0.5f;
2428 uv[2] = scaled_region.p2().x() + 0.5f;
2429 uv[3] = scaled_region.p2().y() + 0.5f;
2430 uv[4] = scaled_region.p3().x() + 0.5f;
2431 uv[5] = scaled_region.p3().y() + 0.5f;
2432 uv[6] = scaled_region.p4().x() + 0.5f;
2433 uv[7] = scaled_region.p4().y() + 0.5f;
2434 PrepareGeometry(CLIPPED_BINDING);
2435 clipped_geometry_->InitializeCustomQuadWithUVs(scaled_region, uv);
2436 FlushTextureQuadCache(CLIPPED_BINDING);
2440 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
2441 const IOSurfaceDrawQuad* quad,
2442 const gfx::QuadF* clip_region) {
2443 SetBlendEnabled(quad->ShouldDrawWithBlending());
2445 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2446 gl_, &highp_threshold_cache_, highp_threshold_min_,
2447 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2449 TexTransformTextureProgramBinding binding;
2450 binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
2452 SetUseProgram(binding.program_id);
2453 gl_->Uniform1i(binding.sampler_location, 0);
2454 if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
2455 gl_->Uniform4f(
2456 binding.tex_transform_location, 0, quad->io_surface_size.height(),
2457 quad->io_surface_size.width(), quad->io_surface_size.height() * -1.0f);
2458 } else {
2459 gl_->Uniform4f(binding.tex_transform_location, 0, 0,
2460 quad->io_surface_size.width(),
2461 quad->io_surface_size.height());
2464 const float vertex_opacity[] = {quad->shared_quad_state->opacity,
2465 quad->shared_quad_state->opacity,
2466 quad->shared_quad_state->opacity,
2467 quad->shared_quad_state->opacity};
2468 gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity);
2470 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2471 quad->io_surface_resource_id());
2472 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2473 gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id());
2475 if (!clip_region) {
2476 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2477 quad->rect, binding.matrix_location);
2478 } else {
2479 float uvs[8] = {0};
2480 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2481 DrawQuadGeometryClippedByQuadF(
2482 frame, quad->shared_quad_state->quad_to_target_transform, quad->rect,
2483 *clip_region, binding.matrix_location, uvs);
2486 gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
2489 void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
2490 if (use_sync_query_) {
2491 DCHECK(current_sync_query_);
2492 current_sync_query_->End();
2493 pending_sync_queries_.push_back(current_sync_query_.Pass());
2496 current_framebuffer_lock_ = nullptr;
2497 swap_buffer_rect_.Union(gfx::ToEnclosingRect(frame->root_damage_rect));
2499 gl_->Disable(GL_BLEND);
2500 blend_shadow_ = false;
2502 ScheduleOverlays(frame);
2505 void GLRenderer::FinishDrawingQuadList() {
2506 FlushTextureQuadCache(SHARED_BINDING);
2509 bool GLRenderer::FlippedFramebuffer(const DrawingFrame* frame) const {
2510 if (frame->current_render_pass != frame->root_render_pass)
2511 return true;
2512 return FlippedRootFramebuffer();
2515 bool GLRenderer::FlippedRootFramebuffer() const {
2516 // GL is normally flipped, so a flipped output results in an unflipping.
2517 return !output_surface_->capabilities().flipped_output_surface;
2520 void GLRenderer::EnsureScissorTestEnabled() {
2521 if (is_scissor_enabled_)
2522 return;
2524 FlushTextureQuadCache(SHARED_BINDING);
2525 gl_->Enable(GL_SCISSOR_TEST);
2526 is_scissor_enabled_ = true;
2529 void GLRenderer::EnsureScissorTestDisabled() {
2530 if (!is_scissor_enabled_)
2531 return;
2533 FlushTextureQuadCache(SHARED_BINDING);
2534 gl_->Disable(GL_SCISSOR_TEST);
2535 is_scissor_enabled_ = false;
2538 void GLRenderer::CopyCurrentRenderPassToBitmap(
2539 DrawingFrame* frame,
2540 scoped_ptr<CopyOutputRequest> request) {
2541 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2542 gfx::Rect copy_rect = frame->current_render_pass->output_rect;
2543 if (request->has_area())
2544 copy_rect.Intersect(request->area());
2545 GetFramebufferPixelsAsync(frame, copy_rect, request.Pass());
2548 void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
2549 transform.matrix().asColMajorf(gl_matrix);
2552 void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
2553 if (quad_location == -1)
2554 return;
2556 float gl_quad[8];
2557 gl_quad[0] = quad.p1().x();
2558 gl_quad[1] = quad.p1().y();
2559 gl_quad[2] = quad.p2().x();
2560 gl_quad[3] = quad.p2().y();
2561 gl_quad[4] = quad.p3().x();
2562 gl_quad[5] = quad.p3().y();
2563 gl_quad[6] = quad.p4().x();
2564 gl_quad[7] = quad.p4().y();
2565 gl_->Uniform2fv(quad_location, 4, gl_quad);
2568 void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2569 if (alpha_location != -1)
2570 gl_->Uniform1f(alpha_location, opacity);
2573 void GLRenderer::SetStencilEnabled(bool enabled) {
2574 if (enabled == stencil_shadow_)
2575 return;
2577 if (enabled)
2578 gl_->Enable(GL_STENCIL_TEST);
2579 else
2580 gl_->Disable(GL_STENCIL_TEST);
2581 stencil_shadow_ = enabled;
2584 void GLRenderer::SetBlendEnabled(bool enabled) {
2585 if (enabled == blend_shadow_)
2586 return;
2588 if (enabled)
2589 gl_->Enable(GL_BLEND);
2590 else
2591 gl_->Disable(GL_BLEND);
2592 blend_shadow_ = enabled;
2595 void GLRenderer::SetUseProgram(unsigned program) {
2596 if (program == program_shadow_)
2597 return;
2598 gl_->UseProgram(program);
2599 program_shadow_ = program;
2602 void GLRenderer::DrawQuadGeometryClippedByQuadF(
2603 const DrawingFrame* frame,
2604 const gfx::Transform& draw_transform,
2605 const gfx::RectF& quad_rect,
2606 const gfx::QuadF& clipping_region_quad,
2607 int matrix_location,
2608 const float* uvs) {
2609 PrepareGeometry(CLIPPED_BINDING);
2610 if (uvs) {
2611 clipped_geometry_->InitializeCustomQuadWithUVs(clipping_region_quad, uvs);
2612 } else {
2613 clipped_geometry_->InitializeCustomQuad(clipping_region_quad);
2615 gfx::Transform quad_rect_matrix;
2616 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2617 static float gl_matrix[16];
2618 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2619 gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]);
2621 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,
2622 reinterpret_cast<const void*>(0));
2625 void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2626 const gfx::Transform& draw_transform,
2627 const gfx::RectF& quad_rect,
2628 int matrix_location) {
2629 PrepareGeometry(SHARED_BINDING);
2630 gfx::Transform quad_rect_matrix;
2631 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2632 static float gl_matrix[16];
2633 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2634 gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]);
2636 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
2639 void GLRenderer::Finish() {
2640 TRACE_EVENT0("cc", "GLRenderer::Finish");
2641 gl_->Finish();
2644 void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2645 DCHECK(!is_backbuffer_discarded_);
2647 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2648 // We're done! Time to swapbuffers!
2650 gfx::Size surface_size = output_surface_->SurfaceSize();
2652 CompositorFrame compositor_frame;
2653 compositor_frame.metadata = metadata;
2654 compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2655 compositor_frame.gl_frame_data->size = surface_size;
2656 if (capabilities_.using_partial_swap) {
2657 // If supported, we can save significant bandwidth by only swapping the
2658 // damaged/scissored region (clamped to the viewport).
2659 swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2660 int flipped_y_pos_of_rect_bottom = surface_size.height() -
2661 swap_buffer_rect_.y() -
2662 swap_buffer_rect_.height();
2663 compositor_frame.gl_frame_data->sub_buffer_rect =
2664 gfx::Rect(swap_buffer_rect_.x(),
2665 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2666 : swap_buffer_rect_.y(),
2667 swap_buffer_rect_.width(),
2668 swap_buffer_rect_.height());
2669 } else {
2670 compositor_frame.gl_frame_data->sub_buffer_rect =
2671 gfx::Rect(output_surface_->SurfaceSize());
2673 output_surface_->SwapBuffers(&compositor_frame);
2675 // Release previously used overlay resources and hold onto the pending ones
2676 // until the next swap buffers.
2677 in_use_overlay_resources_.clear();
2678 in_use_overlay_resources_.swap(pending_overlay_resources_);
2680 swap_buffer_rect_ = gfx::Rect();
2683 void GLRenderer::EnforceMemoryPolicy() {
2684 if (!visible()) {
2685 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2686 ReleaseRenderPassTextures();
2687 DiscardBackbuffer();
2688 output_surface_->context_provider()->DeleteCachedResources();
2689 gl_->Flush();
2691 PrepareGeometry(NO_BINDING);
2694 void GLRenderer::DiscardBackbuffer() {
2695 if (is_backbuffer_discarded_)
2696 return;
2698 output_surface_->DiscardBackbuffer();
2700 is_backbuffer_discarded_ = true;
2702 // Damage tracker needs a full reset every time framebuffer is discarded.
2703 client_->SetFullRootLayerDamage();
2706 void GLRenderer::EnsureBackbuffer() {
2707 if (!is_backbuffer_discarded_)
2708 return;
2710 output_surface_->EnsureBackbuffer();
2711 is_backbuffer_discarded_ = false;
2714 void GLRenderer::GetFramebufferPixelsAsync(
2715 const DrawingFrame* frame,
2716 const gfx::Rect& rect,
2717 scoped_ptr<CopyOutputRequest> request) {
2718 DCHECK(!request->IsEmpty());
2719 if (request->IsEmpty())
2720 return;
2721 if (rect.IsEmpty())
2722 return;
2724 gfx::Rect window_rect = MoveFromDrawToWindowSpace(frame, rect);
2725 DCHECK_GE(window_rect.x(), 0);
2726 DCHECK_GE(window_rect.y(), 0);
2727 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2728 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2730 if (!request->force_bitmap_result()) {
2731 bool own_mailbox = !request->has_texture_mailbox();
2733 GLuint texture_id = 0;
2734 gpu::Mailbox mailbox;
2735 if (own_mailbox) {
2736 gl_->GenMailboxCHROMIUM(mailbox.name);
2737 gl_->GenTextures(1, &texture_id);
2738 gl_->BindTexture(GL_TEXTURE_2D, texture_id);
2740 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2741 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2742 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2743 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2744 gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name);
2745 } else {
2746 mailbox = request->texture_mailbox().mailbox();
2747 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2748 request->texture_mailbox().target());
2749 DCHECK(!mailbox.IsZero());
2750 unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2751 if (incoming_sync_point)
2752 gl_->WaitSyncPointCHROMIUM(incoming_sync_point);
2754 texture_id =
2755 gl_->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name);
2757 GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2759 unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2760 TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2762 scoped_ptr<SingleReleaseCallback> release_callback;
2763 if (own_mailbox) {
2764 gl_->BindTexture(GL_TEXTURE_2D, 0);
2765 release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2766 output_surface_->context_provider(), texture_id);
2767 } else {
2768 gl_->DeleteTextures(1, &texture_id);
2771 request->SendTextureResult(
2772 window_rect.size(), texture_mailbox, release_callback.Pass());
2773 return;
2776 DCHECK(request->force_bitmap_result());
2778 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2779 pending_read->copy_request = request.Pass();
2780 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2781 pending_read.Pass());
2783 bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2785 unsigned temporary_texture = 0;
2786 unsigned temporary_fbo = 0;
2788 if (do_workaround) {
2789 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2790 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2791 // calls, even those on different OpenGL contexts. It is believed that this
2792 // is the root cause of top crasher
2793 // http://crbug.com/99393. <rdar://problem/10949687>
2795 gl_->GenTextures(1, &temporary_texture);
2796 gl_->BindTexture(GL_TEXTURE_2D, temporary_texture);
2797 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2798 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2799 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2800 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2801 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2802 // temporary texture.
2803 GetFramebufferTexture(
2804 temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2805 gl_->GenFramebuffers(1, &temporary_fbo);
2806 // Attach this texture to an FBO, and perform the readback from that FBO.
2807 gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo);
2808 gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
2809 GL_TEXTURE_2D, temporary_texture, 0);
2811 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2812 gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2815 GLuint buffer = 0;
2816 gl_->GenBuffers(1, &buffer);
2817 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer);
2818 gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2819 4 * window_rect.size().GetArea(), NULL, GL_STREAM_READ);
2821 GLuint query = 0;
2822 gl_->GenQueriesEXT(1, &query);
2823 gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query);
2825 gl_->ReadPixels(window_rect.x(), window_rect.y(), window_rect.width(),
2826 window_rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2828 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0);
2830 if (do_workaround) {
2831 // Clean up.
2832 gl_->BindFramebuffer(GL_FRAMEBUFFER, 0);
2833 gl_->BindTexture(GL_TEXTURE_2D, 0);
2834 gl_->DeleteFramebuffers(1, &temporary_fbo);
2835 gl_->DeleteTextures(1, &temporary_texture);
2838 base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2839 base::Unretained(this),
2840 buffer,
2841 query,
2842 window_rect.size());
2843 // Save the finished_callback so it can be cancelled.
2844 pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2845 finished_callback);
2846 base::Closure cancelable_callback =
2847 pending_async_read_pixels_.front()->
2848 finished_read_pixels_callback.callback();
2850 // Save the buffer to verify the callbacks happen in the expected order.
2851 pending_async_read_pixels_.front()->buffer = buffer;
2853 gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM);
2854 context_support_->SignalQuery(query, cancelable_callback);
2856 EnforceMemoryPolicy();
2859 void GLRenderer::FinishedReadback(unsigned source_buffer,
2860 unsigned query,
2861 const gfx::Size& size) {
2862 DCHECK(!pending_async_read_pixels_.empty());
2864 if (query != 0) {
2865 gl_->DeleteQueriesEXT(1, &query);
2868 PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2869 // Make sure we service the readbacks in order.
2870 DCHECK_EQ(source_buffer, current_read->buffer);
2872 uint8* src_pixels = NULL;
2873 scoped_ptr<SkBitmap> bitmap;
2875 if (source_buffer != 0) {
2876 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer);
2877 src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2878 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2880 if (src_pixels) {
2881 bitmap.reset(new SkBitmap);
2882 bitmap->allocN32Pixels(size.width(), size.height());
2883 scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2884 uint8* dest_pixels = static_cast<uint8*>(bitmap->getPixels());
2886 size_t row_bytes = size.width() * 4;
2887 int num_rows = size.height();
2888 size_t total_bytes = num_rows * row_bytes;
2889 for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2890 // Flip Y axis.
2891 size_t src_y = total_bytes - dest_y - row_bytes;
2892 // Swizzle OpenGL -> Skia byte order.
2893 for (size_t x = 0; x < row_bytes; x += 4) {
2894 dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2895 src_pixels[src_y + x + 0];
2896 dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2897 src_pixels[src_y + x + 1];
2898 dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2899 src_pixels[src_y + x + 2];
2900 dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2901 src_pixels[src_y + x + 3];
2905 gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM);
2907 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0);
2908 gl_->DeleteBuffers(1, &source_buffer);
2911 if (bitmap)
2912 current_read->copy_request->SendBitmapResult(bitmap.Pass());
2913 pending_async_read_pixels_.pop_back();
2916 void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2917 ResourceFormat texture_format,
2918 const gfx::Rect& window_rect) {
2919 DCHECK(texture_id);
2920 DCHECK_GE(window_rect.x(), 0);
2921 DCHECK_GE(window_rect.y(), 0);
2922 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2923 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2925 gl_->BindTexture(GL_TEXTURE_2D, texture_id);
2926 gl_->CopyTexImage2D(GL_TEXTURE_2D, 0, GLDataFormat(texture_format),
2927 window_rect.x(), window_rect.y(), window_rect.width(),
2928 window_rect.height(), 0);
2929 gl_->BindTexture(GL_TEXTURE_2D, 0);
2932 bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2933 const ScopedResource* texture,
2934 const gfx::Rect& viewport_rect) {
2935 DCHECK(texture->id());
2936 frame->current_render_pass = NULL;
2937 frame->current_texture = texture;
2939 return BindFramebufferToTexture(frame, texture, viewport_rect);
2942 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2943 current_framebuffer_lock_ = nullptr;
2944 output_surface_->BindFramebuffer();
2946 if (output_surface_->HasExternalStencilTest()) {
2947 SetStencilEnabled(true);
2948 gl_->StencilFunc(GL_EQUAL, 1, 1);
2949 } else {
2950 SetStencilEnabled(false);
2954 bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2955 const ScopedResource* texture,
2956 const gfx::Rect& target_rect) {
2957 DCHECK(texture->id());
2959 // Explicitly release lock, otherwise we can crash when try to lock
2960 // same texture again.
2961 current_framebuffer_lock_ = nullptr;
2963 SetStencilEnabled(false);
2964 gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_);
2965 current_framebuffer_lock_ =
2966 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2967 resource_provider_, texture->id()));
2968 unsigned texture_id = current_framebuffer_lock_->texture_id();
2969 gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
2970 texture_id, 0);
2972 DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2973 GL_FRAMEBUFFER_COMPLETE ||
2974 IsContextLost());
2975 return true;
2978 void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2979 EnsureScissorTestEnabled();
2981 // Don't unnecessarily ask the context to change the scissor, because it
2982 // may cause undesired GPU pipeline flushes.
2983 if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2984 return;
2986 scissor_rect_ = scissor_rect;
2987 FlushTextureQuadCache(SHARED_BINDING);
2988 gl_->Scissor(scissor_rect.x(), scissor_rect.y(), scissor_rect.width(),
2989 scissor_rect.height());
2991 scissor_rect_needs_reset_ = false;
2994 void GLRenderer::SetViewport() {
2995 gl_->Viewport(current_window_space_viewport_.x(),
2996 current_window_space_viewport_.y(),
2997 current_window_space_viewport_.width(),
2998 current_window_space_viewport_.height());
3001 void GLRenderer::InitializeSharedObjects() {
3002 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
3004 // Create an FBO for doing offscreen rendering.
3005 gl_->GenFramebuffers(1, &offscreen_framebuffer_id_);
3007 shared_geometry_ =
3008 make_scoped_ptr(new StaticGeometryBinding(gl_, QuadVertexRect()));
3009 clipped_geometry_ = make_scoped_ptr(new DynamicGeometryBinding(gl_));
3012 void GLRenderer::PrepareGeometry(BoundGeometry binding) {
3013 if (binding == bound_geometry_) {
3014 return;
3017 switch (binding) {
3018 case SHARED_BINDING:
3019 shared_geometry_->PrepareForDraw();
3020 break;
3021 case CLIPPED_BINDING:
3022 clipped_geometry_->PrepareForDraw();
3023 break;
3024 case NO_BINDING:
3025 break;
3027 bound_geometry_ = binding;
3030 const GLRenderer::TileCheckerboardProgram*
3031 GLRenderer::GetTileCheckerboardProgram() {
3032 if (!tile_checkerboard_program_.initialized()) {
3033 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
3034 tile_checkerboard_program_.Initialize(output_surface_->context_provider(),
3035 TEX_COORD_PRECISION_NA,
3036 SAMPLER_TYPE_NA);
3038 return &tile_checkerboard_program_;
3041 const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
3042 if (!debug_border_program_.initialized()) {
3043 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
3044 debug_border_program_.Initialize(output_surface_->context_provider(),
3045 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3047 return &debug_border_program_;
3050 const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
3051 if (!solid_color_program_.initialized()) {
3052 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
3053 solid_color_program_.Initialize(output_surface_->context_provider(),
3054 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3056 return &solid_color_program_;
3059 const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
3060 if (!solid_color_program_aa_.initialized()) {
3061 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
3062 solid_color_program_aa_.Initialize(output_surface_->context_provider(),
3063 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3065 return &solid_color_program_aa_;
3068 const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
3069 TexCoordPrecision precision,
3070 BlendMode blend_mode) {
3071 DCHECK_GE(precision, 0);
3072 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3073 DCHECK_GE(blend_mode, 0);
3074 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3075 RenderPassProgram* program = &render_pass_program_[precision][blend_mode];
3076 if (!program->initialized()) {
3077 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
3078 program->Initialize(output_surface_->context_provider(), precision,
3079 SAMPLER_TYPE_2D, blend_mode);
3081 return program;
3084 const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
3085 TexCoordPrecision precision,
3086 BlendMode blend_mode) {
3087 DCHECK_GE(precision, 0);
3088 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3089 DCHECK_GE(blend_mode, 0);
3090 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3091 RenderPassProgramAA* program =
3092 &render_pass_program_aa_[precision][blend_mode];
3093 if (!program->initialized()) {
3094 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
3095 program->Initialize(output_surface_->context_provider(), precision,
3096 SAMPLER_TYPE_2D, blend_mode);
3098 return program;
3101 const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
3102 TexCoordPrecision precision,
3103 SamplerType sampler,
3104 BlendMode blend_mode,
3105 bool mask_for_background) {
3106 DCHECK_GE(precision, 0);
3107 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3108 DCHECK_GE(sampler, 0);
3109 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3110 DCHECK_GE(blend_mode, 0);
3111 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3112 RenderPassMaskProgram* program =
3113 &render_pass_mask_program_[precision][sampler][blend_mode]
3114 [mask_for_background ? HAS_MASK : NO_MASK];
3115 if (!program->initialized()) {
3116 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
3117 program->Initialize(
3118 output_surface_->context_provider(), precision,
3119 sampler, blend_mode, mask_for_background);
3121 return program;
3124 const GLRenderer::RenderPassMaskProgramAA*
3125 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision,
3126 SamplerType sampler,
3127 BlendMode blend_mode,
3128 bool mask_for_background) {
3129 DCHECK_GE(precision, 0);
3130 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3131 DCHECK_GE(sampler, 0);
3132 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3133 DCHECK_GE(blend_mode, 0);
3134 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3135 RenderPassMaskProgramAA* program =
3136 &render_pass_mask_program_aa_[precision][sampler][blend_mode]
3137 [mask_for_background ? HAS_MASK : NO_MASK];
3138 if (!program->initialized()) {
3139 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
3140 program->Initialize(
3141 output_surface_->context_provider(), precision,
3142 sampler, blend_mode, mask_for_background);
3144 return program;
3147 const GLRenderer::RenderPassColorMatrixProgram*
3148 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision,
3149 BlendMode blend_mode) {
3150 DCHECK_GE(precision, 0);
3151 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3152 DCHECK_GE(blend_mode, 0);
3153 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3154 RenderPassColorMatrixProgram* program =
3155 &render_pass_color_matrix_program_[precision][blend_mode];
3156 if (!program->initialized()) {
3157 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
3158 program->Initialize(output_surface_->context_provider(), precision,
3159 SAMPLER_TYPE_2D, blend_mode);
3161 return program;
3164 const GLRenderer::RenderPassColorMatrixProgramAA*
3165 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision,
3166 BlendMode blend_mode) {
3167 DCHECK_GE(precision, 0);
3168 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3169 DCHECK_GE(blend_mode, 0);
3170 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3171 RenderPassColorMatrixProgramAA* program =
3172 &render_pass_color_matrix_program_aa_[precision][blend_mode];
3173 if (!program->initialized()) {
3174 TRACE_EVENT0("cc",
3175 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
3176 program->Initialize(output_surface_->context_provider(), precision,
3177 SAMPLER_TYPE_2D, blend_mode);
3179 return program;
3182 const GLRenderer::RenderPassMaskColorMatrixProgram*
3183 GLRenderer::GetRenderPassMaskColorMatrixProgram(
3184 TexCoordPrecision precision,
3185 SamplerType sampler,
3186 BlendMode blend_mode,
3187 bool mask_for_background) {
3188 DCHECK_GE(precision, 0);
3189 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3190 DCHECK_GE(sampler, 0);
3191 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3192 DCHECK_GE(blend_mode, 0);
3193 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3194 RenderPassMaskColorMatrixProgram* program =
3195 &render_pass_mask_color_matrix_program_[precision][sampler][blend_mode]
3196 [mask_for_background ? HAS_MASK : NO_MASK];
3197 if (!program->initialized()) {
3198 TRACE_EVENT0("cc",
3199 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
3200 program->Initialize(
3201 output_surface_->context_provider(), precision,
3202 sampler, blend_mode, mask_for_background);
3204 return program;
3207 const GLRenderer::RenderPassMaskColorMatrixProgramAA*
3208 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(
3209 TexCoordPrecision precision,
3210 SamplerType sampler,
3211 BlendMode blend_mode,
3212 bool mask_for_background) {
3213 DCHECK_GE(precision, 0);
3214 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3215 DCHECK_GE(sampler, 0);
3216 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3217 DCHECK_GE(blend_mode, 0);
3218 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3219 RenderPassMaskColorMatrixProgramAA* program =
3220 &render_pass_mask_color_matrix_program_aa_[precision][sampler][blend_mode]
3221 [mask_for_background ? HAS_MASK : NO_MASK];
3222 if (!program->initialized()) {
3223 TRACE_EVENT0("cc",
3224 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
3225 program->Initialize(
3226 output_surface_->context_provider(), precision,
3227 sampler, blend_mode, mask_for_background);
3229 return program;
3232 const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
3233 TexCoordPrecision precision,
3234 SamplerType sampler) {
3235 DCHECK_GE(precision, 0);
3236 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3237 DCHECK_GE(sampler, 0);
3238 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3239 TileProgram* program = &tile_program_[precision][sampler];
3240 if (!program->initialized()) {
3241 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
3242 program->Initialize(
3243 output_surface_->context_provider(), precision, sampler);
3245 return program;
3248 const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
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 TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
3256 if (!program->initialized()) {
3257 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3258 program->Initialize(
3259 output_surface_->context_provider(), precision, sampler);
3261 return program;
3264 const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
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 TileProgramAA* program = &tile_program_aa_[precision][sampler];
3272 if (!program->initialized()) {
3273 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3274 program->Initialize(
3275 output_surface_->context_provider(), precision, sampler);
3277 return program;
3280 const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
3281 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 TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
3288 if (!program->initialized()) {
3289 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3290 program->Initialize(
3291 output_surface_->context_provider(), precision, sampler);
3293 return program;
3296 const GLRenderer::TileProgramSwizzleOpaque*
3297 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
3298 SamplerType sampler) {
3299 DCHECK_GE(precision, 0);
3300 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3301 DCHECK_GE(sampler, 0);
3302 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3303 TileProgramSwizzleOpaque* program =
3304 &tile_program_swizzle_opaque_[precision][sampler];
3305 if (!program->initialized()) {
3306 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3307 program->Initialize(
3308 output_surface_->context_provider(), precision, sampler);
3310 return program;
3313 const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
3314 TexCoordPrecision precision,
3315 SamplerType sampler) {
3316 DCHECK_GE(precision, 0);
3317 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3318 DCHECK_GE(sampler, 0);
3319 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3320 TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
3321 if (!program->initialized()) {
3322 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3323 program->Initialize(
3324 output_surface_->context_provider(), precision, sampler);
3326 return program;
3329 const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
3330 TexCoordPrecision precision,
3331 SamplerType sampler) {
3332 DCHECK_GE(precision, 0);
3333 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3334 DCHECK_GE(sampler, 0);
3335 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3336 TextureProgram* program = &texture_program_[precision][sampler];
3337 if (!program->initialized()) {
3338 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3339 program->Initialize(output_surface_->context_provider(), precision,
3340 sampler);
3342 return program;
3345 const GLRenderer::NonPremultipliedTextureProgram*
3346 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision,
3347 SamplerType sampler) {
3348 DCHECK_GE(precision, 0);
3349 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3350 DCHECK_GE(sampler, 0);
3351 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3352 NonPremultipliedTextureProgram* program =
3353 &nonpremultiplied_texture_program_[precision][sampler];
3354 if (!program->initialized()) {
3355 TRACE_EVENT0("cc",
3356 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3357 program->Initialize(output_surface_->context_provider(), precision,
3358 sampler);
3360 return program;
3363 const GLRenderer::TextureBackgroundProgram*
3364 GLRenderer::GetTextureBackgroundProgram(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 TextureBackgroundProgram* program =
3371 &texture_background_program_[precision][sampler];
3372 if (!program->initialized()) {
3373 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3374 program->Initialize(output_surface_->context_provider(), precision,
3375 sampler);
3377 return program;
3380 const GLRenderer::NonPremultipliedTextureBackgroundProgram*
3381 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3382 TexCoordPrecision precision,
3383 SamplerType sampler) {
3384 DCHECK_GE(precision, 0);
3385 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3386 DCHECK_GE(sampler, 0);
3387 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3388 NonPremultipliedTextureBackgroundProgram* program =
3389 &nonpremultiplied_texture_background_program_[precision][sampler];
3390 if (!program->initialized()) {
3391 TRACE_EVENT0("cc",
3392 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3393 program->Initialize(output_surface_->context_provider(), precision,
3394 sampler);
3396 return program;
3399 const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
3400 TexCoordPrecision precision) {
3401 DCHECK_GE(precision, 0);
3402 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3403 TextureProgram* program = &texture_io_surface_program_[precision];
3404 if (!program->initialized()) {
3405 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3406 program->Initialize(output_surface_->context_provider(), precision,
3407 SAMPLER_TYPE_2D_RECT);
3409 return program;
3412 const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
3413 TexCoordPrecision precision,
3414 SamplerType sampler) {
3415 DCHECK_GE(precision, 0);
3416 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3417 DCHECK_GE(sampler, 0);
3418 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3419 VideoYUVProgram* program = &video_yuv_program_[precision][sampler];
3420 if (!program->initialized()) {
3421 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3422 program->Initialize(output_surface_->context_provider(), precision,
3423 sampler);
3425 return program;
3428 const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
3429 TexCoordPrecision precision,
3430 SamplerType sampler) {
3431 DCHECK_GE(precision, 0);
3432 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3433 DCHECK_GE(sampler, 0);
3434 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3435 VideoYUVAProgram* program = &video_yuva_program_[precision][sampler];
3436 if (!program->initialized()) {
3437 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3438 program->Initialize(output_surface_->context_provider(), precision,
3439 sampler);
3441 return program;
3444 const GLRenderer::VideoStreamTextureProgram*
3445 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
3446 if (!Capabilities().using_egl_image)
3447 return NULL;
3448 DCHECK_GE(precision, 0);
3449 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3450 VideoStreamTextureProgram* program =
3451 &video_stream_texture_program_[precision];
3452 if (!program->initialized()) {
3453 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3454 program->Initialize(output_surface_->context_provider(), precision,
3455 SAMPLER_TYPE_EXTERNAL_OES);
3457 return program;
3460 void GLRenderer::CleanupSharedObjects() {
3461 shared_geometry_ = nullptr;
3463 for (int i = 0; i <= LAST_TEX_COORD_PRECISION; ++i) {
3464 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3465 tile_program_[i][j].Cleanup(gl_);
3466 tile_program_opaque_[i][j].Cleanup(gl_);
3467 tile_program_swizzle_[i][j].Cleanup(gl_);
3468 tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
3469 tile_program_aa_[i][j].Cleanup(gl_);
3470 tile_program_swizzle_aa_[i][j].Cleanup(gl_);
3472 for (int k = 0; k <= LAST_BLEND_MODE; k++) {
3473 for (int l = 0; l <= LAST_MASK_VALUE; ++l) {
3474 render_pass_mask_program_[i][j][k][l].Cleanup(gl_);
3475 render_pass_mask_program_aa_[i][j][k][l].Cleanup(gl_);
3476 render_pass_mask_color_matrix_program_aa_[i][j][k][l].Cleanup(gl_);
3477 render_pass_mask_color_matrix_program_[i][j][k][l].Cleanup(gl_);
3481 video_yuv_program_[i][j].Cleanup(gl_);
3482 video_yuva_program_[i][j].Cleanup(gl_);
3484 for (int j = 0; j <= LAST_BLEND_MODE; j++) {
3485 render_pass_program_[i][j].Cleanup(gl_);
3486 render_pass_program_aa_[i][j].Cleanup(gl_);
3487 render_pass_color_matrix_program_[i][j].Cleanup(gl_);
3488 render_pass_color_matrix_program_aa_[i][j].Cleanup(gl_);
3491 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3492 texture_program_[i][j].Cleanup(gl_);
3493 nonpremultiplied_texture_program_[i][j].Cleanup(gl_);
3494 texture_background_program_[i][j].Cleanup(gl_);
3495 nonpremultiplied_texture_background_program_[i][j].Cleanup(gl_);
3497 texture_io_surface_program_[i].Cleanup(gl_);
3499 video_stream_texture_program_[i].Cleanup(gl_);
3502 tile_checkerboard_program_.Cleanup(gl_);
3504 debug_border_program_.Cleanup(gl_);
3505 solid_color_program_.Cleanup(gl_);
3506 solid_color_program_aa_.Cleanup(gl_);
3508 if (offscreen_framebuffer_id_)
3509 gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_);
3511 if (on_demand_tile_raster_resource_id_)
3512 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
3514 ReleaseRenderPassTextures();
3517 void GLRenderer::ReinitializeGLState() {
3518 is_scissor_enabled_ = false;
3519 scissor_rect_needs_reset_ = true;
3520 stencil_shadow_ = false;
3521 blend_shadow_ = true;
3522 program_shadow_ = 0;
3524 RestoreGLState();
3527 void GLRenderer::RestoreGLState() {
3528 // This restores the current GLRenderer state to the GL context.
3529 bound_geometry_ = NO_BINDING;
3530 PrepareGeometry(SHARED_BINDING);
3532 gl_->Disable(GL_DEPTH_TEST);
3533 gl_->Disable(GL_CULL_FACE);
3534 gl_->ColorMask(true, true, true, true);
3535 gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
3536 gl_->ActiveTexture(GL_TEXTURE0);
3538 if (program_shadow_)
3539 gl_->UseProgram(program_shadow_);
3541 if (stencil_shadow_)
3542 gl_->Enable(GL_STENCIL_TEST);
3543 else
3544 gl_->Disable(GL_STENCIL_TEST);
3546 if (blend_shadow_)
3547 gl_->Enable(GL_BLEND);
3548 else
3549 gl_->Disable(GL_BLEND);
3551 if (is_scissor_enabled_) {
3552 gl_->Enable(GL_SCISSOR_TEST);
3553 gl_->Scissor(scissor_rect_.x(), scissor_rect_.y(), scissor_rect_.width(),
3554 scissor_rect_.height());
3555 } else {
3556 gl_->Disable(GL_SCISSOR_TEST);
3560 void GLRenderer::RestoreFramebuffer(DrawingFrame* frame) {
3561 UseRenderPass(frame, frame->current_render_pass);
3563 // Call SetViewport directly, rather than through PrepareSurfaceForPass.
3564 // PrepareSurfaceForPass also clears the surface, which is not desired when
3565 // restoring.
3566 SetViewport();
3569 bool GLRenderer::IsContextLost() {
3570 return gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR;
3573 void GLRenderer::ScheduleOverlays(DrawingFrame* frame) {
3574 if (!frame->overlay_list.size())
3575 return;
3577 ResourceProvider::ResourceIdArray resources;
3578 OverlayCandidateList& overlays = frame->overlay_list;
3579 for (const OverlayCandidate& overlay : overlays) {
3580 // Skip primary plane.
3581 if (overlay.plane_z_order == 0)
3582 continue;
3584 pending_overlay_resources_.push_back(
3585 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3586 resource_provider_, overlay.resource_id)));
3588 context_support_->ScheduleOverlayPlane(
3589 overlay.plane_z_order,
3590 overlay.transform,
3591 pending_overlay_resources_.back()->texture_id(),
3592 ToNearestRect(overlay.display_rect),
3593 overlay.uv_rect);
3597 } // namespace cc