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"
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
;
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.
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];
82 Float4
PremultipliedColor(SkColor color
) {
83 const float factor
= 1.0f
/ 255.0f
;
84 const float alpha
= SkColorGetA(color
) * factor
;
87 {SkColorGetR(color
) * factor
* alpha
, SkColorGetG(color
) * factor
* alpha
,
88 SkColorGetB(color
) * factor
* alpha
, alpha
}};
92 SamplerType
SamplerTypeFromTextureTarget(GLenum target
) {
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
;
102 return SAMPLER_TYPE_2D
;
106 BlendMode
BlendModeFromSkXfermode(SkXfermode::Mode 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
;
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
);
162 class GLRenderer::ScopedUseGrContext
{
164 static scoped_ptr
<ScopedUseGrContext
> Create(GLRenderer
* renderer
,
165 DrawingFrame
* frame
) {
166 // GrContext for filters is created lazily, and may fail if the context
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
));
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();
187 ScopedUseGrContext(GLRenderer
* renderer
, DrawingFrame
* frame
)
188 : scoped_gpu_raster_(
189 new ScopedGpuRaster(renderer
->output_surface_
->context_provider())),
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
;
210 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels
);
213 class GLRenderer::SyncQuery
{
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()));
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_
);
249 gl_
->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
);
256 unsigned result_available
= 1;
257 gl_
->GetQueryObjectuivEXT(
258 query_id_
, GL_QUERY_RESULT_AVAILABLE_EXT
, &result_available
);
259 is_pending_
= !result_available
;
268 gl_
->GetQueryObjectuivEXT(query_id_
, GL_QUERY_RESULT_EXT
, &result
);
273 class Fence
: public ResourceProvider::Fence
{
275 explicit Fence(base::WeakPtr
<GLRenderer::SyncQuery
> query
)
278 // Overridden from ResourceProvider::Fence:
279 void Set() override
{
283 bool HasPassed() override
{ return !query_
|| !query_
->IsPending(); }
284 void Wait() override
{
292 base::WeakPtr
<SyncQuery
> query_
;
294 DISALLOW_COPY_AND_ASSIGN(Fence
);
297 gpu::gles2::GLES2Interface
* gl_
;
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
,
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
) {
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
)
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(
418 SurfaceInitializationMode initialization_mode
,
419 const gfx::Rect
& render_pass_scissor
) {
422 switch (initialization_mode
) {
423 case SURFACE_INITIALIZATION_MODE_PRESERVE
:
424 EnsureScissorTestDisabled();
426 case SURFACE_INITIALIZATION_MODE_FULL_SURFACE_CLEAR
:
427 EnsureScissorTestDisabled();
429 ClearFramebuffer(frame
);
431 case SURFACE_INITIALIZATION_MODE_SCISSORED_CLEAR
:
432 SetScissorTestRect(render_pass_scissor
);
433 ClearFramebuffer(frame
);
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);
444 gl_
->ClearColor(0, 0, 1, 1);
446 bool always_clear
= false;
450 if (always_clear
|| frame
->current_render_pass
->has_transparent_background
) {
451 GLbitfield clear_bits
= GL_COLOR_BUFFER_BIT
;
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())
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();
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);
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
:
521 case DrawQuad::CHECKERBOARD
:
522 DrawCheckerboardQuad(frame
, CheckerboardDrawQuad::MaterialCast(quad
),
525 case DrawQuad::DEBUG_BORDER
:
526 DrawDebugBorderQuad(frame
, DebugBorderDrawQuad::MaterialCast(quad
));
528 case DrawQuad::IO_SURFACE_CONTENT
:
529 DrawIOSurfaceQuad(frame
, IOSurfaceDrawQuad::MaterialCast(quad
),
532 case DrawQuad::PICTURE_CONTENT
:
533 // PictureDrawQuad should only be used for resourceless software draws.
536 case DrawQuad::RENDER_PASS
:
537 DrawRenderPassQuad(frame
, RenderPassDrawQuad::MaterialCast(quad
),
540 case DrawQuad::SOLID_COLOR
:
541 DrawSolidColorQuad(frame
, SolidColorDrawQuad::MaterialCast(quad
),
544 case DrawQuad::STREAM_VIDEO_CONTENT
:
545 DrawStreamVideoQuad(frame
, StreamVideoDrawQuad::MaterialCast(quad
),
548 case DrawQuad::SURFACE_CONTENT
:
549 // Surface content should be fully resolved to other quad types before
550 // reaching a direct renderer.
553 case DrawQuad::TEXTURE_CONTENT
:
554 EnqueueTextureQuad(frame
, TextureDrawQuad::MaterialCast(quad
),
557 case DrawQuad::TILED_CONTENT
:
558 DrawTileQuad(frame
, TileDrawQuad::MaterialCast(quad
), clip_region
);
560 case DrawQuad::YUV_VIDEO_CONTENT
:
561 DrawYUVVideoQuad(frame
, YUVVideoDrawQuad::MaterialCast(quad
),
567 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame
* frame
,
568 const CheckerboardDrawQuad
* quad
,
569 const gfx::QuadF
* clip_region
) {
570 // TODO(enne) For now since checkerboards shouldn't be part of a 3D
571 // context, clipping regions aren't supported so we skip drawing them
572 // if this becomes the case.
576 SetBlendEnabled(quad
->ShouldDrawWithBlending());
578 const TileCheckerboardProgram
* program
= GetTileCheckerboardProgram();
579 DCHECK(program
&& (program
->initialized() || IsContextLost()));
580 SetUseProgram(program
->program());
582 SkColor color
= quad
->color
;
583 gl_
->Uniform4f(program
->fragment_shader().color_location(),
584 SkColorGetR(color
) * (1.0f
/ 255.0f
),
585 SkColorGetG(color
) * (1.0f
/ 255.0f
),
586 SkColorGetB(color
) * (1.0f
/ 255.0f
), 1);
588 const int kCheckerboardWidth
= 16;
589 float frequency
= 1.0f
/ kCheckerboardWidth
;
591 gfx::Rect tile_rect
= quad
->rect
;
593 static_cast<int>(tile_rect
.x() / quad
->scale
) % kCheckerboardWidth
;
595 static_cast<int>(tile_rect
.y() / quad
->scale
) % kCheckerboardWidth
;
596 float tex_scale_x
= tile_rect
.width() / quad
->scale
;
597 float tex_scale_y
= tile_rect
.height() / quad
->scale
;
598 gl_
->Uniform4f(program
->fragment_shader().tex_transform_location(),
599 tex_offset_x
, tex_offset_y
, tex_scale_x
, tex_scale_y
);
601 gl_
->Uniform1f(program
->fragment_shader().frequency_location(), frequency
);
603 SetShaderOpacity(quad
->shared_quad_state
->opacity
,
604 program
->fragment_shader().alpha_location());
605 DrawQuadGeometry(frame
, quad
->shared_quad_state
->quad_to_target_transform
,
606 quad
->rect
, program
->vertex_shader().matrix_location());
609 // This function does not handle 3D sorting right now, since the debug border
610 // quads are just drawn as their original quads and not in split pieces. This
611 // results in some debug border quads drawing over foreground quads.
612 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame
* frame
,
613 const DebugBorderDrawQuad
* quad
) {
614 SetBlendEnabled(quad
->ShouldDrawWithBlending());
616 static float gl_matrix
[16];
617 const DebugBorderProgram
* program
= GetDebugBorderProgram();
618 DCHECK(program
&& (program
->initialized() || IsContextLost()));
619 SetUseProgram(program
->program());
621 // Use the full quad_rect for debug quads to not move the edges based on
623 gfx::Rect layer_rect
= quad
->rect
;
624 gfx::Transform render_matrix
;
625 QuadRectTransform(&render_matrix
,
626 quad
->shared_quad_state
->quad_to_target_transform
,
628 GLRenderer::ToGLMatrix(&gl_matrix
[0],
629 frame
->projection_matrix
* render_matrix
);
630 gl_
->UniformMatrix4fv(program
->vertex_shader().matrix_location(), 1, false,
633 SkColor color
= quad
->color
;
634 float alpha
= SkColorGetA(color
) * (1.0f
/ 255.0f
);
636 gl_
->Uniform4f(program
->fragment_shader().color_location(),
637 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
638 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
639 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
, alpha
);
641 gl_
->LineWidth(quad
->width
);
643 // The indices for the line are stored in the same array as the triangle
645 gl_
->DrawElements(GL_LINE_LOOP
, 4, GL_UNSIGNED_SHORT
, 0);
648 static skia::RefPtr
<SkImage
> ApplyImageFilter(
649 scoped_ptr
<GLRenderer::ScopedUseGrContext
> use_gr_context
,
650 ResourceProvider
* resource_provider
,
651 const gfx::Rect
& rect
,
652 const gfx::Vector2dF
& scale
,
653 SkImageFilter
* filter
,
654 ScopedResource
* source_texture_resource
) {
656 return skia::RefPtr
<SkImage
>();
659 return skia::RefPtr
<SkImage
>();
661 ResourceProvider::ScopedReadLockGL
lock(resource_provider
,
662 source_texture_resource
->id());
664 // Wrap the source texture in a Ganesh platform texture.
665 GrBackendTextureDesc backend_texture_description
;
666 backend_texture_description
.fWidth
= source_texture_resource
->size().width();
667 backend_texture_description
.fHeight
=
668 source_texture_resource
->size().height();
669 backend_texture_description
.fConfig
= kSkia8888_GrPixelConfig
;
670 backend_texture_description
.fTextureHandle
= lock
.texture_id();
671 backend_texture_description
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
672 skia::RefPtr
<GrTexture
> texture
= skia::AdoptRef(
673 use_gr_context
->context()->textureProvider()->wrapBackendTexture(
674 backend_texture_description
));
676 TRACE_EVENT_INSTANT0("cc",
677 "ApplyImageFilter wrap background texture failed",
678 TRACE_EVENT_SCOPE_THREAD
);
679 return skia::RefPtr
<SkImage
>();
682 SkImageInfo src_info
=
683 SkImageInfo::MakeN32Premul(source_texture_resource
->size().width(),
684 source_texture_resource
->size().height());
685 // Place the platform texture inside an SkBitmap.
687 source
.setInfo(src_info
);
688 skia::RefPtr
<SkGrPixelRef
> pixel_ref
=
689 skia::AdoptRef(new SkGrPixelRef(src_info
, texture
.get()));
690 source
.setPixelRef(pixel_ref
.get());
692 // Create surface to draw into.
693 SkImageInfo dst_info
=
694 SkImageInfo::MakeN32Premul(source
.width(), source
.height());
695 skia::RefPtr
<SkSurface
> surface
= skia::AdoptRef(SkSurface::NewRenderTarget(
696 use_gr_context
->context(), SkSurface::kYes_Budgeted
, dst_info
, 0));
698 TRACE_EVENT_INSTANT0("cc", "ApplyImageFilter surface allocation failed",
699 TRACE_EVENT_SCOPE_THREAD
);
700 return skia::RefPtr
<SkImage
>();
702 skia::RefPtr
<SkCanvas
> canvas
= skia::SharePtr(surface
->getCanvas());
704 // Draw the source bitmap through the filter to the canvas.
706 paint
.setImageFilter(filter
);
707 canvas
->clear(SK_ColorTRANSPARENT
);
709 // The origin of the filter is top-left and the origin of the source is
710 // bottom-left, but the orientation is the same, so we must translate the
711 // filter so that it renders at the bottom of the texture to avoid
713 int y_translate
= source
.height() - rect
.height() - rect
.origin().y();
714 canvas
->translate(-rect
.origin().x(), y_translate
);
715 canvas
->scale(scale
.x(), scale
.y());
716 canvas
->drawSprite(source
, 0, 0, &paint
);
718 skia::RefPtr
<SkImage
> image
= skia::AdoptRef(surface
->newImageSnapshot());
719 if (!image
|| !image
->isTextureBacked()) {
720 return skia::RefPtr
<SkImage
>();
726 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode
) {
727 return use_blend_equation_advanced_
||
728 blend_mode
== SkXfermode::kScreen_Mode
||
729 blend_mode
== SkXfermode::kSrcOver_Mode
;
732 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode
) {
733 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode
));
735 // Any modes set here must be reset in RestoreBlendFuncToDefault
736 if (use_blend_equation_advanced_
) {
737 GLenum equation
= GL_FUNC_ADD
;
739 switch (blend_mode
) {
740 case SkXfermode::kScreen_Mode
:
741 equation
= GL_SCREEN_KHR
;
743 case SkXfermode::kOverlay_Mode
:
744 equation
= GL_OVERLAY_KHR
;
746 case SkXfermode::kDarken_Mode
:
747 equation
= GL_DARKEN_KHR
;
749 case SkXfermode::kLighten_Mode
:
750 equation
= GL_LIGHTEN_KHR
;
752 case SkXfermode::kColorDodge_Mode
:
753 equation
= GL_COLORDODGE_KHR
;
755 case SkXfermode::kColorBurn_Mode
:
756 equation
= GL_COLORBURN_KHR
;
758 case SkXfermode::kHardLight_Mode
:
759 equation
= GL_HARDLIGHT_KHR
;
761 case SkXfermode::kSoftLight_Mode
:
762 equation
= GL_SOFTLIGHT_KHR
;
764 case SkXfermode::kDifference_Mode
:
765 equation
= GL_DIFFERENCE_KHR
;
767 case SkXfermode::kExclusion_Mode
:
768 equation
= GL_EXCLUSION_KHR
;
770 case SkXfermode::kMultiply_Mode
:
771 equation
= GL_MULTIPLY_KHR
;
773 case SkXfermode::kHue_Mode
:
774 equation
= GL_HSL_HUE_KHR
;
776 case SkXfermode::kSaturation_Mode
:
777 equation
= GL_HSL_SATURATION_KHR
;
779 case SkXfermode::kColor_Mode
:
780 equation
= GL_HSL_COLOR_KHR
;
782 case SkXfermode::kLuminosity_Mode
:
783 equation
= GL_HSL_LUMINOSITY_KHR
;
789 gl_
->BlendEquation(equation
);
791 if (blend_mode
== SkXfermode::kScreen_Mode
) {
792 gl_
->BlendFunc(GL_ONE_MINUS_DST_COLOR
, GL_ONE
);
797 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode
) {
798 if (blend_mode
== SkXfermode::kSrcOver_Mode
)
801 if (use_blend_equation_advanced_
) {
802 gl_
->BlendEquation(GL_FUNC_ADD
);
804 gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
);
808 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame
* frame
,
809 const RenderPassDrawQuad
* quad
) {
810 if (quad
->background_filters
.IsEmpty())
813 // TODO(danakj): We only allow background filters on an opaque render surface
814 // because other surfaces may contain translucent pixels, and the contents
815 // behind those translucent pixels wouldn't have the filter applied.
816 if (frame
->current_render_pass
->has_transparent_background
)
819 // TODO(ajuma): Add support for reference filters once
820 // FilterOperations::GetOutsets supports reference filters.
821 if (quad
->background_filters
.HasReferenceFilter())
826 // This takes a gfx::Rect and a clip region quad in the same space,
827 // and returns a quad with the same proportions in the space -0.5->0.5.
828 bool GetScaledRegion(const gfx::Rect
& rect
,
829 const gfx::QuadF
* clip
,
830 gfx::QuadF
* scaled_region
) {
834 gfx::PointF
p1(((clip
->p1().x() - rect
.x()) / rect
.width()) - 0.5f
,
835 ((clip
->p1().y() - rect
.y()) / rect
.height()) - 0.5f
);
836 gfx::PointF
p2(((clip
->p2().x() - rect
.x()) / rect
.width()) - 0.5f
,
837 ((clip
->p2().y() - rect
.y()) / rect
.height()) - 0.5f
);
838 gfx::PointF
p3(((clip
->p3().x() - rect
.x()) / rect
.width()) - 0.5f
,
839 ((clip
->p3().y() - rect
.y()) / rect
.height()) - 0.5f
);
840 gfx::PointF
p4(((clip
->p4().x() - rect
.x()) / rect
.width()) - 0.5f
,
841 ((clip
->p4().y() - rect
.y()) / rect
.height()) - 0.5f
);
842 *scaled_region
= gfx::QuadF(p1
, p2
, p3
, p4
);
846 // This takes a gfx::Rect and a clip region quad in the same space,
847 // and returns the proportional uv's in the space 0->1.
848 bool GetScaledUVs(const gfx::Rect
& rect
, const gfx::QuadF
* clip
, float uvs
[8]) {
852 uvs
[0] = ((clip
->p1().x() - rect
.x()) / rect
.width());
853 uvs
[1] = ((clip
->p1().y() - rect
.y()) / rect
.height());
854 uvs
[2] = ((clip
->p2().x() - rect
.x()) / rect
.width());
855 uvs
[3] = ((clip
->p2().y() - rect
.y()) / rect
.height());
856 uvs
[4] = ((clip
->p3().x() - rect
.x()) / rect
.width());
857 uvs
[5] = ((clip
->p3().y() - rect
.y()) / rect
.height());
858 uvs
[6] = ((clip
->p4().x() - rect
.x()) / rect
.width());
859 uvs
[7] = ((clip
->p4().y() - rect
.y()) / rect
.height());
863 gfx::Rect
GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
865 const RenderPassDrawQuad
* quad
,
866 const gfx::Transform
& contents_device_transform
,
867 const gfx::QuadF
* clip_region
,
869 gfx::QuadF scaled_region
;
870 if (!GetScaledRegion(quad
->rect
, clip_region
, &scaled_region
)) {
871 scaled_region
= SharedGeometryQuad().BoundingBox();
874 gfx::Rect backdrop_rect
= gfx::ToEnclosingRect(MathUtil::MapClippedRect(
875 contents_device_transform
, scaled_region
.BoundingBox()));
877 if (ShouldApplyBackgroundFilters(frame
, quad
)) {
878 int top
, right
, bottom
, left
;
879 quad
->background_filters
.GetOutsets(&top
, &right
, &bottom
, &left
);
880 backdrop_rect
.Inset(-left
, -top
, -right
, -bottom
);
883 if (!backdrop_rect
.IsEmpty() && use_aa
) {
884 const int kOutsetForAntialiasing
= 1;
885 backdrop_rect
.Inset(-kOutsetForAntialiasing
, -kOutsetForAntialiasing
);
888 backdrop_rect
.Intersect(MoveFromDrawToWindowSpace(
889 frame
, frame
->current_render_pass
->output_rect
));
890 return backdrop_rect
;
893 scoped_ptr
<ScopedResource
> GLRenderer::GetBackdropTexture(
894 const gfx::Rect
& bounding_rect
) {
895 scoped_ptr
<ScopedResource
> device_background_texture
=
896 ScopedResource::Create(resource_provider_
);
897 // CopyTexImage2D fails when called on a texture having immutable storage.
898 device_background_texture
->Allocate(
899 bounding_rect
.size(), ResourceProvider::TEXTURE_HINT_DEFAULT
, RGBA_8888
);
901 ResourceProvider::ScopedWriteLockGL
lock(resource_provider_
,
902 device_background_texture
->id());
903 GetFramebufferTexture(
904 lock
.texture_id(), device_background_texture
->format(), bounding_rect
);
906 return device_background_texture
.Pass();
909 skia::RefPtr
<SkImage
> GLRenderer::ApplyBackgroundFilters(
911 const RenderPassDrawQuad
* quad
,
912 ScopedResource
* background_texture
) {
913 DCHECK(ShouldApplyBackgroundFilters(frame
, quad
));
914 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
915 quad
->background_filters
, background_texture
->size());
917 skia::RefPtr
<SkImage
> background_with_filters
= ApplyImageFilter(
918 ScopedUseGrContext::Create(this, frame
), resource_provider_
, quad
->rect
,
919 quad
->filters_scale
, filter
.get(), background_texture
);
920 return background_with_filters
;
923 void GLRenderer::DrawRenderPassQuad(DrawingFrame
* frame
,
924 const RenderPassDrawQuad
* quad
,
925 const gfx::QuadF
* clip_region
) {
926 ScopedResource
* contents_texture
=
927 render_pass_textures_
.get(quad
->render_pass_id
);
928 DCHECK(contents_texture
);
929 DCHECK(contents_texture
->id());
931 gfx::Transform quad_rect_matrix
;
932 QuadRectTransform(&quad_rect_matrix
,
933 quad
->shared_quad_state
->quad_to_target_transform
,
935 gfx::Transform contents_device_transform
=
936 frame
->window_matrix
* frame
->projection_matrix
* quad_rect_matrix
;
937 contents_device_transform
.FlattenTo2d();
939 // Can only draw surface if device matrix is invertible.
940 if (!contents_device_transform
.IsInvertible())
943 gfx::QuadF surface_quad
= SharedGeometryQuad();
945 gfx::QuadF device_layer_quad
;
947 if (settings_
->allow_antialiasing
) {
948 bool clipped
= false;
950 MathUtil::MapQuad(contents_device_transform
, surface_quad
, &clipped
);
951 use_aa
= ShouldAntialiasQuad(device_layer_quad
, clipped
,
952 settings_
->force_antialiasing
);
956 const gfx::QuadF
* aa_quad
= use_aa
? &device_layer_quad
: nullptr;
957 SetupRenderPassQuadForClippingAndAntialiasing(contents_device_transform
, quad
,
958 aa_quad
, clip_region
,
959 &surface_quad
, edge
);
960 SkXfermode::Mode blend_mode
= quad
->shared_quad_state
->blend_mode
;
961 bool use_shaders_for_blending
=
962 !CanApplyBlendModeUsingBlendFunc(blend_mode
) ||
963 ShouldApplyBackgroundFilters(frame
, quad
) ||
964 settings_
->force_blending_with_shaders
;
966 scoped_ptr
<ScopedResource
> background_texture
;
967 skia::RefPtr
<SkImage
> background_image
;
968 GLuint background_image_id
= 0;
969 gfx::Rect background_rect
;
970 if (use_shaders_for_blending
) {
971 // Compute a bounding box around the pixels that will be visible through
973 background_rect
= GetBackdropBoundingBoxForRenderPassQuad(
974 frame
, quad
, contents_device_transform
, clip_region
, use_aa
);
976 if (!background_rect
.IsEmpty()) {
977 // The pixels from the filtered background should completely replace the
978 // current pixel values.
980 SetBlendEnabled(false);
982 // Read the pixels in the bounding box into a buffer R.
983 // This function allocates a texture, which should contribute to the
984 // amount of memory used by render surfaces:
985 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
986 background_texture
= GetBackdropTexture(background_rect
);
988 if (ShouldApplyBackgroundFilters(frame
, quad
) && background_texture
) {
989 // Apply the background filters to R, so that it is applied in the
990 // pixels' coordinate space.
992 ApplyBackgroundFilters(frame
, quad
, background_texture
.get());
993 if (background_image
)
994 background_image_id
= background_image
->getTextureHandle(true);
995 DCHECK(background_image_id
);
999 if (!background_texture
) {
1000 // Something went wrong with reading the backdrop.
1001 DCHECK(!background_image_id
);
1002 use_shaders_for_blending
= false;
1003 } else if (background_image_id
) {
1004 // Reset original background texture if there is not any mask
1005 if (!quad
->mask_resource_id())
1006 background_texture
.reset();
1007 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode
) &&
1008 ShouldApplyBackgroundFilters(frame
, quad
)) {
1009 // Something went wrong with applying background filters to the backdrop.
1010 use_shaders_for_blending
= false;
1011 background_texture
.reset();
1014 // Need original background texture for mask?
1015 bool mask_for_background
=
1016 background_texture
&& // Have original background texture
1017 background_image_id
&& // Have filtered background texture
1018 quad
->mask_resource_id(); // Have mask texture
1020 !use_shaders_for_blending
&&
1021 (quad
->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode
)));
1023 // TODO(senorblanco): Cache this value so that we don't have to do it for both
1024 // the surface and its replica. Apply filters to the contents texture.
1025 skia::RefPtr
<SkImage
> filter_image
;
1026 GLuint filter_image_id
= 0;
1027 SkScalar color_matrix
[20];
1028 bool use_color_matrix
= false;
1029 if (!quad
->filters
.IsEmpty()) {
1030 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
1031 quad
->filters
, contents_texture
->size());
1033 skia::RefPtr
<SkColorFilter
> cf
;
1036 SkColorFilter
* colorfilter_rawptr
= NULL
;
1037 filter
->asColorFilter(&colorfilter_rawptr
);
1038 cf
= skia::AdoptRef(colorfilter_rawptr
);
1041 if (cf
&& cf
->asColorMatrix(color_matrix
) && !filter
->getInput(0)) {
1042 // We have a single color matrix as a filter; apply it locally
1043 // in the compositor.
1044 use_color_matrix
= true;
1046 filter_image
= ApplyImageFilter(
1047 ScopedUseGrContext::Create(this, frame
), resource_provider_
,
1048 quad
->rect
, quad
->filters_scale
, filter
.get(), contents_texture
);
1050 filter_image_id
= filter_image
->getTextureHandle(true);
1051 DCHECK(filter_image_id
);
1057 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> mask_resource_lock
;
1058 unsigned mask_texture_id
= 0;
1059 SamplerType mask_sampler
= SAMPLER_TYPE_NA
;
1060 if (quad
->mask_resource_id()) {
1061 mask_resource_lock
.reset(new ResourceProvider::ScopedSamplerGL(
1062 resource_provider_
, quad
->mask_resource_id(), GL_TEXTURE1
, GL_LINEAR
));
1063 mask_texture_id
= mask_resource_lock
->texture_id();
1064 mask_sampler
= SamplerTypeFromTextureTarget(mask_resource_lock
->target());
1067 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> contents_resource_lock
;
1068 if (filter_image_id
) {
1069 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
1070 gl_
->BindTexture(GL_TEXTURE_2D
, filter_image_id
);
1072 contents_resource_lock
=
1073 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1074 resource_provider_
, contents_texture
->id(), GL_LINEAR
));
1075 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1076 contents_resource_lock
->target());
1079 if (!use_shaders_for_blending
) {
1080 if (!use_blend_equation_advanced_coherent_
&& use_blend_equation_advanced_
)
1081 gl_
->BlendBarrierKHR();
1083 ApplyBlendModeUsingBlendFunc(blend_mode
);
1086 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1087 gl_
, &highp_threshold_cache_
, highp_threshold_min_
,
1088 quad
->shared_quad_state
->visible_quad_layer_rect
.bottom_right());
1090 ShaderLocations locations
;
1092 DCHECK_EQ(background_texture
|| background_image_id
,
1093 use_shaders_for_blending
);
1094 BlendMode shader_blend_mode
= use_shaders_for_blending
1095 ? BlendModeFromSkXfermode(blend_mode
)
1098 if (use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1099 const RenderPassMaskProgramAA
* program
= GetRenderPassMaskProgramAA(
1100 tex_coord_precision
, mask_sampler
,
1101 shader_blend_mode
, mask_for_background
);
1102 SetUseProgram(program
->program());
1103 program
->vertex_shader().FillLocations(&locations
);
1104 program
->fragment_shader().FillLocations(&locations
);
1105 gl_
->Uniform1i(locations
.sampler
, 0);
1106 } else if (!use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1107 const RenderPassMaskProgram
* program
= GetRenderPassMaskProgram(
1108 tex_coord_precision
, mask_sampler
,
1109 shader_blend_mode
, mask_for_background
);
1110 SetUseProgram(program
->program());
1111 program
->vertex_shader().FillLocations(&locations
);
1112 program
->fragment_shader().FillLocations(&locations
);
1113 gl_
->Uniform1i(locations
.sampler
, 0);
1114 } else if (use_aa
&& !mask_texture_id
&& !use_color_matrix
) {
1115 const RenderPassProgramAA
* program
=
1116 GetRenderPassProgramAA(tex_coord_precision
, shader_blend_mode
);
1117 SetUseProgram(program
->program());
1118 program
->vertex_shader().FillLocations(&locations
);
1119 program
->fragment_shader().FillLocations(&locations
);
1120 gl_
->Uniform1i(locations
.sampler
, 0);
1121 } else if (use_aa
&& mask_texture_id
&& use_color_matrix
) {
1122 const RenderPassMaskColorMatrixProgramAA
* program
=
1123 GetRenderPassMaskColorMatrixProgramAA(
1124 tex_coord_precision
, mask_sampler
,
1125 shader_blend_mode
, mask_for_background
);
1126 SetUseProgram(program
->program());
1127 program
->vertex_shader().FillLocations(&locations
);
1128 program
->fragment_shader().FillLocations(&locations
);
1129 gl_
->Uniform1i(locations
.sampler
, 0);
1130 } else if (use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1131 const RenderPassColorMatrixProgramAA
* program
=
1132 GetRenderPassColorMatrixProgramAA(tex_coord_precision
,
1134 SetUseProgram(program
->program());
1135 program
->vertex_shader().FillLocations(&locations
);
1136 program
->fragment_shader().FillLocations(&locations
);
1137 gl_
->Uniform1i(locations
.sampler
, 0);
1138 } else if (!use_aa
&& mask_texture_id
&& use_color_matrix
) {
1139 const RenderPassMaskColorMatrixProgram
* program
=
1140 GetRenderPassMaskColorMatrixProgram(
1141 tex_coord_precision
, mask_sampler
,
1142 shader_blend_mode
, mask_for_background
);
1143 SetUseProgram(program
->program());
1144 program
->vertex_shader().FillLocations(&locations
);
1145 program
->fragment_shader().FillLocations(&locations
);
1146 gl_
->Uniform1i(locations
.sampler
, 0);
1147 } else if (!use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1148 const RenderPassColorMatrixProgram
* program
=
1149 GetRenderPassColorMatrixProgram(tex_coord_precision
, shader_blend_mode
);
1150 SetUseProgram(program
->program());
1151 program
->vertex_shader().FillLocations(&locations
);
1152 program
->fragment_shader().FillLocations(&locations
);
1153 gl_
->Uniform1i(locations
.sampler
, 0);
1155 const RenderPassProgram
* program
=
1156 GetRenderPassProgram(tex_coord_precision
, shader_blend_mode
);
1157 SetUseProgram(program
->program());
1158 program
->vertex_shader().FillLocations(&locations
);
1159 program
->fragment_shader().FillLocations(&locations
);
1160 gl_
->Uniform1i(locations
.sampler
, 0);
1163 quad
->rect
.width() / static_cast<float>(contents_texture
->size().width());
1164 float tex_scale_y
= quad
->rect
.height() /
1165 static_cast<float>(contents_texture
->size().height());
1166 DCHECK_LE(tex_scale_x
, 1.0f
);
1167 DCHECK_LE(tex_scale_y
, 1.0f
);
1169 DCHECK(locations
.tex_transform
!= -1 || IsContextLost());
1170 // Flip the content vertically in the shader, as the RenderPass input
1171 // texture is already oriented the same way as the framebuffer, but the
1172 // projection transform does a flip.
1173 gl_
->Uniform4f(locations
.tex_transform
, 0.0f
, tex_scale_y
, tex_scale_x
,
1176 GLint last_texture_unit
= 0;
1177 if (locations
.mask_sampler
!= -1) {
1178 DCHECK_NE(locations
.mask_tex_coord_scale
, 1);
1179 DCHECK_NE(locations
.mask_tex_coord_offset
, 1);
1180 gl_
->Uniform1i(locations
.mask_sampler
, 1);
1182 gfx::RectF mask_uv_rect
= quad
->MaskUVRect();
1183 if (mask_sampler
!= SAMPLER_TYPE_2D
) {
1184 mask_uv_rect
.Scale(quad
->mask_texture_size
.width(),
1185 quad
->mask_texture_size
.height());
1188 // Mask textures are oriented vertically flipped relative to the framebuffer
1189 // and the RenderPass contents texture, so we flip the tex coords from the
1190 // RenderPass texture to find the mask texture coords.
1191 gl_
->Uniform2f(locations
.mask_tex_coord_offset
, mask_uv_rect
.x(),
1192 mask_uv_rect
.bottom());
1193 gl_
->Uniform2f(locations
.mask_tex_coord_scale
,
1194 mask_uv_rect
.width() / tex_scale_x
,
1195 -mask_uv_rect
.height() / tex_scale_y
);
1197 last_texture_unit
= 1;
1200 if (locations
.edge
!= -1)
1201 gl_
->Uniform3fv(locations
.edge
, 8, edge
);
1203 if (locations
.viewport
!= -1) {
1204 float viewport
[4] = {
1205 static_cast<float>(current_window_space_viewport_
.x()),
1206 static_cast<float>(current_window_space_viewport_
.y()),
1207 static_cast<float>(current_window_space_viewport_
.width()),
1208 static_cast<float>(current_window_space_viewport_
.height()),
1210 gl_
->Uniform4fv(locations
.viewport
, 1, viewport
);
1213 if (locations
.color_matrix
!= -1) {
1215 for (int i
= 0; i
< 4; ++i
) {
1216 for (int j
= 0; j
< 4; ++j
)
1217 matrix
[i
* 4 + j
] = SkScalarToFloat(color_matrix
[j
* 5 + i
]);
1219 gl_
->UniformMatrix4fv(locations
.color_matrix
, 1, false, matrix
);
1221 static const float kScale
= 1.0f
/ 255.0f
;
1222 if (locations
.color_offset
!= -1) {
1224 for (int i
= 0; i
< 4; ++i
)
1225 offset
[i
] = SkScalarToFloat(color_matrix
[i
* 5 + 4]) * kScale
;
1227 gl_
->Uniform4fv(locations
.color_offset
, 1, offset
);
1230 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> shader_background_sampler_lock
;
1231 if (locations
.backdrop
!= -1) {
1232 DCHECK(background_texture
|| background_image_id
);
1233 DCHECK_NE(locations
.backdrop
, 0);
1234 DCHECK_NE(locations
.backdrop_rect
, 0);
1236 gl_
->Uniform1i(locations
.backdrop
, ++last_texture_unit
);
1238 gl_
->Uniform4f(locations
.backdrop_rect
, background_rect
.x(),
1239 background_rect
.y(), background_rect
.width(),
1240 background_rect
.height());
1242 if (background_image_id
) {
1243 gl_
->ActiveTexture(GL_TEXTURE0
+ last_texture_unit
);
1244 gl_
->BindTexture(GL_TEXTURE_2D
, background_image_id
);
1245 gl_
->ActiveTexture(GL_TEXTURE0
);
1246 if (mask_for_background
)
1247 gl_
->Uniform1i(locations
.original_backdrop
, ++last_texture_unit
);
1249 if (background_texture
) {
1250 shader_background_sampler_lock
= make_scoped_ptr(
1251 new ResourceProvider::ScopedSamplerGL(resource_provider_
,
1252 background_texture
->id(),
1253 GL_TEXTURE0
+ last_texture_unit
,
1255 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1256 shader_background_sampler_lock
->target());
1260 SetShaderOpacity(quad
->shared_quad_state
->opacity
, locations
.alpha
);
1261 SetShaderQuadF(surface_quad
, locations
.quad
);
1262 DrawQuadGeometry(frame
, quad
->shared_quad_state
->quad_to_target_transform
,
1263 quad
->rect
, locations
.matrix
);
1265 // Flush the compositor context before the filter bitmap goes out of
1266 // scope, so the draw gets processed before the filter texture gets deleted.
1267 if (filter_image_id
)
1270 if (!use_shaders_for_blending
)
1271 RestoreBlendFuncToDefault(blend_mode
);
1274 struct SolidColorProgramUniforms
{
1276 unsigned matrix_location
;
1277 unsigned viewport_location
;
1278 unsigned quad_location
;
1279 unsigned edge_location
;
1280 unsigned color_location
;
1284 static void SolidColorUniformLocation(T program
,
1285 SolidColorProgramUniforms
* uniforms
) {
1286 uniforms
->program
= program
->program();
1287 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1288 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1289 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1290 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1291 uniforms
->color_location
= program
->fragment_shader().color_location();
1295 // These functions determine if a quad, clipped by a clip_region contains
1296 // the entire {top|bottom|left|right} edge.
1297 bool is_top(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1298 if (!quad
->IsTopEdge())
1303 return std::abs(clip_region
->p1().y()) < kAntiAliasingEpsilon
&&
1304 std::abs(clip_region
->p2().y()) < kAntiAliasingEpsilon
;
1307 bool is_bottom(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1308 if (!quad
->IsBottomEdge())
1313 return std::abs(clip_region
->p3().y() -
1314 quad
->shared_quad_state
->quad_layer_bounds
.height()) <
1315 kAntiAliasingEpsilon
&&
1316 std::abs(clip_region
->p4().y() -
1317 quad
->shared_quad_state
->quad_layer_bounds
.height()) <
1318 kAntiAliasingEpsilon
;
1321 bool is_left(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1322 if (!quad
->IsLeftEdge())
1327 return std::abs(clip_region
->p1().x()) < kAntiAliasingEpsilon
&&
1328 std::abs(clip_region
->p4().x()) < kAntiAliasingEpsilon
;
1331 bool is_right(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1332 if (!quad
->IsRightEdge())
1337 return std::abs(clip_region
->p2().x() -
1338 quad
->shared_quad_state
->quad_layer_bounds
.width()) <
1339 kAntiAliasingEpsilon
&&
1340 std::abs(clip_region
->p3().x() -
1341 quad
->shared_quad_state
->quad_layer_bounds
.width()) <
1342 kAntiAliasingEpsilon
;
1344 } // anonymous namespace
1346 static gfx::QuadF
GetDeviceQuadWithAntialiasingOnExteriorEdges(
1347 const LayerQuad
& device_layer_edges
,
1348 const gfx::Transform
& device_transform
,
1349 const gfx::QuadF
& tile_quad
,
1350 const gfx::QuadF
* clip_region
,
1351 const DrawQuad
* quad
) {
1352 gfx::RectF tile_rect
= quad
->visible_rect
;
1354 gfx::PointF bottom_right
= tile_quad
.p3();
1355 gfx::PointF bottom_left
= tile_quad
.p4();
1356 gfx::PointF top_left
= tile_quad
.p1();
1357 gfx::PointF top_right
= tile_quad
.p2();
1358 bool clipped
= false;
1360 // Map points to device space. We ignore |clipped|, since the result of
1361 // |MapPoint()| still produces a valid point to draw the quad with. When
1362 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1363 bottom_right
= MathUtil::MapPoint(device_transform
, bottom_right
, &clipped
);
1364 bottom_left
= MathUtil::MapPoint(device_transform
, bottom_left
, &clipped
);
1365 top_left
= MathUtil::MapPoint(device_transform
, top_left
, &clipped
);
1366 top_right
= MathUtil::MapPoint(device_transform
, top_right
, &clipped
);
1368 LayerQuad::Edge
bottom_edge(bottom_right
, bottom_left
);
1369 LayerQuad::Edge
left_edge(bottom_left
, top_left
);
1370 LayerQuad::Edge
top_edge(top_left
, top_right
);
1371 LayerQuad::Edge
right_edge(top_right
, bottom_right
);
1373 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1374 // If an edge is degenerate we do not want to replace it with a "proper" edge
1375 // as that will cause the quad to possibly expand is strange ways.
1376 if (!top_edge
.degenerate() && is_top(clip_region
, quad
) &&
1377 tile_rect
.y() == quad
->rect
.y()) {
1378 top_edge
= device_layer_edges
.top();
1380 if (!left_edge
.degenerate() && is_left(clip_region
, quad
) &&
1381 tile_rect
.x() == quad
->rect
.x()) {
1382 left_edge
= device_layer_edges
.left();
1384 if (!right_edge
.degenerate() && is_right(clip_region
, quad
) &&
1385 tile_rect
.right() == quad
->rect
.right()) {
1386 right_edge
= device_layer_edges
.right();
1388 if (!bottom_edge
.degenerate() && is_bottom(clip_region
, quad
) &&
1389 tile_rect
.bottom() == quad
->rect
.bottom()) {
1390 bottom_edge
= device_layer_edges
.bottom();
1393 float sign
= tile_quad
.IsCounterClockwise() ? -1 : 1;
1394 bottom_edge
.scale(sign
);
1395 left_edge
.scale(sign
);
1396 top_edge
.scale(sign
);
1397 right_edge
.scale(sign
);
1399 // Create device space quad.
1400 return LayerQuad(left_edge
, top_edge
, right_edge
, bottom_edge
).ToQuadF();
1403 float GetTotalQuadError(const gfx::QuadF
* clipped_quad
,
1404 const gfx::QuadF
* ideal_rect
) {
1405 return (clipped_quad
->p1() - ideal_rect
->p1()).LengthSquared() +
1406 (clipped_quad
->p2() - ideal_rect
->p2()).LengthSquared() +
1407 (clipped_quad
->p3() - ideal_rect
->p3()).LengthSquared() +
1408 (clipped_quad
->p4() - ideal_rect
->p4()).LengthSquared();
1411 // Attempt to rotate the clipped quad until it lines up the most
1412 // correctly. This is necessary because we check the edges of this
1413 // quad against the expected left/right/top/bottom for anti-aliasing.
1414 void AlignQuadToBoundingBox(gfx::QuadF
* clipped_quad
) {
1415 gfx::QuadF bounding_quad
= gfx::QuadF(clipped_quad
->BoundingBox());
1416 gfx::QuadF best_rotation
= *clipped_quad
;
1417 float least_error_amount
= GetTotalQuadError(clipped_quad
, &bounding_quad
);
1418 for (size_t i
= 1; i
< 4; ++i
) {
1419 clipped_quad
->Realign(1);
1420 float new_error
= GetTotalQuadError(clipped_quad
, &bounding_quad
);
1421 if (new_error
< least_error_amount
) {
1422 least_error_amount
= new_error
;
1423 best_rotation
= *clipped_quad
;
1426 *clipped_quad
= best_rotation
;
1429 // Map device space quad to local space. Device_transform has no 3d
1430 // component since it was flattened, so we don't need to project. We should
1431 // have already checked that the transform was uninvertible before this call.
1432 gfx::QuadF
MapQuadToLocalSpace(const gfx::Transform
& device_transform
,
1433 const gfx::QuadF
& device_quad
) {
1434 gfx::Transform
inverse_device_transform(gfx::Transform::kSkipInitialization
);
1435 DCHECK(device_transform
.IsInvertible());
1436 bool did_invert
= device_transform
.GetInverse(&inverse_device_transform
);
1438 bool clipped
= false;
1439 gfx::QuadF local_quad
=
1440 MathUtil::MapQuad(inverse_device_transform
, device_quad
, &clipped
);
1441 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1442 // cause device_quad to become clipped. To our knowledge this scenario does
1443 // not need to be handled differently than the unclipped case.
1447 void InflateAntiAliasingDistances(const gfx::QuadF
& quad
,
1448 LayerQuad
* device_layer_edges
,
1450 DCHECK(!quad
.BoundingBox().IsEmpty());
1451 LayerQuad
device_layer_bounds(gfx::QuadF(quad
.BoundingBox()));
1453 device_layer_edges
->InflateAntiAliasingDistance();
1454 device_layer_edges
->ToFloatArray(edge
);
1456 device_layer_bounds
.InflateAntiAliasingDistance();
1457 device_layer_bounds
.ToFloatArray(&edge
[12]);
1461 bool GLRenderer::ShouldAntialiasQuad(const gfx::QuadF
& device_layer_quad
,
1464 // AAing clipped quads is not supported by the code yet.
1467 if (device_layer_quad
.BoundingBox().IsEmpty())
1472 bool is_axis_aligned_in_target
= device_layer_quad
.IsRectilinear();
1473 bool is_nearest_rect_within_epsilon
=
1474 is_axis_aligned_in_target
&&
1475 gfx::IsNearestRectWithinDistance(device_layer_quad
.BoundingBox(),
1476 kAntiAliasingEpsilon
);
1477 return !is_nearest_rect_within_epsilon
;
1481 void GLRenderer::SetupQuadForClippingAndAntialiasing(
1482 const gfx::Transform
& device_transform
,
1483 const DrawQuad
* quad
,
1484 const gfx::QuadF
* aa_quad
,
1485 const gfx::QuadF
* clip_region
,
1486 gfx::QuadF
* local_quad
,
1488 gfx::QuadF rotated_clip
;
1489 const gfx::QuadF
* local_clip_region
= clip_region
;
1490 if (local_clip_region
) {
1491 rotated_clip
= *clip_region
;
1492 AlignQuadToBoundingBox(&rotated_clip
);
1493 local_clip_region
= &rotated_clip
;
1497 if (local_clip_region
)
1498 *local_quad
= *local_clip_region
;
1502 LayerQuad
device_layer_edges(*aa_quad
);
1503 InflateAntiAliasingDistances(*aa_quad
, &device_layer_edges
, edge
);
1505 // If we have a clip region then we are split, and therefore
1506 // by necessity, at least one of our edges is not an external
1508 bool is_full_rect
= quad
->visible_rect
== quad
->rect
;
1510 bool region_contains_all_outside_edges
=
1512 (is_top(local_clip_region
, quad
) && is_left(local_clip_region
, quad
) &&
1513 is_bottom(local_clip_region
, quad
) && is_right(local_clip_region
, quad
));
1515 bool use_aa_on_all_four_edges
=
1516 !local_clip_region
&& region_contains_all_outside_edges
;
1518 gfx::QuadF device_quad
;
1519 if (use_aa_on_all_four_edges
) {
1520 device_quad
= device_layer_edges
.ToQuadF();
1522 gfx::QuadF
tile_quad(local_clip_region
? *local_clip_region
1523 : gfx::QuadF(quad
->visible_rect
));
1524 device_quad
= GetDeviceQuadWithAntialiasingOnExteriorEdges(
1525 device_layer_edges
, device_transform
, tile_quad
, local_clip_region
,
1529 *local_quad
= MapQuadToLocalSpace(device_transform
, device_quad
);
1533 void GLRenderer::SetupRenderPassQuadForClippingAndAntialiasing(
1534 const gfx::Transform
& device_transform
,
1535 const RenderPassDrawQuad
* quad
,
1536 const gfx::QuadF
* aa_quad
,
1537 const gfx::QuadF
* clip_region
,
1538 gfx::QuadF
* local_quad
,
1540 gfx::QuadF rotated_clip
;
1541 const gfx::QuadF
* local_clip_region
= clip_region
;
1542 if (local_clip_region
) {
1543 rotated_clip
= *clip_region
;
1544 AlignQuadToBoundingBox(&rotated_clip
);
1545 local_clip_region
= &rotated_clip
;
1549 GetScaledRegion(quad
->rect
, local_clip_region
, local_quad
);
1553 LayerQuad
device_layer_edges(*aa_quad
);
1554 InflateAntiAliasingDistances(*aa_quad
, &device_layer_edges
, edge
);
1556 gfx::QuadF device_quad
;
1558 // Apply anti-aliasing only to the edges that are not being clipped
1559 if (local_clip_region
) {
1560 gfx::QuadF
tile_quad(quad
->visible_rect
);
1561 GetScaledRegion(quad
->rect
, local_clip_region
, &tile_quad
);
1562 device_quad
= GetDeviceQuadWithAntialiasingOnExteriorEdges(
1563 device_layer_edges
, device_transform
, tile_quad
, local_clip_region
,
1566 device_quad
= device_layer_edges
.ToQuadF();
1569 *local_quad
= MapQuadToLocalSpace(device_transform
, device_quad
);
1572 void GLRenderer::DrawSolidColorQuad(const DrawingFrame
* frame
,
1573 const SolidColorDrawQuad
* quad
,
1574 const gfx::QuadF
* clip_region
) {
1575 gfx::Rect tile_rect
= quad
->visible_rect
;
1577 SkColor color
= quad
->color
;
1578 float opacity
= quad
->shared_quad_state
->opacity
;
1579 float alpha
= (SkColorGetA(color
) * (1.0f
/ 255.0f
)) * opacity
;
1581 // Early out if alpha is small enough that quad doesn't contribute to output.
1582 if (alpha
< std::numeric_limits
<float>::epsilon() &&
1583 quad
->ShouldDrawWithBlending())
1586 gfx::Transform device_transform
=
1587 frame
->window_matrix
* frame
->projection_matrix
*
1588 quad
->shared_quad_state
->quad_to_target_transform
;
1589 device_transform
.FlattenTo2d();
1590 if (!device_transform
.IsInvertible())
1593 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1595 gfx::QuadF device_layer_quad
;
1596 bool use_aa
= false;
1597 bool allow_aa
= settings_
->allow_antialiasing
&&
1598 !quad
->force_anti_aliasing_off
&& quad
->IsEdge();
1601 bool clipped
= false;
1602 bool force_aa
= false;
1603 device_layer_quad
= MathUtil::MapQuad(
1605 gfx::QuadF(quad
->shared_quad_state
->visible_quad_layer_rect
), &clipped
);
1606 use_aa
= ShouldAntialiasQuad(device_layer_quad
, clipped
, force_aa
);
1610 const gfx::QuadF
* aa_quad
= use_aa
? &device_layer_quad
: nullptr;
1611 SetupQuadForClippingAndAntialiasing(device_transform
, quad
, aa_quad
,
1612 clip_region
, &local_quad
, edge
);
1614 SolidColorProgramUniforms uniforms
;
1616 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms
);
1618 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms
);
1620 SetUseProgram(uniforms
.program
);
1622 gl_
->Uniform4f(uniforms
.color_location
,
1623 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
1624 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
1625 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
, alpha
);
1627 float viewport
[4] = {
1628 static_cast<float>(current_window_space_viewport_
.x()),
1629 static_cast<float>(current_window_space_viewport_
.y()),
1630 static_cast<float>(current_window_space_viewport_
.width()),
1631 static_cast<float>(current_window_space_viewport_
.height()),
1633 gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
);
1634 gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
);
1637 // Enable blending when the quad properties require it or if we decided
1638 // to use antialiasing.
1639 SetBlendEnabled(quad
->ShouldDrawWithBlending() || use_aa
);
1641 // Normalize to tile_rect.
1642 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1644 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1646 // The transform and vertex data are used to figure out the extents that the
1647 // un-antialiased quad should have and which vertex this is and the float
1648 // quad passed in via uniform is the actual geometry that gets used to draw
1649 // it. This is why this centered rect is used and not the original quad_rect.
1650 gfx::RectF
centered_rect(
1651 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1653 DrawQuadGeometry(frame
, quad
->shared_quad_state
->quad_to_target_transform
,
1654 centered_rect
, uniforms
.matrix_location
);
1657 struct TileProgramUniforms
{
1659 unsigned matrix_location
;
1660 unsigned viewport_location
;
1661 unsigned quad_location
;
1662 unsigned edge_location
;
1663 unsigned vertex_tex_transform_location
;
1664 unsigned sampler_location
;
1665 unsigned fragment_tex_transform_location
;
1666 unsigned alpha_location
;
1670 static void TileUniformLocation(T program
, TileProgramUniforms
* uniforms
) {
1671 uniforms
->program
= program
->program();
1672 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1673 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1674 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1675 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1676 uniforms
->vertex_tex_transform_location
=
1677 program
->vertex_shader().vertex_tex_transform_location();
1679 uniforms
->sampler_location
= program
->fragment_shader().sampler_location();
1680 uniforms
->alpha_location
= program
->fragment_shader().alpha_location();
1681 uniforms
->fragment_tex_transform_location
=
1682 program
->fragment_shader().fragment_tex_transform_location();
1685 void GLRenderer::DrawTileQuad(const DrawingFrame
* frame
,
1686 const TileDrawQuad
* quad
,
1687 const gfx::QuadF
* clip_region
) {
1688 DrawContentQuad(frame
, quad
, quad
->resource_id(), clip_region
);
1691 void GLRenderer::DrawContentQuad(const DrawingFrame
* frame
,
1692 const ContentDrawQuadBase
* quad
,
1693 ResourceId resource_id
,
1694 const gfx::QuadF
* clip_region
) {
1695 gfx::Transform device_transform
=
1696 frame
->window_matrix
* frame
->projection_matrix
*
1697 quad
->shared_quad_state
->quad_to_target_transform
;
1698 device_transform
.FlattenTo2d();
1700 gfx::QuadF device_layer_quad
;
1701 bool use_aa
= false;
1702 bool allow_aa
= settings_
->allow_antialiasing
&& quad
->IsEdge();
1704 bool clipped
= false;
1705 bool force_aa
= false;
1706 device_layer_quad
= MathUtil::MapQuad(
1708 gfx::QuadF(quad
->shared_quad_state
->visible_quad_layer_rect
), &clipped
);
1709 use_aa
= ShouldAntialiasQuad(device_layer_quad
, clipped
, force_aa
);
1712 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1713 // similar to the way DrawContentQuadNoAA works and then consider
1714 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1716 DrawContentQuadAA(frame
, quad
, resource_id
, device_transform
,
1717 device_layer_quad
, clip_region
);
1719 DrawContentQuadNoAA(frame
, quad
, resource_id
, clip_region
);
1722 void GLRenderer::DrawContentQuadAA(const DrawingFrame
* frame
,
1723 const ContentDrawQuadBase
* quad
,
1724 ResourceId resource_id
,
1725 const gfx::Transform
& device_transform
,
1726 const gfx::QuadF
& aa_quad
,
1727 const gfx::QuadF
* clip_region
) {
1728 if (!device_transform
.IsInvertible())
1731 gfx::Rect tile_rect
= quad
->visible_rect
;
1733 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1734 quad
->tex_coord_rect
, quad
->rect
, tile_rect
);
1735 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1736 float tex_to_geom_scale_y
=
1737 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1739 gfx::RectF
clamp_geom_rect(tile_rect
);
1740 gfx::RectF
clamp_tex_rect(tex_coord_rect
);
1741 // Clamp texture coordinates to avoid sampling outside the layer
1742 // by deflating the tile region half a texel or half a texel
1743 // minus epsilon for one pixel layers. The resulting clamp region
1744 // is mapped to the unit square by the vertex shader and mapped
1745 // back to normalized texture coordinates by the fragment shader
1746 // after being clamped to 0-1 range.
1748 std::min(0.5f
, 0.5f
* clamp_tex_rect
.width() - kAntiAliasingEpsilon
);
1750 std::min(0.5f
, 0.5f
* clamp_tex_rect
.height() - kAntiAliasingEpsilon
);
1751 float geom_clamp_x
=
1752 std::min(tex_clamp_x
* tex_to_geom_scale_x
,
1753 0.5f
* clamp_geom_rect
.width() - kAntiAliasingEpsilon
);
1754 float geom_clamp_y
=
1755 std::min(tex_clamp_y
* tex_to_geom_scale_y
,
1756 0.5f
* clamp_geom_rect
.height() - kAntiAliasingEpsilon
);
1757 clamp_geom_rect
.Inset(geom_clamp_x
, geom_clamp_y
, geom_clamp_x
, geom_clamp_y
);
1758 clamp_tex_rect
.Inset(tex_clamp_x
, tex_clamp_y
, tex_clamp_x
, tex_clamp_y
);
1760 // Map clamping rectangle to unit square.
1761 float vertex_tex_translate_x
= -clamp_geom_rect
.x() / clamp_geom_rect
.width();
1762 float vertex_tex_translate_y
=
1763 -clamp_geom_rect
.y() / clamp_geom_rect
.height();
1764 float vertex_tex_scale_x
= tile_rect
.width() / clamp_geom_rect
.width();
1765 float vertex_tex_scale_y
= tile_rect
.height() / clamp_geom_rect
.height();
1767 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1768 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1770 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1772 SetupQuadForClippingAndAntialiasing(device_transform
, quad
, &aa_quad
,
1773 clip_region
, &local_quad
, edge
);
1774 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1775 resource_provider_
, resource_id
,
1776 quad
->nearest_neighbor
? GL_NEAREST
: GL_LINEAR
);
1777 SamplerType sampler
=
1778 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1780 float fragment_tex_translate_x
= clamp_tex_rect
.x();
1781 float fragment_tex_translate_y
= clamp_tex_rect
.y();
1782 float fragment_tex_scale_x
= clamp_tex_rect
.width();
1783 float fragment_tex_scale_y
= clamp_tex_rect
.height();
1785 // Map to normalized texture coordinates.
1786 if (sampler
!= SAMPLER_TYPE_2D_RECT
) {
1787 gfx::Size texture_size
= quad
->texture_size
;
1788 DCHECK(!texture_size
.IsEmpty());
1789 fragment_tex_translate_x
/= texture_size
.width();
1790 fragment_tex_translate_y
/= texture_size
.height();
1791 fragment_tex_scale_x
/= texture_size
.width();
1792 fragment_tex_scale_y
/= texture_size
.height();
1795 TileProgramUniforms uniforms
;
1796 if (quad
->swizzle_contents
) {
1797 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision
, sampler
),
1800 TileUniformLocation(GetTileProgramAA(tex_coord_precision
, sampler
),
1804 SetUseProgram(uniforms
.program
);
1805 gl_
->Uniform1i(uniforms
.sampler_location
, 0);
1807 float viewport
[4] = {
1808 static_cast<float>(current_window_space_viewport_
.x()),
1809 static_cast<float>(current_window_space_viewport_
.y()),
1810 static_cast<float>(current_window_space_viewport_
.width()),
1811 static_cast<float>(current_window_space_viewport_
.height()),
1813 gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
);
1814 gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
);
1816 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
, vertex_tex_translate_x
,
1817 vertex_tex_translate_y
, vertex_tex_scale_x
,
1818 vertex_tex_scale_y
);
1819 gl_
->Uniform4f(uniforms
.fragment_tex_transform_location
,
1820 fragment_tex_translate_x
, fragment_tex_translate_y
,
1821 fragment_tex_scale_x
, fragment_tex_scale_y
);
1823 // Blending is required for antialiasing.
1824 SetBlendEnabled(true);
1826 // Normalize to tile_rect.
1827 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1829 SetShaderOpacity(quad
->shared_quad_state
->opacity
, uniforms
.alpha_location
);
1830 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1832 // The transform and vertex data are used to figure out the extents that the
1833 // un-antialiased quad should have and which vertex this is and the float
1834 // quad passed in via uniform is the actual geometry that gets used to draw
1835 // it. This is why this centered rect is used and not the original quad_rect.
1836 gfx::RectF
centered_rect(
1837 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1839 DrawQuadGeometry(frame
, quad
->shared_quad_state
->quad_to_target_transform
,
1840 centered_rect
, uniforms
.matrix_location
);
1843 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame
* frame
,
1844 const ContentDrawQuadBase
* quad
,
1845 ResourceId resource_id
,
1846 const gfx::QuadF
* clip_region
) {
1847 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1848 quad
->tex_coord_rect
, quad
->rect
, quad
->visible_rect
);
1849 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1850 float tex_to_geom_scale_y
=
1851 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1853 bool scaled
= (tex_to_geom_scale_x
!= 1.f
|| tex_to_geom_scale_y
!= 1.f
);
1854 GLenum filter
= (scaled
||
1855 !quad
->shared_quad_state
->quad_to_target_transform
1856 .IsIdentityOrIntegerTranslation()) &&
1857 !quad
->nearest_neighbor
1861 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1862 resource_provider_
, resource_id
, filter
);
1863 SamplerType sampler
=
1864 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1866 float vertex_tex_translate_x
= tex_coord_rect
.x();
1867 float vertex_tex_translate_y
= tex_coord_rect
.y();
1868 float vertex_tex_scale_x
= tex_coord_rect
.width();
1869 float vertex_tex_scale_y
= tex_coord_rect
.height();
1871 // Map to normalized texture coordinates.
1872 if (sampler
!= SAMPLER_TYPE_2D_RECT
) {
1873 gfx::Size texture_size
= quad
->texture_size
;
1874 DCHECK(!texture_size
.IsEmpty());
1875 vertex_tex_translate_x
/= texture_size
.width();
1876 vertex_tex_translate_y
/= texture_size
.height();
1877 vertex_tex_scale_x
/= texture_size
.width();
1878 vertex_tex_scale_y
/= texture_size
.height();
1881 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1882 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1884 TileProgramUniforms uniforms
;
1885 if (quad
->ShouldDrawWithBlending()) {
1886 if (quad
->swizzle_contents
) {
1887 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision
, sampler
),
1890 TileUniformLocation(GetTileProgram(tex_coord_precision
, sampler
),
1894 if (quad
->swizzle_contents
) {
1895 TileUniformLocation(
1896 GetTileProgramSwizzleOpaque(tex_coord_precision
, sampler
), &uniforms
);
1898 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision
, sampler
),
1903 SetUseProgram(uniforms
.program
);
1904 gl_
->Uniform1i(uniforms
.sampler_location
, 0);
1906 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
, vertex_tex_translate_x
,
1907 vertex_tex_translate_y
, vertex_tex_scale_x
,
1908 vertex_tex_scale_y
);
1910 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1912 SetShaderOpacity(quad
->shared_quad_state
->opacity
, uniforms
.alpha_location
);
1914 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1915 // does, then vertices will match the texture mapping in the vertex buffer.
1916 // The method SetShaderQuadF() changes the order of vertices and so it's
1918 gfx::QuadF
tile_rect(quad
->visible_rect
);
1919 float width
= quad
->visible_rect
.width();
1920 float height
= quad
->visible_rect
.height();
1921 gfx::PointF top_left
= quad
->visible_rect
.origin();
1923 tile_rect
= *clip_region
;
1925 (tile_rect
.p4().x() - top_left
.x()) / width
,
1926 (tile_rect
.p4().y() - top_left
.y()) / height
,
1927 (tile_rect
.p1().x() - top_left
.x()) / width
,
1928 (tile_rect
.p1().y() - top_left
.y()) / height
,
1929 (tile_rect
.p2().x() - top_left
.x()) / width
,
1930 (tile_rect
.p2().y() - top_left
.y()) / height
,
1931 (tile_rect
.p3().x() - top_left
.x()) / width
,
1932 (tile_rect
.p3().y() - top_left
.y()) / height
,
1934 PrepareGeometry(CLIPPED_BINDING
);
1935 clipped_geometry_
->InitializeCustomQuadWithUVs(
1936 gfx::QuadF(quad
->visible_rect
), gl_uv
);
1938 PrepareGeometry(SHARED_BINDING
);
1940 float gl_quad
[8] = {
1950 gl_
->Uniform2fv(uniforms
.quad_location
, 4, gl_quad
);
1952 static float gl_matrix
[16];
1953 ToGLMatrix(&gl_matrix
[0],
1954 frame
->projection_matrix
*
1955 quad
->shared_quad_state
->quad_to_target_transform
);
1956 gl_
->UniformMatrix4fv(uniforms
.matrix_location
, 1, false, &gl_matrix
[0]);
1958 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0);
1961 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame
* frame
,
1962 const YUVVideoDrawQuad
* quad
,
1963 const gfx::QuadF
* clip_region
) {
1964 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1966 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1967 gl_
, &highp_threshold_cache_
, highp_threshold_min_
,
1968 quad
->shared_quad_state
->visible_quad_layer_rect
.bottom_right());
1970 bool use_alpha_plane
= quad
->a_plane_resource_id() != 0;
1972 ResourceProvider::ScopedSamplerGL
y_plane_lock(
1973 resource_provider_
, quad
->y_plane_resource_id(), GL_TEXTURE1
, GL_LINEAR
);
1974 ResourceProvider::ScopedSamplerGL
u_plane_lock(
1975 resource_provider_
, quad
->u_plane_resource_id(), GL_TEXTURE2
, GL_LINEAR
);
1976 DCHECK_EQ(y_plane_lock
.target(), u_plane_lock
.target());
1977 ResourceProvider::ScopedSamplerGL
v_plane_lock(
1978 resource_provider_
, quad
->v_plane_resource_id(), GL_TEXTURE3
, GL_LINEAR
);
1979 DCHECK_EQ(y_plane_lock
.target(), v_plane_lock
.target());
1980 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> a_plane_lock
;
1981 if (use_alpha_plane
) {
1982 a_plane_lock
.reset(new ResourceProvider::ScopedSamplerGL(
1983 resource_provider_
, quad
->a_plane_resource_id(), GL_TEXTURE4
,
1985 DCHECK_EQ(y_plane_lock
.target(), a_plane_lock
->target());
1988 // All planes must have the same sampler type.
1989 SamplerType sampler
= SamplerTypeFromTextureTarget(y_plane_lock
.target());
1991 int matrix_location
= -1;
1992 int ya_tex_scale_location
= -1;
1993 int ya_tex_offset_location
= -1;
1994 int uv_tex_scale_location
= -1;
1995 int uv_tex_offset_location
= -1;
1996 int ya_clamp_rect_location
= -1;
1997 int uv_clamp_rect_location
= -1;
1998 int y_texture_location
= -1;
1999 int u_texture_location
= -1;
2000 int v_texture_location
= -1;
2001 int a_texture_location
= -1;
2002 int yuv_matrix_location
= -1;
2003 int yuv_adj_location
= -1;
2004 int alpha_location
= -1;
2005 if (use_alpha_plane
) {
2006 const VideoYUVAProgram
* program
=
2007 GetVideoYUVAProgram(tex_coord_precision
, sampler
);
2008 DCHECK(program
&& (program
->initialized() || IsContextLost()));
2009 SetUseProgram(program
->program());
2010 matrix_location
= program
->vertex_shader().matrix_location();
2011 ya_tex_scale_location
= program
->vertex_shader().ya_tex_scale_location();
2012 ya_tex_offset_location
= program
->vertex_shader().ya_tex_offset_location();
2013 uv_tex_scale_location
= program
->vertex_shader().uv_tex_scale_location();
2014 uv_tex_offset_location
= program
->vertex_shader().uv_tex_offset_location();
2015 y_texture_location
= program
->fragment_shader().y_texture_location();
2016 u_texture_location
= program
->fragment_shader().u_texture_location();
2017 v_texture_location
= program
->fragment_shader().v_texture_location();
2018 a_texture_location
= program
->fragment_shader().a_texture_location();
2019 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
2020 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
2021 ya_clamp_rect_location
=
2022 program
->fragment_shader().ya_clamp_rect_location();
2023 uv_clamp_rect_location
=
2024 program
->fragment_shader().uv_clamp_rect_location();
2025 alpha_location
= program
->fragment_shader().alpha_location();
2027 const VideoYUVProgram
* program
=
2028 GetVideoYUVProgram(tex_coord_precision
, sampler
);
2029 DCHECK(program
&& (program
->initialized() || IsContextLost()));
2030 SetUseProgram(program
->program());
2031 matrix_location
= program
->vertex_shader().matrix_location();
2032 ya_tex_scale_location
= program
->vertex_shader().ya_tex_scale_location();
2033 ya_tex_offset_location
= program
->vertex_shader().ya_tex_offset_location();
2034 uv_tex_scale_location
= program
->vertex_shader().uv_tex_scale_location();
2035 uv_tex_offset_location
= program
->vertex_shader().uv_tex_offset_location();
2036 y_texture_location
= program
->fragment_shader().y_texture_location();
2037 u_texture_location
= program
->fragment_shader().u_texture_location();
2038 v_texture_location
= program
->fragment_shader().v_texture_location();
2039 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
2040 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
2041 ya_clamp_rect_location
=
2042 program
->fragment_shader().ya_clamp_rect_location();
2043 uv_clamp_rect_location
=
2044 program
->fragment_shader().uv_clamp_rect_location();
2045 alpha_location
= program
->fragment_shader().alpha_location();
2048 gfx::SizeF
ya_tex_scale(1.0f
, 1.0f
);
2049 gfx::SizeF
uv_tex_scale(1.0f
, 1.0f
);
2050 if (sampler
!= SAMPLER_TYPE_2D_RECT
) {
2051 DCHECK(!quad
->ya_tex_size
.IsEmpty());
2052 DCHECK(!quad
->uv_tex_size
.IsEmpty());
2053 ya_tex_scale
= gfx::SizeF(1.0f
/ quad
->ya_tex_size
.width(),
2054 1.0f
/ quad
->ya_tex_size
.height());
2055 uv_tex_scale
= gfx::SizeF(1.0f
/ quad
->uv_tex_size
.width(),
2056 1.0f
/ quad
->uv_tex_size
.height());
2059 float ya_vertex_tex_translate_x
=
2060 quad
->ya_tex_coord_rect
.x() * ya_tex_scale
.width();
2061 float ya_vertex_tex_translate_y
=
2062 quad
->ya_tex_coord_rect
.y() * ya_tex_scale
.height();
2063 float ya_vertex_tex_scale_x
=
2064 quad
->ya_tex_coord_rect
.width() * ya_tex_scale
.width();
2065 float ya_vertex_tex_scale_y
=
2066 quad
->ya_tex_coord_rect
.height() * ya_tex_scale
.height();
2068 float uv_vertex_tex_translate_x
=
2069 quad
->uv_tex_coord_rect
.x() * uv_tex_scale
.width();
2070 float uv_vertex_tex_translate_y
=
2071 quad
->uv_tex_coord_rect
.y() * uv_tex_scale
.height();
2072 float uv_vertex_tex_scale_x
=
2073 quad
->uv_tex_coord_rect
.width() * uv_tex_scale
.width();
2074 float uv_vertex_tex_scale_y
=
2075 quad
->uv_tex_coord_rect
.height() * uv_tex_scale
.height();
2077 gl_
->Uniform2f(ya_tex_scale_location
, ya_vertex_tex_scale_x
,
2078 ya_vertex_tex_scale_y
);
2079 gl_
->Uniform2f(ya_tex_offset_location
, ya_vertex_tex_translate_x
,
2080 ya_vertex_tex_translate_y
);
2081 gl_
->Uniform2f(uv_tex_scale_location
, uv_vertex_tex_scale_x
,
2082 uv_vertex_tex_scale_y
);
2083 gl_
->Uniform2f(uv_tex_offset_location
, uv_vertex_tex_translate_x
,
2084 uv_vertex_tex_translate_y
);
2086 gfx::RectF
ya_clamp_rect(ya_vertex_tex_translate_x
, ya_vertex_tex_translate_y
,
2087 ya_vertex_tex_scale_x
, ya_vertex_tex_scale_y
);
2088 ya_clamp_rect
.Inset(0.5f
* ya_tex_scale
.width(),
2089 0.5f
* ya_tex_scale
.height());
2090 gfx::RectF
uv_clamp_rect(uv_vertex_tex_translate_x
, uv_vertex_tex_translate_y
,
2091 uv_vertex_tex_scale_x
, uv_vertex_tex_scale_y
);
2092 uv_clamp_rect
.Inset(0.5f
* uv_tex_scale
.width(),
2093 0.5f
* uv_tex_scale
.height());
2094 gl_
->Uniform4f(ya_clamp_rect_location
, ya_clamp_rect
.x(), ya_clamp_rect
.y(),
2095 ya_clamp_rect
.right(), ya_clamp_rect
.bottom());
2096 gl_
->Uniform4f(uv_clamp_rect_location
, uv_clamp_rect
.x(), uv_clamp_rect
.y(),
2097 uv_clamp_rect
.right(), uv_clamp_rect
.bottom());
2099 gl_
->Uniform1i(y_texture_location
, 1);
2100 gl_
->Uniform1i(u_texture_location
, 2);
2101 gl_
->Uniform1i(v_texture_location
, 3);
2102 if (use_alpha_plane
)
2103 gl_
->Uniform1i(a_texture_location
, 4);
2105 // These values are magic numbers that are used in the transformation from YUV
2106 // to RGB color values. They are taken from the following webpage:
2107 // http://www.fourcc.org/fccyvrgb.php
2108 float yuv_to_rgb_rec601
[9] = {
2109 1.164f
, 1.164f
, 1.164f
, 0.0f
, -.391f
, 2.018f
, 1.596f
, -.813f
, 0.0f
,
2111 float yuv_to_rgb_jpeg
[9] = {
2112 1.f
, 1.f
, 1.f
, 0.0f
, -.34414f
, 1.772f
, 1.402f
, -.71414f
, 0.0f
,
2114 float yuv_to_rgb_rec709
[9] = {
2115 1.164f
, 1.164f
, 1.164f
, 0.0f
, -0.213f
, 2.112f
, 1.793f
, -0.533f
, 0.0f
,
2118 // These values map to 16, 128, and 128 respectively, and are computed
2119 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
2120 // They are used in the YUV to RGBA conversion formula:
2121 // Y - 16 : Gives 16 values of head and footroom for overshooting
2122 // U - 128 : Turns unsigned U into signed U [-128,127]
2123 // V - 128 : Turns unsigned V into signed V [-128,127]
2124 float yuv_adjust_constrained
[3] = {
2125 -0.0625f
, -0.5f
, -0.5f
,
2128 // Same as above, but without the head and footroom.
2129 float yuv_adjust_full
[3] = {
2133 float* yuv_to_rgb
= NULL
;
2134 float* yuv_adjust
= NULL
;
2136 switch (quad
->color_space
) {
2137 case YUVVideoDrawQuad::REC_601
:
2138 yuv_to_rgb
= yuv_to_rgb_rec601
;
2139 yuv_adjust
= yuv_adjust_constrained
;
2141 case YUVVideoDrawQuad::REC_709
:
2142 yuv_to_rgb
= yuv_to_rgb_rec709
;
2143 yuv_adjust
= yuv_adjust_constrained
;
2145 case YUVVideoDrawQuad::JPEG
:
2146 yuv_to_rgb
= yuv_to_rgb_jpeg
;
2147 yuv_adjust
= yuv_adjust_full
;
2151 // The transform and vertex data are used to figure out the extents that the
2152 // un-antialiased quad should have and which vertex this is and the float
2153 // quad passed in via uniform is the actual geometry that gets used to draw
2154 // it. This is why this centered rect is used and not the original quad_rect.
2155 gfx::RectF tile_rect
= quad
->rect
;
2156 gl_
->UniformMatrix3fv(yuv_matrix_location
, 1, 0, yuv_to_rgb
);
2157 gl_
->Uniform3fv(yuv_adj_location
, 1, yuv_adjust
);
2159 SetShaderOpacity(quad
->shared_quad_state
->opacity
, alpha_location
);
2161 DrawQuadGeometry(frame
, quad
->shared_quad_state
->quad_to_target_transform
,
2162 tile_rect
, matrix_location
);
2165 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2166 gfx::QuadF region_quad
= *clip_region
;
2167 region_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
2168 region_quad
-= gfx::Vector2dF(0.5f
, 0.5f
);
2169 DrawQuadGeometryClippedByQuadF(
2170 frame
, quad
->shared_quad_state
->quad_to_target_transform
, tile_rect
,
2171 region_quad
, matrix_location
, uvs
);
2175 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame
* frame
,
2176 const StreamVideoDrawQuad
* quad
,
2177 const gfx::QuadF
* clip_region
) {
2178 SetBlendEnabled(quad
->ShouldDrawWithBlending());
2180 static float gl_matrix
[16];
2182 DCHECK(capabilities_
.using_egl_image
);
2184 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2185 gl_
, &highp_threshold_cache_
, highp_threshold_min_
,
2186 quad
->shared_quad_state
->visible_quad_layer_rect
.bottom_right());
2188 const VideoStreamTextureProgram
* program
=
2189 GetVideoStreamTextureProgram(tex_coord_precision
);
2190 SetUseProgram(program
->program());
2192 ToGLMatrix(&gl_matrix
[0], quad
->matrix
);
2193 gl_
->UniformMatrix4fv(program
->vertex_shader().tex_matrix_location(), 1,
2196 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2197 quad
->resource_id());
2198 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2199 gl_
->BindTexture(GL_TEXTURE_EXTERNAL_OES
, lock
.texture_id());
2201 gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0);
2203 SetShaderOpacity(quad
->shared_quad_state
->opacity
,
2204 program
->fragment_shader().alpha_location());
2206 DrawQuadGeometry(frame
, quad
->shared_quad_state
->quad_to_target_transform
,
2207 quad
->rect
, program
->vertex_shader().matrix_location());
2209 gfx::QuadF
region_quad(*clip_region
);
2210 region_quad
.Scale(1.0f
/ quad
->rect
.width(), 1.0f
/ quad
->rect
.height());
2211 region_quad
-= gfx::Vector2dF(0.5f
, 0.5f
);
2213 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2214 DrawQuadGeometryClippedByQuadF(
2215 frame
, quad
->shared_quad_state
->quad_to_target_transform
, quad
->rect
,
2216 region_quad
, program
->vertex_shader().matrix_location(), uvs
);
2220 struct TextureProgramBinding
{
2221 template <class Program
>
2222 void Set(Program
* program
) {
2224 program_id
= program
->program();
2225 sampler_location
= program
->fragment_shader().sampler_location();
2226 matrix_location
= program
->vertex_shader().matrix_location();
2227 background_color_location
=
2228 program
->fragment_shader().background_color_location();
2231 int sampler_location
;
2232 int matrix_location
;
2233 int transform_location
;
2234 int background_color_location
;
2237 struct TexTransformTextureProgramBinding
: TextureProgramBinding
{
2238 template <class Program
>
2239 void Set(Program
* program
) {
2240 TextureProgramBinding::Set(program
);
2241 tex_transform_location
= program
->vertex_shader().tex_transform_location();
2242 vertex_opacity_location
=
2243 program
->vertex_shader().vertex_opacity_location();
2245 int tex_transform_location
;
2246 int vertex_opacity_location
;
2249 void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding
) {
2250 // Check to see if we have anything to draw.
2251 if (draw_cache_
.program_id
== -1)
2254 PrepareGeometry(flush_binding
);
2256 // Set the correct blending mode.
2257 SetBlendEnabled(draw_cache_
.needs_blending
);
2259 // Bind the program to the GL state.
2260 SetUseProgram(draw_cache_
.program_id
);
2262 // Bind the correct texture sampler location.
2263 gl_
->Uniform1i(draw_cache_
.sampler_location
, 0);
2265 // Assume the current active textures is 0.
2266 ResourceProvider::ScopedSamplerGL
locked_quad(
2268 draw_cache_
.resource_id
,
2269 draw_cache_
.nearest_neighbor
? GL_NEAREST
: GL_LINEAR
);
2270 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2271 gl_
->BindTexture(locked_quad
.target(), locked_quad
.texture_id());
2273 static_assert(sizeof(Float4
) == 4 * sizeof(float),
2274 "Float4 struct should be densely packed");
2275 static_assert(sizeof(Float16
) == 16 * sizeof(float),
2276 "Float16 struct should be densely packed");
2278 // Upload the tranforms for both points and uvs.
2279 gl_
->UniformMatrix4fv(
2280 static_cast<int>(draw_cache_
.matrix_location
),
2281 static_cast<int>(draw_cache_
.matrix_data
.size()), false,
2282 reinterpret_cast<float*>(&draw_cache_
.matrix_data
.front()));
2283 gl_
->Uniform4fv(static_cast<int>(draw_cache_
.uv_xform_location
),
2284 static_cast<int>(draw_cache_
.uv_xform_data
.size()),
2285 reinterpret_cast<float*>(&draw_cache_
.uv_xform_data
.front()));
2287 if (draw_cache_
.background_color
!= SK_ColorTRANSPARENT
) {
2288 Float4 background_color
= PremultipliedColor(draw_cache_
.background_color
);
2289 gl_
->Uniform4fv(draw_cache_
.background_color_location
, 1,
2290 background_color
.data
);
2294 static_cast<int>(draw_cache_
.vertex_opacity_location
),
2295 static_cast<int>(draw_cache_
.vertex_opacity_data
.size()),
2296 static_cast<float*>(&draw_cache_
.vertex_opacity_data
.front()));
2298 DCHECK_LE(draw_cache_
.matrix_data
.size(),
2299 static_cast<size_t>(std::numeric_limits
<int>::max()) / 6u);
2301 gl_
->DrawElements(GL_TRIANGLES
,
2302 6 * static_cast<int>(draw_cache_
.matrix_data
.size()),
2303 GL_UNSIGNED_SHORT
, 0);
2306 draw_cache_
.program_id
= -1;
2307 draw_cache_
.uv_xform_data
.resize(0);
2308 draw_cache_
.vertex_opacity_data
.resize(0);
2309 draw_cache_
.matrix_data
.resize(0);
2311 // If we had a clipped binding, prepare the shared binding for the
2313 if (flush_binding
== CLIPPED_BINDING
) {
2314 PrepareGeometry(SHARED_BINDING
);
2318 void GLRenderer::EnqueueTextureQuad(const DrawingFrame
* frame
,
2319 const TextureDrawQuad
* quad
,
2320 const gfx::QuadF
* clip_region
) {
2321 // If we have a clip_region then we have to render the next quad
2322 // with dynamic geometry, therefore we must flush all pending
2325 // We send in false here because we want to flush what's currently in the
2326 // queue using the shared_geometry and not clipped_geometry
2327 FlushTextureQuadCache(SHARED_BINDING
);
2330 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2331 gl_
, &highp_threshold_cache_
, highp_threshold_min_
,
2332 quad
->shared_quad_state
->visible_quad_layer_rect
.bottom_right());
2334 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2335 quad
->resource_id());
2336 const SamplerType sampler
= SamplerTypeFromTextureTarget(lock
.target());
2337 // Choose the correct texture program binding
2338 TexTransformTextureProgramBinding binding
;
2339 if (quad
->premultiplied_alpha
) {
2340 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2341 binding
.Set(GetTextureProgram(tex_coord_precision
, sampler
));
2343 binding
.Set(GetTextureBackgroundProgram(tex_coord_precision
, sampler
));
2346 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2348 GetNonPremultipliedTextureProgram(tex_coord_precision
, sampler
));
2350 binding
.Set(GetNonPremultipliedTextureBackgroundProgram(
2351 tex_coord_precision
, sampler
));
2355 int resource_id
= quad
->resource_id();
2357 if (draw_cache_
.program_id
!= binding
.program_id
||
2358 draw_cache_
.resource_id
!= resource_id
||
2359 draw_cache_
.needs_blending
!= quad
->ShouldDrawWithBlending() ||
2360 draw_cache_
.nearest_neighbor
!= quad
->nearest_neighbor
||
2361 draw_cache_
.background_color
!= quad
->background_color
||
2362 draw_cache_
.matrix_data
.size() >= 8) {
2363 FlushTextureQuadCache(SHARED_BINDING
);
2364 draw_cache_
.program_id
= binding
.program_id
;
2365 draw_cache_
.resource_id
= resource_id
;
2366 draw_cache_
.needs_blending
= quad
->ShouldDrawWithBlending();
2367 draw_cache_
.nearest_neighbor
= quad
->nearest_neighbor
;
2368 draw_cache_
.background_color
= quad
->background_color
;
2370 draw_cache_
.uv_xform_location
= binding
.tex_transform_location
;
2371 draw_cache_
.background_color_location
= binding
.background_color_location
;
2372 draw_cache_
.vertex_opacity_location
= binding
.vertex_opacity_location
;
2373 draw_cache_
.matrix_location
= binding
.matrix_location
;
2374 draw_cache_
.sampler_location
= binding
.sampler_location
;
2377 // Generate the uv-transform
2379 draw_cache_
.uv_xform_data
.push_back(UVTransform(quad
));
2381 Float4 uv_transform
= {{0.0f
, 0.0f
, 1.0f
, 1.0f
}};
2382 draw_cache_
.uv_xform_data
.push_back(uv_transform
);
2385 // Generate the vertex opacity
2386 const float opacity
= quad
->shared_quad_state
->opacity
;
2387 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[0] * opacity
);
2388 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[1] * opacity
);
2389 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[2] * opacity
);
2390 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[3] * opacity
);
2392 // Generate the transform matrix
2393 gfx::Transform quad_rect_matrix
;
2394 QuadRectTransform(&quad_rect_matrix
,
2395 quad
->shared_quad_state
->quad_to_target_transform
,
2397 quad_rect_matrix
= frame
->projection_matrix
* quad_rect_matrix
;
2400 quad_rect_matrix
.matrix().asColMajorf(m
.data
);
2401 draw_cache_
.matrix_data
.push_back(m
);
2404 gfx::QuadF scaled_region
;
2405 if (!GetScaledRegion(quad
->rect
, clip_region
, &scaled_region
)) {
2406 scaled_region
= SharedGeometryQuad().BoundingBox();
2408 // Both the scaled region and the SharedGeomtryQuad are in the space
2409 // -0.5->0.5. We need to move that to the space 0->1.
2411 uv
[0] = scaled_region
.p1().x() + 0.5f
;
2412 uv
[1] = scaled_region
.p1().y() + 0.5f
;
2413 uv
[2] = scaled_region
.p2().x() + 0.5f
;
2414 uv
[3] = scaled_region
.p2().y() + 0.5f
;
2415 uv
[4] = scaled_region
.p3().x() + 0.5f
;
2416 uv
[5] = scaled_region
.p3().y() + 0.5f
;
2417 uv
[6] = scaled_region
.p4().x() + 0.5f
;
2418 uv
[7] = scaled_region
.p4().y() + 0.5f
;
2419 PrepareGeometry(CLIPPED_BINDING
);
2420 clipped_geometry_
->InitializeCustomQuadWithUVs(scaled_region
, uv
);
2421 FlushTextureQuadCache(CLIPPED_BINDING
);
2425 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame
* frame
,
2426 const IOSurfaceDrawQuad
* quad
,
2427 const gfx::QuadF
* clip_region
) {
2428 SetBlendEnabled(quad
->ShouldDrawWithBlending());
2430 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2431 gl_
, &highp_threshold_cache_
, highp_threshold_min_
,
2432 quad
->shared_quad_state
->visible_quad_layer_rect
.bottom_right());
2434 TexTransformTextureProgramBinding binding
;
2435 binding
.Set(GetTextureIOSurfaceProgram(tex_coord_precision
));
2437 SetUseProgram(binding
.program_id
);
2438 gl_
->Uniform1i(binding
.sampler_location
, 0);
2439 if (quad
->orientation
== IOSurfaceDrawQuad::FLIPPED
) {
2441 binding
.tex_transform_location
, 0, quad
->io_surface_size
.height(),
2442 quad
->io_surface_size
.width(), quad
->io_surface_size
.height() * -1.0f
);
2444 gl_
->Uniform4f(binding
.tex_transform_location
, 0, 0,
2445 quad
->io_surface_size
.width(),
2446 quad
->io_surface_size
.height());
2449 const float vertex_opacity
[] = {quad
->shared_quad_state
->opacity
,
2450 quad
->shared_quad_state
->opacity
,
2451 quad
->shared_quad_state
->opacity
,
2452 quad
->shared_quad_state
->opacity
};
2453 gl_
->Uniform1fv(binding
.vertex_opacity_location
, 4, vertex_opacity
);
2455 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2456 quad
->io_surface_resource_id());
2457 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2458 gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, lock
.texture_id());
2461 DrawQuadGeometry(frame
, quad
->shared_quad_state
->quad_to_target_transform
,
2462 quad
->rect
, binding
.matrix_location
);
2465 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2466 DrawQuadGeometryClippedByQuadF(
2467 frame
, quad
->shared_quad_state
->quad_to_target_transform
, quad
->rect
,
2468 *clip_region
, binding
.matrix_location
, uvs
);
2471 gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, 0);
2474 void GLRenderer::FinishDrawingFrame(DrawingFrame
* frame
) {
2475 if (use_sync_query_
) {
2476 DCHECK(current_sync_query_
);
2477 current_sync_query_
->End();
2478 pending_sync_queries_
.push_back(current_sync_query_
.Pass());
2481 current_framebuffer_lock_
= nullptr;
2482 swap_buffer_rect_
.Union(gfx::ToEnclosingRect(frame
->root_damage_rect
));
2484 gl_
->Disable(GL_BLEND
);
2485 blend_shadow_
= false;
2487 ScheduleOverlays(frame
);
2490 void GLRenderer::FinishDrawingQuadList() {
2491 FlushTextureQuadCache(SHARED_BINDING
);
2494 bool GLRenderer::FlippedFramebuffer(const DrawingFrame
* frame
) const {
2495 if (frame
->current_render_pass
!= frame
->root_render_pass
)
2497 return FlippedRootFramebuffer();
2500 bool GLRenderer::FlippedRootFramebuffer() const {
2501 // GL is normally flipped, so a flipped output results in an unflipping.
2502 return !output_surface_
->capabilities().flipped_output_surface
;
2505 void GLRenderer::EnsureScissorTestEnabled() {
2506 if (is_scissor_enabled_
)
2509 FlushTextureQuadCache(SHARED_BINDING
);
2510 gl_
->Enable(GL_SCISSOR_TEST
);
2511 is_scissor_enabled_
= true;
2514 void GLRenderer::EnsureScissorTestDisabled() {
2515 if (!is_scissor_enabled_
)
2518 FlushTextureQuadCache(SHARED_BINDING
);
2519 gl_
->Disable(GL_SCISSOR_TEST
);
2520 is_scissor_enabled_
= false;
2523 void GLRenderer::CopyCurrentRenderPassToBitmap(
2524 DrawingFrame
* frame
,
2525 scoped_ptr
<CopyOutputRequest
> request
) {
2526 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2527 gfx::Rect copy_rect
= frame
->current_render_pass
->output_rect
;
2528 if (request
->has_area())
2529 copy_rect
.Intersect(request
->area());
2530 GetFramebufferPixelsAsync(frame
, copy_rect
, request
.Pass());
2533 void GLRenderer::ToGLMatrix(float* gl_matrix
, const gfx::Transform
& transform
) {
2534 transform
.matrix().asColMajorf(gl_matrix
);
2537 void GLRenderer::SetShaderQuadF(const gfx::QuadF
& quad
, int quad_location
) {
2538 if (quad_location
== -1)
2542 gl_quad
[0] = quad
.p1().x();
2543 gl_quad
[1] = quad
.p1().y();
2544 gl_quad
[2] = quad
.p2().x();
2545 gl_quad
[3] = quad
.p2().y();
2546 gl_quad
[4] = quad
.p3().x();
2547 gl_quad
[5] = quad
.p3().y();
2548 gl_quad
[6] = quad
.p4().x();
2549 gl_quad
[7] = quad
.p4().y();
2550 gl_
->Uniform2fv(quad_location
, 4, gl_quad
);
2553 void GLRenderer::SetShaderOpacity(float opacity
, int alpha_location
) {
2554 if (alpha_location
!= -1)
2555 gl_
->Uniform1f(alpha_location
, opacity
);
2558 void GLRenderer::SetStencilEnabled(bool enabled
) {
2559 if (enabled
== stencil_shadow_
)
2563 gl_
->Enable(GL_STENCIL_TEST
);
2565 gl_
->Disable(GL_STENCIL_TEST
);
2566 stencil_shadow_
= enabled
;
2569 void GLRenderer::SetBlendEnabled(bool enabled
) {
2570 if (enabled
== blend_shadow_
)
2574 gl_
->Enable(GL_BLEND
);
2576 gl_
->Disable(GL_BLEND
);
2577 blend_shadow_
= enabled
;
2580 void GLRenderer::SetUseProgram(unsigned program
) {
2581 if (program
== program_shadow_
)
2583 gl_
->UseProgram(program
);
2584 program_shadow_
= program
;
2587 void GLRenderer::DrawQuadGeometryClippedByQuadF(
2588 const DrawingFrame
* frame
,
2589 const gfx::Transform
& draw_transform
,
2590 const gfx::RectF
& quad_rect
,
2591 const gfx::QuadF
& clipping_region_quad
,
2592 int matrix_location
,
2594 PrepareGeometry(CLIPPED_BINDING
);
2596 clipped_geometry_
->InitializeCustomQuadWithUVs(clipping_region_quad
, uvs
);
2598 clipped_geometry_
->InitializeCustomQuad(clipping_region_quad
);
2600 gfx::Transform quad_rect_matrix
;
2601 QuadRectTransform(&quad_rect_matrix
, draw_transform
, quad_rect
);
2602 static float gl_matrix
[16];
2603 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad_rect_matrix
);
2604 gl_
->UniformMatrix4fv(matrix_location
, 1, false, &gl_matrix
[0]);
2606 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
,
2607 reinterpret_cast<const void*>(0));
2610 void GLRenderer::DrawQuadGeometry(const DrawingFrame
* frame
,
2611 const gfx::Transform
& draw_transform
,
2612 const gfx::RectF
& quad_rect
,
2613 int matrix_location
) {
2614 PrepareGeometry(SHARED_BINDING
);
2615 gfx::Transform quad_rect_matrix
;
2616 QuadRectTransform(&quad_rect_matrix
, draw_transform
, quad_rect
);
2617 static float gl_matrix
[16];
2618 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad_rect_matrix
);
2619 gl_
->UniformMatrix4fv(matrix_location
, 1, false, &gl_matrix
[0]);
2621 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0);
2624 void GLRenderer::Finish() {
2625 TRACE_EVENT0("cc", "GLRenderer::Finish");
2629 void GLRenderer::SwapBuffers(const CompositorFrameMetadata
& metadata
) {
2630 DCHECK(!is_backbuffer_discarded_
);
2632 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2633 // We're done! Time to swapbuffers!
2635 gfx::Size surface_size
= output_surface_
->SurfaceSize();
2637 CompositorFrame compositor_frame
;
2638 compositor_frame
.metadata
= metadata
;
2639 compositor_frame
.gl_frame_data
= make_scoped_ptr(new GLFrameData
);
2640 compositor_frame
.gl_frame_data
->size
= surface_size
;
2641 if (capabilities_
.using_partial_swap
) {
2642 // If supported, we can save significant bandwidth by only swapping the
2643 // damaged/scissored region (clamped to the viewport).
2644 swap_buffer_rect_
.Intersect(gfx::Rect(surface_size
));
2645 int flipped_y_pos_of_rect_bottom
= surface_size
.height() -
2646 swap_buffer_rect_
.y() -
2647 swap_buffer_rect_
.height();
2648 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2649 gfx::Rect(swap_buffer_rect_
.x(),
2650 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2651 : swap_buffer_rect_
.y(),
2652 swap_buffer_rect_
.width(),
2653 swap_buffer_rect_
.height());
2655 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2656 gfx::Rect(output_surface_
->SurfaceSize());
2658 output_surface_
->SwapBuffers(&compositor_frame
);
2660 // Release previously used overlay resources and hold onto the pending ones
2661 // until the next swap buffers.
2662 in_use_overlay_resources_
.clear();
2663 in_use_overlay_resources_
.swap(pending_overlay_resources_
);
2665 swap_buffer_rect_
= gfx::Rect();
2668 void GLRenderer::EnforceMemoryPolicy() {
2670 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2671 ReleaseRenderPassTextures();
2672 DiscardBackbuffer();
2673 output_surface_
->context_provider()->DeleteCachedResources();
2676 PrepareGeometry(NO_BINDING
);
2679 void GLRenderer::DiscardBackbuffer() {
2680 if (is_backbuffer_discarded_
)
2683 output_surface_
->DiscardBackbuffer();
2685 is_backbuffer_discarded_
= true;
2687 // Damage tracker needs a full reset every time framebuffer is discarded.
2688 client_
->SetFullRootLayerDamage();
2691 void GLRenderer::EnsureBackbuffer() {
2692 if (!is_backbuffer_discarded_
)
2695 output_surface_
->EnsureBackbuffer();
2696 is_backbuffer_discarded_
= false;
2699 void GLRenderer::GetFramebufferPixelsAsync(
2700 const DrawingFrame
* frame
,
2701 const gfx::Rect
& rect
,
2702 scoped_ptr
<CopyOutputRequest
> request
) {
2703 DCHECK(!request
->IsEmpty());
2704 if (request
->IsEmpty())
2709 gfx::Rect window_rect
= MoveFromDrawToWindowSpace(frame
, rect
);
2710 DCHECK_GE(window_rect
.x(), 0);
2711 DCHECK_GE(window_rect
.y(), 0);
2712 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2713 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2715 if (!request
->force_bitmap_result()) {
2716 bool own_mailbox
= !request
->has_texture_mailbox();
2718 GLuint texture_id
= 0;
2719 gpu::Mailbox mailbox
;
2721 gl_
->GenMailboxCHROMIUM(mailbox
.name
);
2722 gl_
->GenTextures(1, &texture_id
);
2723 gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
);
2725 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
2726 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
);
2727 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
2728 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
2729 gl_
->ProduceTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
);
2731 mailbox
= request
->texture_mailbox().mailbox();
2732 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D
),
2733 request
->texture_mailbox().target());
2734 DCHECK(!mailbox
.IsZero());
2735 unsigned incoming_sync_point
= request
->texture_mailbox().sync_point();
2736 if (incoming_sync_point
)
2737 gl_
->WaitSyncPointCHROMIUM(incoming_sync_point
);
2740 gl_
->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
);
2742 GetFramebufferTexture(texture_id
, RGBA_8888
, window_rect
);
2744 unsigned sync_point
= gl_
->InsertSyncPointCHROMIUM();
2745 TextureMailbox
texture_mailbox(mailbox
, GL_TEXTURE_2D
, sync_point
);
2747 scoped_ptr
<SingleReleaseCallback
> release_callback
;
2749 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2750 release_callback
= texture_mailbox_deleter_
->GetReleaseCallback(
2751 output_surface_
->context_provider(), texture_id
);
2753 gl_
->DeleteTextures(1, &texture_id
);
2756 request
->SendTextureResult(
2757 window_rect
.size(), texture_mailbox
, release_callback
.Pass());
2761 DCHECK(request
->force_bitmap_result());
2763 scoped_ptr
<PendingAsyncReadPixels
> pending_read(new PendingAsyncReadPixels
);
2764 pending_read
->copy_request
= request
.Pass();
2765 pending_async_read_pixels_
.insert(pending_async_read_pixels_
.begin(),
2766 pending_read
.Pass());
2768 bool do_workaround
= NeedsIOSurfaceReadbackWorkaround();
2770 unsigned temporary_texture
= 0;
2771 unsigned temporary_fbo
= 0;
2773 if (do_workaround
) {
2774 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2775 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2776 // calls, even those on different OpenGL contexts. It is believed that this
2777 // is the root cause of top crasher
2778 // http://crbug.com/99393. <rdar://problem/10949687>
2780 gl_
->GenTextures(1, &temporary_texture
);
2781 gl_
->BindTexture(GL_TEXTURE_2D
, temporary_texture
);
2782 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
2783 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
);
2784 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
2785 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
2786 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2787 // temporary texture.
2788 GetFramebufferTexture(
2789 temporary_texture
, RGBA_8888
, gfx::Rect(current_surface_size_
));
2790 gl_
->GenFramebuffers(1, &temporary_fbo
);
2791 // Attach this texture to an FBO, and perform the readback from that FBO.
2792 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, temporary_fbo
);
2793 gl_
->FramebufferTexture2D(GL_FRAMEBUFFER
, GL_COLOR_ATTACHMENT0
,
2794 GL_TEXTURE_2D
, temporary_texture
, 0);
2796 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE
),
2797 gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
));
2801 gl_
->GenBuffers(1, &buffer
);
2802 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, buffer
);
2803 gl_
->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
,
2804 4 * window_rect
.size().GetArea(), NULL
, GL_STREAM_READ
);
2807 gl_
->GenQueriesEXT(1, &query
);
2808 gl_
->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
, query
);
2810 gl_
->ReadPixels(window_rect
.x(), window_rect
.y(), window_rect
.width(),
2811 window_rect
.height(), GL_RGBA
, GL_UNSIGNED_BYTE
, NULL
);
2813 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0);
2815 if (do_workaround
) {
2817 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0);
2818 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2819 gl_
->DeleteFramebuffers(1, &temporary_fbo
);
2820 gl_
->DeleteTextures(1, &temporary_texture
);
2823 base::Closure finished_callback
= base::Bind(&GLRenderer::FinishedReadback
,
2824 base::Unretained(this),
2827 window_rect
.size());
2828 // Save the finished_callback so it can be cancelled.
2829 pending_async_read_pixels_
.front()->finished_read_pixels_callback
.Reset(
2831 base::Closure cancelable_callback
=
2832 pending_async_read_pixels_
.front()->
2833 finished_read_pixels_callback
.callback();
2835 // Save the buffer to verify the callbacks happen in the expected order.
2836 pending_async_read_pixels_
.front()->buffer
= buffer
;
2838 gl_
->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
);
2839 context_support_
->SignalQuery(query
, cancelable_callback
);
2841 EnforceMemoryPolicy();
2844 void GLRenderer::FinishedReadback(unsigned source_buffer
,
2846 const gfx::Size
& size
) {
2847 DCHECK(!pending_async_read_pixels_
.empty());
2850 gl_
->DeleteQueriesEXT(1, &query
);
2853 PendingAsyncReadPixels
* current_read
= pending_async_read_pixels_
.back();
2854 // Make sure we service the readbacks in order.
2855 DCHECK_EQ(source_buffer
, current_read
->buffer
);
2857 uint8
* src_pixels
= NULL
;
2858 scoped_ptr
<SkBitmap
> bitmap
;
2860 if (source_buffer
!= 0) {
2861 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, source_buffer
);
2862 src_pixels
= static_cast<uint8
*>(gl_
->MapBufferCHROMIUM(
2863 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, GL_READ_ONLY
));
2866 bitmap
.reset(new SkBitmap
);
2867 bitmap
->allocN32Pixels(size
.width(), size
.height());
2868 scoped_ptr
<SkAutoLockPixels
> lock(new SkAutoLockPixels(*bitmap
));
2869 uint8
* dest_pixels
= static_cast<uint8
*>(bitmap
->getPixels());
2871 size_t row_bytes
= size
.width() * 4;
2872 int num_rows
= size
.height();
2873 size_t total_bytes
= num_rows
* row_bytes
;
2874 for (size_t dest_y
= 0; dest_y
< total_bytes
; dest_y
+= row_bytes
) {
2876 size_t src_y
= total_bytes
- dest_y
- row_bytes
;
2877 // Swizzle OpenGL -> Skia byte order.
2878 for (size_t x
= 0; x
< row_bytes
; x
+= 4) {
2879 dest_pixels
[dest_y
+ x
+ SK_R32_SHIFT
/ 8] =
2880 src_pixels
[src_y
+ x
+ 0];
2881 dest_pixels
[dest_y
+ x
+ SK_G32_SHIFT
/ 8] =
2882 src_pixels
[src_y
+ x
+ 1];
2883 dest_pixels
[dest_y
+ x
+ SK_B32_SHIFT
/ 8] =
2884 src_pixels
[src_y
+ x
+ 2];
2885 dest_pixels
[dest_y
+ x
+ SK_A32_SHIFT
/ 8] =
2886 src_pixels
[src_y
+ x
+ 3];
2890 gl_
->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
);
2892 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0);
2893 gl_
->DeleteBuffers(1, &source_buffer
);
2897 current_read
->copy_request
->SendBitmapResult(bitmap
.Pass());
2898 pending_async_read_pixels_
.pop_back();
2901 void GLRenderer::GetFramebufferTexture(unsigned texture_id
,
2902 ResourceFormat texture_format
,
2903 const gfx::Rect
& window_rect
) {
2905 DCHECK_GE(window_rect
.x(), 0);
2906 DCHECK_GE(window_rect
.y(), 0);
2907 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2908 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2910 gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
);
2911 gl_
->CopyTexImage2D(GL_TEXTURE_2D
, 0, GLDataFormat(texture_format
),
2912 window_rect
.x(), window_rect
.y(), window_rect
.width(),
2913 window_rect
.height(), 0);
2914 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2917 bool GLRenderer::UseScopedTexture(DrawingFrame
* frame
,
2918 const ScopedResource
* texture
,
2919 const gfx::Rect
& viewport_rect
) {
2920 DCHECK(texture
->id());
2921 frame
->current_render_pass
= NULL
;
2922 frame
->current_texture
= texture
;
2924 return BindFramebufferToTexture(frame
, texture
, viewport_rect
);
2927 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame
* frame
) {
2928 current_framebuffer_lock_
= nullptr;
2929 output_surface_
->BindFramebuffer();
2931 if (output_surface_
->HasExternalStencilTest()) {
2932 SetStencilEnabled(true);
2933 gl_
->StencilFunc(GL_EQUAL
, 1, 1);
2935 SetStencilEnabled(false);
2939 bool GLRenderer::BindFramebufferToTexture(DrawingFrame
* frame
,
2940 const ScopedResource
* texture
,
2941 const gfx::Rect
& target_rect
) {
2942 DCHECK(texture
->id());
2944 // Explicitly release lock, otherwise we can crash when try to lock
2945 // same texture again.
2946 current_framebuffer_lock_
= nullptr;
2948 SetStencilEnabled(false);
2949 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, offscreen_framebuffer_id_
);
2950 current_framebuffer_lock_
=
2951 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2952 resource_provider_
, texture
->id()));
2953 unsigned texture_id
= current_framebuffer_lock_
->texture_id();
2954 gl_
->FramebufferTexture2D(GL_FRAMEBUFFER
, GL_COLOR_ATTACHMENT0
, GL_TEXTURE_2D
,
2957 DCHECK(gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
) ==
2958 GL_FRAMEBUFFER_COMPLETE
||
2963 void GLRenderer::SetScissorTestRect(const gfx::Rect
& scissor_rect
) {
2964 EnsureScissorTestEnabled();
2966 // Don't unnecessarily ask the context to change the scissor, because it
2967 // may cause undesired GPU pipeline flushes.
2968 if (scissor_rect
== scissor_rect_
&& !scissor_rect_needs_reset_
)
2971 scissor_rect_
= scissor_rect
;
2972 FlushTextureQuadCache(SHARED_BINDING
);
2973 gl_
->Scissor(scissor_rect
.x(), scissor_rect
.y(), scissor_rect
.width(),
2974 scissor_rect
.height());
2976 scissor_rect_needs_reset_
= false;
2979 void GLRenderer::SetViewport() {
2980 gl_
->Viewport(current_window_space_viewport_
.x(),
2981 current_window_space_viewport_
.y(),
2982 current_window_space_viewport_
.width(),
2983 current_window_space_viewport_
.height());
2986 void GLRenderer::InitializeSharedObjects() {
2987 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2989 // Create an FBO for doing offscreen rendering.
2990 gl_
->GenFramebuffers(1, &offscreen_framebuffer_id_
);
2993 make_scoped_ptr(new StaticGeometryBinding(gl_
, QuadVertexRect()));
2994 clipped_geometry_
= make_scoped_ptr(new DynamicGeometryBinding(gl_
));
2997 void GLRenderer::PrepareGeometry(BoundGeometry binding
) {
2998 if (binding
== bound_geometry_
) {
3003 case SHARED_BINDING
:
3004 shared_geometry_
->PrepareForDraw();
3006 case CLIPPED_BINDING
:
3007 clipped_geometry_
->PrepareForDraw();
3012 bound_geometry_
= binding
;
3015 const GLRenderer::TileCheckerboardProgram
*
3016 GLRenderer::GetTileCheckerboardProgram() {
3017 if (!tile_checkerboard_program_
.initialized()) {
3018 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
3019 tile_checkerboard_program_
.Initialize(output_surface_
->context_provider(),
3020 TEX_COORD_PRECISION_NA
,
3023 return &tile_checkerboard_program_
;
3026 const GLRenderer::DebugBorderProgram
* GLRenderer::GetDebugBorderProgram() {
3027 if (!debug_border_program_
.initialized()) {
3028 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
3029 debug_border_program_
.Initialize(output_surface_
->context_provider(),
3030 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
3032 return &debug_border_program_
;
3035 const GLRenderer::SolidColorProgram
* GLRenderer::GetSolidColorProgram() {
3036 if (!solid_color_program_
.initialized()) {
3037 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
3038 solid_color_program_
.Initialize(output_surface_
->context_provider(),
3039 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
3041 return &solid_color_program_
;
3044 const GLRenderer::SolidColorProgramAA
* GLRenderer::GetSolidColorProgramAA() {
3045 if (!solid_color_program_aa_
.initialized()) {
3046 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
3047 solid_color_program_aa_
.Initialize(output_surface_
->context_provider(),
3048 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
3050 return &solid_color_program_aa_
;
3053 const GLRenderer::RenderPassProgram
* GLRenderer::GetRenderPassProgram(
3054 TexCoordPrecision precision
,
3055 BlendMode blend_mode
) {
3056 DCHECK_GE(precision
, 0);
3057 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3058 DCHECK_GE(blend_mode
, 0);
3059 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3060 RenderPassProgram
* program
= &render_pass_program_
[precision
][blend_mode
];
3061 if (!program
->initialized()) {
3062 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
3063 program
->Initialize(output_surface_
->context_provider(), precision
,
3064 SAMPLER_TYPE_2D
, blend_mode
);
3069 const GLRenderer::RenderPassProgramAA
* GLRenderer::GetRenderPassProgramAA(
3070 TexCoordPrecision precision
,
3071 BlendMode blend_mode
) {
3072 DCHECK_GE(precision
, 0);
3073 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3074 DCHECK_GE(blend_mode
, 0);
3075 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3076 RenderPassProgramAA
* program
=
3077 &render_pass_program_aa_
[precision
][blend_mode
];
3078 if (!program
->initialized()) {
3079 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
3080 program
->Initialize(output_surface_
->context_provider(), precision
,
3081 SAMPLER_TYPE_2D
, blend_mode
);
3086 const GLRenderer::RenderPassMaskProgram
* GLRenderer::GetRenderPassMaskProgram(
3087 TexCoordPrecision precision
,
3088 SamplerType sampler
,
3089 BlendMode blend_mode
,
3090 bool mask_for_background
) {
3091 DCHECK_GE(precision
, 0);
3092 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3093 DCHECK_GE(sampler
, 0);
3094 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3095 DCHECK_GE(blend_mode
, 0);
3096 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3097 RenderPassMaskProgram
* program
=
3098 &render_pass_mask_program_
[precision
][sampler
][blend_mode
]
3099 [mask_for_background
? HAS_MASK
: NO_MASK
];
3100 if (!program
->initialized()) {
3101 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
3102 program
->Initialize(
3103 output_surface_
->context_provider(), precision
,
3104 sampler
, blend_mode
, mask_for_background
);
3109 const GLRenderer::RenderPassMaskProgramAA
*
3110 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision
,
3111 SamplerType sampler
,
3112 BlendMode blend_mode
,
3113 bool mask_for_background
) {
3114 DCHECK_GE(precision
, 0);
3115 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3116 DCHECK_GE(sampler
, 0);
3117 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3118 DCHECK_GE(blend_mode
, 0);
3119 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3120 RenderPassMaskProgramAA
* program
=
3121 &render_pass_mask_program_aa_
[precision
][sampler
][blend_mode
]
3122 [mask_for_background
? HAS_MASK
: NO_MASK
];
3123 if (!program
->initialized()) {
3124 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
3125 program
->Initialize(
3126 output_surface_
->context_provider(), precision
,
3127 sampler
, blend_mode
, mask_for_background
);
3132 const GLRenderer::RenderPassColorMatrixProgram
*
3133 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision
,
3134 BlendMode blend_mode
) {
3135 DCHECK_GE(precision
, 0);
3136 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3137 DCHECK_GE(blend_mode
, 0);
3138 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3139 RenderPassColorMatrixProgram
* program
=
3140 &render_pass_color_matrix_program_
[precision
][blend_mode
];
3141 if (!program
->initialized()) {
3142 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
3143 program
->Initialize(output_surface_
->context_provider(), precision
,
3144 SAMPLER_TYPE_2D
, blend_mode
);
3149 const GLRenderer::RenderPassColorMatrixProgramAA
*
3150 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision
,
3151 BlendMode blend_mode
) {
3152 DCHECK_GE(precision
, 0);
3153 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3154 DCHECK_GE(blend_mode
, 0);
3155 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3156 RenderPassColorMatrixProgramAA
* program
=
3157 &render_pass_color_matrix_program_aa_
[precision
][blend_mode
];
3158 if (!program
->initialized()) {
3160 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
3161 program
->Initialize(output_surface_
->context_provider(), precision
,
3162 SAMPLER_TYPE_2D
, blend_mode
);
3167 const GLRenderer::RenderPassMaskColorMatrixProgram
*
3168 GLRenderer::GetRenderPassMaskColorMatrixProgram(
3169 TexCoordPrecision precision
,
3170 SamplerType sampler
,
3171 BlendMode blend_mode
,
3172 bool mask_for_background
) {
3173 DCHECK_GE(precision
, 0);
3174 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3175 DCHECK_GE(sampler
, 0);
3176 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3177 DCHECK_GE(blend_mode
, 0);
3178 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3179 RenderPassMaskColorMatrixProgram
* program
=
3180 &render_pass_mask_color_matrix_program_
[precision
][sampler
][blend_mode
]
3181 [mask_for_background
? HAS_MASK
: NO_MASK
];
3182 if (!program
->initialized()) {
3184 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
3185 program
->Initialize(
3186 output_surface_
->context_provider(), precision
,
3187 sampler
, blend_mode
, mask_for_background
);
3192 const GLRenderer::RenderPassMaskColorMatrixProgramAA
*
3193 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(
3194 TexCoordPrecision precision
,
3195 SamplerType sampler
,
3196 BlendMode blend_mode
,
3197 bool mask_for_background
) {
3198 DCHECK_GE(precision
, 0);
3199 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3200 DCHECK_GE(sampler
, 0);
3201 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3202 DCHECK_GE(blend_mode
, 0);
3203 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3204 RenderPassMaskColorMatrixProgramAA
* program
=
3205 &render_pass_mask_color_matrix_program_aa_
[precision
][sampler
][blend_mode
]
3206 [mask_for_background
? HAS_MASK
: NO_MASK
];
3207 if (!program
->initialized()) {
3209 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
3210 program
->Initialize(
3211 output_surface_
->context_provider(), precision
,
3212 sampler
, blend_mode
, mask_for_background
);
3217 const GLRenderer::TileProgram
* GLRenderer::GetTileProgram(
3218 TexCoordPrecision precision
,
3219 SamplerType sampler
) {
3220 DCHECK_GE(precision
, 0);
3221 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3222 DCHECK_GE(sampler
, 0);
3223 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3224 TileProgram
* program
= &tile_program_
[precision
][sampler
];
3225 if (!program
->initialized()) {
3226 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
3227 program
->Initialize(
3228 output_surface_
->context_provider(), precision
, sampler
);
3233 const GLRenderer::TileProgramOpaque
* GLRenderer::GetTileProgramOpaque(
3234 TexCoordPrecision precision
,
3235 SamplerType sampler
) {
3236 DCHECK_GE(precision
, 0);
3237 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3238 DCHECK_GE(sampler
, 0);
3239 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3240 TileProgramOpaque
* program
= &tile_program_opaque_
[precision
][sampler
];
3241 if (!program
->initialized()) {
3242 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3243 program
->Initialize(
3244 output_surface_
->context_provider(), precision
, sampler
);
3249 const GLRenderer::TileProgramAA
* GLRenderer::GetTileProgramAA(
3250 TexCoordPrecision precision
,
3251 SamplerType sampler
) {
3252 DCHECK_GE(precision
, 0);
3253 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3254 DCHECK_GE(sampler
, 0);
3255 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3256 TileProgramAA
* program
= &tile_program_aa_
[precision
][sampler
];
3257 if (!program
->initialized()) {
3258 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3259 program
->Initialize(
3260 output_surface_
->context_provider(), precision
, sampler
);
3265 const GLRenderer::TileProgramSwizzle
* GLRenderer::GetTileProgramSwizzle(
3266 TexCoordPrecision precision
,
3267 SamplerType sampler
) {
3268 DCHECK_GE(precision
, 0);
3269 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3270 DCHECK_GE(sampler
, 0);
3271 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3272 TileProgramSwizzle
* program
= &tile_program_swizzle_
[precision
][sampler
];
3273 if (!program
->initialized()) {
3274 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3275 program
->Initialize(
3276 output_surface_
->context_provider(), precision
, sampler
);
3281 const GLRenderer::TileProgramSwizzleOpaque
*
3282 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision
,
3283 SamplerType sampler
) {
3284 DCHECK_GE(precision
, 0);
3285 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3286 DCHECK_GE(sampler
, 0);
3287 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3288 TileProgramSwizzleOpaque
* program
=
3289 &tile_program_swizzle_opaque_
[precision
][sampler
];
3290 if (!program
->initialized()) {
3291 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3292 program
->Initialize(
3293 output_surface_
->context_provider(), precision
, sampler
);
3298 const GLRenderer::TileProgramSwizzleAA
* GLRenderer::GetTileProgramSwizzleAA(
3299 TexCoordPrecision precision
,
3300 SamplerType sampler
) {
3301 DCHECK_GE(precision
, 0);
3302 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3303 DCHECK_GE(sampler
, 0);
3304 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3305 TileProgramSwizzleAA
* program
= &tile_program_swizzle_aa_
[precision
][sampler
];
3306 if (!program
->initialized()) {
3307 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3308 program
->Initialize(
3309 output_surface_
->context_provider(), precision
, sampler
);
3314 const GLRenderer::TextureProgram
* GLRenderer::GetTextureProgram(
3315 TexCoordPrecision precision
,
3316 SamplerType sampler
) {
3317 DCHECK_GE(precision
, 0);
3318 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3319 DCHECK_GE(sampler
, 0);
3320 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3321 TextureProgram
* program
= &texture_program_
[precision
][sampler
];
3322 if (!program
->initialized()) {
3323 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3324 program
->Initialize(output_surface_
->context_provider(), precision
,
3330 const GLRenderer::NonPremultipliedTextureProgram
*
3331 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision
,
3332 SamplerType sampler
) {
3333 DCHECK_GE(precision
, 0);
3334 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3335 DCHECK_GE(sampler
, 0);
3336 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3337 NonPremultipliedTextureProgram
* program
=
3338 &nonpremultiplied_texture_program_
[precision
][sampler
];
3339 if (!program
->initialized()) {
3341 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3342 program
->Initialize(output_surface_
->context_provider(), precision
,
3348 const GLRenderer::TextureBackgroundProgram
*
3349 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision
,
3350 SamplerType sampler
) {
3351 DCHECK_GE(precision
, 0);
3352 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3353 DCHECK_GE(sampler
, 0);
3354 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3355 TextureBackgroundProgram
* program
=
3356 &texture_background_program_
[precision
][sampler
];
3357 if (!program
->initialized()) {
3358 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3359 program
->Initialize(output_surface_
->context_provider(), precision
,
3365 const GLRenderer::NonPremultipliedTextureBackgroundProgram
*
3366 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3367 TexCoordPrecision precision
,
3368 SamplerType sampler
) {
3369 DCHECK_GE(precision
, 0);
3370 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3371 DCHECK_GE(sampler
, 0);
3372 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3373 NonPremultipliedTextureBackgroundProgram
* program
=
3374 &nonpremultiplied_texture_background_program_
[precision
][sampler
];
3375 if (!program
->initialized()) {
3377 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3378 program
->Initialize(output_surface_
->context_provider(), precision
,
3384 const GLRenderer::TextureProgram
* GLRenderer::GetTextureIOSurfaceProgram(
3385 TexCoordPrecision precision
) {
3386 DCHECK_GE(precision
, 0);
3387 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3388 TextureProgram
* program
= &texture_io_surface_program_
[precision
];
3389 if (!program
->initialized()) {
3390 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3391 program
->Initialize(output_surface_
->context_provider(), precision
,
3392 SAMPLER_TYPE_2D_RECT
);
3397 const GLRenderer::VideoYUVProgram
* GLRenderer::GetVideoYUVProgram(
3398 TexCoordPrecision precision
,
3399 SamplerType sampler
) {
3400 DCHECK_GE(precision
, 0);
3401 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3402 DCHECK_GE(sampler
, 0);
3403 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3404 VideoYUVProgram
* program
= &video_yuv_program_
[precision
][sampler
];
3405 if (!program
->initialized()) {
3406 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3407 program
->Initialize(output_surface_
->context_provider(), precision
,
3413 const GLRenderer::VideoYUVAProgram
* GLRenderer::GetVideoYUVAProgram(
3414 TexCoordPrecision precision
,
3415 SamplerType sampler
) {
3416 DCHECK_GE(precision
, 0);
3417 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3418 DCHECK_GE(sampler
, 0);
3419 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3420 VideoYUVAProgram
* program
= &video_yuva_program_
[precision
][sampler
];
3421 if (!program
->initialized()) {
3422 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3423 program
->Initialize(output_surface_
->context_provider(), precision
,
3429 const GLRenderer::VideoStreamTextureProgram
*
3430 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision
) {
3431 if (!Capabilities().using_egl_image
)
3433 DCHECK_GE(precision
, 0);
3434 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3435 VideoStreamTextureProgram
* program
=
3436 &video_stream_texture_program_
[precision
];
3437 if (!program
->initialized()) {
3438 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3439 program
->Initialize(output_surface_
->context_provider(), precision
,
3440 SAMPLER_TYPE_EXTERNAL_OES
);
3445 void GLRenderer::CleanupSharedObjects() {
3446 shared_geometry_
= nullptr;
3448 for (int i
= 0; i
<= LAST_TEX_COORD_PRECISION
; ++i
) {
3449 for (int j
= 0; j
<= LAST_SAMPLER_TYPE
; ++j
) {
3450 tile_program_
[i
][j
].Cleanup(gl_
);
3451 tile_program_opaque_
[i
][j
].Cleanup(gl_
);
3452 tile_program_swizzle_
[i
][j
].Cleanup(gl_
);
3453 tile_program_swizzle_opaque_
[i
][j
].Cleanup(gl_
);
3454 tile_program_aa_
[i
][j
].Cleanup(gl_
);
3455 tile_program_swizzle_aa_
[i
][j
].Cleanup(gl_
);
3457 for (int k
= 0; k
<= LAST_BLEND_MODE
; k
++) {
3458 for (int l
= 0; l
<= LAST_MASK_VALUE
; ++l
) {
3459 render_pass_mask_program_
[i
][j
][k
][l
].Cleanup(gl_
);
3460 render_pass_mask_program_aa_
[i
][j
][k
][l
].Cleanup(gl_
);
3461 render_pass_mask_color_matrix_program_aa_
[i
][j
][k
][l
].Cleanup(gl_
);
3462 render_pass_mask_color_matrix_program_
[i
][j
][k
][l
].Cleanup(gl_
);
3466 video_yuv_program_
[i
][j
].Cleanup(gl_
);
3467 video_yuva_program_
[i
][j
].Cleanup(gl_
);
3469 for (int j
= 0; j
<= LAST_BLEND_MODE
; j
++) {
3470 render_pass_program_
[i
][j
].Cleanup(gl_
);
3471 render_pass_program_aa_
[i
][j
].Cleanup(gl_
);
3472 render_pass_color_matrix_program_
[i
][j
].Cleanup(gl_
);
3473 render_pass_color_matrix_program_aa_
[i
][j
].Cleanup(gl_
);
3476 for (int j
= 0; j
<= LAST_SAMPLER_TYPE
; ++j
) {
3477 texture_program_
[i
][j
].Cleanup(gl_
);
3478 nonpremultiplied_texture_program_
[i
][j
].Cleanup(gl_
);
3479 texture_background_program_
[i
][j
].Cleanup(gl_
);
3480 nonpremultiplied_texture_background_program_
[i
][j
].Cleanup(gl_
);
3482 texture_io_surface_program_
[i
].Cleanup(gl_
);
3484 video_stream_texture_program_
[i
].Cleanup(gl_
);
3487 tile_checkerboard_program_
.Cleanup(gl_
);
3489 debug_border_program_
.Cleanup(gl_
);
3490 solid_color_program_
.Cleanup(gl_
);
3491 solid_color_program_aa_
.Cleanup(gl_
);
3493 if (offscreen_framebuffer_id_
)
3494 gl_
->DeleteFramebuffers(1, &offscreen_framebuffer_id_
);
3496 if (on_demand_tile_raster_resource_id_
)
3497 resource_provider_
->DeleteResource(on_demand_tile_raster_resource_id_
);
3499 ReleaseRenderPassTextures();
3502 void GLRenderer::ReinitializeGLState() {
3503 is_scissor_enabled_
= false;
3504 scissor_rect_needs_reset_
= true;
3505 stencil_shadow_
= false;
3506 blend_shadow_
= true;
3507 program_shadow_
= 0;
3512 void GLRenderer::RestoreGLState() {
3513 // This restores the current GLRenderer state to the GL context.
3514 bound_geometry_
= NO_BINDING
;
3515 PrepareGeometry(SHARED_BINDING
);
3517 gl_
->Disable(GL_DEPTH_TEST
);
3518 gl_
->Disable(GL_CULL_FACE
);
3519 gl_
->ColorMask(true, true, true, true);
3520 gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
);
3521 gl_
->ActiveTexture(GL_TEXTURE0
);
3523 if (program_shadow_
)
3524 gl_
->UseProgram(program_shadow_
);
3526 if (stencil_shadow_
)
3527 gl_
->Enable(GL_STENCIL_TEST
);
3529 gl_
->Disable(GL_STENCIL_TEST
);
3532 gl_
->Enable(GL_BLEND
);
3534 gl_
->Disable(GL_BLEND
);
3536 if (is_scissor_enabled_
) {
3537 gl_
->Enable(GL_SCISSOR_TEST
);
3538 gl_
->Scissor(scissor_rect_
.x(), scissor_rect_
.y(), scissor_rect_
.width(),
3539 scissor_rect_
.height());
3541 gl_
->Disable(GL_SCISSOR_TEST
);
3545 void GLRenderer::RestoreFramebuffer(DrawingFrame
* frame
) {
3546 UseRenderPass(frame
, frame
->current_render_pass
);
3548 // Call SetViewport directly, rather than through PrepareSurfaceForPass.
3549 // PrepareSurfaceForPass also clears the surface, which is not desired when
3554 bool GLRenderer::IsContextLost() {
3555 return gl_
->GetGraphicsResetStatusKHR() != GL_NO_ERROR
;
3558 void GLRenderer::ScheduleOverlays(DrawingFrame
* frame
) {
3559 if (!frame
->overlay_list
.size())
3562 ResourceProvider::ResourceIdArray resources
;
3563 OverlayCandidateList
& overlays
= frame
->overlay_list
;
3564 for (const OverlayCandidate
& overlay
: overlays
) {
3565 // Skip primary plane.
3566 if (overlay
.plane_z_order
== 0)
3569 pending_overlay_resources_
.push_back(
3570 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3571 resource_provider_
, overlay
.resource_id
)));
3573 context_support_
->ScheduleOverlayPlane(
3574 overlay
.plane_z_order
,
3576 pending_overlay_resources_
.back()->texture_id(),
3577 ToNearestRect(overlay
.display_rect
),