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